@react-grab/opencode 0.0.98 → 0.1.0-beta.0

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.
@@ -1,5 +1,2 @@
1
- var ReactGrabOpenCode=(function(exports){'use strict';var m=5e3,O="react-grab:agent-sessions",b=t=>{let e="",o="";for(let r of t.split(`
2
- `))r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&(o=r.slice(5).trim());return {eventType:e,data:o}},v=async function*(t,e){let o=t.getReader(),r=new TextDecoder,n="",s=false,a=()=>{s=true,o.cancel().catch(()=>{});};e.addEventListener("abort",a);try{if(e.aborted)throw new DOMException("Aborted","AbortError");for(;;){let d=await o.read();if(s||e.aborted)throw new DOMException("Aborted","AbortError");let{done:i,value:p}=d;p&&(n+=r.decode(p,{stream:!0}));let c;for(;(c=n.indexOf(`
3
-
4
- `))!==-1;){let{eventType:f,data:l}=b(n.slice(0,c));if(n=n.slice(c+2),f==="done")return;if(f==="error")throw new Error(l||"Agent error");l&&(yield l);}if(i)break}}finally{e.removeEventListener("abort",a);try{o.releaseLock();}catch{}}},A=t=>typeof t=="object"&&t!==null,S=(t,e,o=O)=>{let r=t.getItem(o);if(!r)throw new Error("No sessions to resume");let n;try{n=JSON.parse(r);}catch{throw new Error("Failed to parse stored sessions")}if(!A(n))throw new Error("Invalid stored sessions");let s=n[e];if(!A(s))throw new Error(`Session ${e} not found`);let a=s.context;if(!A(a))throw new Error(`Session ${e} is invalid`);let d=a.content,i=a.prompt;if(!Array.isArray(d)||typeof i!="string")throw new Error(`Session ${e} is invalid`);let p=a.options,c=a.sessionId;return {content:d,prompt:i,options:p,sessionId:typeof c=="string"?c:void 0}},y=async function*(t,e,o){let r=Date.now(),n=e.sessionId,s=t.pollIntervalMs??100,a=`${t.serverUrl}${t.agentPath??"/agent"}`,d=()=>{if(!n)return;let i=t.abortPath?.(n)??`/abort/${n}`;fetch(`${t.serverUrl}${i}`,{method:"POST"}).catch(()=>{});};o.addEventListener("abort",d);try{let i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:o});if(!i.ok)throw new Error(`Server error: ${i.status}`);if(!i.body)throw new Error("No response body");let p=v(i.body,o)[Symbol.asyncIterator](),c=!1,f=p.next(),l=null;for(;!c;){let C=await Promise.race([f.then(u=>({type:"status",iteratorResult:u})),new Promise(u=>setTimeout(()=>u({type:"timeout"}),s))]),g=(Date.now()-r)/1e3;if(C.type==="status"){let u=C.iteratorResult;c=u.done??!1,!c&&u.value&&(l=u.value,f=p.next());}l===t.completedStatus?yield `Completed in ${g.toFixed(1)}s`:l?yield `${l} ${g.toFixed(1)}s`:yield `Working\u2026 ${g.toFixed(1)}s`;}}finally{o.removeEventListener("abort",d);}},E=(t,e=m)=>{let o=null;return async()=>{let r=Date.now();if(o&&r-o.timestamp<e)return o.result;try{let n=await t();return o={result:n,timestamp:r},n}catch{return o={result:false,timestamp:r},false}}};var w="Completed successfully";var x=`http://localhost:${6567}`,h=t=>typeof t=="object"&&t!==null&&"setAgent"in t,_=(t={})=>{let{serverUrl:e=x,getOptions:o}=t,r=s=>({...o?.()??{},...s??{}}),n=E(async()=>(await fetch(`${e}/health`,{method:"GET"})).ok,m);return {send:async function*(s,a){let d={...s,options:r(s.options)};yield*y({serverUrl:e,completedStatus:w},d,a);},resume:async function*(s,a,d){let i=S(d,s),p={content:i.content,prompt:i.prompt,options:i.options,sessionId:i.sessionId??s},c={...p,options:r(p.options)};yield "Resuming...",yield*y({serverUrl:e,completedStatus:w},c,a);},supportsResume:true,supportsFollowUp:true,checkConnection:n,undo:async()=>{try{await fetch(`${e}/undo`,{method:"POST"});}catch{}}}},R=async()=>{if(typeof window>"u")return;let t=_(),e=n=>{n.setAgent({provider:t,storage:sessionStorage});},o=window.__REACT_GRAB__;if(h(o)){e(o);return}window.addEventListener("react-grab:init",n=>{n instanceof CustomEvent&&h(n.detail)&&e(n.detail);},{once:true});let r=window.__REACT_GRAB__;h(r)&&e(r);};R();
5
- exports.attachAgent=R;exports.createOpenCodeAgentProvider=_;return exports;})({});
1
+ var ReactGrabOpenCode=(function(exports){'use strict';var q=4722,x=3e3,D="token",G=(i={})=>{let n=i.serverUrl??`ws://localhost:${q}`,c=i.autoReconnect??true,E=i.reconnectIntervalMs??x,h=i.token,s=null,f=false,p=[],A=null,t=null,o=null,w=false,y=new Set,g=new Set,r=new Set,d=()=>{!c||A||w||(A=setTimeout(()=>{A=null,C().catch(()=>{});},E));},l=e=>{try{let a=JSON.parse(e.data);if(a.type==="handlers"&&a.handlers){p=a.handlers;for(let S of g)S(p);}for(let S of y)S(a);}catch{}},C=()=>s?.readyState===WebSocket.OPEN?Promise.resolve():t||(w=false,t=new Promise((e,a)=>{o=a;let S=h?`${n}?${D}=${encodeURIComponent(h)}`:n;s=new WebSocket(S),s.onopen=()=>{t=null,o=null,f=true;for(let P of r)P(true);e();},s.onmessage=l,s.onclose=()=>{o&&(o(new Error("WebSocket connection closed")),o=null),t=null,f=false,p=[];for(let P of g)P(p);for(let P of r)P(false);d();},s.onerror=()=>{t=null,o=null,f=false,a(new Error("WebSocket connection failed"));};}),t),v=()=>{w=true,A&&(clearTimeout(A),A=null),o&&(o(new Error("Connection aborted")),o=null),t=null,s?.close(),s=null,f=false,p=[];},m=()=>f,R=e=>s?.readyState===WebSocket.OPEN?(s.send(JSON.stringify(e)),true):false;return {connect:C,disconnect:v,isConnected:m,sendAgentRequest:(e,a)=>R({type:"agent-request",agentId:e,sessionId:a.sessionId,context:a}),abortAgent:(e,a)=>{R({type:"agent-abort",agentId:e,sessionId:a});},undoAgent:(e,a)=>R({type:"agent-undo",agentId:e,sessionId:a}),redoAgent:(e,a)=>R({type:"agent-redo",agentId:e,sessionId:a}),onMessage:e=>(y.add(e),()=>y.delete(e)),onHandlersChange:e=>(g.add(e),()=>g.delete(e)),onConnectionChange:e=>(r.add(e),queueMicrotask(()=>{r.has(e)&&e(f);}),()=>r.delete(e)),getAvailableHandlers:()=>p}},I=i=>{let{relayClient:n,agentId:c}=i,E=async()=>{if(!n.isConnected())try{await n.connect();}catch{return false}return n.getAvailableHandlers().includes(c)},h=async function*(t,o){if(o.aborted)throw new DOMException("Aborted","AbortError");yield "Connecting\u2026";let w=t.sessionId??`session-${Date.now()}-${Math.random().toString(36).slice(2)}`,y={...t,sessionId:w},g=[],r=null,d=null,l=false,C=null,v=()=>{n.abortAgent(c,w),l=true,r&&(r({value:void 0,done:true}),r=null,d=null);};o.addEventListener("abort",v);let m=u=>{!u&&!l&&(C="Relay connection lost",l=true,d&&(d(new Error(C)),r=null,d=null));},R=n.onConnectionChange(m),M=n.onMessage(u=>{if(u.sessionId===w)if(u.type==="agent-status"&&u.content){if(g.push(u.content),r){let b=g.shift();b!==void 0&&(r({value:b,done:false}),r=null,d=null);}}else u.type==="agent-done"?(l=true,r&&(r({value:void 0,done:true}),r=null,d=null)):u.type==="agent-error"&&(C=u.content??"Unknown error",l=true,d&&(d(new Error(C)),r=null,d=null));});if(!n.isConnected())throw R(),M(),o.removeEventListener("abort",v),new Error("Relay connection is not open");if(!n.sendAgentRequest(c,y))throw R(),M(),o.removeEventListener("abort",v),new Error("Failed to send agent request: connection not open");try{for(;;){if(g.length>0){let b=g.shift();b!==void 0&&(yield b);continue}if(l||o.aborted)break;let u=await new Promise((b,O)=>{r=b,d=O;});if(u.done)break;yield u.value;}if(C)throw new Error(C)}finally{o.removeEventListener("abort",v),R(),M();}},s=async t=>{n.abortAgent(c,t);},f=t=>new Promise((o,w)=>{let y=false,g=()=>{y||(y=true,r(),d());},r=n.onMessage(l=>{l.sessionId===t&&(g(),l.type==="agent-done"?o():l.type==="agent-error"&&w(new Error(l.content??"Operation failed")));}),d=n.onConnectionChange(l=>{l||(g(),w(new Error("Connection lost while waiting for operation response")));});});return {send:h,abort:s,undo:async()=>{let t=`undo-${c}-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!n.undoAgent(c,t))throw new Error("Failed to send undo request: connection not open");return f(t)},redo:async()=>{let t=`redo-${c}-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!n.redoAgent(c,t))throw new Error("Failed to send redo request: connection not open");return f(t)},checkConnection:E,supportsResume:true,supportsFollowUp:true}},_=null,k=()=>typeof window>"u"?null:window.__REACT_GRAB_RELAY__?(_=window.__REACT_GRAB_RELAY__,_):(_||(_=G(),window.__REACT_GRAB_RELAY__=_),_);var L="opencode",T=i=>typeof i=="object"&&i!==null&&"registerPlugin"in i,Y=(i={})=>{let n=i.relayClient??k();if(!n)throw new Error("RelayClient is required in browser environments");return I({relayClient:n,agentId:L})},N=async()=>{if(typeof window>"u")return;let i=k();if(!i)return;try{await i.connect();}catch{return}let n=I({relayClient:i,agentId:L}),c=s=>{let f={provider:n,storage:sessionStorage},p={name:"opencode-agent",actions:[{id:"edit-with-opencode",label:"Edit with OpenCode",shortcut:"Enter",onAction:A=>{A.enterPromptMode?.(f);},agent:f}]};s.registerPlugin(p);},E=window.__REACT_GRAB__;if(T(E)){c(E);return}window.addEventListener("react-grab:init",s=>{s instanceof CustomEvent&&T(s.detail)&&c(s.detail);},{once:true});let h=window.__REACT_GRAB__;T(h)&&c(h);};N();
2
+ exports.attachAgent=N;exports.createOpenCodeAgentProvider=Y;return exports;})({});
package/dist/client.js CHANGED
@@ -1,228 +1,414 @@
1
- // ../utils/dist/client.js
2
- var CONNECTION_CHECK_TTL_MS = 5e3;
3
- var STORAGE_KEY = "react-grab:agent-sessions";
4
- var parseSSEEvent = (eventBlock) => {
5
- let eventType = "";
6
- let data = "";
7
- for (const line of eventBlock.split("\n")) {
8
- if (line.startsWith("event:")) eventType = line.slice(6).trim();
9
- else if (line.startsWith("data:")) data = line.slice(5).trim();
10
- }
11
- return { eventType, data };
12
- };
13
- var streamSSE = async function* (stream, signal) {
14
- const reader = stream.getReader();
15
- const decoder = new TextDecoder();
16
- let buffer = "";
17
- let aborted = false;
18
- const onAbort = () => {
19
- aborted = true;
20
- reader.cancel().catch(() => {
21
- });
1
+ // ../relay/dist/client.js
2
+ var DEFAULT_RELAY_PORT = 4722;
3
+ var DEFAULT_RECONNECT_INTERVAL_MS = 3e3;
4
+ var RELAY_TOKEN_PARAM = "token";
5
+ var createRelayClient = (options = {}) => {
6
+ const serverUrl = options.serverUrl ?? `ws://localhost:${DEFAULT_RELAY_PORT}`;
7
+ const autoReconnect = options.autoReconnect ?? true;
8
+ const reconnectIntervalMs = options.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS;
9
+ const token = options.token;
10
+ let webSocketConnection = null;
11
+ let isConnectedState = false;
12
+ let availableHandlers = [];
13
+ let reconnectTimeoutId = null;
14
+ let pendingConnectionPromise = null;
15
+ let pendingConnectionReject = null;
16
+ let isIntentionalDisconnect = false;
17
+ const messageCallbacks = /* @__PURE__ */ new Set();
18
+ const handlersChangeCallbacks = /* @__PURE__ */ new Set();
19
+ const connectionChangeCallbacks = /* @__PURE__ */ new Set();
20
+ const scheduleReconnect = () => {
21
+ if (!autoReconnect || reconnectTimeoutId || isIntentionalDisconnect) return;
22
+ reconnectTimeoutId = setTimeout(() => {
23
+ reconnectTimeoutId = null;
24
+ connect().catch(() => {
25
+ });
26
+ }, reconnectIntervalMs);
22
27
  };
23
- signal.addEventListener("abort", onAbort);
24
- try {
25
- if (signal.aborted) {
26
- throw new DOMException("Aborted", "AbortError");
27
- }
28
- while (true) {
29
- const result = await reader.read();
30
- if (aborted || signal.aborted) {
31
- throw new DOMException("Aborted", "AbortError");
28
+ const handleMessage = (event) => {
29
+ try {
30
+ const message = JSON.parse(event.data);
31
+ if (message.type === "handlers" && message.handlers) {
32
+ availableHandlers = message.handlers;
33
+ for (const callback of handlersChangeCallbacks) {
34
+ callback(availableHandlers);
35
+ }
32
36
  }
33
- const { done, value } = result;
34
- if (value) buffer += decoder.decode(value, { stream: true });
35
- let boundary;
36
- while ((boundary = buffer.indexOf("\n\n")) !== -1) {
37
- const { eventType, data } = parseSSEEvent(buffer.slice(0, boundary));
38
- buffer = buffer.slice(boundary + 2);
39
- if (eventType === "done") return;
40
- if (eventType === "error") throw new Error(data || "Agent error");
41
- if (data) yield data;
37
+ for (const callback of messageCallbacks) {
38
+ callback(message);
42
39
  }
43
- if (done) break;
44
- }
45
- } finally {
46
- signal.removeEventListener("abort", onAbort);
47
- try {
48
- reader.releaseLock();
49
40
  } catch {
50
41
  }
51
- }
52
- };
53
- var isRecord = (value) => typeof value === "object" && value !== null;
54
- var getStoredAgentContext = (storage, sessionId, storageKey = STORAGE_KEY) => {
55
- const rawSessions = storage.getItem(storageKey);
56
- if (!rawSessions) throw new Error("No sessions to resume");
57
- let parsed;
58
- try {
59
- parsed = JSON.parse(rawSessions);
60
- } catch {
61
- throw new Error("Failed to parse stored sessions");
62
- }
63
- if (!isRecord(parsed)) throw new Error("Invalid stored sessions");
64
- const storedSession = parsed[sessionId];
65
- if (!isRecord(storedSession)) {
66
- throw new Error(`Session ${sessionId} not found`);
67
- }
68
- const context = storedSession.context;
69
- if (!isRecord(context)) throw new Error(`Session ${sessionId} is invalid`);
70
- const content = context.content;
71
- const prompt = context.prompt;
72
- if (!Array.isArray(content) || typeof prompt !== "string") {
73
- throw new Error(`Session ${sessionId} is invalid`);
74
- }
75
- const options = context.options;
76
- const storedSessionId = context.sessionId;
42
+ };
43
+ const connect = () => {
44
+ if (webSocketConnection?.readyState === WebSocket.OPEN) {
45
+ return Promise.resolve();
46
+ }
47
+ if (pendingConnectionPromise) {
48
+ return pendingConnectionPromise;
49
+ }
50
+ isIntentionalDisconnect = false;
51
+ pendingConnectionPromise = new Promise((resolve, reject) => {
52
+ pendingConnectionReject = reject;
53
+ const connectionUrl = token ? `${serverUrl}?${RELAY_TOKEN_PARAM}=${encodeURIComponent(token)}` : serverUrl;
54
+ webSocketConnection = new WebSocket(connectionUrl);
55
+ webSocketConnection.onopen = () => {
56
+ pendingConnectionPromise = null;
57
+ pendingConnectionReject = null;
58
+ isConnectedState = true;
59
+ for (const callback of connectionChangeCallbacks) {
60
+ callback(true);
61
+ }
62
+ resolve();
63
+ };
64
+ webSocketConnection.onmessage = handleMessage;
65
+ webSocketConnection.onclose = () => {
66
+ if (pendingConnectionReject) {
67
+ pendingConnectionReject(new Error("WebSocket connection closed"));
68
+ pendingConnectionReject = null;
69
+ }
70
+ pendingConnectionPromise = null;
71
+ isConnectedState = false;
72
+ availableHandlers = [];
73
+ for (const callback of handlersChangeCallbacks) {
74
+ callback(availableHandlers);
75
+ }
76
+ for (const callback of connectionChangeCallbacks) {
77
+ callback(false);
78
+ }
79
+ scheduleReconnect();
80
+ };
81
+ webSocketConnection.onerror = () => {
82
+ pendingConnectionPromise = null;
83
+ pendingConnectionReject = null;
84
+ isConnectedState = false;
85
+ reject(new Error("WebSocket connection failed"));
86
+ };
87
+ });
88
+ return pendingConnectionPromise;
89
+ };
90
+ const disconnect = () => {
91
+ isIntentionalDisconnect = true;
92
+ if (reconnectTimeoutId) {
93
+ clearTimeout(reconnectTimeoutId);
94
+ reconnectTimeoutId = null;
95
+ }
96
+ if (pendingConnectionReject) {
97
+ pendingConnectionReject(new Error("Connection aborted"));
98
+ pendingConnectionReject = null;
99
+ }
100
+ pendingConnectionPromise = null;
101
+ webSocketConnection?.close();
102
+ webSocketConnection = null;
103
+ isConnectedState = false;
104
+ availableHandlers = [];
105
+ };
106
+ const isConnected = () => isConnectedState;
107
+ const sendMessage = (message) => {
108
+ if (webSocketConnection?.readyState === WebSocket.OPEN) {
109
+ webSocketConnection.send(JSON.stringify(message));
110
+ return true;
111
+ }
112
+ return false;
113
+ };
114
+ const sendAgentRequest = (agentId, context) => {
115
+ return sendMessage({
116
+ type: "agent-request",
117
+ agentId,
118
+ sessionId: context.sessionId,
119
+ context
120
+ });
121
+ };
122
+ const abortAgent = (agentId, sessionId) => {
123
+ sendMessage({
124
+ type: "agent-abort",
125
+ agentId,
126
+ sessionId
127
+ });
128
+ };
129
+ const undoAgent = (agentId, sessionId) => {
130
+ return sendMessage({
131
+ type: "agent-undo",
132
+ agentId,
133
+ sessionId
134
+ });
135
+ };
136
+ const redoAgent = (agentId, sessionId) => {
137
+ return sendMessage({
138
+ type: "agent-redo",
139
+ agentId,
140
+ sessionId
141
+ });
142
+ };
143
+ const onMessage = (callback) => {
144
+ messageCallbacks.add(callback);
145
+ return () => messageCallbacks.delete(callback);
146
+ };
147
+ const onHandlersChange = (callback) => {
148
+ handlersChangeCallbacks.add(callback);
149
+ return () => handlersChangeCallbacks.delete(callback);
150
+ };
151
+ const onConnectionChange = (callback) => {
152
+ connectionChangeCallbacks.add(callback);
153
+ queueMicrotask(() => {
154
+ if (connectionChangeCallbacks.has(callback)) {
155
+ callback(isConnectedState);
156
+ }
157
+ });
158
+ return () => connectionChangeCallbacks.delete(callback);
159
+ };
160
+ const getAvailableHandlers = () => availableHandlers;
77
161
  return {
78
- content,
79
- prompt,
80
- options,
81
- sessionId: typeof storedSessionId === "string" ? storedSessionId : void 0
162
+ connect,
163
+ disconnect,
164
+ isConnected,
165
+ sendAgentRequest,
166
+ abortAgent,
167
+ undoAgent,
168
+ redoAgent,
169
+ onMessage,
170
+ onHandlersChange,
171
+ onConnectionChange,
172
+ getAvailableHandlers
82
173
  };
83
174
  };
84
- var streamAgentStatusFromServer = async function* (options, context, signal) {
85
- const startTime = Date.now();
86
- const sessionId = context.sessionId;
87
- const pollIntervalMs = options.pollIntervalMs ?? 100;
88
- const agentUrl = `${options.serverUrl}${options.agentPath ?? "/agent"}`;
89
- const handleAbort = () => {
90
- if (!sessionId) return;
91
- const abortPath = options.abortPath?.(sessionId) ?? `/abort/${sessionId}`;
92
- fetch(`${options.serverUrl}${abortPath}`, { method: "POST" }).catch(
93
- () => {
175
+ var createRelayAgentProvider = (options) => {
176
+ const { relayClient, agentId } = options;
177
+ const checkConnection = async () => {
178
+ if (!relayClient.isConnected()) {
179
+ try {
180
+ await relayClient.connect();
181
+ } catch {
182
+ return false;
94
183
  }
95
- );
96
- };
97
- signal.addEventListener("abort", handleAbort);
98
- try {
99
- const response = await fetch(agentUrl, {
100
- method: "POST",
101
- headers: { "Content-Type": "application/json" },
102
- body: JSON.stringify(context),
103
- signal
104
- });
105
- if (!response.ok) {
106
- throw new Error(`Server error: ${response.status}`);
107
184
  }
108
- if (!response.body) {
109
- throw new Error("No response body");
185
+ return relayClient.getAvailableHandlers().includes(agentId);
186
+ };
187
+ const send = async function* (context, signal) {
188
+ if (signal.aborted) {
189
+ throw new DOMException("Aborted", "AbortError");
110
190
  }
111
- const iterator = streamSSE(response.body, signal)[Symbol.asyncIterator]();
191
+ yield "Connecting\u2026";
192
+ const sessionId = context.sessionId ?? `session-${Date.now()}-${Math.random().toString(36).slice(2)}`;
193
+ const contextWithSession = {
194
+ ...context,
195
+ sessionId
196
+ };
197
+ const messageQueue = [];
198
+ let resolveNextMessage = null;
199
+ let rejectNextMessage = null;
112
200
  let isDone = false;
113
- let pendingNext = iterator.next();
114
- let lastStatus = null;
115
- while (!isDone) {
116
- const result = await Promise.race([
117
- pendingNext.then((iteratorResult) => ({
118
- type: "status",
119
- iteratorResult
120
- })),
121
- new Promise(
122
- (resolve) => setTimeout(() => resolve({ type: "timeout" }), pollIntervalMs)
123
- )
124
- ]);
125
- const elapsedSeconds = (Date.now() - startTime) / 1e3;
126
- if (result.type === "status") {
127
- const iteratorResult = result.iteratorResult;
128
- isDone = iteratorResult.done ?? false;
129
- if (!isDone && iteratorResult.value) {
130
- lastStatus = iteratorResult.value;
131
- pendingNext = iterator.next();
201
+ let errorMessage = null;
202
+ const handleAbort = () => {
203
+ relayClient.abortAgent(agentId, sessionId);
204
+ isDone = true;
205
+ if (resolveNextMessage) {
206
+ resolveNextMessage({ value: void 0, done: true });
207
+ resolveNextMessage = null;
208
+ rejectNextMessage = null;
209
+ }
210
+ };
211
+ signal.addEventListener("abort", handleAbort);
212
+ const handleConnectionChange = (connected) => {
213
+ if (!connected && !isDone) {
214
+ errorMessage = "Relay connection lost";
215
+ isDone = true;
216
+ if (rejectNextMessage) {
217
+ rejectNextMessage(new Error(errorMessage));
218
+ resolveNextMessage = null;
219
+ rejectNextMessage = null;
132
220
  }
133
221
  }
134
- if (lastStatus === options.completedStatus) {
135
- yield `Completed in ${elapsedSeconds.toFixed(1)}s`;
136
- } else if (lastStatus) {
137
- yield `${lastStatus} ${elapsedSeconds.toFixed(1)}s`;
138
- } else {
139
- yield `Working\u2026 ${elapsedSeconds.toFixed(1)}s`;
222
+ };
223
+ const unsubscribeConnection = relayClient.onConnectionChange(
224
+ handleConnectionChange
225
+ );
226
+ const unsubscribeMessage = relayClient.onMessage((message) => {
227
+ if (message.sessionId !== sessionId) return;
228
+ if (message.type === "agent-status" && message.content) {
229
+ messageQueue.push(message.content);
230
+ if (resolveNextMessage) {
231
+ const nextMessage = messageQueue.shift();
232
+ if (nextMessage !== void 0) {
233
+ resolveNextMessage({ value: nextMessage, done: false });
234
+ resolveNextMessage = null;
235
+ rejectNextMessage = null;
236
+ }
237
+ }
238
+ } else if (message.type === "agent-done") {
239
+ isDone = true;
240
+ if (resolveNextMessage) {
241
+ resolveNextMessage({ value: void 0, done: true });
242
+ resolveNextMessage = null;
243
+ rejectNextMessage = null;
244
+ }
245
+ } else if (message.type === "agent-error") {
246
+ errorMessage = message.content ?? "Unknown error";
247
+ isDone = true;
248
+ if (rejectNextMessage) {
249
+ rejectNextMessage(new Error(errorMessage));
250
+ resolveNextMessage = null;
251
+ rejectNextMessage = null;
252
+ }
140
253
  }
254
+ });
255
+ if (!relayClient.isConnected()) {
256
+ unsubscribeConnection();
257
+ unsubscribeMessage();
258
+ signal.removeEventListener("abort", handleAbort);
259
+ throw new Error("Relay connection is not open");
260
+ }
261
+ const didSendRequest = relayClient.sendAgentRequest(agentId, contextWithSession);
262
+ if (!didSendRequest) {
263
+ unsubscribeConnection();
264
+ unsubscribeMessage();
265
+ signal.removeEventListener("abort", handleAbort);
266
+ throw new Error("Failed to send agent request: connection not open");
141
267
  }
142
- } finally {
143
- signal.removeEventListener("abort", handleAbort);
144
- }
145
- };
146
- var createCachedConnectionChecker = (checkConnection, ttlMs = CONNECTION_CHECK_TTL_MS) => {
147
- let cache = null;
148
- return async () => {
149
- const now = Date.now();
150
- if (cache && now - cache.timestamp < ttlMs) return cache.result;
151
268
  try {
152
- const result = await checkConnection();
153
- cache = { result, timestamp: now };
154
- return result;
155
- } catch {
156
- cache = { result: false, timestamp: now };
157
- return false;
269
+ while (true) {
270
+ if (messageQueue.length > 0) {
271
+ const next = messageQueue.shift();
272
+ if (next !== void 0) {
273
+ yield next;
274
+ }
275
+ continue;
276
+ }
277
+ if (isDone || signal.aborted) {
278
+ break;
279
+ }
280
+ const result = await new Promise(
281
+ (resolve, reject) => {
282
+ resolveNextMessage = resolve;
283
+ rejectNextMessage = reject;
284
+ }
285
+ );
286
+ if (result.done) break;
287
+ yield result.value;
288
+ }
289
+ if (errorMessage) {
290
+ throw new Error(errorMessage);
291
+ }
292
+ } finally {
293
+ signal.removeEventListener("abort", handleAbort);
294
+ unsubscribeConnection();
295
+ unsubscribeMessage();
296
+ }
297
+ };
298
+ const abort = async (sessionId) => {
299
+ relayClient.abortAgent(agentId, sessionId);
300
+ };
301
+ const waitForOperationResponse = (sessionId) => {
302
+ return new Promise((resolve, reject) => {
303
+ let didCleanup = false;
304
+ const cleanup = () => {
305
+ if (didCleanup) return;
306
+ didCleanup = true;
307
+ unsubscribeMessage();
308
+ unsubscribeConnection();
309
+ };
310
+ const unsubscribeMessage = relayClient.onMessage((message) => {
311
+ if (message.sessionId !== sessionId) return;
312
+ cleanup();
313
+ if (message.type === "agent-done") {
314
+ resolve();
315
+ } else if (message.type === "agent-error") {
316
+ reject(new Error(message.content ?? "Operation failed"));
317
+ }
318
+ });
319
+ const unsubscribeConnection = relayClient.onConnectionChange((connected) => {
320
+ if (!connected) {
321
+ cleanup();
322
+ reject(new Error("Connection lost while waiting for operation response"));
323
+ }
324
+ });
325
+ });
326
+ };
327
+ const undo = async () => {
328
+ const sessionId = `undo-${agentId}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
329
+ const didSend = relayClient.undoAgent(agentId, sessionId);
330
+ if (!didSend) {
331
+ throw new Error("Failed to send undo request: connection not open");
158
332
  }
333
+ return waitForOperationResponse(sessionId);
334
+ };
335
+ const redo = async () => {
336
+ const sessionId = `redo-${agentId}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
337
+ const didSend = relayClient.redoAgent(agentId, sessionId);
338
+ if (!didSend) {
339
+ throw new Error("Failed to send redo request: connection not open");
340
+ }
341
+ return waitForOperationResponse(sessionId);
342
+ };
343
+ return {
344
+ send,
345
+ abort,
346
+ undo,
347
+ redo,
348
+ checkConnection,
349
+ supportsResume: true,
350
+ supportsFollowUp: true
159
351
  };
160
352
  };
161
-
162
- // src/constants.ts
163
- var DEFAULT_PORT = 6567;
164
- var COMPLETED_STATUS = "Completed successfully";
353
+ var defaultRelayClient = null;
354
+ var getDefaultRelayClient = () => {
355
+ if (typeof window === "undefined") {
356
+ return null;
357
+ }
358
+ if (window.__REACT_GRAB_RELAY__) {
359
+ defaultRelayClient = window.__REACT_GRAB_RELAY__;
360
+ return defaultRelayClient;
361
+ }
362
+ if (!defaultRelayClient) {
363
+ defaultRelayClient = createRelayClient();
364
+ window.__REACT_GRAB_RELAY__ = defaultRelayClient;
365
+ }
366
+ return defaultRelayClient;
367
+ };
165
368
 
166
369
  // src/client.ts
167
- var DEFAULT_SERVER_URL = `http://localhost:${DEFAULT_PORT}`;
168
- var isReactGrabApi = (value) => typeof value === "object" && value !== null && "setAgent" in value;
169
- var createOpenCodeAgentProvider = (options = {}) => {
170
- const { serverUrl = DEFAULT_SERVER_URL, getOptions } = options;
171
- const mergeOptions = (contextOptions) => ({
172
- ...getOptions?.() ?? {},
173
- ...contextOptions ?? {}
370
+ var AGENT_ID = "opencode";
371
+ var isReactGrabApi = (value) => typeof value === "object" && value !== null && "registerPlugin" in value;
372
+ var createOpenCodeAgentProvider = (providerOptions = {}) => {
373
+ const relayClient = providerOptions.relayClient ?? getDefaultRelayClient();
374
+ if (!relayClient) {
375
+ throw new Error("RelayClient is required in browser environments");
376
+ }
377
+ return createRelayAgentProvider({
378
+ relayClient,
379
+ agentId: AGENT_ID
174
380
  });
175
- const checkConnection = createCachedConnectionChecker(async () => {
176
- const response = await fetch(`${serverUrl}/health`, { method: "GET" });
177
- return response.ok;
178
- }, CONNECTION_CHECK_TTL_MS);
179
- return {
180
- send: async function* (context, signal) {
181
- const combinedContext = {
182
- ...context,
183
- options: mergeOptions(context.options)
184
- };
185
- yield* streamAgentStatusFromServer(
186
- { serverUrl, completedStatus: COMPLETED_STATUS },
187
- combinedContext,
188
- signal
189
- );
190
- },
191
- resume: async function* (sessionId, signal, storage) {
192
- const storedContext = getStoredAgentContext(storage, sessionId);
193
- const context = {
194
- content: storedContext.content,
195
- prompt: storedContext.prompt,
196
- options: storedContext.options,
197
- sessionId: storedContext.sessionId ?? sessionId
198
- };
199
- const combinedContext = {
200
- ...context,
201
- options: mergeOptions(context.options)
202
- };
203
- yield "Resuming...";
204
- yield* streamAgentStatusFromServer(
205
- { serverUrl, completedStatus: COMPLETED_STATUS },
206
- combinedContext,
207
- signal
208
- );
209
- },
210
- supportsResume: true,
211
- supportsFollowUp: true,
212
- checkConnection,
213
- undo: async () => {
214
- try {
215
- await fetch(`${serverUrl}/undo`, { method: "POST" });
216
- } catch {
217
- }
218
- }
219
- };
220
381
  };
221
382
  var attachAgent = async () => {
222
383
  if (typeof window === "undefined") return;
223
- const provider = createOpenCodeAgentProvider();
384
+ const relayClient = getDefaultRelayClient();
385
+ if (!relayClient) return;
386
+ try {
387
+ await relayClient.connect();
388
+ } catch {
389
+ return;
390
+ }
391
+ const provider = createRelayAgentProvider({
392
+ relayClient,
393
+ agentId: AGENT_ID
394
+ });
224
395
  const attach = (api) => {
225
- api.setAgent({ provider, storage: sessionStorage });
396
+ const agent = { provider, storage: sessionStorage };
397
+ const plugin = {
398
+ name: "opencode-agent",
399
+ actions: [
400
+ {
401
+ id: "edit-with-opencode",
402
+ label: "Edit with OpenCode",
403
+ shortcut: "Enter",
404
+ onAction: (actionContext) => {
405
+ actionContext.enterPromptMode?.(agent);
406
+ },
407
+ agent
408
+ }
409
+ ]
410
+ };
411
+ api.registerPlugin(plugin);
226
412
  };
227
413
  const existingApi = window.__REACT_GRAB__;
228
414
  if (isReactGrabApi(existingApi)) {