Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(cli): three-ws CLI and @three-ws/agent self-hosted agent runtime packages
nirholasbfcce6df4b07
diff --git a/packages/agent-cli/LICENSE b/packages/agent-cli/LICENSEnew file mode 100644index 000000000..b5ae2a4e1--- /dev/null+++ b/packages/agent-cli/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2026 nirholas++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/agent-cli/package.json b/packages/agent-cli/package.jsonnew file mode 100644index 000000000..95a53c7ae--- /dev/null+++ b/packages/agent-cli/package.json@@ -0,0 +1,67 @@+{+ "name": "@three-ws/agent",+ "version": "0.1.0",+ "description": "Run a three.ws agent on your own machine or VPS: a terminal UI with slash commands, streaming tool output, local file and shell tools in a resource-limited sandbox, the three.ws MCP tools and agent wallet, SQLite sessions with full-text search, parallel subagents, natural-language cron, and a Telegram gateway.",+ "keywords": [+ "three.ws",+ "agent",+ "ai-agent",+ "tui",+ "terminal",+ "cli",+ "mcp",+ "model-context-protocol",+ "cron",+ "subagents",+ "telegram",+ "solana",+ "openai-compatible"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws/docs/agent-cli",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/agent-cli"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "type": "module",+ "bin": {+ "three-ws-agent": "./bin/three-ws-agent.js"+ },+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js",+ "./cli": "./src/cli.js",+ "./package.json": "./package.json"+ },+ "files": [+ "bin",+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "vitest run --root ../.. packages/agent-cli/tests"+ },+ "engines": {+ "node": ">=22.13"+ },+ "publishConfig": {+ "access": "public"+ },+ "devDependencies": {+ "ink-testing-library": "^4.0.0"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.30.0",+ "cron-parser": "^5.10.1",+ "cronstrue": "^3.27.0",+ "ink": "^7.1.1",+ "react": "^19.3.0",+ "turndown": "^7.2.4"+ }+}diff --git a/packages/three-ws-cli/LICENSE b/packages/three-ws-cli/LICENSEnew file mode 100644index 000000000..b5ae2a4e1--- /dev/null+++ b/packages/three-ws-cli/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2026 nirholas++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/three-ws-cli/package.json b/packages/three-ws-cli/package.jsonnew file mode 100644index 000000000..7a0d6bc8f--- /dev/null+++ b/packages/three-ws-cli/package.json@@ -0,0 +1,60 @@+{+ "name": "three-ws",+ "version": "0.1.0",+ "description": "One command to connect any MCP client to three.ws: sign in with OAuth or an API key, write the three.ws MCP servers into Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI or Hermes, and verify each with a live tools/list.",+ "keywords": [+ "three.ws",+ "mcp",+ "model-context-protocol",+ "cli",+ "oauth",+ "claude",+ "cursor",+ "vscode",+ "codex",+ "gemini",+ "solana",+ "agents"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws/docs/cli",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/three-ws-cli"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "type": "module",+ "bin": {+ "three-ws": "./src/cli.js"+ },+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js",+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "vitest run --root ../.. packages/three-ws-cli/tests",+ "publish:both": "node scripts/publish.mjs"+ },+ "dependencies": {+ "@clack/prompts": "^1.8.0",+ "jsonc-parser": "^3.3.0",+ "smol-toml": "^1.3.0",+ "yaml": "^2.8.0"+ },+ "engines": {+ "node": ">=20.12"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/packages/three-ws-cli/src/auth.js b/packages/three-ws-cli/src/auth.jsnew file mode 100644index 000000000..8a3e67b75--- /dev/null+++ b/packages/three-ws-cli/src/auth.js@@ -0,0 +1,121 @@+// Signing in, and asking the platform who we are.+//+// Three ways in, one stored shape (see store.js):+// oauth browser + loopback redirect + PKCE; refreshable, 1h access tokens+// device browser on any machine approves a code; yields an API key+// key paste an sk_live_ key from /dashboard/api+// All three are verified with GET /api/cli/whoami before anything is stored,+// so a typo'd key or a half-finished flow never lands in the store.++import os from 'node:os';+import { requestJson, ApiError } from './http.js';+import { authorizeInBrowser, bearerFor, revokeOAuth } from './oauth.js';+import { deviceLogin } from './device.js';+import { readStore, writeStore, updateStore } from './store.js';+import { systemEnv } from './paths.js';++const BASE_SCOPES = ['profile', 'avatars:read', 'avatars:write', 'memory:read', 'memory:write', 'agents:read', 'wallet:read'];+const FINANCIAL_SCOPES = ['wallet:write', 'services:write'];++/** Scopes to request. Money-moving scopes only when the person opted in. */+export function scopesFor({ financial = false, oauth = false } = {}) {+ return [...(oauth ? ['offline_access'] : []), ...BASE_SCOPES, ...(financial ? FINANCIAL_SCOPES : [])].join(' ');+}++export async function whoami(origin, bearer) {+ return requestJson(`${origin}/api/cli/whoami`, { headers: { authorization: `Bearer ${bearer}` } });+}++export function looksLikeKey(value) {+ return /^sk_(live|test)_[A-Za-z0-9_-]{16,}$/.test(String(value || '').trim());+}++async function persist({ origin, auth, env }) {+ const bearer = auth.type === 'apikey' ? auth.key : auth.access_token;+ const me = await whoami(origin, bearer);+ const store = readStore(env);+ // Switching accounts: the old account's stdio key must not be written into+ // the new account's clients.+ if (store.account?.user_id && store.account.user_id !== me.user.id) store.stdio_key = null;+ store.origin = origin;+ store.auth = auth;+ store.account = { user_id: me.user.id, email: me.user.email || null };+ writeStore(store, env);+ return me;+}++export async function loginOAuth({ origin, financial, env = systemEnv(), onUrl }) {+ const auth = await authorizeInBrowser({ origin, scope: scopesFor({ financial, oauth: true }), env, onUrl });+ return persist({ origin, auth, env });+}++export async function loginDevice({ origin, financial, env = systemEnv(), onCode }) {+ const { auth } = await deviceLogin({ origin, scope: scopesFor({ financial }), env, onCode });+ return persist({ origin, auth, env });+}++export async function loginKey({ origin, key, env = systemEnv() }) {+ const trimmed = String(key || '').trim();+ if (!looksLikeKey(trimmed)) throw new ApiError('that does not look like a three.ws API key (they start with sk_live_). Create one at https://three.ws/dashboard/api.');+ let me;+ try {+ me = await whoami(origin, trimmed);+ } catch (err) {+ if (err.status === 401) throw new ApiError('three.ws does not recognize that key; it may be revoked or expired. Create a new one at https://three.ws/dashboard/api.', { status: 401 });+ throw err;+ }+ const store = readStore(env);+ if (store.account?.user_id && store.account.user_id !== me.user.id) store.stdio_key = null;+ store.origin = origin;+ store.auth = { type: 'apikey', key: trimmed, prefix: me.credential?.api_key?.prefix || trimmed.slice(0, 12), key_id: null, scope: me.credential?.scope || '' };+ store.account = { user_id: me.user.id, email: me.user.email || null };+ writeStore(store, env);+ return me;+}++/** The current account, refreshing an OAuth token when needed. null when signed out. */+export async function currentIdentity({ origin, env = systemEnv() }) {+ const bearer = await bearerFor(env, { origin });+ if (!bearer) return null;+ return whoami(origin, bearer);+}++/**+ * The API key written into stdio package env blocks. With an API key login it+ * is that key. With OAuth, a dedicated key is minted once through the+ * authenticated /api/api-keys route and reused, so a stdio package never+ * holds an access token that expires in an hour.+ */+export async function ensureStdioKey({ origin, env = systemEnv() }) {+ const store = readStore(env);+ if (store.auth?.type === 'apikey') return store.auth.key;+ if (store.stdio_key?.key) return store.stdio_key.key;+ const bearer = await bearerFor(env, { origin });+ if (!bearer) throw new ApiError('sign in first: `npx three-ws login`');+ const scope = (store.auth?.scope || '').split(/\s+/).filter((s) => s && s !== 'offline_access').join(' ');+ const res = await requestJson(`${origin}/api/api-keys`, {+ method: 'POST',+ headers: { authorization: `Bearer ${bearer}` },+ json: { name: `three-ws CLI stdio on ${os.hostname()}`.slice(0, 80), scope: scope || 'profile avatars:read' },+ });+ const minted = res.data;+ updateStore((s) => {+ s.stdio_key = { key: minted.token, prefix: minted.prefix, key_id: minted.id, scope: minted.scope };+ return s;+ }, env);+ return minted.token;+}++export async function logout({ origin, env = systemEnv() }) {+ const store = readStore(env);+ let revoked = false;+ if (store.auth?.type === 'oauth') {+ try { revoked = await revokeOAuth(store.auth, origin); } catch { revoked = false; }+ }+ const had = Boolean(store.auth || store.stdio_key);+ store.auth = null;+ store.stdio_key = null;+ store.account = null;+ writeStore(store, env);+ return { had, revoked };+}diff --git a/packages/three-ws-cli/src/browser.js b/packages/three-ws-cli/src/browser.jsnew file mode 100644index 000000000..290df65f9--- /dev/null+++ b/packages/three-ws-cli/src/browser.js@@ -0,0 +1,29 @@+// Open a URL in the user's default browser with the OS's own launcher. No+// dependency: `open` on macOS, `xdg-open` on Linux, `start` via cmd on Windows.+// Returns false (never throws) when no launcher exists, e.g. over SSH, so the+// caller prints the URL instead.++import { spawn } from 'node:child_process';++export function openBrowser(url, { platform = process.platform, env = process.env } = {}) {+ if (env.THREE_WS_NO_BROWSER === '1') return Promise.resolve(false);+ // A remote shell has no display to open anything on.+ if (platform === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY && !env.BROWSER) return Promise.resolve(false);+ const [cmd, args] =+ platform === 'darwin' ? ['open', [url]]+ : platform === 'win32' ? ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]]+ : [env.BROWSER || 'xdg-open', [url]];+ return new Promise((resolve) => {+ let child;+ try {+ child = spawn(cmd, args, { stdio: 'ignore', detached: true });+ } catch {+ return resolve(false);+ }+ child.once('error', () => resolve(false));+ child.once('spawn', () => {+ child.unref();+ resolve(true);+ });+ });+}diff --git a/packages/three-ws-cli/src/clients/formats.js b/packages/three-ws-cli/src/clients/formats.jsnew file mode 100644index 000000000..4ed379352--- /dev/null+++ b/packages/three-ws-cli/src/clients/formats.js@@ -0,0 +1,166 @@+// Read and write one named server entry in a client config file, preserving+// everything else in the file: other servers, unrelated settings, comments and+// formatting. Three on-disk formats cover every supported client.+//+// json JSON or JSONC (VS Code allows comments). Edited with jsonc-parser's+// modify/applyEdits, the same engine VS Code uses on its own settings,+// so a hand-formatted file keeps its layout and its comments.+// toml Codex. The server's [mcp_servers.<name>] table family is cut out of+// the text and a fresh one appended, so comments elsewhere survive; the+// result is re-parsed before it is written.+// yaml Hermes. yaml's Document API keeps comments and key order.+//+// Before any change the current bytes are copied to `<file>.three-ws.bak`.++import fs from 'node:fs';+import path from 'node:path';+import { parse as parseJsonc, modify, applyEdits, printParseErrorCode } from 'jsonc-parser';+import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';+import YAML from 'yaml';++function readText(file) {+ try {+ return fs.readFileSync(file, 'utf8');+ } catch (err) {+ if (err.code === 'ENOENT') return null;+ throw err;+ }+}++function writeText(file, text, previous) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ if (previous != null) fs.writeFileSync(`${file}.three-ws.bak`, previous, { mode: 0o600 });+ let mode = 0o600;+ try { mode = fs.statSync(file).mode & 0o777; } catch { /* new file: owner-only, it may hold a key */ }+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, text, { mode });+ fs.renameSync(tmp, file);+}++// ── json / jsonc ─────────────────────────────────────────────────────────────++function parseJsonText(text, file) {+ if (text == null || !text.trim()) return {};+ const errors = [];+ const data = parseJsonc(text, errors, { allowTrailingComma: true, disallowComments: false });+ if (errors.length) {+ const first = errors[0];+ throw new Error(`${file} is not valid JSON (${printParseErrorCode(first.error)} at offset ${first.offset}); fix it by hand, then run setup again`);+ }+ return data && typeof data === 'object' ? data : {};+}++function formattingFor(text) {+ const indented = /\n([ \t]+)\S/.exec(text || '');+ if (indented && indented[1].startsWith('\t')) return { insertSpaces: false, tabSize: 1, eol: '\n' };+ const size = indented ? indented[1].length : 2;+ return { insertSpaces: true, tabSize: Math.min(Math.max(size, 2), 8), eol: '\n' };+}++const json = {+ read(file, rootKey) {+ const data = parseJsonText(readText(file), file);+ const root = data?.[rootKey];+ return root && typeof root === 'object' ? root : {};+ },+ set(file, rootKey, name, value) {+ const before = readText(file);+ parseJsonText(before, file);+ const text = before && before.trim() ? before : '{}\n';+ const edits = modify(text, [rootKey, name], value, { formattingOptions: formattingFor(text) });+ let next = applyEdits(text, edits);+ if (!next.endsWith('\n')) next += '\n';+ parseJsonText(next, file);+ writeText(file, next, before);+ },+ remove(file, rootKey, name) {+ const before = readText(file);+ if (before == null) return false;+ const data = parseJsonText(before, file);+ if (!data?.[rootKey] || !(name in data[rootKey])) return false;+ const next = applyEdits(before, modify(before, [rootKey, name], undefined, { formattingOptions: formattingFor(before) }));+ writeText(file, next, before);+ return true;+ },+};++// ── toml (Codex) ─────────────────────────────────────────────────────────────++function escapeRe(s) {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++// Lines of `text` with every table belonging to [<root>.<name>] removed.+export function stripTomlTable(text, root, name) {+ const namePattern = `(?:${escapeRe(name)}|"${escapeRe(name)}"|'${escapeRe(name)}')`;+ const own = new RegExp(`^\\s*\\[\\s*${escapeRe(root)}\\s*\\.\\s*${namePattern}\\s*(?:\\.[^\\]]*)?\\]\\s*(?:#.*)?$`);+ const anyHeader = /^\s*\[/;+ const out = [];+ let skipping = false;+ for (const line of String(text).split('\n')) {+ if (own.test(line)) { skipping = true; continue; }+ if (skipping && anyHeader.test(line)) skipping = false;+ if (!skipping) out.push(line);+ }+ return out.join('\n').replace(/\n{3,}$/g, '\n\n');+}++const toml = {+ read(file, rootKey) {+ const text = readText(file);+ if (!text || !text.trim()) return {};+ const data = parseToml(text);+ return data?.[rootKey] && typeof data[rootKey] === 'object' ? data[rootKey] : {};+ },+ set(file, rootKey, name, value) {+ const before = readText(file);+ if (before && before.trim()) parseToml(before);+ const kept = stripTomlTable(before || '', rootKey, name).replace(/\s+$/, '');+ const block = stringifyToml({ [rootKey]: { [name]: value } });+ const next = `${kept ? `${kept}\n\n` : ''}${block.trim()}\n`;+ parseToml(next);+ writeText(file, next, before);+ },+ remove(file, rootKey, name) {+ const before = readText(file);+ if (!before) return false;+ const data = parseToml(before);+ if (!data?.[rootKey]?.[name]) return false;+ const next = `${stripTomlTable(before, rootKey, name).replace(/\s+$/, '')}\n`;+ parseToml(next);+ writeText(file, next, before);+ return true;+ },+};++// ── yaml (Hermes) ────────────────────────────────────────────────────────────++const yaml = {+ read(file, rootKey) {+ const text = readText(file);+ if (!text || !text.trim()) return {};+ const doc = YAML.parseDocument(text);+ if (doc.errors.length) throw new Error(`${file} is not valid YAML: ${doc.errors[0].message}`);+ const root = doc.toJS()?.[rootKey];+ return root && typeof root === 'object' ? root : {};+ },+ set(file, rootKey, name, value) {+ const before = readText(file);+ const doc = YAML.parseDocument(before || '');+ if (doc.errors.length) throw new Error(`${file} is not valid YAML: ${doc.errors[0].message}`);+ if (!doc.contents) doc.contents = doc.createNode({});+ doc.setIn([rootKey, name], doc.createNode(value));+ writeText(file, doc.toString(), before);+ },+ remove(file, rootKey, name) {+ const before = readText(file);+ if (!before) return false;+ const doc = YAML.parseDocument(before);+ if (!doc.hasIn([rootKey, name])) return false;+ doc.deleteIn([rootKey, name]);+ writeText(file, doc.toString(), before);+ return true;+ },+};++export const FORMATS = { json, toml, yaml };diff --git a/packages/three-ws-cli/src/clients/index.js b/packages/three-ws-cli/src/clients/index.jsnew file mode 100644index 000000000..2e45de57b--- /dev/null+++ b/packages/three-ws-cli/src/clients/index.js@@ -0,0 +1,147 @@+// Every MCP client the CLI knows how to configure: where its config lives on+// each OS, how to tell it is installed, and the exact entry shape it reads.+//+// An entry is built from one of two transports:+// http { url, headers } the client talks to the hosted server directly+// stdio { command, args, env } the client launches a local process+// A client that has no remote-server field in its config file (Claude Desktop)+// or whose remote support varies by version (Codex) only gets stdio, and the+// stdio process is the three-ws proxy, which forwards to the hosted server.++import fs from 'node:fs';+import path from 'node:path';+import { appDataDir, systemEnv } from '../paths.js';+import { FORMATS } from './formats.js';++const exists = (p) => {+ try { fs.accessSync(p); return true; } catch { return false; }+};++function stdioJson({ command, args, env }) {+ return { command, args, ...(env && Object.keys(env).length ? { env } : {}) };+}++export const CLIENTS = [+ {+ id: 'claude-code',+ label: 'Claude Code',+ format: 'json',+ rootKey: 'mcpServers',+ configPath: (env, { project } = {}) => (project ? path.join(env.cwd, '.mcp.json') : path.join(env.home, '.claude.json')),+ detect: (env) => exists(path.join(env.home, '.claude.json')) || exists(path.join(env.home, '.claude')),+ http: ({ url, headers }) => ({ type: 'http', url, ...(Object.keys(headers).length ? { headers } : {}) }),+ stdio: (s) => ({ type: 'stdio', ...stdioJson(s) }),+ scopes: ['user', 'project'],+ },+ {+ id: 'claude-desktop',+ label: 'Claude Desktop',+ format: 'json',+ rootKey: 'mcpServers',+ configPath: (env) => path.join(appDataDir(env), 'Claude', 'claude_desktop_config.json'),+ detect: (env) => exists(path.join(appDataDir(env), 'Claude')),+ http: null,+ stdio: stdioJson,+ },+ {+ id: 'cursor',+ label: 'Cursor',+ format: 'json',+ rootKey: 'mcpServers',+ configPath: (env, { project } = {}) => (project ? path.join(env.cwd, '.cursor', 'mcp.json') : path.join(env.home, '.cursor', 'mcp.json')),+ detect: (env) => exists(path.join(env.home, '.cursor')),+ http: ({ url, headers }) => ({ url, ...(Object.keys(headers).length ? { headers } : {}) }),+ stdio: stdioJson,+ scopes: ['user', 'project'],+ },+ {+ id: 'windsurf',+ label: 'Windsurf',+ format: 'json',+ rootKey: 'mcpServers',+ configPath: (env) => path.join(env.home, '.codeium', 'windsurf', 'mcp_config.json'),+ detect: (env) => exists(path.join(env.home, '.codeium', 'windsurf')),+ http: ({ url, headers }) => ({ serverUrl: url, ...(Object.keys(headers).length ? { headers } : {}) }),+ stdio: stdioJson,+ },+ {+ id: 'vscode',+ label: 'VS Code',+ format: 'json',+ rootKey: 'servers',+ configPath: (env, { project } = {}) => (project ? path.join(env.cwd, '.vscode', 'mcp.json') : path.join(appDataDir(env), 'Code', 'User', 'mcp.json')),+ detect: (env) => exists(path.join(appDataDir(env), 'Code', 'User')),+ http: ({ url, headers }) => ({ type: 'http', url, ...(Object.keys(headers).length ? { headers } : {}) }),+ stdio: (s) => ({ type: 'stdio', ...stdioJson(s) }),+ scopes: ['user', 'project'],+ },+ {+ id: 'codex',+ label: 'Codex',+ format: 'toml',+ rootKey: 'mcp_servers',+ configPath: (env) => path.join(env.vars.CODEX_HOME || path.join(env.home, '.codex'), 'config.toml'),+ detect: (env) => exists(env.vars.CODEX_HOME || path.join(env.home, '.codex')),+ http: null,+ stdio: stdioJson,+ },+ {+ id: 'gemini',+ label: 'Gemini CLI',+ format: 'json',+ rootKey: 'mcpServers',+ configPath: (env, { project } = {}) => (project ? path.join(env.cwd, '.gemini', 'settings.json') : path.join(env.home, '.gemini', 'settings.json')),+ detect: (env) => exists(path.join(env.home, '.gemini')),+ http: ({ url, headers, includeTools }) => ({+ httpUrl: url,+ ...(Object.keys(headers).length ? { headers } : {}),+ ...(includeTools ? { includeTools } : {}),+ }),+ stdio: stdioJson,+ // Gemini CLI enforces an allow list per server on its own side.+ allowList: true,+ scopes: ['user', 'project'],+ },+ {+ id: 'hermes',+ label: 'Hermes',+ format: 'yaml',+ rootKey: 'mcp_servers',+ configPath: (env) => path.join(env.vars.HERMES_HOME || path.join(env.home, '.hermes'), 'config.yaml'),+ detect: (env) => exists(env.vars.HERMES_HOME || path.join(env.home, '.hermes')),+ http: ({ url, headers }) => ({ url, ...(Object.keys(headers).length ? { headers } : {}) }),+ stdio: stdioJson,+ },+];++// Not a real client: the shape `setup` prints for any client it does not know.+export const PRINT_CLIENT = {+ id: 'print',+ label: 'Any MCP client',+ http: ({ url, headers }) => ({ type: 'http', url, ...(Object.keys(headers).length ? { headers } : {}) }),+ stdio: stdioJson,+};++export function getClient(id) {+ const c = CLIENTS.find((x) => x.id === id);+ if (!c) throw new Error(`unknown client "${id}". Known: ${CLIENTS.map((x) => x.id).join(', ')}`);+ return c;+}++export function detectClients(env = systemEnv()) {+ return CLIENTS.filter((c) => c.detect(env));+}++export function readServers(client, env = systemEnv(), opts = {}) {+ return FORMATS[client.format].read(client.configPath(env, opts), client.rootKey);+}++export function writeServer(client, name, entry, env = systemEnv(), opts = {}) {+ const file = client.configPath(env, opts);+ FORMATS[client.format].set(file, client.rootKey, name, entry);+ return file;+}++export function removeServer(client, name, env = systemEnv(), opts = {}) {+ return FORMATS[client.format].remove(client.configPath(env, opts), client.rootKey, name);+}diff --git a/packages/three-ws-cli/src/commands/account.js b/packages/three-ws-cli/src/commands/account.jsnew file mode 100644index 000000000..c55bfa554--- /dev/null+++ b/packages/three-ws-cli/src/commands/account.js@@ -0,0 +1,161 @@+// login, logout, whoami, status.++import { signIn, authModeFromFlags } from './common.js';+import { c, line, rows, sym, printJson, tildify, relativeExpiry, shortAddress } from '../ui.js';+import { readStore, mask } from '../store.js';+import { currentIdentity, logout as doLogout } from '../auth.js';+import { credentialsPath } from '../paths.js';+import { CLIENTS, readServers } from '../clients/index.js';+import { isThreeWsEntry } from '../servers.js';++function credentialSummary(store) {+ const a = store.auth;+ if (!a) return null;+ if (a.type === 'oauth') {+ return {+ type: 'oauth',+ label: `OAuth, access token ${a.expires_at ? `expires ${relativeExpiry(a.expires_at)}` : 'expiry unknown'}${a.refresh_token ? ', refreshes automatically' : ''}`,+ expires_at: a.expires_at ? new Date(a.expires_at).toISOString() : null,+ scope: a.scope,+ };+ }+ return { type: 'apikey', label: `API key ${a.prefix ? `${a.prefix}` : ''}${mask(a.key)}`, expires_at: null, scope: a.scope };+}++export async function login(ctx) {+ const me = await signIn(ctx, { mode: authModeFromFlags(ctx.flags), financial: Boolean(ctx.flags.financial) });+ const store = readStore(ctx.env);+ if (ctx.flags.json) {+ printJson({ account: me.user, credential: credentialSummary(store), store: credentialsPath(ctx.env) });+ return 0;+ }+ line(`${c.green(sym.ok)} Signed in as ${c.bold(me.user.email || me.user.id)} ${c.dim(`(${credentialSummary(store).label})`)}`);+ line(c.dim(` Stored in ${tildify(credentialsPath(ctx.env))} (owner-only). Run \`three-ws setup\` to wire your clients.`));+ return 0;+}++export async function logout(ctx) {+ const { had, revoked } = await doLogout({ origin: ctx.origin, env: ctx.env });+ if (ctx.flags.json) {+ printJson({ signed_out: had, revoked });+ return 0;+ }+ if (!had) line('Not signed in; nothing to remove.');+ else line(`${c.green(sym.ok)} Signed out. ${revoked ? 'The refresh token was revoked on the server.' : 'API keys stay valid until you revoke them at /dashboard/api.'}`);+ line(c.dim(' Client configs are untouched; `three-ws mcp remove <server>` removes entries.'));+ return 0;+}++export async function whoami(ctx) {+ const me = await currentIdentity({ origin: ctx.origin, env: ctx.env });+ if (!me) {+ if (ctx.flags.json) printJson({ signed_in: false });+ else line('Not signed in. Run `npx three-ws login`.');+ return 1;+ }+ if (ctx.flags.json) printJson({ signed_in: true, ...me });+ else line(me.user.email || me.user.id);+ return 0;+}++/** Every three.ws entry in every client config on this machine. */+export function scanClients(env, origin) {+ return CLIENTS.map((client) => {+ const scopes = client.scopes?.includes('project') ? [false, true] : [false];+ const found = [];+ let error = null;+ const files = [];+ for (const project of scopes) {+ const file = client.configPath(env, { project });+ try {+ const servers = readServers(client, env, { project });+ const names = Object.entries(servers).filter(([name, entry]) => isThreeWsEntry(name, entry, origin)).map(([name, entry]) => ({ name, entry, project }));+ if (names.length) files.push(file);+ found.push(...names);+ } catch (err) {+ error = err.message;+ }+ }+ return { client, detected: client.detect(env), entries: found, files, error };+ });+}++function describeEntry(entry) {+ if (entry.url || entry.httpUrl || entry.serverUrl) return 'http';+ const args = Array.isArray(entry.args) ? entry.args : [];+ if (args.includes('proxy')) return 'proxy';+ return 'stdio';+}++export async function status(ctx) {+ const { env, origin } = ctx;+ const store = readStore(env);+ let me = null;+ let authError = null;+ try {+ me = await currentIdentity({ origin, env });+ } catch (err) {+ authError = err.message;+ }+ const cred = credentialSummary(store);+ const clients = scanClients(env, origin);++ if (ctx.flags.json) {+ printJson({+ origin,+ store: credentialsPath(env),+ signed_in: Boolean(me),+ auth_error: authError,+ account: me?.user || null,+ plan: me?.plan || null,+ credential: cred,+ wallet: me?.wallet || null,+ clients: clients.map((x) => ({ id: x.client.id, detected: x.detected, files: x.files, servers: x.entries.map((e) => ({ name: e.name, transport: describeEntry(e.entry), project: e.project })), error: x.error })),+ });+ return me ? 0 : 1;+ }++ line(`${c.bold('three.ws')} ${c.dim(origin)}`);+ const pairs = [];+ if (me) {+ pairs.push(['Account', `${me.user.email || me.user.id}`]);+ if (me.plan) {+ const quota = me.plan.mcp_calls_per_day != null ? `, ${me.plan.mcp_calls_24h}/${me.plan.mcp_calls_per_day} MCP calls in the last 24h` : '';+ pairs.push(['Plan', `${me.plan.plan}${quota}`]);+ }+ } else {+ pairs.push(['Account', authError ? c.red(authError) : c.yellow('not signed in; run `npx three-ws login`')]);+ }+ if (cred) pairs.push(['Credential', cred.label]);+ if (me?.wallet) {+ const w = me.wallet;+ if (w.provisioned) {+ const bal = `${w.balances?.sol ?? '?'} SOL, ${w.balances?.usdc ?? '?'} USDC`;+ pairs.push(['Wallet', `${shortAddress(w.address)}${w.agent_name ? ` (${w.agent_name})` : ''} on Solana: ${bal}`]);+ pairs.push(['Spending', `${w.spend_enabled ? 'enabled' : 'disabled'}, caps $${w.caps.max_per_call_usdc}/call, $${w.caps.max_per_day_usdc}/day`]);+ } else {+ pairs.push(['Wallet', `none yet; create an agent at ${origin}/create`]);+ }+ } else if (me?.missing?.includes('wallet:read')) {+ pairs.push(['Wallet', c.dim('this credential lacks wallet:read; `three-ws login` again to grant it')]);+ }+ rows(pairs, ' ');+ line('');+ line(c.bold('Clients'));+ for (const x of clients) {+ if (!x.detected && !x.entries.length) continue;+ if (x.error) {+ line(` ${c.red(sym.fail)} ${x.client.label.padEnd(15)} ${x.error}`);+ continue;+ }+ if (!x.entries.length) {+ line(` ${c.dim(sym.dot)} ${x.client.label.padEnd(15)} ${c.dim('installed, not configured; `three-ws setup` adds it')}`);+ continue;+ }+ const names = x.entries.map((e) => `${e.name}${describeEntry(e.entry) === 'proxy' ? c.dim(' (proxy)') : ''}${e.project ? c.dim(' [project]') : ''}`).join(', ');+ line(` ${c.green(sym.ok)} ${x.client.label.padEnd(15)} ${names}`);+ line(` ${c.dim(x.files.map(tildify).join(', '))}`);+ }+ if (!clients.some((x) => x.detected || x.entries.length)) line(c.dim(' No MCP clients found. `three-ws setup` can still print a config for any client.'));+ return me ? 0 : 1;+}diff --git a/packages/three-ws-cli/src/commands/common.js b/packages/three-ws-cli/src/commands/common.jsnew file mode 100644index 000000000..bf3bf9837--- /dev/null+++ b/packages/three-ws-cli/src/commands/common.js@@ -0,0 +1,102 @@+// Pieces every command shares: cancellation, the sign-in step, and the rule+// for when the CLI may prompt at all.++import * as p from '@clack/prompts';+import { c, line, sym } from '../ui.js';+import { loginOAuth, loginDevice, loginKey, looksLikeKey } from '../auth.js';++export class CancelledError extends Error {+ constructor() {+ super('cancelled');+ this.name = 'CancelledError';+ }+}++/** Unwrap a clack answer, turning Ctrl-C into a CancelledError. */+export function answer(value) {+ if (p.isCancel(value)) throw new CancelledError();+ return value;+}++/** Prompts are allowed only on a TTY, and never with --json or --yes. */+export function canPrompt(ctx) {+ return Boolean(process.stdin.isTTY && process.stdout.isTTY && !ctx.flags.json && !ctx.flags.yes);+}++export function authModeFromFlags(flags) {+ if (flags.key !== undefined) return 'key';+ if (flags.device) return 'device';+ if (flags.oauth) return 'oauth';+ return null;+}++function say(ctx, text) {+ if (!ctx.flags.json) line(text);+}++/**+ * Sign in by the chosen mode. `mode` null means ask (or default to OAuth when+ * prompting is not allowed). Returns the whoami payload.+ */+export async function signIn(ctx, { mode = null, financial = false } = {}) {+ const { origin, env } = ctx;+ let chosen = mode;+ if (!chosen && canPrompt(ctx)) {+ chosen = answer(await p.select({+ message: 'How should this machine sign in to three.ws?',+ options: [+ { value: 'oauth', label: 'Browser sign-in (OAuth)', hint: 'recommended; tokens refresh automatically' },+ { value: 'device', label: 'API key, approved in a browser', hint: 'works over SSH; approve on any device' },+ { value: 'key', label: 'Paste an API key', hint: 'from three.ws/dashboard/api' },+ ],+ initialValue: 'oauth',+ }));+ }+ chosen = chosen || 'oauth';++ if (chosen === 'key') {+ let key = typeof ctx.flags.key === 'string' && ctx.flags.key ? ctx.flags.key : env.vars.THREE_WS_API_KEY || '';+ if (!key && canPrompt(ctx)) {+ key = answer(await p.password({+ message: `Paste your API key ${c.dim('(create one at ' + origin + '/dashboard/api)')}`,+ validate: (v) => (looksLikeKey(v) ? undefined : 'Keys start with sk_live_ and are about 45 characters.'),+ }));+ }+ if (!key) throw new Error('pass the key with --key <sk_live_...> or THREE_WS_API_KEY');+ return loginKey({ origin, key, env });+ }++ if (chosen === 'device') {+ const spin = !ctx.flags.json && canPrompt(ctx) ? p.spinner() : null;+ const me = await loginDevice({+ origin,+ financial,+ env,+ onCode: (link, opened) => {+ say(ctx, '');+ say(ctx, ` ${c.bold('Your code:')} ${c.cyan(c.bold(link.user_code))}`);+ say(ctx, ` ${opened ? 'Opened' : 'Open'} ${c.cyan(link.verification_uri_complete)}`);+ say(ctx, ` ${c.dim('and approve it there. Any device works; the code expires in 10 minutes.')}`);+ say(ctx, '');+ spin?.start('Waiting for approval in the browser');+ },+ }).finally(() => spin?.stop('Browser step finished'));+ return me;+ }++ const spin = !ctx.flags.json && canPrompt(ctx) ? p.spinner() : null;+ const me = await loginOAuth({+ origin,+ financial,+ env,+ onUrl: (url, opened) => {+ if (!opened) {+ say(ctx, ` ${sym.arrow} Open this URL to sign in:`);+ say(ctx, ` ${c.cyan(url)}`);+ say(ctx, ` ${c.dim('No browser here? Press Ctrl-C and run with --device instead.')}`);+ }+ spin?.start(opened ? 'Finish signing in in the browser window that just opened' : 'Waiting for the browser sign-in');+ },+ }).finally(() => spin?.stop('Browser step finished'));+ return me;+}diff --git a/packages/three-ws-cli/src/commands/setup.js b/packages/three-ws-cli/src/commands/setup.jsnew file mode 100644index 000000000..d88087263--- /dev/null+++ b/packages/three-ws-cli/src/commands/setup.js@@ -0,0 +1,185 @@+// `three-ws setup`: sign in, pick servers and clients, write every config,+// then prove it with a real tools/list per server.++import * as p from '@clack/prompts';+import { answer, canPrompt, signIn, authModeFromFlags } from './common.js';+import { c, line, sym, printJson, tildify } from '../ui.js';+import { readStore } from '../store.js';+import { currentIdentity, ensureStdioKey } from '../auth.js';+import { loadDirectory, loadCatalog, hostedServers, stdioPackages } from '../servers.js';+import { CLIENTS, PRINT_CLIENT, detectClients, getClient } from '../clients/index.js';+import { verifyServers, ensureSelections, applyToClients } from '../configure.js';+import { usesProxy, buildEntry } from '../entries.js';+import { VERSION } from '../http.js';++function list(value) {+ if (!value) return null;+ return String(value).split(',').map((s) => s.trim()).filter(Boolean);+}++function pickServers(all, requested) {+ if (!requested) return null;+ const wanted = new Set(requested);+ const picked = all.filter((s) => wanted.has(s.slug) || wanted.has(s.path) || wanted.has(s.name));+ const unknown = requested.filter((r) => !all.some((s) => s.slug === r || s.path === r || s.name === r));+ if (unknown.length) throw new Error(`unknown server(s): ${unknown.join(', ')}. Run \`three-ws mcp list --available\` to see them.`);+ return picked;+}++export async function setup(ctx) {+ const { flags, origin, env } = ctx;+ const interactive = canPrompt(ctx);+ if (interactive) p.intro(`${c.bold('three.ws')} setup ${c.dim(`v${VERSION} · ${origin}`)}`);++ // 1. Account. Reuse a working credential unless a mode was asked for.+ const requestedMode = authModeFromFlags(flags);+ let me = null;+ if (!requestedMode) {+ try { me = await currentIdentity({ origin, env }); } catch { me = null; }+ }+ if (me && interactive) {+ const keep = answer(await p.confirm({ message: `Signed in as ${c.bold(me.user.email || me.user.id)}. Use this account?`, initialValue: true }));+ if (!keep) me = null;+ }+ let financial = Boolean(flags.financial);+ if (!me) {+ if (interactive && !flags.financial) {+ financial = answer(await p.confirm({+ message: 'Allow tools that move funds (spend USDC from your agent wallet, within your caps)?',+ initialValue: false,+ }));+ }+ me = await signIn(ctx, { mode: requestedMode, financial });+ if (interactive) p.log.success(`Signed in as ${c.bold(me.user.email || me.user.id)}`);+ }+ const store = readStore(env);+ const mode = store.auth?.type === 'apikey' ? 'apikey' : 'oauth';++ // 2. Servers, live from the platform's own directory.+ const directory = await loadDirectory(origin);+ const allServers = hostedServers(directory, origin);+ let servers = pickServers(allServers, list(flags.servers));+ if (!servers) {+ if (interactive) {+ const chosen = answer(await p.multiselect({+ message: 'Which three.ws servers should your clients get?',+ options: allServers.map((s) => ({ value: s.slug, label: `${s.name} ${c.dim(s.path)}`, hint: s.auth === 'none' ? 'no account needed' : s.description.slice(0, 70) })),+ initialValues: allServers.filter((s) => s.defaultSelected).map((s) => s.slug),+ required: true,+ }));+ servers = allServers.filter((s) => chosen.includes(s.slug));+ } else {+ servers = allServers.filter((s) => s.defaultSelected);+ }+ }++ // 3. Clients.+ const detected = detectClients(env);+ let clients;+ let printOnly = false;+ const requestedClients = list(flags.clients);+ if (requestedClients) {+ printOnly = requestedClients.includes('print');+ clients = requestedClients.filter((id) => id !== 'print').map(getClient);+ } else if (interactive) {+ const chosen = answer(await p.multiselect({+ message: detected.length ? 'Write the config into which clients?' : 'No MCP clients found on this machine. Write a config for which ones anyway?',+ options: [+ ...CLIENTS.map((cl) => ({ value: cl.id, label: cl.label, hint: detected.includes(cl) ? tildify(cl.configPath(env, { project: flags.project })) : 'not detected' })),+ { value: 'print', label: 'Print the JSON instead', hint: 'for any other MCP client' },+ ],+ initialValues: detected.length ? detected.map((cl) => cl.id) : ['print'],+ required: true,+ }));+ printOnly = chosen.includes('print');+ clients = chosen.filter((id) => id !== 'print').map(getClient);+ } else {+ clients = detected;+ printOnly = !detected.length;+ }++ // 4. Optional stdio packages.+ let packages = [];+ const requestedPackages = list(flags.packages);+ if (requestedPackages || (interactive && clients.length && !flags.servers)) {+ const catalog = await loadCatalog(origin);+ const available = stdioPackages(catalog);+ if (requestedPackages) {+ packages = available.filter((pkg) => requestedPackages.includes(pkg.package) || requestedPackages.includes(pkg.slug));+ } else {+ const want = answer(await p.confirm({ message: `Also add stdio servers from npm? ${c.dim(`(${available.length} @three-ws/*-mcp packages)`)}`, initialValue: false }));+ if (want) {+ const chosen = answer(await p.multiselect({+ message: 'Which packages?',+ options: available.map((pkg) => ({ value: pkg.package, label: pkg.package, hint: `${pkg.tools} tools` })),+ required: false,+ }));+ packages = available.filter((pkg) => chosen.includes(pkg.package));+ }+ }+ }+ const stdioKey = packages.some((pkg) => pkg.auth === 'key') ? await ensureStdioKey({ origin, env }) : null;++ // 5. Verify first, so the entries can carry the live tool selection.+ ensureSelections(servers, { financial: financial || /\bwallet:write\b/.test(store.auth?.scope || ''), env });+ const spin = interactive ? p.spinner() : null;+ spin?.start(`Calling tools/list on ${servers.length} server${servers.length === 1 ? '' : 's'}`);+ const results = await verifyServers({ servers, env, origin });+ spin?.stop('Verified with live tool calls');+ const liveTools = Object.fromEntries(results.filter((r) => r.ok).map((r) => [r.server.slug, r.tools]));++ // 6. Write.+ const apiKey = mode === 'apikey' ? readStore(env).auth.key : null;+ const writes = applyToClients({ clients, servers, packages, mode, apiKey, stdioKey, liveTools, forceProxy: Boolean(flags.proxy), project: Boolean(flags.project), origin, env });+ const selections = readStore(env).tools || {};+ const printed = printOnly+ ? Object.fromEntries(servers.map((s) => [s.slug, buildEntry({ client: PRINT_CLIENT, server: s, mode, apiKey, selection: selections[s.slug], liveTools: liveTools[s.slug], forceProxy: Boolean(flags.proxy) })]))+ : null;++ if (ctx.flags.json) {+ printJson({+ account: { email: me.user.email || null, user_id: me.user.id },+ auth: mode,+ servers: results.map((r) => ({ slug: r.server.slug, url: r.server.url, ok: r.ok, tools: r.ok ? r.total : null, enabled: r.ok ? r.enabled : null, error: r.error || null })),+ clients: writes.map((w) => ({ id: w.client.id, file: w.file, servers: w.servers, error: w.error })),+ ...(printed ? { print: { mcpServers: printed } } : {}),+ });+ return results.every((r) => r.ok) && writes.every((w) => !w.error) ? 0 : 1;+ }++ line('');+ line(c.bold('Servers'));+ for (const r of results) {+ if (r.ok) {+ const hidden = r.hidden ? c.dim(` (${r.hidden} off; \`three-ws tools\` to change)`) : '';+ line(` ${c.green(sym.ok)} ${r.server.slug.padEnd(22)} ${c.bold(String(r.enabled))} tools${hidden}`);+ } else {+ line(` ${c.red(sym.fail)} ${r.server.slug.padEnd(22)} ${r.error}`);+ }+ }+ if (writes.length) {+ line('');+ line(c.bold('Clients'));+ for (const w of writes) {+ if (w.error) line(` ${c.red(sym.fail)} ${w.client.label.padEnd(15)} ${w.error}`);+ else {+ const viaProxy = servers.some((s) => usesProxy({ client: w.client, server: s, mode, forceProxy: flags.proxy })) ? c.dim(' (OAuth via the three-ws proxy)') : '';+ line(` ${c.green(sym.ok)} ${w.client.label.padEnd(15)} ${tildify(w.file)} ${c.dim(`${w.servers.length} servers`)}${viaProxy}`);+ }+ }+ }+ if (printed) {+ line('');+ line(c.bold('Add this to any MCP client:'));+ printJson({ mcpServers: printed });+ }+ line('');+ const failed = results.filter((r) => !r.ok).length + writes.filter((w) => w.error).length;+ if (interactive) {+ if (failed) p.outro(c.yellow(`${failed} step${failed === 1 ? '' : 's'} failed above. Fix it and run \`three-ws setup\` again; finished steps are kept.`));+ else p.outro(`Done. Restart your client${writes.length === 1 ? '' : 's'} to load the tools. ${c.dim('Check anytime: three-ws status')}`);+ } else {+ line(failed ? c.yellow(`${failed} step(s) failed.`) : `Done. Restart your clients to load the tools. Check anytime: three-ws status`);+ }+ return failed ? 1 : 0;+}diff --git a/packages/three-ws-cli/src/commands/skills.js b/packages/three-ws-cli/src/commands/skills.jsnew file mode 100644index 000000000..6957067e9--- /dev/null+++ b/packages/three-ws-cli/src/commands/skills.js@@ -0,0 +1,146 @@+// `three-ws skills`: browse the public community skills registry and import a+// skill onto one of your agents as an editable prompt-only custom skill.+//+// three-ws skills list [--tag <tag>] [--author <name>]+// three-ws skills search <query>+// three-ws skills show <slug>+// three-ws skills import <slug> --agent <agent-id> [--disabled]+// three-ws skills installed --agent <agent-id>+//+// Every subcommand takes --json. Reads are public; import and installed use+// the stored credential (`three-ws login`) or THREE_WS_API_KEY. Server side:+// /api/skills/community and /api/agents/:id/custom-skills (docs/skills.md).++import { requestJson, ApiError } from '../http.js';+import { bearerFor } from '../oauth.js';+import { readStore, resolveOrigin } from '../store.js';+import { systemEnv } from '../paths.js';++export const SKILLS_USAGE = `Usage:+ three-ws skills list [--tag <tag>] [--author <name>] [--json]+ three-ws skills search <query> [--json]+ three-ws skills show <slug> [--json]+ three-ws skills import <slug> --agent <agent-id> [--disabled] [--json]+ three-ws skills installed --agent <agent-id> [--json]++Browse every skill: https://three.ws/skills/community`;++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** Split argv into positionals and --flags (a flag followed by a non-flag takes it as its value). */+export function parseSkillsArgs(argv) {+ const positional = [];+ const flags = {};+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (!a.startsWith('--')) {+ positional.push(a);+ continue;+ }+ const [key, inline] = a.slice(2).split('=', 2);+ if (inline !== undefined) flags[key] = inline;+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[key] = argv[++i];+ else flags[key] = true;+ }+ return { sub: positional[0] || 'list', args: positional.slice(1), flags };+}++async function authHeaders(env) {+ const key = env.vars.THREE_WS_API_KEY;+ const bearer = key || (await bearerFor(env));+ if (!bearer) {+ throw new ApiError('not signed in. Run `npx three-ws login`, or set THREE_WS_API_KEY.', { code: 'login_required' });+ }+ return { authorization: `Bearer ${bearer}` };+}++function pad(s, n) {+ const str = String(s ?? '');+ return str.length >= n ? `${str.slice(0, n - 1)}…` : str.padEnd(n);+}++/** One line per skill, fixed columns. */+export function formatSkillTable(skills) {+ if (!skills.length) return 'No skills match. Try `three-ws skills list` with no filters.';+ const lines = [`${pad('SLUG', 24)} ${pad('TOKENS', 7)} ${pad('TAGS', 30)} DESCRIPTION`];+ for (const s of skills) {+ lines.push(`${pad(s.slug, 24)} ${pad(`~${s.tokens}`, 7)} ${pad(s.tags.join(','), 30)} ${s.description}`);+ }+ return lines.join('\n');+}++/** The installed list with the budget line the chat path enforces. */+export function formatInstalled({ skills, budget }) {+ const head = `Budget: ${budget.used_tokens} / ${budget.cap_tokens} tokens injected (${budget.injected_count} of ${skills.length} skills)`;+ if (!skills.length) return `${head}\nNo custom skills yet. Import one: three-ws skills import <slug> --agent <agent-id>`;+ const rows = skills.map((s) => {+ const state = s.injected ? 'on' : s.skip_reason === 'disabled' ? 'off' : 'over budget';+ const update = s.registry?.update_available ? ' (update available)' : '';+ return `${pad(s.slug, 24)} ${pad(`~${s.tokens}`, 7)} ${pad(state, 12)} ${s.id}${update}`;+ });+ return [head, `${pad('SLUG', 24)} ${pad('TOKENS', 7)} ${pad('STATE', 12)} ID`, ...rows].join('\n');+}++/**+ * Run a `skills` subcommand. Returns { code, output } so the dispatcher decides+ * where it goes; nothing here writes to stdout directly.+ */+export async function runSkills(argv, { env = systemEnv(), origin: originFlag } = {}) {+ const { sub, args, flags } = parseSkillsArgs(argv);+ const origin = resolveOrigin({ flag: originFlag || flags.origin, env, store: readStore(env) });+ const json = Boolean(flags.json);+ const done = (data, text) => ({ code: 0, output: json ? JSON.stringify(data, null, 2) : text });++ if (sub === 'list' || sub === 'search') {+ const q = new URLSearchParams();+ if (sub === 'search') {+ if (!args.length) return { code: 2, output: SKILLS_USAGE };+ q.set('q', args.join(' '));+ }+ if (typeof flags.tag === 'string') q.set('tag', flags.tag);+ if (typeof flags.author === 'string') q.set('author', flags.author);+ const data = await requestJson(`${origin}/api/skills/community?${q}`);+ return done(data, `${formatSkillTable(data.skills)}\n\n${data.count} of ${data.total} skills. Import: three-ws skills import <slug> --agent <agent-id>`);+ }++ if (sub === 'show') {+ if (!args[0]) return { code: 2, output: SKILLS_USAGE };+ const { skill } = await requestJson(`${origin}/api/skills/community/${encodeURIComponent(args[0])}`);+ return done(skill, `${skill.name} (${skill.slug} v${skill.version}) by ${skill.author}\n${skill.description}\nTags: ${skill.tags.join(', ')} ~${skill.tokens} tokens\nSource: ${skill.source_url}\n\n${skill.body}`);+ }++ if (sub === 'import' || sub === 'installed') {+ const agent = flags.agent;+ if (typeof agent !== 'string' || !UUID_RE.test(agent)) {+ return { code: 2, output: `--agent <agent-id> is required (a uuid; list yours with GET ${origin}/api/agents).\n\n${SKILLS_USAGE}` };+ }+ const headers = await authHeaders(env);+ const base = `${origin}/api/agents/${agent}/custom-skills`;+ if (sub === 'installed') {+ const { data } = await requestJson(base, { headers });+ return done(data, formatInstalled(data));+ }+ if (!args[0]) return { code: 2, output: SKILLS_USAGE };+ try {+ const { data } = await requestJson(base, {+ method: 'POST',+ headers,+ json: { source: 'community', slug: args[0], enabled: !flags.disabled },+ });+ const { skill, budget } = data;+ const state = skill.injected+ ? 'active in the agent\'s next reply'+ : skill.skip_reason === 'over_budget'+ ? `saved but NOT injected: it does not fit the ${budget.cap_tokens}-token budget. Disable another skill to make room.`+ : 'saved, disabled';+ return done(data, `Imported ${skill.name} (${skill.slug}) onto ${agent}: ${state}.\nBudget: ${budget.used_tokens} / ${budget.cap_tokens} tokens.\nManage: ${origin}/skills/community?agent=${agent}`);+ } catch (err) {+ if (err instanceof ApiError && err.code === 'already_installed') {+ return { code: 1, output: `${args[0]} is already installed on this agent (skill ${err.body?.skill_id}). Manage it at ${origin}/skills/community?agent=${agent}` };+ }+ throw err;+ }+ }++ return { code: 2, output: `Unknown skills subcommand "${sub}".\n\n${SKILLS_USAGE}` };+}diff --git a/packages/three-ws-cli/src/configure.js b/packages/three-ws-cli/src/configure.jsnew file mode 100644index 000000000..845ed0edd--- /dev/null+++ b/packages/three-ws-cli/src/configure.js@@ -0,0 +1,85 @@+// The work `setup` and `mcp add` share: run a real tools/list against each+// server with the stored credential, then write the entries into each client.++import { listTools } from './mcp-http.js';+import { bearerFor } from './oauth.js';+import { readStore, updateStore } from './store.js';+import { systemEnv } from './paths.js';+import { buildEntry, buildPackageEntry } from './entries.js';+import { writeServer } from './clients/index.js';+import { filterTools, groupByTier, normalizeSelection, defaultSelection } from './policy.js';++/** tools/list per server. Never throws; each result carries its own error. */+export async function verifyServers({ servers, env = systemEnv(), origin }) {+ const store = readStore(env);+ let bearer = null;+ let bearerError = null;+ try {+ bearer = await bearerFor(env, { origin });+ } catch (err) {+ bearerError = err.message;+ }+ return Promise.all(servers.map(async (server) => {+ const selection = normalizeSelection(store.tools?.[server.slug]);+ if (server.auth === 'required' && bearerError) return { server, ok: false, error: bearerError };+ try {+ const { tools } = await listTools(server.url, { bearer: server.auth === 'required' ? bearer : null });+ const enabled = filterTools(tools, selection);+ const byTier = groupByTier(tools);+ const hidden = tools.length - enabled.length;+ return { server, ok: true, tools, total: tools.length, enabled: enabled.length, hidden, financial: byTier.financial.length };+ } catch (err) {+ return { server, ok: false, error: err.message };+ }+ }));+}++/** Give every server a stored selection, keeping any the person already chose. */+export function ensureSelections(servers, { financial = false, env = systemEnv() } = {}) {+ return updateStore((store) => {+ store.tools = store.tools || {};+ for (const s of servers) {+ if (store.tools[s.slug]) continue;+ const sel = defaultSelection();+ if (financial) sel.tiers.push('financial');+ store.tools[s.slug] = sel;+ }+ return store;+ }, env);+}++/**+ * Write each server (and stdio package) into each client. Returns one result+ * per client: { client, file, servers: [slug], error }.+ */+export function applyToClients({ clients, servers, packages = [], mode, apiKey = null, stdioKey = null, liveTools = {}, forceProxy = false, project = false, origin, env = systemEnv() }) {+ const store = readStore(env);+ return clients.map((client) => {+ const written = [];+ let file = null;+ try {+ const opts = { project: project && client.scopes?.includes('project') };+ for (const server of servers) {+ const entry = buildEntry({+ client,+ server,+ mode,+ apiKey,+ selection: store.tools?.[server.slug] || null,+ liveTools: liveTools[server.slug] || null,+ forceProxy,+ });+ file = writeServer(client, server.slug, entry, env, opts);+ written.push(server.slug);+ }+ for (const pkg of packages) {+ const entry = buildPackageEntry({ client, pkg, apiKey: pkg.auth === 'key' ? stdioKey : null, origin });+ file = writeServer(client, pkg.slug, entry, env, opts);+ written.push(pkg.slug);+ }+ return { client, file, servers: written, error: null };+ } catch (err) {+ return { client, file, servers: written, error: err.message };+ }+ });+}diff --git a/packages/three-ws-cli/src/device.js b/packages/three-ws-cli/src/device.jsnew file mode 100644index 000000000..37e49de53--- /dev/null+++ b/packages/three-ws-cli/src/device.js@@ -0,0 +1,54 @@+// The device link (api/cli/[action].js): the CLI shows a short code and a URL,+// the person approves it at /cli/authorize in any browser (another machine is+// fine), and the CLI polls until a freshly minted API key comes back. RFC 8628+// poll semantics: authorization_pending keeps waiting, slow_down backs off by+// five seconds, access_denied and expired_token end the flow.++import os from 'node:os';+import { request, requestJson, ApiError, VERSION } from './http.js';+import { openBrowser } from './browser.js';++export async function startLink({ origin, scope, clientName = `three-ws CLI ${VERSION}` }) {+ return requestJson(`${origin}/api/cli/link`, {+ method: 'POST',+ json: { client_name: clientName, hostname: os.hostname(), scope },+ });+}++export async function pollLink({ origin, link, signal, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {+ let interval = (Number(link.interval) || 3) * 1000;+ const deadline = Date.now() + (Number(link.expires_in) || 600) * 1000;+ while (Date.now() < deadline) {+ if (signal?.aborted) throw new ApiError('sign-in cancelled');+ await sleep(interval);+ const res = await request(`${origin}/api/cli/token`, { method: 'POST', json: { device_code: link.device_code } });+ const data = await res.json().catch(() => ({}));+ if (res.ok) return data;+ switch (data.error) {+ case 'authorization_pending':+ continue;+ case 'slow_down':+ interval += 5000;+ continue;+ case 'access_denied':+ throw new ApiError('the sign-in was denied in the browser', { code: 'access_denied' });+ case 'expired_token':+ throw new ApiError('the code expired before it was approved. Run the command again.', { code: 'expired_token' });+ default:+ throw new ApiError(`${res.status} ${data.error || ''}: ${data.error_description || 'unexpected response'}`, { status: res.status, code: data.error });+ }+ }+ throw new ApiError('the code expired before it was approved. Run the command again.', { code: 'expired_token' });+}++/** Full flow: start, show, open, poll. Returns an `apikey` auth record. */+export async function deviceLogin({ origin, scope, env, onCode = () => {} }) {+ const link = await startLink({ origin, scope });+ const opened = await openBrowser(link.verification_uri_complete, { env: env?.vars || process.env });+ onCode(link, opened);+ const granted = await pollLink({ origin, link });+ return {+ auth: { type: 'apikey', key: granted.access_token, prefix: granted.key?.prefix || null, key_id: granted.key?.id || null, scope: granted.scope },+ account: { email: granted.account?.email || null },+ };+}diff --git a/packages/three-ws-cli/src/entries.js b/packages/three-ws-cli/src/entries.jsnew file mode 100644index 000000000..1bd4520a4--- /dev/null+++ b/packages/three-ws-cli/src/entries.js@@ -0,0 +1,70 @@+// Build the config entry one client gets for one server.+//+// Direct HTTP when the client supports remote servers in its config AND the+// credential is static (an API key, or a keyless server). Everything else goes+// through `three-ws proxy`, a stdio process that forwards to the hosted server:+// - OAuth access tokens live an hour; the proxy refreshes them from the+// credential store, so a client config never holds a token that dies.+// - Clients with stdio-only configs (Claude Desktop, Codex) reach remote+// servers this way.+// - `--proxy` forces it everywhere, which also enforces the tool picker+// locally for every client.++import { fileURLToPath } from 'node:url';+import { DEFAULT_ORIGIN } from './store.js';+import { TOOLS_HEADER, isDefaultSelection, headerValue, filterTools } from './policy.js';++/** How to launch this same CLI later, from inside a client. */+export function proxyInvocation({ platform = process.platform, cliPath = fileURLToPath(new URL('./cli.js', import.meta.url)), nodePath = process.execPath } = {}) {+ // Run from the npm cache or an install: every launch resolves the published+ // package. Run from a source checkout: pin this checkout, so a developer+ // testing unreleased changes gets exactly them.+ if (/[\\/](_npx|node_modules)[\\/]/.test(cliPath)) return npxInvocation(['three-ws'], platform);+ return { command: nodePath, args: [cliPath] };+}++// Windows resolves `npx` to npx.cmd, which child_process cannot spawn without a+// shell, and several clients spawn without one. `cmd /c` is the portable form.+export function npxInvocation(pkgArgs, platform = process.platform) {+ return platform === 'win32'+ ? { command: 'cmd', args: ['/c', 'npx', '-y', ...pkgArgs] }+ : { command: 'npx', args: ['-y', ...pkgArgs] };+}++export function usesProxy({ client, server, mode, forceProxy = false }) {+ if (forceProxy || !client.http) return true;+ return server.auth === 'required' && mode !== 'apikey';+}++export function buildEntry({ client, server, mode, apiKey = null, selection = null, liveTools = null, forceProxy = false, proxy = proxyInvocation() }) {+ const needsAuth = server.auth === 'required';+ if (needsAuth && mode === 'apikey' && !apiKey) throw new Error(`an API key is required to configure ${server.slug}`);++ if (!usesProxy({ client, server, mode, forceProxy })) {+ const headers = {};+ if (needsAuth) headers.Authorization = `Bearer ${apiKey}`;+ let includeTools;+ if (liveTools && selection && !isDefaultSelection(selection)) {+ headers[TOOLS_HEADER] = headerValue(liveTools, selection);+ if (client.allowList) includeTools = filterTools(liveTools, selection).map((t) => t.name).sort();+ }+ return client.http({ url: server.url, headers, includeTools });+ }++ const env = {};+ if (needsAuth && mode === 'apikey') env.THREE_WS_API_KEY = apiKey;+ return client.stdio({+ command: proxy.command,+ args: [...proxy.args, 'proxy', server.url, '--server', server.slug],+ env,+ });+}++/** A stdio @three-ws/*-mcp package: launched with npx, the key in its env block. */+export function buildPackageEntry({ client, pkg, apiKey, origin = DEFAULT_ORIGIN, platform = process.platform }) {+ const run = npxInvocation([pkg.package], platform);+ const env = {};+ if (apiKey) env.THREE_WS_API_KEY = apiKey;+ if (origin !== DEFAULT_ORIGIN) env.THREE_WS_BASE = origin;+ return client.stdio({ ...run, env });+}diff --git a/packages/three-ws-cli/src/http.js b/packages/three-ws-cli/src/http.jsnew file mode 100644index 000000000..85fa1a34c--- /dev/null+++ b/packages/three-ws-cli/src/http.js@@ -0,0 +1,53 @@+// Thin fetch wrappers. Node 20's global fetch is the HTTP client; these only add+// a deadline, a User-Agent, and one error type that carries the server's own+// `error` / `error_description` so every command can print what actually failed.++import { readFileSync } from 'node:fs';++const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));+export const VERSION = pkg.version;+export const USER_AGENT = `three-ws-cli/${VERSION} (node ${process.versions.node}; ${process.platform})`;++export class ApiError extends Error {+ constructor(message, { status = 0, code = null, body = null } = {}) {+ super(message);+ this.name = 'ApiError';+ this.status = status;+ this.code = code;+ this.body = body;+ }+}++export async function request(url, { method = 'GET', headers = {}, body, form, json, timeoutMs = 20_000 } = {}) {+ const h = { 'user-agent': USER_AGENT, accept: 'application/json', ...headers };+ let payload = body;+ if (json !== undefined) {+ h['content-type'] = 'application/json';+ payload = JSON.stringify(json);+ } else if (form !== undefined) {+ h['content-type'] = 'application/x-www-form-urlencoded';+ payload = new URLSearchParams(form).toString();+ }+ let res;+ try {+ res = await fetch(url, { method, headers: h, body: payload, signal: AbortSignal.timeout(timeoutMs), redirect: 'manual' });+ } catch (err) {+ const reason = err?.name === 'TimeoutError' ? `timed out after ${Math.round(timeoutMs / 1000)}s` : err?.cause?.code || err?.message || 'network error';+ throw new ApiError(`could not reach ${new URL(url).host}: ${reason}`);+ }+ return res;+}++/** Request and parse JSON; throws ApiError on any non-2xx with the server's reason. */+export async function requestJson(url, opts = {}) {+ const res = await request(url, opts);+ const text = await res.text();+ let data = null;+ try { data = text ? JSON.parse(text) : null; } catch { data = null; }+ if (!res.ok) {+ const code = data?.error && typeof data.error === 'string' ? data.error : data?.error?.code || null;+ const desc = data?.error_description || data?.error?.message || data?.message || text.slice(0, 200) || res.statusText;+ throw new ApiError(`${res.status} ${code ? `${code}: ` : ''}${desc}`, { status: res.status, code, body: data });+ }+ return data;+}diff --git a/packages/three-ws-cli/src/mcp-http.js b/packages/three-ws-cli/src/mcp-http.jsnew file mode 100644index 000000000..d3eea5376--- /dev/null+++ b/packages/three-ws-cli/src/mcp-http.js@@ -0,0 +1,101 @@+// A minimal MCP Streamable HTTP client (spec 2025-06-18): POST one JSON-RPC+// message or batch, read back either application/json or a text/event-stream+// of messages. Used by `setup`/`status` to run a real tools/list, and by the+// stdio proxy to forward a client's traffic.++import { request, ApiError, VERSION } from './http.js';++export const PROTOCOL_VERSION = '2025-06-18';++/** Parse a text/event-stream body into the JSON-RPC messages its data lines carry. */+export function parseSse(text) {+ const out = [];+ for (const block of String(text).split(/\r?\n\r?\n/)) {+ const data = block+ .split(/\r?\n/)+ .filter((line) => line.startsWith('data:'))+ .map((line) => line.slice(5).replace(/^ /, ''))+ .join('\n');+ if (!data) continue;+ try {+ const msg = JSON.parse(data);+ if (Array.isArray(msg)) out.push(...msg);+ else out.push(msg);+ } catch {+ // A non-JSON data line is a keep-alive or comment; nothing to deliver.+ }+ }+ return out;+}++/**+ * POST a JSON-RPC payload. Returns { status, messages, sessionId }.+ * `messages` is always an array (empty for 202 Accepted notifications).+ */+export async function post(url, payload, { bearer, sessionId, protocolVersion = PROTOCOL_VERSION, headers = {}, timeoutMs = 60_000 } = {}) {+ const h = {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': protocolVersion,+ ...headers,+ };+ if (bearer) h.authorization = `Bearer ${bearer}`;+ if (sessionId) h['mcp-session-id'] = sessionId;+ const res = await request(url, { method: 'POST', headers: h, body: JSON.stringify(payload), timeoutMs });+ const nextSession = res.headers.get('mcp-session-id') || sessionId || null;+ if (res.status === 202 || res.status === 204) return { status: res.status, messages: [], sessionId: nextSession };+ const type = res.headers.get('content-type') || '';+ const text = await res.text();+ let messages = [];+ if (type.includes('text/event-stream')) messages = parseSse(text);+ else if (text) {+ try {+ const parsed = JSON.parse(text);+ messages = Array.isArray(parsed) ? parsed : [parsed];+ } catch {+ messages = [];+ }+ }+ return { status: res.status, messages, sessionId: nextSession, body: text };+}++function describeHttpFailure(url, result) {+ let detail = '';+ try {+ const body = JSON.parse(result.body || '{}');+ detail = body.error_description || body.error?.message || body.error || '';+ } catch {+ detail = '';+ }+ return `${new URL(url).pathname} answered ${result.status}${detail ? `: ${detail}` : ''}`;+}++/** initialize + notifications/initialized + tools/list; returns the tool array. */+export async function listTools(url, { bearer, headers } = {}) {+ const init = await post(url, {+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'three-ws-cli', version: VERSION } },+ }, { bearer, headers });+ if (init.status === 401) throw new ApiError(`${new URL(url).pathname} rejected the credential (401). Run \`npx three-ws login\`.`, { status: 401, code: 'unauthorized' });+ if (init.status >= 400) throw new ApiError(describeHttpFailure(url, init), { status: init.status });+ const initMsg = init.messages.find((m) => m.id === 1);+ if (initMsg?.error) throw new ApiError(`initialize failed: ${initMsg.error.message}`);+ const protocolVersion = initMsg?.result?.protocolVersion || PROTOCOL_VERSION;+ await post(url, { jsonrpc: '2.0', method: 'notifications/initialized' }, { bearer, headers, sessionId: init.sessionId, protocolVersion });++ const tools = [];+ let cursor;+ for (let page = 0; page < 20; page++) {+ const res = await post(url, { jsonrpc: '2.0', id: 2 + page, method: 'tools/list', params: cursor ? { cursor } : {} }, { bearer, headers, sessionId: init.sessionId, protocolVersion });+ if (res.status >= 400) throw new ApiError(describeHttpFailure(url, res), { status: res.status });+ const msg = res.messages.find((m) => m.id === 2 + page);+ if (!msg) throw new ApiError(`${new URL(url).pathname} returned no tools/list response`);+ if (msg.error) throw new ApiError(`tools/list failed: ${msg.error.message}`);+ tools.push(...(msg.result?.tools || []));+ cursor = msg.result?.nextCursor;+ if (!cursor) break;+ }+ return { tools, serverInfo: initMsg?.result?.serverInfo || null };+}diff --git a/packages/three-ws-cli/src/oauth.js b/packages/three-ws-cli/src/oauth.jsnew file mode 100644index 000000000..b253ae7e5--- /dev/null+++ b/packages/three-ws-cli/src/oauth.js@@ -0,0 +1,212 @@+// OAuth 2.1 against the three.ws authorization server, as a native app+// (RFC 8252): dynamic client registration once per origin, then authorization+// code + PKCE with the code delivered to a loopback listener on an ephemeral+// port. The server accepts any port on a registered 127.0.0.1 redirect, so the+// one registration is reused for every later login.++import http from 'node:http';+import crypto from 'node:crypto';+import { request, requestJson, ApiError, VERSION } from './http.js';+import { openBrowser } from './browser.js';+import { readStore, writeStore, withStoreLock } from './store.js';+import { systemEnv } from './paths.js';++export const REDIRECT_PATH = '/callback';+const REGISTERED_REDIRECT = `http://127.0.0.1${REDIRECT_PATH}`;++// Everything the CLI could ever ask for; the scope actually requested at+// authorize time is narrower (see scopesFor in auth.js) and the consent screen+// lists exactly that narrower set.+export const REGISTRATION_SCOPE = 'profile offline_access avatars:read avatars:write memory:read memory:write agents:read agents:write wallet:read wallet:write services:write';++export async function discover(origin) {+ const meta = await requestJson(`${origin}/.well-known/oauth-authorization-server`);+ for (const k of ['authorization_endpoint', 'token_endpoint', 'registration_endpoint']) {+ if (!meta?.[k]) throw new ApiError(`${origin} does not advertise ${k}; is this a three.ws server?`);+ }+ return meta;+}++function base64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}++export function pkcePair() {+ const verifier = base64url(crypto.randomBytes(32));+ const challenge = base64url(crypto.createHash('sha256').update(verifier).digest());+ return { verifier, challenge };+}++export async function ensureClient(origin, meta, env = systemEnv()) {+ const store = readStore(env);+ const cached = store.oauth_clients?.[origin];+ if (cached?.client_id && cached.scope === REGISTRATION_SCOPE) return cached.client_id;+ const reg = await requestJson(meta.registration_endpoint, {+ method: 'POST',+ json: {+ client_name: 'three-ws CLI',+ client_uri: 'https://three.ws/docs/cli',+ redirect_uris: [REGISTERED_REDIRECT],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ token_endpoint_auth_method: 'none',+ scope: REGISTRATION_SCOPE,+ software_id: 'three-ws-cli',+ software_version: VERSION,+ },+ });+ const next = readStore(env);+ next.oauth_clients = { ...(next.oauth_clients || {}), [origin]: { client_id: reg.client_id, redirect_uri: REGISTERED_REDIRECT, scope: REGISTRATION_SCOPE } };+ writeStore(next, env);+ return reg.client_id;+}++const CALLBACK_PAGE = (ok, detail) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>three-ws CLI</title><style>:root{color-scheme:light dark}body{font:16px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;background:#0b0b10;color:#eee;padding:24px}.c{max-width:420px;background:#14141c;border:1px solid #2a2a36;border-radius:16px;padding:28px}h1{font-size:20px;margin:0 0 8px}p{color:#aaa;margin:0}</style></head><body><div class="c"><h1>${ok ? 'Signed in. Back to your terminal.' : 'Sign-in did not finish'}</h1><p>${detail}</p></div></body></html>`;++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++/**+ * Run the browser half of the flow and resolve with the token response.+ * `onUrl(url, opened)` lets the caller print the URL (always) and say whether+ * the browser opened.+ */+export async function authorizeInBrowser({ origin, scope, env = systemEnv(), onUrl = () => {}, timeoutMs = 5 * 60_000 }) {+ const meta = await discover(origin);+ const clientId = await ensureClient(origin, meta, env);+ const { verifier, challenge } = pkcePair();+ const state = base64url(crypto.randomBytes(16));+ const resource = `${origin}/api/mcp`;++ let settle;+ const done = new Promise((resolve, reject) => { settle = { resolve, reject }; });+ const server = http.createServer((req, res) => {+ const url = new URL(req.url, 'http://127.0.0.1');+ if (url.pathname !== REDIRECT_PATH) {+ res.writeHead(404).end();+ return;+ }+ const send = (ok, detail) => {+ res.writeHead(ok ? 200 : 400, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });+ res.end(CALLBACK_PAGE(ok, escapeHtml(detail)));+ };+ if (url.searchParams.get('state') !== state) {+ send(false, 'The response did not match this sign-in. Run the command again.');+ return;+ }+ const err = url.searchParams.get('error');+ if (err) {+ send(false, err === 'access_denied' ? 'You cancelled the sign-in. Nothing was granted.' : `The server said: ${err}`);+ settle.reject(new ApiError(err === 'access_denied' ? 'sign-in cancelled in the browser' : `authorization failed: ${err}`, { code: err }));+ return;+ }+ const code = url.searchParams.get('code');+ if (!code) {+ send(false, 'No authorization code came back. Run the command again.');+ return;+ }+ send(true, 'You can close this tab. The three-ws CLI is finishing setup.');+ settle.resolve(code);+ });+ await new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', resolve);+ });+ const redirectUri = `http://127.0.0.1:${server.address().port}${REDIRECT_PATH}`;+ const authUrl = new URL(meta.authorization_endpoint);+ authUrl.search = new URLSearchParams({+ response_type: 'code',+ client_id: clientId,+ redirect_uri: redirectUri,+ scope,+ state,+ code_challenge: challenge,+ code_challenge_method: 'S256',+ resource,+ }).toString();++ const opened = await openBrowser(authUrl.toString(), { env: env.vars });+ onUrl(authUrl.toString(), opened);+ const timer = setTimeout(() => settle.reject(new ApiError('timed out waiting for the browser sign-in (5 minutes). Run the command again, or use --device.')), timeoutMs);+ let code;+ try {+ code = await done;+ } finally {+ clearTimeout(timer);+ server.close();+ }+ const token = await requestJson(meta.token_endpoint, {+ method: 'POST',+ form: { grant_type: 'authorization_code', code, redirect_uri: redirectUri, code_verifier: verifier, client_id: clientId, resource },+ });+ return {+ type: 'oauth',+ access_token: token.access_token,+ refresh_token: token.refresh_token || null,+ expires_at: Date.now() + (Number(token.expires_in) || 3600) * 1000,+ scope: token.scope || scope,+ client_id: clientId,+ token_endpoint: meta.token_endpoint,+ revocation_endpoint: meta.revocation_endpoint || null,+ };+}++const REFRESH_MARGIN_MS = 90_000;++export function needsRefresh(auth, now = Date.now()) {+ return auth?.type === 'oauth' && (!auth.expires_at || auth.expires_at - now < REFRESH_MARGIN_MS);+}++/**+ * A usable bearer for the stored credential, refreshing an OAuth token first+ * when it is close to expiry. `force` refreshes even a fresh token (after a 401).+ */+export async function bearerFor(env = systemEnv(), { force = false, origin } = {}) {+ const store = readStore(env);+ const auth = store.auth;+ if (!auth) return null;+ if (auth.type === 'apikey') return auth.key;+ if (!force && !needsRefresh(auth)) return auth.access_token;+ if (!auth.refresh_token) throw new ApiError('your three.ws session expired. Run `npx three-ws login`.', { code: 'login_required' });+ return withStoreLock(async () => {+ // Another process may have refreshed while this one waited on the lock.+ const fresh = readStore(env);+ const current = fresh.auth;+ if (current?.type !== 'oauth') return current?.key || null;+ if (current.access_token !== auth.access_token && !needsRefresh(current)) return current.access_token;+ const endpoint = current.token_endpoint || `${origin || fresh.origin}/api/oauth/token`;+ let token;+ try {+ token = await requestJson(endpoint, {+ method: 'POST',+ form: { grant_type: 'refresh_token', refresh_token: current.refresh_token, client_id: current.client_id, resource: `${origin || fresh.origin}/api/mcp` },+ });+ } catch (err) {+ if (err.status === 400 || err.status === 401) {+ throw new ApiError('your three.ws session was revoked or expired. Run `npx three-ws login`.', { code: 'login_required', status: err.status });+ }+ throw err;+ }+ fresh.auth = {+ ...current,+ access_token: token.access_token,+ refresh_token: token.refresh_token || current.refresh_token,+ expires_at: Date.now() + (Number(token.expires_in) || 3600) * 1000,+ scope: token.scope || current.scope,+ };+ writeStore(fresh, env);+ return fresh.auth.access_token;+ }, env);+}++/** Best-effort revocation of a stored OAuth refresh token (RFC 7009). */+export async function revokeOAuth(auth, origin) {+ if (auth?.type !== 'oauth' || !auth.refresh_token) return false;+ const endpoint = auth.revocation_endpoint || `${origin}/api/oauth/revoke`;+ const res = await request(endpoint, {+ method: 'POST',+ form: { token: auth.refresh_token, token_type_hint: 'refresh_token', client_id: auth.client_id },+ });+ return res.ok;+}diff --git a/packages/three-ws-cli/src/paths.js b/packages/three-ws-cli/src/paths.jsnew file mode 100644index 000000000..e1c1b48f6--- /dev/null+++ b/packages/three-ws-cli/src/paths.js@@ -0,0 +1,36 @@+// Where the CLI keeps its own state, and where every supported MCP client keeps+// its config. Each resolver takes an explicit `env` (home, platform, env vars)+// so tests exercise the real resolution logic against a temporary home.++import os from 'node:os';+import path from 'node:path';++/** The resolution context: override any field in tests. */+export function systemEnv(overrides = {}) {+ return {+ home: os.homedir(),+ platform: process.platform,+ cwd: process.cwd(),+ vars: process.env,+ ...overrides,+ };+}++/** `$XDG_CONFIG_HOME/three-ws`, else `~/.config/three-ws` (all platforms, one place to look). */+export function configDir(env = systemEnv()) {+ const xdg = env.vars.XDG_CONFIG_HOME;+ return path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(env.home, '.config'), 'three-ws');+}++export function credentialsPath(env = systemEnv()) {+ return env.vars.THREE_WS_CREDENTIALS || path.join(configDir(env), 'credentials.json');+}++// The per-user application data root on each OS, where desktop apps (Claude+// Desktop, VS Code) keep their settings.+export function appDataDir(env = systemEnv()) {+ if (env.platform === 'darwin') return path.join(env.home, 'Library', 'Application Support');+ if (env.platform === 'win32') return env.vars.APPDATA || path.join(env.home, 'AppData', 'Roaming');+ const xdg = env.vars.XDG_CONFIG_HOME;+ return xdg && path.isAbsolute(xdg) ? xdg : path.join(env.home, '.config');+}diff --git a/packages/three-ws-cli/src/policy.js b/packages/three-ws-cli/src/policy.jsnew file mode 100644index 000000000..5bc88ed0d--- /dev/null+++ b/packages/three-ws-cli/src/policy.js@@ -0,0 +1,72 @@+// Which tools a server exposes through this CLI.+//+// Every three.ws tool carries MCP annotations that `npm run audit:mcp-safety`+// verifies against what the handler actually does, and the platform derives one+// safety class from them (scripts/build-mcp-catalog.mjs):+// readOnlyHint: true -> read on by default+// destructiveHint: true -> financial off by default (moves funds or cannot be undone)+// anything else -> write on by default (changes state, reversible)+// The CLI classifies live tools/list results the same way, so a tool added to+// a server tomorrow lands in the right tier with no CLI release.+//+// A selection is { tiers, allow, deny }: whole tiers on, plus per-tool+// exceptions either way. It lives in the credential store under tools[slug].++export const TIERS = Object.freeze(['read', 'write', 'financial']);+export const DEFAULT_TIERS = Object.freeze(['read', 'write']);++export const TIER_LABELS = {+ read: 'Read-only',+ write: 'Changes state (reversible)',+ financial: 'Moves funds or irreversible',+};++export function tierOf(tool) {+ const a = tool?.annotations || {};+ if (a.readOnlyHint === true) return 'read';+ return a.destructiveHint === true ? 'financial' : 'write';+}++export function defaultSelection() {+ return { tiers: [...DEFAULT_TIERS], allow: [], deny: [] };+}++export function normalizeSelection(sel) {+ if (!sel || typeof sel !== 'object') return defaultSelection();+ return {+ tiers: Array.isArray(sel.tiers) ? sel.tiers.filter((t) => TIERS.includes(t)) : [...DEFAULT_TIERS],+ allow: Array.isArray(sel.allow) ? [...new Set(sel.allow.map(String))] : [],+ deny: Array.isArray(sel.deny) ? [...new Set(sel.deny.map(String))] : [],+ };+}++export function isEnabled(tool, selection) {+ const sel = normalizeSelection(selection);+ if (sel.deny.includes(tool.name)) return false;+ if (sel.allow.includes(tool.name)) return true;+ return sel.tiers.includes(tierOf(tool));+}++export function filterTools(tools, selection) {+ return (tools || []).filter((t) => isEnabled(t, selection));+}++export function isDefaultSelection(selection) {+ const sel = normalizeSelection(selection);+ return !sel.allow.length && !sel.deny.length && sel.tiers.length === DEFAULT_TIERS.length && DEFAULT_TIERS.every((t) => sel.tiers.includes(t));+}++/** Group a live tool list by tier, for the picker and `status`. */+export function groupByTier(tools) {+ const out = { read: [], write: [], financial: [] };+ for (const t of tools || []) out[tierOf(t)].push(t);+ return out;+}++// The `X-Three-Tools` request header (docs/cli.md) carries the enabled tool+// names for a direct HTTP entry, where no local proxy sits in between to filter.+export const TOOLS_HEADER = 'X-Three-Tools';++export function headerValue(tools, selection) {+ return filterTools(tools, selection).map((t) => t.name).sort().join(',');+}diff --git a/packages/three-ws-cli/src/proxy.js b/packages/three-ws-cli/src/proxy.jsnew file mode 100644index 000000000..cb899b3d3--- /dev/null+++ b/packages/three-ws-cli/src/proxy.js@@ -0,0 +1,154 @@+// `three-ws proxy <url>`: a stdio MCP server that forwards every message to a+// hosted three.ws server over Streamable HTTP.+//+// What it adds over talking to the server directly:+// - Credentials come from THREE_WS_API_KEY or the credential store, and an+// OAuth token is refreshed before it expires and again after any 401, so a+// client that launched the proxy days ago keeps working.+// - The tool selection from `three-ws tools` is enforced here: tools/list+// only returns enabled tools, and a tools/call for a disabled one is+// answered with an error that says how to enable it, without the request+// ever reaching the server.+//+// stdout carries JSON-RPC only (one message per line, the MCP stdio framing);+// every diagnostic goes to stderr, which clients surface in their logs.++import readline from 'node:readline';+import { post, PROTOCOL_VERSION } from './mcp-http.js';+import { bearerFor } from './oauth.js';+import { readStore } from './store.js';+import { systemEnv } from './paths.js';+import { isEnabled, normalizeSelection, tierOf, TIER_LABELS } from './policy.js';++function log(msg) {+ process.stderr.write(`[three-ws proxy] ${msg}\n`);+}++export function disabledToolError(id, name, tool) {+ const tier = tool ? tierOf(tool) : null;+ return {+ jsonrpc: '2.0',+ id,+ error: {+ code: -32601,+ message: `The three.ws tool "${name}" is turned off on this machine${tier ? ` (${TIER_LABELS[tier].toLowerCase()} tools are off)` : ''}. Run \`npx three-ws tools\` to enable it.`,+ data: { tool: name, tier, enable: 'npx three-ws tools' },+ },+ };+}++/**+ * Apply the selection to one server response. Mutates and returns `msg`.+ * `knownTools` collects the annotations seen in tools/list, so a later+ * tools/call can be judged by the same tier rules.+ */+export function filterResponse(msg, requestMethod, selection, knownTools) {+ if (requestMethod !== 'tools/list' || !msg?.result?.tools) return msg;+ for (const t of msg.result.tools) knownTools.set(t.name, t);+ msg.result.tools = msg.result.tools.filter((t) => isEnabled(t, selection));+ return msg;+}++export async function runProxy({ url, server, env = systemEnv(), input = process.stdin, output = process.stdout }) {+ const staticKey = env.vars.THREE_WS_API_KEY || null;+ const store = readStore(env);+ const selection = normalizeSelection(server ? store.tools?.[server] : null);+ const origin = new URL(url).origin;+ const knownTools = new Map();+ const pending = new Map();+ let sessionId = null;+ let protocolVersion = PROTOCOL_VERSION;++ const write = (msg) => output.write(`${JSON.stringify(msg)}\n`);++ async function credential(force = false) {+ if (staticKey) return staticKey;+ try {+ return await bearerFor(env, { force, origin });+ } catch (err) {+ log(err.message);+ return null;+ }+ }++ async function forward(payload) {+ let bearer = await credential();+ let res = await post(url, payload, { bearer, sessionId, protocolVersion });+ if (res.status === 401 && !staticKey && bearer) {+ bearer = await credential(true);+ res = await post(url, payload, { bearer, sessionId, protocolVersion });+ }+ if (res.sessionId) sessionId = res.sessionId;+ return res;+ }++ async function handle(line) {+ let msg;+ try {+ msg = JSON.parse(line);+ } catch {+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });+ return;+ }+ const batch = Array.isArray(msg) ? msg : [msg];+ const outgoing = [];+ for (const m of batch) {+ if (m?.method === 'tools/call' && m.params?.name) {+ const tool = knownTools.get(m.params.name) || { name: m.params.name };+ if (!isEnabled(tool, selection)) {+ write(disabledToolError(m.id, m.params.name, knownTools.get(m.params.name)));+ continue;+ }+ }+ if (m?.method === 'initialize' && m.params?.protocolVersion) protocolVersion = m.params.protocolVersion;+ if (m?.id !== undefined && m?.method) pending.set(m.id, m.method);+ outgoing.push(m);+ }+ if (!outgoing.length) return;+ let res;+ try {+ res = await forward(Array.isArray(msg) ? outgoing : outgoing[0]);+ } catch (err) {+ for (const m of outgoing) {+ if (m?.id === undefined) continue;+ pending.delete(m.id);+ write({ jsonrpc: '2.0', id: m.id, error: { code: -32603, message: `three.ws is unreachable: ${err.message}` } });+ }+ return;+ }+ if (res.status === 401) {+ for (const m of outgoing) {+ if (m?.id === undefined) continue;+ pending.delete(m.id);+ write({ jsonrpc: '2.0', id: m.id, error: { code: -32001, message: 'three.ws rejected the credential. Run `npx three-ws login`, then restart this client.' } });+ }+ return;+ }+ for (const reply of res.messages) {+ const method = pending.get(reply.id);+ if (reply.id !== undefined) pending.delete(reply.id);+ if (reply.result?.protocolVersion) protocolVersion = reply.result.protocolVersion;+ write(filterResponse(reply, method, selection, knownTools));+ }+ // A non-2xx with no JSON-RPC body still owes each request an answer.+ if (!res.messages.length && res.status >= 400) {+ for (const m of outgoing) {+ if (m?.id === undefined) continue;+ pending.delete(m.id);+ write({ jsonrpc: '2.0', id: m.id, error: { code: -32603, message: `three.ws answered HTTP ${res.status}` } });+ }+ }+ }++ if (!staticKey && !store.auth) log('no credential stored; keyless servers still work. Run `npx three-ws login` for the rest.');+ const rl = readline.createInterface({ input, crlfDelay: Infinity });+ const inflight = new Set();+ rl.on('line', (line) => {+ if (!line.trim()) return;+ const p = handle(line).catch((err) => log(`unexpected: ${err.stack || err.message}`));+ inflight.add(p);+ p.finally(() => inflight.delete(p));+ });+ await new Promise((resolve) => rl.once('close', resolve));+ await Promise.allSettled([...inflight]);+}diff --git a/packages/three-ws-cli/src/servers.js b/packages/three-ws-cli/src/servers.jsnew file mode 100644index 000000000..bd7fe4d75--- /dev/null+++ b/packages/three-ws-cli/src/servers.js@@ -0,0 +1,82 @@+// The servers the CLI can wire up, read live from the platform:+// hosted Streamable HTTP servers <- {origin}/.well-known/mcp.json+// stdio @three-ws/*-mcp packages <- {origin}/mcp-catalog.json (servers[])+// Nothing here is a hardcoded server list; a server added to the directory+// shows up in `three-ws setup` the next time anyone runs it.++import { requestJson } from './http.js';++// Offered pre-selected. The two keyless servers are always offered too, since+// they work with no account at all.+export const DEFAULT_PATHS = ['/api/mcp', '/api/mcp-agent', '/api/mcp-3d'];++/**+ * The config key a server gets in every client: /api/mcp -> three-ws,+ * /api/mcp-agent -> three-ws-agent, /api/pump-fun-mcp -> three-ws-pump-fun.+ */+export function slugForPath(pathname) {+ const rest = String(pathname)+ .replace(/^\/api\//, '')+ .split('-')+ .filter((part) => part && part !== 'mcp')+ .join('-');+ return rest ? `three-ws-${rest}` : 'three-ws';+}++export function authRequired(authText) {+ return !/^none\b/i.test(String(authText || '').trim());+}++/** Normalize the live directory into the CLI's server records, rebased onto `origin`. */+export function hostedServers(directory, origin) {+ const list = Array.isArray(directory?.servers) ? directory.servers : [];+ return list+ .filter((s) => s?.endpoint && (s.transport || 'streamable-http') === 'streamable-http')+ .map((s) => {+ const pathname = new URL(s.endpoint).pathname;+ const needsAuth = authRequired(s.auth);+ return {+ slug: slugForPath(pathname),+ name: s.name,+ path: pathname,+ url: `${origin}${pathname}`,+ description: s.description || '',+ auth: needsAuth ? 'required' : 'none',+ defaultSelected: DEFAULT_PATHS.includes(pathname) || !needsAuth,+ };+ });+}++/** The stdio packages from the catalog, each run with `npx -y <package>`. */+export function stdioPackages(catalog) {+ const list = Array.isArray(catalog?.servers) ? catalog.servers : [];+ return list+ .filter((s) => s.transport === 'stdio' && /^npx\s+-y\s+@three-ws\/[\w.-]+$/.test(s.endpoint || ''))+ .map((s) => {+ const pkg = s.endpoint.split(/\s+/).pop();+ return {+ slug: `three-ws-${pkg.split('/').pop().replace(/-mcp$/, '')}`,+ name: pkg,+ package: pkg,+ tools: Number(s.tools) || 0,+ auth: s.auth === 'none' ? 'none' : 'key',+ };+ })+ .sort((a, b) => a.name.localeCompare(b.name));+}++export async function loadDirectory(origin) {+ return requestJson(`${origin}/.well-known/mcp.json`);+}++export async function loadCatalog(origin) {+ return requestJson(`${origin}/mcp-catalog.json`, { timeoutMs: 45_000 });+}++/** True when a client config entry points at one of this origin's servers. */+export function isThreeWsEntry(name, entry, origin) {+ if (/^three-ws(-|$)/.test(name)) return true;+ const blob = JSON.stringify(entry || {});+ if (blob.includes(new URL(origin).host) || blob.includes('@three-ws/')) return true;+ return blob.includes('three-ws') && blob.includes('"proxy"');+}diff --git a/packages/three-ws-cli/src/store.js b/packages/three-ws-cli/src/store.jsnew file mode 100644index 000000000..77004c99d--- /dev/null+++ b/packages/three-ws-cli/src/store.js@@ -0,0 +1,115 @@+// The credential store: ~/.config/three-ws/credentials.json, mode 0600.+//+// Shape (version 1):+// {+// version: 1,+// origin: 'https://three.ws',+// account: { user_id, email } | null,+// auth: { type: 'oauth', access_token, refresh_token, expires_at, scope, client_id }+// | { type: 'apikey', key, prefix, scope, key_id }+// | null,+// stdio_key: { key, prefix, key_id, scope } | null, // for @three-ws/*-mcp stdio packages+// oauth_clients: { [origin]: { client_id, redirect_uri } },+// tools: { [serverSlug]: { tiers: ['read','write'], enabled: [toolName...] } },+// }+//+// Writes go to a temp file in the same directory and are renamed into place, so+// a crash mid-write never leaves a half-written credential file, and a reader in+// another process (a proxy starting up) sees either the old file or the new one.++import fs from 'node:fs';+import path from 'node:path';+import { credentialsPath, systemEnv } from './paths.js';++export const DEFAULT_ORIGIN = 'https://three.ws';++function emptyStore() {+ return { version: 1, origin: DEFAULT_ORIGIN, account: null, auth: null, stdio_key: null, oauth_clients: {}, tools: {} };+}++export function readStore(env = systemEnv()) {+ const file = credentialsPath(env);+ let raw;+ try {+ raw = fs.readFileSync(file, 'utf8');+ } catch (err) {+ if (err.code === 'ENOENT') return emptyStore();+ throw err;+ }+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ throw new Error(`${file} is not valid JSON. Delete it and run \`three-ws login\` again.`);+ }+ return { ...emptyStore(), ...parsed };+}++export function writeStore(store, env = systemEnv()) {+ const file = credentialsPath(env);+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });+ fs.renameSync(tmp, file);+ // rename keeps the temp file's mode, but an existing file created by an older+ // build or by hand might have been wider; enforce it every time.+ if (process.platform !== 'win32') fs.chmodSync(file, 0o600);+ return file;+}++export function updateStore(mutator, env = systemEnv()) {+ const store = readStore(env);+ const next = mutator(store) || store;+ writeStore(next, env);+ return next;+}++/** The origin every command talks to: flag, then env, then the stored one. */+export function resolveOrigin({ flag, env = systemEnv(), store } = {}) {+ const raw = flag || env.vars.THREE_WS_ORIGIN || store?.origin || DEFAULT_ORIGIN;+ return String(raw).replace(/\/+$/, '');+}++/** Last four characters only. A stored secret is never printed whole. */+export function mask(secret) {+ if (!secret) return '';+ const s = String(secret);+ return `…${s.slice(-4)}`;+}++// ── Cross-process lock ───────────────────────────────────────────────────────+// Refresh tokens rotate on every use and the server treats a reused one as+// theft, revoking the whole family. Six proxies starting together would each+// refresh the same token and sign the user out, so a refresh holds this lock,+// re-reads the store, and only refreshes if nobody else just did.++const LOCK_STALE_MS = 30_000;++export async function withStoreLock(fn, env = systemEnv(), { timeoutMs = 20_000 } = {}) {+ const lock = `${credentialsPath(env)}.lock`;+ fs.mkdirSync(path.dirname(lock), { recursive: true, mode: 0o700 });+ const started = Date.now();+ for (;;) {+ try {+ const fd = fs.openSync(lock, 'wx', 0o600);+ fs.writeSync(fd, String(process.pid));+ fs.closeSync(fd);+ break;+ } catch (err) {+ if (err.code !== 'EEXIST') throw err;+ let age = 0;+ try { age = Date.now() - fs.statSync(lock).mtimeMs; } catch { continue; }+ if (age > LOCK_STALE_MS) {+ try { fs.unlinkSync(lock); } catch { /* another waiter removed it first */ }+ continue;+ }+ if (Date.now() - started > timeoutMs) throw new Error(`timed out waiting for ${lock}; delete it if no other three-ws process is running`);+ await new Promise((r) => setTimeout(r, 100));+ }+ }+ try {+ return await fn();+ } finally {+ try { fs.unlinkSync(lock); } catch { /* already gone */ }+ }+}diff --git a/packages/three-ws-cli/src/ui.js b/packages/three-ws-cli/src/ui.jsnew file mode 100644index 000000000..21ae9e394--- /dev/null+++ b/packages/three-ws-cli/src/ui.js@@ -0,0 +1,67 @@+// Terminal output. Colour and glyphs follow NO_COLOR / FORCE_COLOR / --no-color+// and degrade to plain ASCII off a TTY. With --json every command prints one+// JSON document on stdout and nothing else, so it pipes into jq or a CI step.++import os from 'node:os';++const argv = process.argv;+const noColor = argv.includes('--no-color') || (process.env.NO_COLOR != null && process.env.NO_COLOR !== '');+const forceColor = ['1', '2', '3', 'true'].includes(process.env.FORCE_COLOR ?? '');+export const isTTY = Boolean(process.stdout.isTTY);+const color = !noColor && (forceColor || isTTY);++const paint = (code) => (t) => (color ? `\x1b[${code}m${t}\x1b[0m` : String(t));+export const c = {+ bold: paint(1),+ dim: paint(2),+ red: paint(31),+ green: paint(32),+ yellow: paint(33),+ cyan: paint(36),+ gray: paint(90),+};++const unicode = isTTY || forceColor;+export const sym = {+ ok: unicode ? '✔' : 'ok',+ fail: unicode ? '✖' : 'x',+ warn: unicode ? '▲' : '!',+ dot: unicode ? '•' : '-',+ arrow: unicode ? '→' : '->',+};++export function tildify(p) {+ const home = os.homedir();+ return p && p.startsWith(home) ? `~${p.slice(home.length)}` : p;+}++export function printJson(value) {+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);+}++export function line(text = '') {+ process.stdout.write(`${text}\n`);+}++export function errorLine(text) {+ process.stderr.write(`${c.red(sym.fail)} ${text}\n`);+}++/** Two-column rows with the label column padded to the widest label. */+export function rows(pairs, indent = '') {+ const width = Math.max(...pairs.map(([k]) => k.length));+ for (const [k, v] of pairs) line(`${indent}${c.dim(k.padEnd(width))} ${v}`);+}++export function relativeExpiry(ms, now = Date.now()) {+ const delta = Math.round((ms - now) / 1000);+ if (delta <= 0) return 'expired';+ if (delta < 90) return `in ${delta}s`;+ const mins = Math.round(delta / 60);+ if (mins < 90) return `in ${mins}m`;+ return `in ${Math.round(mins / 60)}h`;+}++export function shortAddress(a) {+ return a && a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '';+}