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(packages): add ai-sdk and langchain framework adapters for the three.ws MCP tools
nirholase388d145872c
diff --git a/package-lock.json b/package-lock.jsonindex b71e2d42e..166d6364f 100644--- a/package-lock.json+++ b/package-lock.json@@ -78,7 +78,9 @@"packages/tty-avatar","packages/home-bridge","packages/home-mcp",- "packages/blender-mcp"+ "packages/blender-mcp",+ "packages/ai-sdk",+ "packages/langchain"],"dependencies": {"@0xsplits/splits-sdk": "^6.6.0",@@ -3687,6 +3689,13 @@"integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==","license": "(Apache-2.0 AND BSD-3-Clause)"},+ "node_modules/@cfworker/json-schema": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz",+ "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@chainsafe/as-chacha20poly1305": {"version": "0.1.0","license": "Apache-2.0"@@ -13684,6 +13693,62 @@"robust-predicates": "^3.0.1"}},+ "node_modules/@langchain/core": {+ "version": "1.2.17",+ "resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.2.17.tgz",+ "integrity": "sha512-aLQLSed6oLCMLtJHrINhnFmsu79G2UiDlRslbOx+TSN9NmU+WuDv1OtVxrLpYglhXNy53elSduMVk3XBPG9ulw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@cfworker/json-schema": "^4.0.2",+ "@standard-schema/spec": "^1.1.0",+ "js-tiktoken": "^1.0.12",+ "langsmith": ">=0.5.0 <1.0.0",+ "mustache": "^4.2.0",+ "p-queue": "^6.6.2",+ "zod": "^3.25.76 || ^4"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@langchain/core/node_modules/eventemitter3": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@langchain/core/node_modules/p-queue": {+ "version": "6.6.2",+ "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",+ "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "eventemitter3": "^4.0.4",+ "p-timeout": "^3.2.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@langchain/core/node_modules/p-timeout": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",+ "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-finally": "^1.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/@leeoniya/ufuzzy": {"version": "1.0.19","license": "MIT"@@ -27901,6 +27966,10 @@"resolved": "packages/agora-mcp","link": true},+ "node_modules/@three-ws/ai-sdk": {+ "resolved": "packages/ai-sdk",+ "link": true+ },"node_modules/@three-ws/alerts-mcp": {"resolved": "packages/alerts-mcp","link": true@@ -28009,6 +28078,10 @@"resolved": "packages/kol-mcp","link": true},+ "node_modules/@three-ws/langchain": {+ "resolved": "packages/langchain",+ "link": true+ },"node_modules/@three-ws/liquidation-collector": {"resolved": "services/liquidation-collector","link": true@@ -41538,6 +41611,16 @@"version": "0.8.0","license": "MIT"},+ "node_modules/js-tiktoken": {+ "version": "1.0.21",+ "resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz",+ "integrity": "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.5.1"+ }+ },"node_modules/js-tokens": {"version": "4.0.0","license": "MIT"@@ -42085,6 +42168,77 @@"multiformats": "^14.0.0"}},+ "node_modules/langsmith": {+ "version": "0.10.13",+ "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.10.13.tgz",+ "integrity": "sha512-v5500fr7rVzQSfQphTBJV2/OrMRDzb2QfLfoO+gvPBY/kER99QF2+wbG6QQUydm0N7ueyJfBOYhq6tqYacXVAA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-queue": "6.6.2"+ },+ "peerDependencies": {+ "@opentelemetry/api": "*",+ "@opentelemetry/exporter-trace-otlp-proto": "*",+ "@opentelemetry/sdk-trace-base": "*",+ "openai": "*",+ "ws": ">=7"+ },+ "peerDependenciesMeta": {+ "@opentelemetry/api": {+ "optional": true+ },+ "@opentelemetry/exporter-trace-otlp-proto": {+ "optional": true+ },+ "@opentelemetry/sdk-trace-base": {+ "optional": true+ },+ "openai": {+ "optional": true+ },+ "ws": {+ "optional": true+ }+ }+ },+ "node_modules/langsmith/node_modules/eventemitter3": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/langsmith/node_modules/p-queue": {+ "version": "6.6.2",+ "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",+ "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "eventemitter3": "^4.0.4",+ "p-timeout": "^3.2.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/langsmith/node_modules/p-timeout": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",+ "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-finally": "^1.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/lazystream": {"version": "1.0.1","resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz",@@ -44726,6 +44880,16 @@"integrity": "sha512-vbIm83F2yZ1pWJGS0yl0ysracIvv56LtbrIyiIQHoLdYDJOMoLfVFsXhh9DUH4SFdkdkFhucyWniihsNzVEjkQ==","license": "Apache-2.0 OR MIT"},+ "node_modules/mustache": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz",+ "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "mustache": "bin/mustache"+ }+ },"node_modules/mz": {"version": "2.7.0","dev": true,@@ -45562,6 +45726,16 @@"node": ">=8"}},+ "node_modules/p-finally": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",+ "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },"node_modules/p-limit": {"version": "7.3.2","resolved": "https://registry.npmjs.org/p-limit/-/p-limit-7.3.2.tgz",@@ -53308,6 +53482,18 @@"node": ">=20"}},+ "packages/ai-sdk": {+ "name": "@three-ws/ai-sdk",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "ai": "^5.0.0 || ^6.0.0 || ^7.0.0",+ "zod": "^3.23.0"+ }+ },"packages/alerts-mcp": {"name": "@three-ws/alerts-mcp","version": "0.1.3",@@ -53701,6 +53887,21 @@"node": ">=20"}},+ "packages/langchain": {+ "name": "@three-ws/langchain",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "devDependencies": {+ "@langchain/core": "^1.2.17"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "@langchain/core": ">=0.3.0",+ "zod": "^3.25.76 || ^4"+ }+ },"packages/loom-mcp": {"name": "@three-ws/loom-mcp","version": "0.1.3",diff --git a/package.json b/package.jsonindex 8d49c6ab9..013adbb2a 100644--- a/package.json+++ b/package.json@@ -135,7 +135,9 @@"packages/tty-avatar","packages/home-bridge","packages/home-mcp",- "packages/blender-mcp"+ "packages/blender-mcp",+ "packages/ai-sdk",+ "packages/langchain"],"main": "src/app.js","browserslist": [diff --git a/packages/ai-sdk/LICENSE b/packages/ai-sdk/LICENSEnew file mode 100644index 000000000..b5ae2a4e1--- /dev/null+++ b/packages/ai-sdk/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/ai-sdk/README.md b/packages/ai-sdk/README.mdnew file mode 100644index 000000000..79cb43659--- /dev/null+++ b/packages/ai-sdk/README.md@@ -0,0 +1,100 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/ai-sdk</h1>++<p align="center"><strong>Give any Vercel AI SDK agent the ability to forge, rig, animate, and render 3D models, and talk to a three.ws agent.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/ai-sdk"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/ai-sdk?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/ai-sdk?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/ai-sdk?color=339933&logo=node.js">+ <a href="https://three.ws"><img alt="three.ws" src="https://img.shields.io/badge/built%20by-three.ws-000"></a>+</p>++---++Five [`tool()`](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling) definitions that wrap three.ws's generative 3D pipeline, ready to drop into `generateText`/`streamText`:++| Tool | What it does | Auth |+| --- | --- | --- |+| `forge` | Text prompt → textured GLB | Free |+| `rig` | Static GLB → humanoid-rigged GLB | Free |+| `render` | Any public GLB → turntable preview + geometry stats | Free |+| `animate` | Text prompt → retargeted motion on a rigged GLB | Paid (x402) |+| `agentChat` | Message → a three.ws agent's reply | Free |++`forge`, `rig`, and `render` call three.ws's free, no-key `/api/mcp-studio` server. `agentChat` calls the public `/api/chat` endpoint. `animate` calls the paid, [x402](https://x402.org)-gated `/api/mcp` server: this package never signs a payment for you, it surfaces the real `PaymentRequired` challenge so your own x402 client (e.g. [`x402-fetch`](https://www.npmjs.com/package/x402-fetch)) can pay from your own wallet.++## Install++```bash+npm install @three-ws/ai-sdk ai zod+```++## Quick start++```js+import { generateText } from 'ai';+import { createOpenAI } from '@ai-sdk/openai';+import { createThreeWsTools } from '@three-ws/ai-sdk';++const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY });+const tools = createThreeWsTools();++const { text, toolResults } = await generateText({+ model: openai('gpt-5.5'),+ tools,+ prompt: 'Forge a low-poly fox, then render a turntable of it so I can see it.',+});++console.log(text);+console.log(toolResults);+```++Run it directly (no model needed) to see the tools call the live API:++```js+import { createThreeWsTools } from '@three-ws/ai-sdk';++const tools = createThreeWsTools();+const forged = await tools.forge.execute({ prompt: 'a friendly round robot mascot', tier: 'draft' });+console.log(forged);+// { ok: true, text: 'Generated this model from your prompt...', raw: {...} }++const rendered = await tools.render.execute({+ glbUrl: 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb',+});+console.log(rendered.text);+```++## Paying for `animate`++```js+import { wrapFetchWithPayment } from 'x402-fetch';+import { createThreeWsTools } from '@three-ws/ai-sdk';++// Resolve the x402 challenge with your own wallet, then pass the resulting+// X-PAYMENT header value straight through. This package never spends for you.+const tools = createThreeWsTools();+const unpaid = await tools.animate.execute({ glbUrl: myRiggedGlbUrl, prompt: 'wave hello' });+if (unpaid.paymentRequired) {+ // use your x402 client + wallet against unpaid.challenge, then retry with xPayment set+}+```++## Configuration++```js+createThreeWsTools({+ baseUrl: 'https://three.ws', // override for a self-hosted deployment+ apiKey: process.env.THREE_WS_API_KEY, // only needed for `animate`+});+```++Each tool is also exported individually: `forgeTool`, `rigTool`, `renderTool`, `animateTool`, `agentChatTool`.++## License++Apache-2.0diff --git a/packages/ai-sdk/package.json b/packages/ai-sdk/package.jsonnew file mode 100644index 000000000..8c1aecab5--- /dev/null+++ b/packages/ai-sdk/package.json@@ -0,0 +1,51 @@+{+ "name": "@three-ws/ai-sdk",+ "version": "0.1.0",+ "description": "Vercel AI SDK tool() definitions for three.ws: forge, rig, render, and animate 3D models, and chat with a three.ws agent, from any AI SDK agent loop.",+ "type": "module",+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test \"test/**/*.test.js\""+ },+ "publishConfig": {+ "access": "public"+ },+ "keywords": [+ "ai-sdk",+ "vercel-ai-sdk",+ "tool-calling",+ "three.ws",+ "3d",+ "glb",+ "gltf",+ "ai-agent",+ "model-context-protocol",+ "x402"+ ],+ "license": "Apache-2.0",+ "author": "three.ws <[email protected]> (https://three.ws)",+ "homepage": "https://three.ws/",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/ai-sdk"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "peerDependencies": {+ "ai": "^5.0.0 || ^6.0.0 || ^7.0.0",+ "zod": "^3.23.0"+ },+ "engines": {+ "node": ">=18"+ }+}diff --git a/packages/ai-sdk/src/client.js b/packages/ai-sdk/src/client.jsnew file mode 100644index 000000000..351c04c8d--- /dev/null+++ b/packages/ai-sdk/src/client.js@@ -0,0 +1,108 @@+// Thin client for three.ws's MCP JSON-RPC servers and its public chat API.+// No SDK dependency here on purpose: both /api/mcp-studio (free) and /api/mcp+// (paid, x402-gated) speak plain JSON-RPC 2.0 "tools/call" over HTTPS, and+// /api/chat is a plain SSE POST. Framework adapters (ai-sdk, langchain) wrap+// these calls in their own tool shape; this file is the one place that knows+// the wire format, so neither adapter can drift from the live API.++const DEFAULT_BASE_URL = 'https://three.ws';+const FREE_MCP_PATH = '/api/mcp-studio';+const PAID_MCP_PATH = '/api/mcp';+const CHAT_PATH = '/api/chat';++/**+ * Call a tool on a three.ws MCP JSON-RPC server.+ * @param {object} opts+ * @param {string} [opts.baseUrl]+ * @param {'free'|'paid'} [opts.surface] which server to call+ * @param {string} opts.tool the MCP tool name, e.g. "forge_free"+ * @param {object} opts.args the tool's arguments+ * @param {string} [opts.apiKey] bearer token for the paid server+ * @param {string} [opts.xPayment] a pre-signed X-PAYMENT header value for an+ * x402-gated tool. three.ws never signs a payment on the caller's behalf;+ * obtain this from an x402 client (e.g. the `x402-fetch` package) wired to+ * the caller's own wallet, then pass the resulting header value through.+ * @returns {Promise<{ok: true, result: object} | {ok: false, paymentRequired: true, challenge: object} | {ok: false, error: string}>}+ */+export async function callThreeWsTool({ baseUrl = DEFAULT_BASE_URL, surface = 'free', tool, args, apiKey, xPayment }) {+ const path = surface === 'paid' ? PAID_MCP_PATH : FREE_MCP_PATH;+ const headers = { 'content-type': 'application/json' };+ if (apiKey) headers.authorization = `Bearer ${apiKey}`;+ if (xPayment) headers['x-payment'] = xPayment;++ const res = await fetch(`${baseUrl}${path}`, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: Date.now(),+ method: 'tools/call',+ params: { name: tool, arguments: args },+ }),+ });++ if (res.status === 402) {+ const challenge = await res.json().catch(() => null);+ return { ok: false, paymentRequired: true, challenge };+ }+ if (!res.ok) {+ return { ok: false, error: `three.ws ${surface} MCP ${res.status}: ${await res.text().catch(() => res.statusText)}` };+ }++ const body = await res.json();+ if (body.error) return { ok: false, error: body.error.message || JSON.stringify(body.error) };+ const result = body.result;+ if (result?.isError) {+ const text = result.content?.find((c) => c.type === 'text')?.text || 'tool call failed';+ return { ok: false, error: text };+ }+ return { ok: true, result };+}++/** Pull the plain-text answer out of an MCP tool result's content blocks. */+export function toolResultText(result) {+ return (result?.content || [])+ .filter((c) => c.type === 'text')+ .map((c) => c.text)+ .join('\n');+}++/**+ * Send one message to a three.ws agent (or the default viewer agent) and+ * return its full reply. Streams the real SSE response and resolves once the+ * "done" event lands; does not fabricate a reply on network failure.+ * @param {object} opts+ * @param {string} [opts.baseUrl]+ * @param {string} opts.message+ * @param {string} [opts.agentId] a three.ws agent UUID; omitted = default agent+ * @param {Array<{role: string, content: string}>} [opts.history]+ */+export async function callThreeWsChat({ baseUrl = DEFAULT_BASE_URL, message, agentId, history }) {+ const res = await fetch(`${baseUrl}${CHAT_PATH}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message, ...(agentId ? { agentId } : {}), ...(history ? { history } : {}) }),+ });+ if (!res.ok) throw new Error(`three.ws chat ${res.status}: ${await res.text().catch(() => res.statusText)}`);++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let done = null;+ while (true) {+ const { value, done: streamDone } = await reader.read();+ if (streamDone) break;+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n\n');+ buffer = lines.pop();+ for (const line of lines) {+ const payload = line.replace(/^data: /, '').trim();+ if (!payload) continue;+ const event = JSON.parse(payload);+ if (event.type === 'done') done = event;+ if (event.type === 'error') throw new Error(event.error || 'three.ws chat stream error');+ }+ }+ if (!done) throw new Error('three.ws chat stream ended without a done event');+ return done;+}diff --git a/packages/ai-sdk/src/index.js b/packages/ai-sdk/src/index.jsnew file mode 100644index 000000000..f32e94eb3--- /dev/null+++ b/packages/ai-sdk/src/index.js@@ -0,0 +1,139 @@+// Vercel AI SDK `tool()` definitions for three.ws's generative 3D pipeline:+// forge a model from text, rig it for animation, render a turntable preview,+// animate it from a text prompt, and chat with a three.ws agent persona.+// forge/rig/render call the free, no-auth /api/mcp-studio server; animate+// calls the paid, x402-gated /api/mcp server and never pays on the caller's+// behalf (see `animateTool`'s doc comment); agentChat calls the public+// /api/chat SSE endpoint.++import { tool } from 'ai';+import { z } from 'zod';+import { callThreeWsTool, callThreeWsChat, toolResultText } from './client.js';++/**+ * Build all five three.ws tools bound to one configuration. Pass the result's+ * values straight into `generateText({ tools })` / `streamText({ tools })`.+ * @param {object} [config]+ * @param {string} [config.baseUrl] override for self-hosted / staging deployments+ * @param {string} [config.apiKey] three.ws API key, only needed for `animateTool`+ */+export function createThreeWsTools(config = {}) {+ return {+ forge: forgeTool(config),+ rig: rigTool(config),+ render: renderTool(config),+ animate: animateTool(config),+ agentChat: agentChatTool(config),+ };+}++export function forgeTool({ baseUrl } = {}) {+ return tool({+ description:+ 'Generate a textured, downloadable 3D model (GLB) from a text prompt. Free, no API key required. ' ++ 'Describe a single object, character, or creature.',+ inputSchema: z.object({+ prompt: z.string().min(3).max(1000).describe('What to model, e.g. "a friendly round robot mascot, glossy white plastic".'),+ tier: z.enum(['draft', 'standard', 'high']).optional().describe('Detail level; standard is the default.'),+ }),+ execute: async ({ prompt, tier }) => {+ const res = await callThreeWsTool({ baseUrl, surface: 'free', tool: 'forge_free', args: { prompt, ...(tier ? { tier } : {}) } });+ if (!res.ok) return { ok: false, error: res.error || 'forge failed' };+ return { ok: true, text: toolResultText(res.result), raw: res.result.structuredContent ?? null };+ },+ });+}++export function rigTool({ baseUrl } = {}) {+ return tool({+ description:+ 'Auto-rig a static 3D model (GLB) into an animation-ready model: adds a humanoid skeleton and skin ' ++ 'weights. Free, no API key required. Provide the GLB URL of a model (e.g. one `forge` just produced).',+ inputSchema: z.object({+ glbUrl: z.string().url().describe('http(s) URL to the static GLB mesh to rig.'),+ }),+ execute: async ({ glbUrl }) => {+ const res = await callThreeWsTool({ baseUrl, surface: 'free', tool: 'rig_mesh', args: { glb_url: glbUrl } });+ if (!res.ok) return { ok: false, error: res.error || 'rig failed' };+ return { ok: true, text: toolResultText(res.result), raw: res.result.structuredContent ?? null };+ },+ });+}++export function renderTool({ baseUrl } = {}) {+ return tool({+ description:+ 'Render a turntable preview of any public .glb: several angles as images, plus its geometry stats and ' ++ 'a plain reading of what they mean. Free, no API key required, works on any public https .glb.',+ inputSchema: z.object({+ glbUrl: z.string().url().describe('Public https URL of the .glb to look at.'),+ views: z+ .array(z.enum(['front', 'three-quarter', 'side', 'back', 'top', 'bottom']))+ .max(6)+ .optional()+ .describe('Angles to render. Default: three-quarter, front, side, back.'),+ size: z.number().int().min(128).max(1024).optional().describe('Pixel size of each square frame. Default 512.'),+ }),+ execute: async ({ glbUrl, views, size }) => {+ const res = await callThreeWsTool({+ baseUrl,+ surface: 'free',+ tool: 'look_at_model',+ args: { glb_url: glbUrl, ...(views ? { views } : {}), ...(size ? { size } : {}) },+ });+ if (!res.ok) return { ok: false, error: res.error || 'render failed' };+ return { ok: true, text: toolResultText(res.result), raw: res.result.structuredContent ?? null };+ },+ });+}++/**+ * Animate a rigged GLB from a text prompt. This is a PAID, x402-gated tool on+ * three.ws's main MCP server: calling it without a payment returns the raw+ * x402 PaymentRequired challenge (`paymentRequired: true, challenge: {...}`)+ * instead of a model, and this package never signs or sends that payment for+ * you. Resolve the challenge with your own x402 client against your own+ * wallet (e.g. the `x402-fetch` package), then pass the resulting header+ * value in as `xPayment`.+ */+export function animateTool({ baseUrl, apiKey } = {}) {+ return tool({+ description:+ 'Retarget a text-described motion onto a rigged humanoid GLB (e.g. one `rig` just produced). PAID: ' ++ 'returns an x402 payment challenge unless a pre-signed X-PAYMENT value is supplied.',+ inputSchema: z.object({+ glbUrl: z.string().url().describe('http(s) URL to a rigged GLB to animate.'),+ prompt: z.string().min(1).max(500).describe('The motion to generate, e.g. "wave hello", "walk forward".'),+ xPayment: z.string().optional().describe('A pre-signed x402 X-PAYMENT header value from your own wallet/x402 client.'),+ }),+ execute: async ({ glbUrl, prompt, xPayment }) => {+ const res = await callThreeWsTool({+ baseUrl,+ surface: 'paid',+ tool: 'text_to_animation',+ args: { glb_url: glbUrl, prompt },+ apiKey,+ xPayment,+ });+ if (res.paymentRequired) return { ok: false, paymentRequired: true, challenge: res.challenge };+ if (!res.ok) return { ok: false, error: res.error || 'animate failed' };+ return { ok: true, text: toolResultText(res.result), raw: res.result.structuredContent ?? null };+ },+ });+}++export function agentChatTool({ baseUrl } = {}) {+ return tool({+ description:+ 'Send a message to a three.ws agent (or the default viewer agent) and get its reply. Free, no API ' ++ 'key required.',+ inputSchema: z.object({+ message: z.string().min(1).describe('What to say to the agent.'),+ agentId: z.string().uuid().optional().describe('A specific three.ws agent UUID; omit for the default agent.'),+ }),+ execute: async ({ message, agentId }) => {+ const done = await callThreeWsChat({ baseUrl, message, agentId });+ return { ok: true, reply: done.reply, model: done.model, provider: done.provider };+ },+ });+}diff --git a/packages/ai-sdk/test/tools.test.js b/packages/ai-sdk/test/tools.test.jsnew file mode 100644index 000000000..ebdd24456--- /dev/null+++ b/packages/ai-sdk/test/tools.test.js@@ -0,0 +1,50 @@+// Tests run against the LIVE three.ws API (https://three.ws), per repo policy:+// no mocks. `render` and `agentChat` hit free, stable endpoints and assert a+// real success. `forge`/`rig` hit the free GPU-worker-fleet generation path,+// which can genuinely fail independently of this package (queue load, a+// provider outage), those two assert the tool returns a well-formed result+// shape either way, without fabricating success. `animate` is paid and+// x402-gated; it asserts the real PaymentRequired challenge comes back+// unpaid, since this package must never sign a payment itself.++import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createThreeWsTools } from '../src/index.js';++const DUCK_GLB = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb';++const tools = createThreeWsTools();++test('render: turntable preview of a public GLB', async () => {+ const result = await tools.render.execute({ glbUrl: DUCK_GLB, views: ['front'], size: 256 });+ assert.equal(result.ok, true);+ assert.match(result.text, /Rendered this model/);+});++test('agentChat: the default agent replies to a message', async () => {+ const result = await tools.agentChat.execute({ message: 'Reply with exactly the word: pong' });+ assert.equal(result.ok, true);+ assert.equal(typeof result.reply, 'string');+ assert.ok(result.reply.length > 0);+});++test('forge: generates a model from text, or reports the real failure', async () => {+ const result = await tools.forge.execute({ prompt: 'a small red toy cube', tier: 'draft' });+ assert.equal(typeof result.ok, 'boolean');+ if (result.ok) assert.equal(typeof result.text, 'string');+ else assert.equal(typeof result.error, 'string');+});++test('rig: rigs a static GLB, or reports the real failure', async () => {+ const result = await tools.rig.execute({ glbUrl: DUCK_GLB });+ assert.equal(typeof result.ok, 'boolean');+ if (result.ok) assert.equal(typeof result.text, 'string');+ else assert.equal(typeof result.error, 'string');+});++test('animate: unpaid call returns a real x402 PaymentRequired challenge', async () => {+ const result = await tools.animate.execute({ glbUrl: DUCK_GLB, prompt: 'wave hello' });+ assert.equal(result.ok, false);+ assert.equal(result.paymentRequired, true);+ assert.ok(Array.isArray(result.challenge?.accepts) && result.challenge.accepts.length > 0);+});diff --git a/packages/langchain/INTEGRATION_ISSUE.md b/packages/langchain/INTEGRATION_ISSUE.mdnew file mode 100644index 000000000..c9eeaabfe--- /dev/null+++ b/packages/langchain/INTEGRATION_ISSUE.md@@ -0,0 +1,38 @@+# LangChain JS integration listing++Per `docs/partners/prospects.md`: LangChain's integration directory is populated from published npm+packages, not hand-written listing PRs ("Publish on npm, then file their 'Integration listing issue'.+Hand-written listing pull requests are now closed automatically"). This file is the issue text to file+against `langchain-ai/langchainjs` once `@three-ws/langchain` is live on npm.++## Owner steps (not automatable here)++1. `npm publish --access public` from `packages/langchain` (after `npm pack --dry-run` is clean).+2. Open an issue on `https://github.com/langchain-ai/langchainjs` using the "Integration request" template+ (or the closest current equivalent) with the title and body below.++## Issue title++Add integration: @three-ws/langchain++## Issue body++**Package**: [`@three-ws/langchain`](https://www.npmjs.com/package/@three-ws/langchain)+**Repo**: https://github.com/nirholas/three.ws/tree/main/packages/langchain++Five `tool()` definitions wrapping three.ws's generative 3D pipeline for any LangChain JS agent:++- `three_ws_forge`: text prompt -> textured GLB (free)+- `three_ws_rig`: static GLB -> humanoid-rigged GLB (free)+- `three_ws_render`: any public GLB -> turntable preview + geometry stats (free)+- `three_ws_animate`: text prompt -> retargeted motion on a rigged GLB (paid, x402)+- `three_ws_agent_chat`: message -> a three.ws agent's reply (free)++All five use `responseFormat: "content_and_artifact"` and are built on `@langchain/core/tools`'s `tool()`+API (peer dependency `@langchain/core >= 0.3.0`). `three_ws_animate` is the one paid tool: it never signs a+payment itself, it surfaces the real x402 `PaymentRequired` challenge as the tool's artifact so the caller's+own x402 client can pay from their own wallet.++Tests run against the live three.ws API (no mocks): see `test/tools.test.js` in the package.++README: https://github.com/nirholas/three.ws/tree/main/packages/langchain#readmediff --git a/packages/langchain/LICENSE b/packages/langchain/LICENSEnew file mode 100644index 000000000..b5ae2a4e1--- /dev/null+++ b/packages/langchain/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/langchain/README.md b/packages/langchain/README.mdnew file mode 100644index 000000000..02c8f4b6a--- /dev/null+++ b/packages/langchain/README.md@@ -0,0 +1,97 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/langchain</h1>++<p align="center"><strong>Give any LangChain JS agent the ability to forge, rig, animate, and render 3D models, and talk to a three.ws agent.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/langchain"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/langchain?logo=npm&color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/langchain?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/langchain?color=339933&logo=node.js">+ <a href="https://three.ws"><img alt="three.ws" src="https://img.shields.io/badge/built%20by-three.ws-000"></a>+</p>++---++Five [`tool()`](https://js.langchain.com/docs/how_to/custom_tools/) definitions that wrap three.ws's generative 3D pipeline, ready to bind onto any LangChain model or agent:++| Tool | What it does | Auth |+| --- | --- | --- |+| `three_ws_forge` | Text prompt → textured GLB | Free |+| `three_ws_rig` | Static GLB → humanoid-rigged GLB | Free |+| `three_ws_render` | Any public GLB → turntable preview + geometry stats | Free |+| `three_ws_animate` | Text prompt → retargeted motion on a rigged GLB | Paid (x402) |+| `three_ws_agent_chat` | Message → a three.ws agent's reply | Free |++`three_ws_forge`, `three_ws_rig`, and `three_ws_render` call three.ws's free, no-key `/api/mcp-studio` server. `three_ws_agent_chat` calls the public `/api/chat` endpoint. `three_ws_animate` calls the paid, [x402](https://x402.org)-gated `/api/mcp` server: this package never signs a payment for you, it surfaces the real `PaymentRequired` challenge in the tool's artifact so your own x402 client (e.g. [`x402-fetch`](https://www.npmjs.com/package/x402-fetch)) can pay from your own wallet.++Each tool uses `responseFormat: "content_and_artifact"`: the string `content` is what the model reads back, and `artifact` carries the structured result (`{ ok, raw }` or `{ ok: false, error }` / `{ ok: false, paymentRequired: true, challenge }`) for your application code.++## Install++```bash+npm install @three-ws/langchain @langchain/core zod+```++## Quick start++```js+import { ChatOpenAI } from '@langchain/openai';+import { createThreeWsTools } from '@three-ws/langchain';++const tools = createThreeWsTools();+const model = new ChatOpenAI({ model: 'gpt-5.5' }).bindTools(tools);++const response = await model.invoke('Forge a low-poly fox, then render a turntable of it so I can see it.');+console.log(response.tool_calls);+```++Run a tool directly (no model needed) to see it call the live API:++```js+import { createThreeWsTools } from '@three-ws/langchain';++const [forge, rig, render] = createThreeWsTools();++const forged = await forge.invoke({ name: 'three_ws_forge', args: { prompt: 'a friendly round robot mascot', tier: 'draft' }, id: '1', type: 'tool_call' });+console.log(forged.content, forged.artifact);++const rendered = await render.invoke({+ name: 'three_ws_render',+ args: { glbUrl: 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb' },+ id: '2',+ type: 'tool_call',+});+console.log(rendered.content);+```++## Paying for `three_ws_animate`++```js+import { createThreeWsTools } from '@three-ws/langchain';++// Resolve the x402 challenge with your own wallet, then pass the resulting+// X-PAYMENT header value straight through. This package never spends for you.+const [, , , animate] = createThreeWsTools();+const msg = await animate.invoke({ name: 'three_ws_animate', args: { glbUrl: myRiggedGlbUrl, prompt: 'wave hello' }, id: '3', type: 'tool_call' });+if (msg.artifact.paymentRequired) {+ // use your x402 client + wallet against msg.artifact.challenge, then retry with args.xPayment set+}+```++## Configuration++```js+createThreeWsTools({+ baseUrl: 'https://three.ws', // override for a self-hosted deployment+ apiKey: process.env.THREE_WS_API_KEY, // only needed for three_ws_animate+});+```++Each tool is also exported individually via a factory: `createForgeTool`, `createRigTool`, `createRenderTool`, `createAnimateTool`, `createAgentChatTool`.++## License++Apache-2.0diff --git a/packages/langchain/package.json b/packages/langchain/package.jsonnew file mode 100644index 000000000..a3b312f6b--- /dev/null+++ b/packages/langchain/package.json@@ -0,0 +1,54 @@+{+ "name": "@three-ws/langchain",+ "version": "0.1.0",+ "description": "LangChain JS tool() definitions for three.ws: forge, rig, render, and animate 3D models, and chat with a three.ws agent, from any LangChain agent.",+ "type": "module",+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test \"test/**/*.test.js\""+ },+ "publishConfig": {+ "access": "public"+ },+ "keywords": [+ "langchain",+ "langchainjs",+ "tool-calling",+ "three.ws",+ "3d",+ "glb",+ "gltf",+ "ai-agent",+ "model-context-protocol",+ "x402"+ ],+ "license": "Apache-2.0",+ "author": "three.ws <[email protected]> (https://three.ws)",+ "homepage": "https://three.ws/",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/langchain"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "peerDependencies": {+ "@langchain/core": ">=0.3.0",+ "zod": "^3.25.76 || ^4"+ },+ "devDependencies": {+ "@langchain/core": "^1.2.17"+ },+ "engines": {+ "node": ">=20"+ }+}diff --git a/packages/langchain/src/client.js b/packages/langchain/src/client.jsnew file mode 100644index 000000000..351c04c8d--- /dev/null+++ b/packages/langchain/src/client.js@@ -0,0 +1,108 @@+// Thin client for three.ws's MCP JSON-RPC servers and its public chat API.+// No SDK dependency here on purpose: both /api/mcp-studio (free) and /api/mcp+// (paid, x402-gated) speak plain JSON-RPC 2.0 "tools/call" over HTTPS, and+// /api/chat is a plain SSE POST. Framework adapters (ai-sdk, langchain) wrap+// these calls in their own tool shape; this file is the one place that knows+// the wire format, so neither adapter can drift from the live API.++const DEFAULT_BASE_URL = 'https://three.ws';+const FREE_MCP_PATH = '/api/mcp-studio';+const PAID_MCP_PATH = '/api/mcp';+const CHAT_PATH = '/api/chat';++/**+ * Call a tool on a three.ws MCP JSON-RPC server.+ * @param {object} opts+ * @param {string} [opts.baseUrl]+ * @param {'free'|'paid'} [opts.surface] which server to call+ * @param {string} opts.tool the MCP tool name, e.g. "forge_free"+ * @param {object} opts.args the tool's arguments+ * @param {string} [opts.apiKey] bearer token for the paid server+ * @param {string} [opts.xPayment] a pre-signed X-PAYMENT header value for an+ * x402-gated tool. three.ws never signs a payment on the caller's behalf;+ * obtain this from an x402 client (e.g. the `x402-fetch` package) wired to+ * the caller's own wallet, then pass the resulting header value through.+ * @returns {Promise<{ok: true, result: object} | {ok: false, paymentRequired: true, challenge: object} | {ok: false, error: string}>}+ */+export async function callThreeWsTool({ baseUrl = DEFAULT_BASE_URL, surface = 'free', tool, args, apiKey, xPayment }) {+ const path = surface === 'paid' ? PAID_MCP_PATH : FREE_MCP_PATH;+ const headers = { 'content-type': 'application/json' };+ if (apiKey) headers.authorization = `Bearer ${apiKey}`;+ if (xPayment) headers['x-payment'] = xPayment;++ const res = await fetch(`${baseUrl}${path}`, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: Date.now(),+ method: 'tools/call',+ params: { name: tool, arguments: args },+ }),+ });++ if (res.status === 402) {+ const challenge = await res.json().catch(() => null);+ return { ok: false, paymentRequired: true, challenge };+ }+ if (!res.ok) {+ return { ok: false, error: `three.ws ${surface} MCP ${res.status}: ${await res.text().catch(() => res.statusText)}` };+ }++ const body = await res.json();+ if (body.error) return { ok: false, error: body.error.message || JSON.stringify(body.error) };+ const result = body.result;+ if (result?.isError) {+ const text = result.content?.find((c) => c.type === 'text')?.text || 'tool call failed';+ return { ok: false, error: text };+ }+ return { ok: true, result };+}++/** Pull the plain-text answer out of an MCP tool result's content blocks. */+export function toolResultText(result) {+ return (result?.content || [])+ .filter((c) => c.type === 'text')+ .map((c) => c.text)+ .join('\n');+}++/**+ * Send one message to a three.ws agent (or the default viewer agent) and+ * return its full reply. Streams the real SSE response and resolves once the+ * "done" event lands; does not fabricate a reply on network failure.+ * @param {object} opts+ * @param {string} [opts.baseUrl]+ * @param {string} opts.message+ * @param {string} [opts.agentId] a three.ws agent UUID; omitted = default agent+ * @param {Array<{role: string, content: string}>} [opts.history]+ */+export async function callThreeWsChat({ baseUrl = DEFAULT_BASE_URL, message, agentId, history }) {+ const res = await fetch(`${baseUrl}${CHAT_PATH}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message, ...(agentId ? { agentId } : {}), ...(history ? { history } : {}) }),+ });+ if (!res.ok) throw new Error(`three.ws chat ${res.status}: ${await res.text().catch(() => res.statusText)}`);++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let done = null;+ while (true) {+ const { value, done: streamDone } = await reader.read();+ if (streamDone) break;+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n\n');+ buffer = lines.pop();+ for (const line of lines) {+ const payload = line.replace(/^data: /, '').trim();+ if (!payload) continue;+ const event = JSON.parse(payload);+ if (event.type === 'done') done = event;+ if (event.type === 'error') throw new Error(event.error || 'three.ws chat stream error');+ }+ }+ if (!done) throw new Error('three.ws chat stream ended without a done event');+ return done;+}diff --git a/packages/langchain/src/index.js b/packages/langchain/src/index.jsnew file mode 100644index 000000000..21a4bf43a--- /dev/null+++ b/packages/langchain/src/index.js@@ -0,0 +1,156 @@+// LangChain JS `tool()` definitions for three.ws's generative 3D pipeline:+// forge a model from text, rig it for animation, render a turntable preview,+// animate it from a text prompt, and chat with a three.ws agent persona.+// forge/rig/render call the free, no-auth /api/mcp-studio server; animate+// calls the paid, x402-gated /api/mcp server and never pays on the caller's+// behalf (see `createAnimateTool`'s doc comment); agentChat calls the public+// /api/chat SSE endpoint.++import { tool } from '@langchain/core/tools';+import { z } from 'zod';+import { callThreeWsTool, callThreeWsChat, toolResultText } from './client.js';++/**+ * Build all five three.ws tools bound to one configuration, ready to pass+ * into `createAgent({ tools })` / `.bindTools(tools)`.+ * @param {object} [config]+ * @param {string} [config.baseUrl] override for self-hosted / staging deployments+ * @param {string} [config.apiKey] three.ws API key, only needed for the animate tool+ */+export function createThreeWsTools(config = {}) {+ return [createForgeTool(config), createRigTool(config), createRenderTool(config), createAnimateTool(config), createAgentChatTool(config)];+}++export function createForgeTool({ baseUrl } = {}) {+ return tool(+ async ({ prompt, tier }) => {+ const res = await callThreeWsTool({ baseUrl, surface: 'free', tool: 'forge_free', args: { prompt, ...(tier ? { tier } : {}) } });+ if (!res.ok) return [`forge failed: ${res.error}`, { ok: false, error: res.error }];+ return [toolResultText(res.result), { ok: true, raw: res.result.structuredContent ?? null }];+ },+ {+ name: 'three_ws_forge',+ description:+ 'Generate a textured, downloadable 3D model (GLB) from a text prompt. Free, no API key required. ' ++ 'Describe a single object, character, or creature.',+ schema: z.object({+ prompt: z.string().min(3).max(1000).describe('What to model, e.g. "a friendly round robot mascot, glossy white plastic".'),+ tier: z.enum(['draft', 'standard', 'high']).optional().describe('Detail level; standard is the default.'),+ }),+ responseFormat: 'content_and_artifact',+ },+ );+}++export function createRigTool({ baseUrl } = {}) {+ return tool(+ async ({ glbUrl }) => {+ const res = await callThreeWsTool({ baseUrl, surface: 'free', tool: 'rig_mesh', args: { glb_url: glbUrl } });+ if (!res.ok) return [`rig failed: ${res.error}`, { ok: false, error: res.error }];+ return [toolResultText(res.result), { ok: true, raw: res.result.structuredContent ?? null }];+ },+ {+ name: 'three_ws_rig',+ description:+ 'Auto-rig a static 3D model (GLB) into an animation-ready model: adds a humanoid skeleton and skin ' ++ 'weights. Free, no API key required. Provide the GLB URL of a model (e.g. one three_ws_forge just produced).',+ schema: z.object({+ glbUrl: z.string().url().describe('http(s) URL to the static GLB mesh to rig.'),+ }),+ responseFormat: 'content_and_artifact',+ },+ );+}++export function createRenderTool({ baseUrl } = {}) {+ return tool(+ async ({ glbUrl, views, size }) => {+ const res = await callThreeWsTool({+ baseUrl,+ surface: 'free',+ tool: 'look_at_model',+ args: { glb_url: glbUrl, ...(views ? { views } : {}), ...(size ? { size } : {}) },+ });+ if (!res.ok) return [`render failed: ${res.error}`, { ok: false, error: res.error }];+ return [toolResultText(res.result), { ok: true, raw: res.result.structuredContent ?? null }];+ },+ {+ name: 'three_ws_render',+ description:+ 'Render a turntable preview of any public .glb: several angles as images, plus its geometry stats and ' ++ 'a plain reading of what they mean. Free, no API key required, works on any public https .glb.',+ schema: z.object({+ glbUrl: z.string().url().describe('Public https URL of the .glb to look at.'),+ views: z+ .array(z.enum(['front', 'three-quarter', 'side', 'back', 'top', 'bottom']))+ .max(6)+ .optional()+ .describe('Angles to render. Default: three-quarter, front, side, back.'),+ size: z.number().int().min(128).max(1024).optional().describe('Pixel size of each square frame. Default 512.'),+ }),+ responseFormat: 'content_and_artifact',+ },+ );+}++/**+ * Animate a rigged GLB from a text prompt. This is a PAID, x402-gated tool on+ * three.ws's main MCP server: calling it without a payment returns the raw+ * x402 PaymentRequired challenge as the tool's artifact instead of a model,+ * and this package never signs or sends that payment for you. Resolve the+ * challenge with your own x402 client against your own wallet (e.g. the+ * `x402-fetch` package), then pass the resulting header value in as+ * `xPayment`.+ */+export function createAnimateTool({ baseUrl, apiKey } = {}) {+ return tool(+ async ({ glbUrl, prompt, xPayment }) => {+ const res = await callThreeWsTool({+ baseUrl,+ surface: 'paid',+ tool: 'text_to_animation',+ args: { glb_url: glbUrl, prompt },+ apiKey,+ xPayment,+ });+ if (res.paymentRequired) {+ return [+ 'payment required: this is a paid three.ws tool. Resolve res.artifact.challenge with your own x402 client and retry with xPayment set.',+ { ok: false, paymentRequired: true, challenge: res.challenge },+ ];+ }+ if (!res.ok) return [`animate failed: ${res.error}`, { ok: false, error: res.error }];+ return [toolResultText(res.result), { ok: true, raw: res.result.structuredContent ?? null }];+ },+ {+ name: 'three_ws_animate',+ description:+ 'Retarget a text-described motion onto a rigged humanoid GLB (e.g. one three_ws_rig just produced). PAID: ' ++ 'returns an x402 payment challenge unless a pre-signed X-PAYMENT value is supplied.',+ schema: z.object({+ glbUrl: z.string().url().describe('http(s) URL to a rigged GLB to animate.'),+ prompt: z.string().min(1).max(500).describe('The motion to generate, e.g. "wave hello", "walk forward".'),+ xPayment: z.string().optional().describe('A pre-signed x402 X-PAYMENT header value from your own wallet/x402 client.'),+ }),+ responseFormat: 'content_and_artifact',+ },+ );+}++export function createAgentChatTool({ baseUrl } = {}) {+ return tool(+ async ({ message, agentId }) => {+ const done = await callThreeWsChat({ baseUrl, message, agentId });+ return [done.reply, { ok: true, model: done.model, provider: done.provider }];+ },+ {+ name: 'three_ws_agent_chat',+ description: 'Send a message to a three.ws agent (or the default viewer agent) and get its reply. Free, no API key required.',+ schema: z.object({+ message: z.string().min(1).describe('What to say to the agent.'),+ agentId: z.string().uuid().optional().describe('A specific three.ws agent UUID; omit for the default agent.'),+ }),+ responseFormat: 'content_and_artifact',+ },+ );+}diff --git a/packages/langchain/test/tools.test.js b/packages/langchain/test/tools.test.jsnew file mode 100644index 000000000..6eaf6113a--- /dev/null+++ b/packages/langchain/test/tools.test.js@@ -0,0 +1,53 @@+// Tests run against the LIVE three.ws API (https://three.ws), per repo policy:+// no mocks. `render` and `agentChat` hit free, stable endpoints and assert a+// real success. `forge`/`rig` hit the free GPU-worker-fleet generation path,+// which can genuinely fail independently of this package (queue load, a+// provider outage), those two assert the tool returns a well-formed artifact+// either way, without fabricating success. `animate` is paid and x402-gated;+// it asserts the real PaymentRequired challenge comes back unpaid, since this+// package must never sign a payment itself.++import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createThreeWsTools } from '../src/index.js';++const DUCK_GLB = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb';++const [forgeTool, rigTool, renderTool, animateTool, agentChatTool] = createThreeWsTools();++// `tool.invoke(rawArgs)` returns only the string content; invoking with a+// ToolCall shape (name/args/id/type) returns the full ToolMessage, whose+// `.artifact` carries the structured half of `content_and_artifact`.+function asToolCall(name, args) {+ return { name, args, id: `test-${name}`, type: 'tool_call' };+}++test('three_ws_render: turntable preview of a public GLB', async () => {+ const msg = await renderTool.invoke(asToolCall('three_ws_render', { glbUrl: DUCK_GLB, views: ['front'], size: 256 }));+ assert.match(msg.content, /Rendered this model/);+ assert.equal(msg.artifact.ok, true);+});++test('three_ws_agent_chat: the default agent replies to a message', async () => {+ const msg = await agentChatTool.invoke(asToolCall('three_ws_agent_chat', { message: 'Reply with exactly the word: pong' }));+ assert.equal(typeof msg.content, 'string');+ assert.ok(msg.content.length > 0);+ assert.equal(msg.artifact.ok, true);+});++test('three_ws_forge: generates a model from text, or reports the real failure', async () => {+ const msg = await forgeTool.invoke(asToolCall('three_ws_forge', { prompt: 'a small red toy cube', tier: 'draft' }));+ assert.equal(typeof msg.artifact.ok, 'boolean');+});++test('three_ws_rig: rigs a static GLB, or reports the real failure', async () => {+ const msg = await rigTool.invoke(asToolCall('three_ws_rig', { glbUrl: DUCK_GLB }));+ assert.equal(typeof msg.artifact.ok, 'boolean');+});++test('three_ws_animate: unpaid call returns a real x402 PaymentRequired challenge', async () => {+ const msg = await animateTool.invoke(asToolCall('three_ws_animate', { glbUrl: DUCK_GLB, prompt: 'wave hello' }));+ assert.equal(msg.artifact.ok, false);+ assert.equal(msg.artifact.paymentRequired, true);+ assert.ok(Array.isArray(msg.artifact.challenge?.accepts) && msg.artifact.challenge.accepts.length > 0);+});