@react-grab/opencode 0.0.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aiden Bai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # @react-grab/opencode
2
+
3
+ Opencode agent provider for React Grab. Requires running a local server that interfaces with the Opencode CLI.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @react-grab/opencode
9
+ # or
10
+ pnpm add @react-grab/opencode
11
+ # or
12
+ bun add @react-grab/opencode
13
+ # or
14
+ yarn add @react-grab/opencode
15
+ ```
16
+
17
+ ## Server Setup
18
+
19
+ The server runs on port `6567` by default.
20
+
21
+ ### Quick Start (CLI)
22
+
23
+ Start the server in the background before running your dev server:
24
+
25
+ ```bash
26
+ npx @react-grab/opencode@latest && pnpm run dev
27
+ ```
28
+
29
+ The server will run as a detached background process. **Note:** Stopping your dev server (Ctrl+C) won't stop the React Grab server. To stop it:
30
+
31
+ ```bash
32
+ pkill -f "react-grab.*server"
33
+ ```
34
+
35
+ ### Recommended: Config File (Automatic Lifecycle)
36
+
37
+ For better lifecycle management, start the server from your config file. This ensures the server stops when your dev server stops:
38
+
39
+ ### Vite
40
+
41
+ ```ts
42
+ // vite.config.ts
43
+ import { startServer } from "@react-grab/opencode/server";
44
+
45
+ if (process.env.NODE_ENV === "development") {
46
+ startServer();
47
+ }
48
+ ```
49
+
50
+ ### Next.js
51
+
52
+ ```ts
53
+ // next.config.ts
54
+ import { startServer } from "@react-grab/opencode/server";
55
+
56
+ if (process.env.NODE_ENV === "development") {
57
+ startServer();
58
+ }
59
+ ```
60
+
61
+ > **Note:** You must have [Opencode](https://opencode.ai) installed (`npm i -g opencode-ai@latest`).
62
+
63
+ ## Client Usage
64
+
65
+ ### Script Tag
66
+
67
+ ```html
68
+ <script src="//unpkg.com/react-grab/dist/index.global.js"></script>
69
+ <script src="//unpkg.com/@react-grab/opencode/dist/client.global.js"></script>
70
+ ```
71
+
72
+ ### Next.js
73
+
74
+ Using the `Script` component in your `app/layout.tsx`:
75
+
76
+ ```jsx
77
+ import Script from "next/script";
78
+
79
+ export default function RootLayout({ children }) {
80
+ return (
81
+ <html>
82
+ <head>
83
+ {process.env.NODE_ENV === "development" && (
84
+ <>
85
+ <Script
86
+ src="//unpkg.com/react-grab/dist/index.global.js"
87
+ strategy="beforeInteractive"
88
+ />
89
+ <Script
90
+ src="//unpkg.com/@react-grab/opencode/dist/client.global.js"
91
+ strategy="lazyOnload"
92
+ />
93
+ </>
94
+ )}
95
+ </head>
96
+ <body>{children}</body>
97
+ </html>
98
+ );
99
+ }
100
+ ```
101
+
102
+ ### ES Module
103
+
104
+ ```tsx
105
+ import { attachAgent } from "@react-grab/opencode/client";
106
+
107
+ attachAgent();
108
+ ```
109
+
110
+ ## Options
111
+
112
+ You can configure the Opencode agent provider:
113
+
114
+ ```typescript
115
+ import { createOpencodeAgentProvider } from "@react-grab/opencode/client";
116
+
117
+ const provider = createOpencodeAgentProvider({
118
+ serverUrl: "http://localhost:6567", // Custom server URL
119
+ getOptions: () => ({
120
+ model: "claude-sonnet-4-20250514", // AI model to use
121
+ agent: "build", // Agent type: "build" or "plan"
122
+ directory: "/path/to/project", // Project directory
123
+ }),
124
+ });
125
+ ```
126
+
127
+ ## How It Works
128
+
129
+ ```
130
+ ┌─────────────────┐ HTTP ┌─────────────────┐ stdin ┌─────────────────┐
131
+ │ │ localhost:6567 │ │ │ │
132
+ │ React Grab │ ──────────────► │ Server │ ─────────────► │ opencode │
133
+ │ (Browser) │ ◄────────────── │ (Node.js) │ ◄───────────── │ (CLI) │
134
+ │ │ SSE │ │ stdout │ │
135
+ └─────────────────┘ └─────────────────┘ └─────────────────┘
136
+ Client Server Agent
137
+ ```
138
+
139
+ 1. **React Grab** sends the selected element context to the server via HTTP POST
140
+ 2. **Server** receives the request and spawns the `opencode` CLI process
141
+ 3. **Opencode** processes the request and streams JSON responses to stdout
142
+ 4. **Server** relays status updates to the client via Server-Sent Events (SSE)
package/dist/cli.cjs ADDED
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var child_process = require('child_process');
5
+ var url = require('url');
6
+ var path = require('path');
7
+
8
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
+ var __create = Object.create;
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __getProtoOf = Object.getPrototypeOf;
14
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __commonJS = (cb, mod) => function __require() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
32
+ mod
33
+ ));
34
+
35
+ // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
36
+ var require_picocolors = __commonJS({
37
+ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
38
+ var p = process || {};
39
+ var argv = p.argv || [];
40
+ var env = p.env || {};
41
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
42
+ var formatter = (open, close, replace = open) => (input) => {
43
+ let string = "" + input, index = string.indexOf(close, open.length);
44
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
45
+ };
46
+ var replaceClose = (string, close, replace, index) => {
47
+ let result = "", cursor = 0;
48
+ do {
49
+ result += string.substring(cursor, index) + replace;
50
+ cursor = index + close.length;
51
+ index = string.indexOf(close, cursor);
52
+ } while (~index);
53
+ return result + string.substring(cursor);
54
+ };
55
+ var createColors = (enabled = isColorSupported) => {
56
+ let f = enabled ? formatter : () => String;
57
+ return {
58
+ isColorSupported: enabled,
59
+ reset: f("\x1B[0m", "\x1B[0m"),
60
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
61
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
62
+ italic: f("\x1B[3m", "\x1B[23m"),
63
+ underline: f("\x1B[4m", "\x1B[24m"),
64
+ inverse: f("\x1B[7m", "\x1B[27m"),
65
+ hidden: f("\x1B[8m", "\x1B[28m"),
66
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
67
+ black: f("\x1B[30m", "\x1B[39m"),
68
+ red: f("\x1B[31m", "\x1B[39m"),
69
+ green: f("\x1B[32m", "\x1B[39m"),
70
+ yellow: f("\x1B[33m", "\x1B[39m"),
71
+ blue: f("\x1B[34m", "\x1B[39m"),
72
+ magenta: f("\x1B[35m", "\x1B[39m"),
73
+ cyan: f("\x1B[36m", "\x1B[39m"),
74
+ white: f("\x1B[37m", "\x1B[39m"),
75
+ gray: f("\x1B[90m", "\x1B[39m"),
76
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
77
+ bgRed: f("\x1B[41m", "\x1B[49m"),
78
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
79
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
80
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
81
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
82
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
83
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
84
+ blackBright: f("\x1B[90m", "\x1B[39m"),
85
+ redBright: f("\x1B[91m", "\x1B[39m"),
86
+ greenBright: f("\x1B[92m", "\x1B[39m"),
87
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
88
+ blueBright: f("\x1B[94m", "\x1B[39m"),
89
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
90
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
91
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
92
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
93
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
94
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
95
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
96
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
97
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
98
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
99
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
100
+ };
101
+ };
102
+ module.exports = createColors();
103
+ module.exports.createColors = createColors;
104
+ }
105
+ });
106
+
107
+ // src/cli.ts
108
+ var import_picocolors = __toESM(require_picocolors());
109
+
110
+ // src/constants.ts
111
+ var DEFAULT_PORT = 6567;
112
+
113
+ // src/cli.ts
114
+ var VERSION = "0.0.68";
115
+ var __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
116
+ var __dirname$1 = path.dirname(__filename$1);
117
+ var serverPath = path.join(__dirname$1, "server.js");
118
+ child_process.spawn(process.execPath, [serverPath], {
119
+ detached: true,
120
+ stdio: "ignore"
121
+ }).unref();
122
+ console.log(`${import_picocolors.default.magenta("\u269B")} ${import_picocolors.default.bold("React Grab")} ${import_picocolors.default.gray(VERSION)} ${import_picocolors.default.dim("(Opencode)")}`);
123
+ console.log(`- Local: ${import_picocolors.default.cyan(`http://localhost:${DEFAULT_PORT}`)}`);
package/dist/cli.js ADDED
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'child_process';
3
+ import { fileURLToPath } from 'url';
4
+ import { dirname, join } from 'path';
5
+
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __commonJS = (cb, mod) => function __require() {
13
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
29
+ mod
30
+ ));
31
+
32
+ // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
33
+ var require_picocolors = __commonJS({
34
+ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
35
+ var p = process || {};
36
+ var argv = p.argv || [];
37
+ var env = p.env || {};
38
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
39
+ var formatter = (open, close, replace = open) => (input) => {
40
+ let string = "" + input, index = string.indexOf(close, open.length);
41
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
42
+ };
43
+ var replaceClose = (string, close, replace, index) => {
44
+ let result = "", cursor = 0;
45
+ do {
46
+ result += string.substring(cursor, index) + replace;
47
+ cursor = index + close.length;
48
+ index = string.indexOf(close, cursor);
49
+ } while (~index);
50
+ return result + string.substring(cursor);
51
+ };
52
+ var createColors = (enabled = isColorSupported) => {
53
+ let f = enabled ? formatter : () => String;
54
+ return {
55
+ isColorSupported: enabled,
56
+ reset: f("\x1B[0m", "\x1B[0m"),
57
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
58
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
59
+ italic: f("\x1B[3m", "\x1B[23m"),
60
+ underline: f("\x1B[4m", "\x1B[24m"),
61
+ inverse: f("\x1B[7m", "\x1B[27m"),
62
+ hidden: f("\x1B[8m", "\x1B[28m"),
63
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
64
+ black: f("\x1B[30m", "\x1B[39m"),
65
+ red: f("\x1B[31m", "\x1B[39m"),
66
+ green: f("\x1B[32m", "\x1B[39m"),
67
+ yellow: f("\x1B[33m", "\x1B[39m"),
68
+ blue: f("\x1B[34m", "\x1B[39m"),
69
+ magenta: f("\x1B[35m", "\x1B[39m"),
70
+ cyan: f("\x1B[36m", "\x1B[39m"),
71
+ white: f("\x1B[37m", "\x1B[39m"),
72
+ gray: f("\x1B[90m", "\x1B[39m"),
73
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
74
+ bgRed: f("\x1B[41m", "\x1B[49m"),
75
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
76
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
77
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
78
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
79
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
80
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
81
+ blackBright: f("\x1B[90m", "\x1B[39m"),
82
+ redBright: f("\x1B[91m", "\x1B[39m"),
83
+ greenBright: f("\x1B[92m", "\x1B[39m"),
84
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
85
+ blueBright: f("\x1B[94m", "\x1B[39m"),
86
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
87
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
88
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
89
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
90
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
91
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
92
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
93
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
94
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
95
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
96
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
97
+ };
98
+ };
99
+ module.exports = createColors();
100
+ module.exports.createColors = createColors;
101
+ }
102
+ });
103
+
104
+ // src/cli.ts
105
+ var import_picocolors = __toESM(require_picocolors());
106
+
107
+ // src/constants.ts
108
+ var DEFAULT_PORT = 6567;
109
+
110
+ // src/cli.ts
111
+ var VERSION = "0.0.68";
112
+ var __filename = fileURLToPath(import.meta.url);
113
+ var __dirname = dirname(__filename);
114
+ var serverPath = join(__dirname, "server.js");
115
+ spawn(process.execPath, [serverPath], {
116
+ detached: true,
117
+ stdio: "ignore"
118
+ }).unref();
119
+ console.log(`${import_picocolors.default.magenta("\u269B")} ${import_picocolors.default.bold("React Grab")} ${import_picocolors.default.gray(VERSION)} ${import_picocolors.default.dim("(Opencode)")}`);
120
+ console.log(`- Local: ${import_picocolors.default.cyan(`http://localhost:${DEFAULT_PORT}`)}`);
@@ -0,0 +1,119 @@
1
+ 'use strict';
2
+
3
+ // src/constants.ts
4
+ var DEFAULT_PORT = 6567;
5
+
6
+ // src/client.ts
7
+ var DEFAULT_SERVER_URL = `http://localhost:${DEFAULT_PORT}`;
8
+ var STORAGE_KEY = "react-grab:agent-sessions";
9
+ var parseServerSentEvent = (eventStringBlock) => {
10
+ let eventType = "";
11
+ let data = "";
12
+ for (const line of eventStringBlock.split("\n")) {
13
+ if (line.startsWith("event:")) eventType = line.slice(6).trim();
14
+ else if (line.startsWith("data:")) data = line.slice(5).trim();
15
+ }
16
+ return { eventType, data };
17
+ };
18
+ var streamSSE = async function* (stream) {
19
+ const streamReader = stream.getReader();
20
+ const textDecoder = new TextDecoder();
21
+ let textBuffer = "";
22
+ try {
23
+ while (true) {
24
+ const { done, value } = await streamReader.read();
25
+ if (value) textBuffer += textDecoder.decode(value, { stream: true });
26
+ let boundaryIndex;
27
+ while ((boundaryIndex = textBuffer.indexOf("\n\n")) !== -1) {
28
+ const { eventType, data } = parseServerSentEvent(
29
+ textBuffer.slice(0, boundaryIndex)
30
+ );
31
+ textBuffer = textBuffer.slice(boundaryIndex + 2);
32
+ if (eventType === "done") return;
33
+ if (eventType === "error") throw new Error(data || "Agent error");
34
+ if (data) yield data;
35
+ }
36
+ if (done) break;
37
+ }
38
+ } finally {
39
+ streamReader.releaseLock();
40
+ }
41
+ };
42
+ var streamFromServer = async function* (serverUrl, context, signal) {
43
+ const response = await fetch(`${serverUrl}/agent`, {
44
+ method: "POST",
45
+ headers: { "Content-Type": "application/json" },
46
+ body: JSON.stringify(context),
47
+ signal
48
+ });
49
+ if (!response.ok) {
50
+ throw new Error(`Server error: ${response.status}`);
51
+ }
52
+ if (!response.body) {
53
+ throw new Error("No response body");
54
+ }
55
+ yield* streamSSE(response.body);
56
+ };
57
+ var createOpencodeAgentProvider = (options = {}) => {
58
+ const { serverUrl = DEFAULT_SERVER_URL, getOptions } = options;
59
+ const mergeOptions = (contextOptions) => ({
60
+ ...getOptions?.() ?? {},
61
+ ...contextOptions ?? {}
62
+ });
63
+ return {
64
+ send: async function* (context, signal) {
65
+ const combinedContext = {
66
+ ...context,
67
+ options: mergeOptions(context.options)
68
+ };
69
+ yield* streamFromServer(serverUrl, combinedContext, signal);
70
+ },
71
+ resume: async function* (sessionId, signal, storage) {
72
+ const storedSessions = storage.getItem(STORAGE_KEY);
73
+ if (!storedSessions) {
74
+ throw new Error("No sessions to resume");
75
+ }
76
+ const parsedSessions = JSON.parse(storedSessions);
77
+ const session = parsedSessions[sessionId];
78
+ if (!session) {
79
+ throw new Error(`Session ${sessionId} not found`);
80
+ }
81
+ const context = session.context;
82
+ const combinedContext = {
83
+ ...context,
84
+ options: mergeOptions(context.options)
85
+ };
86
+ yield "Resuming...";
87
+ yield* streamFromServer(serverUrl, combinedContext, signal);
88
+ },
89
+ supportsResume: true
90
+ };
91
+ };
92
+ var attachAgent = async () => {
93
+ if (typeof window === "undefined") return;
94
+ const provider = createOpencodeAgentProvider();
95
+ const api = window.__REACT_GRAB__;
96
+ if (api) {
97
+ api.setAgent({ provider, storage: sessionStorage });
98
+ return;
99
+ }
100
+ window.addEventListener(
101
+ "react-grab:init",
102
+ (event) => {
103
+ if (event instanceof CustomEvent) {
104
+ const customEvent = event;
105
+ if (customEvent.detail && typeof customEvent.detail.setAgent === "function") {
106
+ customEvent.detail.setAgent({
107
+ provider,
108
+ storage: sessionStorage
109
+ });
110
+ }
111
+ }
112
+ },
113
+ { once: true }
114
+ );
115
+ };
116
+ attachAgent();
117
+
118
+ exports.attachAgent = attachAgent;
119
+ exports.createOpencodeAgentProvider = createOpencodeAgentProvider;
@@ -0,0 +1,4 @@
1
+ var ReactGrabOpencode=(function(exports){'use strict';var l=`http://localhost:${6567}`,O="react-grab:agent-sessions",S=o=>{let t="",n="";for(let e of o.split(`
2
+ `))e.startsWith("event:")?t=e.slice(6).trim():e.startsWith("data:")&&(n=e.slice(5).trim());return {eventType:t,data:n}},y=async function*(o){let t=o.getReader(),n=new TextDecoder,e="";try{for(;;){let{done:r,value:i}=await t.read();i&&(e+=n.decode(i,{stream:!0}));let s;for(;(s=e.indexOf(`
3
+
4
+ `))!==-1;){let{eventType:a,data:c}=S(e.slice(0,s));if(e=e.slice(s+2),a==="done")return;if(a==="error")throw new Error(c||"Agent error");c&&(yield c);}if(r)break}}finally{t.releaseLock();}},p=async function*(o,t,n){let e=await fetch(`${o}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n});if(!e.ok)throw new Error(`Server error: ${e.status}`);if(!e.body)throw new Error("No response body");yield*y(e.body);},u=(o={})=>{let{serverUrl:t=l,getOptions:n}=o,e=r=>({...n?.()??{},...r??{}});return {send:async function*(r,i){let s={...r,options:e(r.options)};yield*p(t,s,i);},resume:async function*(r,i,s){let a=s.getItem(O);if(!a)throw new Error("No sessions to resume");let d=JSON.parse(a)[r];if(!d)throw new Error(`Session ${r} not found`);let g=d.context,f={...g,options:e(g.options)};yield "Resuming...",yield*p(t,f,i);},supportsResume:true}},m=async()=>{if(typeof window>"u")return;let o=u(),t=window.__REACT_GRAB__;if(t){t.setAgent({provider:o,storage:sessionStorage});return}window.addEventListener("react-grab:init",n=>{if(n instanceof CustomEvent){let e=n;e.detail&&typeof e.detail.setAgent=="function"&&e.detail.setAgent({provider:o,storage:sessionStorage});}},{once:true});};m();exports.attachAgent=m;exports.createOpencodeAgentProvider=u;return exports;})({});
package/dist/client.js ADDED
@@ -0,0 +1,116 @@
1
+ // src/constants.ts
2
+ var DEFAULT_PORT = 6567;
3
+
4
+ // src/client.ts
5
+ var DEFAULT_SERVER_URL = `http://localhost:${DEFAULT_PORT}`;
6
+ var STORAGE_KEY = "react-grab:agent-sessions";
7
+ var parseServerSentEvent = (eventStringBlock) => {
8
+ let eventType = "";
9
+ let data = "";
10
+ for (const line of eventStringBlock.split("\n")) {
11
+ if (line.startsWith("event:")) eventType = line.slice(6).trim();
12
+ else if (line.startsWith("data:")) data = line.slice(5).trim();
13
+ }
14
+ return { eventType, data };
15
+ };
16
+ var streamSSE = async function* (stream) {
17
+ const streamReader = stream.getReader();
18
+ const textDecoder = new TextDecoder();
19
+ let textBuffer = "";
20
+ try {
21
+ while (true) {
22
+ const { done, value } = await streamReader.read();
23
+ if (value) textBuffer += textDecoder.decode(value, { stream: true });
24
+ let boundaryIndex;
25
+ while ((boundaryIndex = textBuffer.indexOf("\n\n")) !== -1) {
26
+ const { eventType, data } = parseServerSentEvent(
27
+ textBuffer.slice(0, boundaryIndex)
28
+ );
29
+ textBuffer = textBuffer.slice(boundaryIndex + 2);
30
+ if (eventType === "done") return;
31
+ if (eventType === "error") throw new Error(data || "Agent error");
32
+ if (data) yield data;
33
+ }
34
+ if (done) break;
35
+ }
36
+ } finally {
37
+ streamReader.releaseLock();
38
+ }
39
+ };
40
+ var streamFromServer = async function* (serverUrl, context, signal) {
41
+ const response = await fetch(`${serverUrl}/agent`, {
42
+ method: "POST",
43
+ headers: { "Content-Type": "application/json" },
44
+ body: JSON.stringify(context),
45
+ signal
46
+ });
47
+ if (!response.ok) {
48
+ throw new Error(`Server error: ${response.status}`);
49
+ }
50
+ if (!response.body) {
51
+ throw new Error("No response body");
52
+ }
53
+ yield* streamSSE(response.body);
54
+ };
55
+ var createOpencodeAgentProvider = (options = {}) => {
56
+ const { serverUrl = DEFAULT_SERVER_URL, getOptions } = options;
57
+ const mergeOptions = (contextOptions) => ({
58
+ ...getOptions?.() ?? {},
59
+ ...contextOptions ?? {}
60
+ });
61
+ return {
62
+ send: async function* (context, signal) {
63
+ const combinedContext = {
64
+ ...context,
65
+ options: mergeOptions(context.options)
66
+ };
67
+ yield* streamFromServer(serverUrl, combinedContext, signal);
68
+ },
69
+ resume: async function* (sessionId, signal, storage) {
70
+ const storedSessions = storage.getItem(STORAGE_KEY);
71
+ if (!storedSessions) {
72
+ throw new Error("No sessions to resume");
73
+ }
74
+ const parsedSessions = JSON.parse(storedSessions);
75
+ const session = parsedSessions[sessionId];
76
+ if (!session) {
77
+ throw new Error(`Session ${sessionId} not found`);
78
+ }
79
+ const context = session.context;
80
+ const combinedContext = {
81
+ ...context,
82
+ options: mergeOptions(context.options)
83
+ };
84
+ yield "Resuming...";
85
+ yield* streamFromServer(serverUrl, combinedContext, signal);
86
+ },
87
+ supportsResume: true
88
+ };
89
+ };
90
+ var attachAgent = async () => {
91
+ if (typeof window === "undefined") return;
92
+ const provider = createOpencodeAgentProvider();
93
+ const api = window.__REACT_GRAB__;
94
+ if (api) {
95
+ api.setAgent({ provider, storage: sessionStorage });
96
+ return;
97
+ }
98
+ window.addEventListener(
99
+ "react-grab:init",
100
+ (event) => {
101
+ if (event instanceof CustomEvent) {
102
+ const customEvent = event;
103
+ if (customEvent.detail && typeof customEvent.detail.setAgent === "function") {
104
+ customEvent.detail.setAgent({
105
+ provider,
106
+ storage: sessionStorage
107
+ });
108
+ }
109
+ }
110
+ },
111
+ { once: true }
112
+ );
113
+ };
114
+ attachAgent();
115
+
116
+ export { attachAgent, createOpencodeAgentProvider };