@react-grab/copilot 0.1.16

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/dist/cli.cjs ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var child_process = require('child_process');
5
+ var fs = require('fs');
6
+ var path = require('path');
7
+
8
+ var realScriptPath = fs.realpathSync(process.argv[1]);
9
+ var scriptDir = path.dirname(realScriptPath);
10
+ var serverPath = path.join(scriptDir, "server.cjs");
11
+ var child = child_process.spawn(
12
+ process.execPath,
13
+ ["-e", `require(${JSON.stringify(serverPath)}).startServer()`],
14
+ {
15
+ detached: true,
16
+ stdio: "inherit"
17
+ }
18
+ );
19
+ child.unref();
20
+ process.exit(0);
package/dist/cli.d.cts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'child_process';
3
+ import { realpathSync } from 'fs';
4
+ import { dirname, join } from 'path';
5
+
6
+ var realScriptPath = realpathSync(process.argv[1]);
7
+ var scriptDir = dirname(realScriptPath);
8
+ var serverPath = join(scriptDir, "server.cjs");
9
+ var child = spawn(
10
+ process.execPath,
11
+ ["-e", `require(${JSON.stringify(serverPath)}).startServer()`],
12
+ {
13
+ detached: true,
14
+ stdio: "inherit"
15
+ }
16
+ );
17
+ child.unref();
18
+ process.exit(0);
@@ -0,0 +1,451 @@
1
+ 'use strict';
2
+
3
+ // ../relay/dist/client.js
4
+ var DEFAULT_RELAY_PORT = 4722;
5
+ var DEFAULT_RECONNECT_INTERVAL_MS = 3e3;
6
+ var RELAY_TOKEN_PARAM = "token";
7
+ var createRelayClient = (options = {}) => {
8
+ const serverUrl = options.serverUrl ?? `ws://localhost:${DEFAULT_RELAY_PORT}`;
9
+ const autoReconnect = options.autoReconnect ?? true;
10
+ const reconnectIntervalMs = options.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS;
11
+ const token = options.token;
12
+ let webSocketConnection = null;
13
+ let isConnectedState = false;
14
+ let availableHandlers = [];
15
+ let reconnectTimeoutId = null;
16
+ let pendingConnectionPromise = null;
17
+ let pendingConnectionReject = null;
18
+ let isIntentionalDisconnect = false;
19
+ const messageCallbacks = /* @__PURE__ */ new Set();
20
+ const handlersChangeCallbacks = /* @__PURE__ */ new Set();
21
+ const connectionChangeCallbacks = /* @__PURE__ */ new Set();
22
+ const scheduleReconnect = () => {
23
+ if (!autoReconnect || reconnectTimeoutId || isIntentionalDisconnect) return;
24
+ reconnectTimeoutId = setTimeout(() => {
25
+ reconnectTimeoutId = null;
26
+ connect().catch(() => {
27
+ });
28
+ }, reconnectIntervalMs);
29
+ };
30
+ const handleMessage = (event) => {
31
+ try {
32
+ const message = JSON.parse(event.data);
33
+ if (message.type === "handlers" && message.handlers) {
34
+ availableHandlers = message.handlers;
35
+ for (const callback of handlersChangeCallbacks) {
36
+ callback(availableHandlers);
37
+ }
38
+ }
39
+ for (const callback of messageCallbacks) {
40
+ callback(message);
41
+ }
42
+ } catch {
43
+ }
44
+ };
45
+ const connect = () => {
46
+ if (webSocketConnection?.readyState === WebSocket.OPEN) {
47
+ return Promise.resolve();
48
+ }
49
+ if (pendingConnectionPromise) {
50
+ return pendingConnectionPromise;
51
+ }
52
+ isIntentionalDisconnect = false;
53
+ pendingConnectionPromise = new Promise((resolve, reject) => {
54
+ pendingConnectionReject = reject;
55
+ const connectionUrl = token ? `${serverUrl}?${RELAY_TOKEN_PARAM}=${encodeURIComponent(token)}` : serverUrl;
56
+ webSocketConnection = new WebSocket(connectionUrl);
57
+ webSocketConnection.onopen = () => {
58
+ pendingConnectionPromise = null;
59
+ pendingConnectionReject = null;
60
+ isConnectedState = true;
61
+ for (const callback of connectionChangeCallbacks) {
62
+ callback(true);
63
+ }
64
+ resolve();
65
+ };
66
+ webSocketConnection.onmessage = handleMessage;
67
+ webSocketConnection.onclose = () => {
68
+ if (pendingConnectionReject) {
69
+ pendingConnectionReject(new Error("WebSocket connection closed"));
70
+ pendingConnectionReject = null;
71
+ }
72
+ pendingConnectionPromise = null;
73
+ isConnectedState = false;
74
+ availableHandlers = [];
75
+ for (const callback of handlersChangeCallbacks) {
76
+ callback(availableHandlers);
77
+ }
78
+ for (const callback of connectionChangeCallbacks) {
79
+ callback(false);
80
+ }
81
+ scheduleReconnect();
82
+ };
83
+ webSocketConnection.onerror = () => {
84
+ pendingConnectionPromise = null;
85
+ pendingConnectionReject = null;
86
+ isConnectedState = false;
87
+ reject(new Error("WebSocket connection failed"));
88
+ };
89
+ });
90
+ return pendingConnectionPromise;
91
+ };
92
+ const disconnect = () => {
93
+ isIntentionalDisconnect = true;
94
+ if (reconnectTimeoutId) {
95
+ clearTimeout(reconnectTimeoutId);
96
+ reconnectTimeoutId = null;
97
+ }
98
+ if (pendingConnectionReject) {
99
+ pendingConnectionReject(new Error("Connection aborted"));
100
+ pendingConnectionReject = null;
101
+ }
102
+ pendingConnectionPromise = null;
103
+ webSocketConnection?.close();
104
+ webSocketConnection = null;
105
+ isConnectedState = false;
106
+ availableHandlers = [];
107
+ };
108
+ const isConnected = () => isConnectedState;
109
+ const sendMessage = (message) => {
110
+ if (webSocketConnection?.readyState === WebSocket.OPEN) {
111
+ webSocketConnection.send(JSON.stringify(message));
112
+ return true;
113
+ }
114
+ return false;
115
+ };
116
+ const sendAgentRequest = (agentId, context) => {
117
+ return sendMessage({
118
+ type: "agent-request",
119
+ agentId,
120
+ sessionId: context.sessionId,
121
+ context
122
+ });
123
+ };
124
+ const abortAgent = (agentId, sessionId) => {
125
+ sendMessage({
126
+ type: "agent-abort",
127
+ agentId,
128
+ sessionId
129
+ });
130
+ };
131
+ const undoAgent = (agentId, sessionId) => {
132
+ return sendMessage({
133
+ type: "agent-undo",
134
+ agentId,
135
+ sessionId
136
+ });
137
+ };
138
+ const redoAgent = (agentId, sessionId) => {
139
+ return sendMessage({
140
+ type: "agent-redo",
141
+ agentId,
142
+ sessionId
143
+ });
144
+ };
145
+ const onMessage = (callback) => {
146
+ messageCallbacks.add(callback);
147
+ return () => messageCallbacks.delete(callback);
148
+ };
149
+ const onHandlersChange = (callback) => {
150
+ handlersChangeCallbacks.add(callback);
151
+ return () => handlersChangeCallbacks.delete(callback);
152
+ };
153
+ const onConnectionChange = (callback) => {
154
+ connectionChangeCallbacks.add(callback);
155
+ queueMicrotask(() => {
156
+ if (connectionChangeCallbacks.has(callback)) {
157
+ callback(isConnectedState);
158
+ }
159
+ });
160
+ return () => connectionChangeCallbacks.delete(callback);
161
+ };
162
+ const getAvailableHandlers = () => availableHandlers;
163
+ return {
164
+ connect,
165
+ disconnect,
166
+ isConnected,
167
+ sendAgentRequest,
168
+ abortAgent,
169
+ undoAgent,
170
+ redoAgent,
171
+ onMessage,
172
+ onHandlersChange,
173
+ onConnectionChange,
174
+ getAvailableHandlers
175
+ };
176
+ };
177
+ var createRelayAgentProvider = (options) => {
178
+ const { relayClient, agentId } = options;
179
+ const checkConnection = async () => {
180
+ if (!relayClient.isConnected()) {
181
+ try {
182
+ await relayClient.connect();
183
+ } catch {
184
+ return false;
185
+ }
186
+ }
187
+ return relayClient.getAvailableHandlers().includes(agentId);
188
+ };
189
+ const send = async function* (context, signal) {
190
+ if (signal.aborted) {
191
+ throw new DOMException("Aborted", "AbortError");
192
+ }
193
+ yield "Connecting\u2026";
194
+ const sessionId = context.sessionId ?? `session-${Date.now()}-${Math.random().toString(36).slice(2)}`;
195
+ const contextWithSession = {
196
+ ...context,
197
+ sessionId
198
+ };
199
+ const messageQueue = [];
200
+ let resolveNextMessage = null;
201
+ let rejectNextMessage = null;
202
+ let isDone = false;
203
+ let errorMessage = null;
204
+ const handleAbort = () => {
205
+ relayClient.abortAgent(agentId, sessionId);
206
+ isDone = true;
207
+ if (resolveNextMessage) {
208
+ resolveNextMessage({ value: void 0, done: true });
209
+ resolveNextMessage = null;
210
+ rejectNextMessage = null;
211
+ }
212
+ };
213
+ signal.addEventListener("abort", handleAbort, { once: true });
214
+ const handleConnectionChange = (connected) => {
215
+ if (!connected && !isDone) {
216
+ errorMessage = "Relay connection lost";
217
+ isDone = true;
218
+ if (rejectNextMessage) {
219
+ rejectNextMessage(new Error(errorMessage));
220
+ resolveNextMessage = null;
221
+ rejectNextMessage = null;
222
+ }
223
+ }
224
+ };
225
+ const unsubscribeConnection = relayClient.onConnectionChange(
226
+ handleConnectionChange
227
+ );
228
+ const unsubscribeMessage = relayClient.onMessage((message) => {
229
+ if (message.sessionId !== sessionId) return;
230
+ if (message.type === "agent-status" && message.content) {
231
+ messageQueue.push(message.content);
232
+ if (resolveNextMessage) {
233
+ const nextMessage = messageQueue.shift();
234
+ if (nextMessage !== void 0) {
235
+ resolveNextMessage({ value: nextMessage, done: false });
236
+ resolveNextMessage = null;
237
+ rejectNextMessage = null;
238
+ }
239
+ }
240
+ } else if (message.type === "agent-done") {
241
+ isDone = true;
242
+ if (resolveNextMessage) {
243
+ resolveNextMessage({ value: void 0, done: true });
244
+ resolveNextMessage = null;
245
+ rejectNextMessage = null;
246
+ }
247
+ } else if (message.type === "agent-error") {
248
+ errorMessage = message.content ?? "Unknown error";
249
+ isDone = true;
250
+ if (rejectNextMessage) {
251
+ rejectNextMessage(new Error(errorMessage));
252
+ resolveNextMessage = null;
253
+ rejectNextMessage = null;
254
+ }
255
+ }
256
+ });
257
+ if (!relayClient.isConnected()) {
258
+ unsubscribeConnection();
259
+ unsubscribeMessage();
260
+ signal.removeEventListener("abort", handleAbort);
261
+ throw new Error("Relay connection is not open");
262
+ }
263
+ const didSendRequest = relayClient.sendAgentRequest(
264
+ agentId,
265
+ contextWithSession
266
+ );
267
+ if (!didSendRequest) {
268
+ unsubscribeConnection();
269
+ unsubscribeMessage();
270
+ signal.removeEventListener("abort", handleAbort);
271
+ throw new Error("Failed to send agent request: connection not open");
272
+ }
273
+ try {
274
+ while (true) {
275
+ if (messageQueue.length > 0) {
276
+ const next = messageQueue.shift();
277
+ if (next !== void 0) {
278
+ yield next;
279
+ }
280
+ continue;
281
+ }
282
+ if (isDone || signal.aborted) {
283
+ break;
284
+ }
285
+ const result = await new Promise(
286
+ (resolve, reject) => {
287
+ resolveNextMessage = resolve;
288
+ rejectNextMessage = reject;
289
+ }
290
+ );
291
+ if (result.done) break;
292
+ yield result.value;
293
+ }
294
+ if (errorMessage) {
295
+ throw new Error(errorMessage);
296
+ }
297
+ } finally {
298
+ signal.removeEventListener("abort", handleAbort);
299
+ unsubscribeConnection();
300
+ unsubscribeMessage();
301
+ }
302
+ };
303
+ const abort = async (sessionId) => {
304
+ relayClient.abortAgent(agentId, sessionId);
305
+ };
306
+ const waitForOperationResponse = (sessionId) => {
307
+ return new Promise((resolve, reject) => {
308
+ let didCleanup = false;
309
+ const cleanup = () => {
310
+ if (didCleanup) return;
311
+ didCleanup = true;
312
+ unsubscribeMessage();
313
+ unsubscribeConnection();
314
+ };
315
+ const unsubscribeMessage = relayClient.onMessage((message) => {
316
+ if (message.sessionId !== sessionId) return;
317
+ cleanup();
318
+ if (message.type === "agent-done") {
319
+ resolve();
320
+ } else if (message.type === "agent-error") {
321
+ reject(new Error(message.content ?? "Operation failed"));
322
+ }
323
+ });
324
+ const unsubscribeConnection = relayClient.onConnectionChange(
325
+ (connected) => {
326
+ if (!connected) {
327
+ cleanup();
328
+ reject(
329
+ new Error("Connection lost while waiting for operation response")
330
+ );
331
+ }
332
+ }
333
+ );
334
+ });
335
+ };
336
+ const undo = async () => {
337
+ const sessionId = `undo-${agentId}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
338
+ const didSend = relayClient.undoAgent(agentId, sessionId);
339
+ if (!didSend) {
340
+ throw new Error("Failed to send undo request: connection not open");
341
+ }
342
+ return waitForOperationResponse(sessionId);
343
+ };
344
+ const redo = async () => {
345
+ const sessionId = `redo-${agentId}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
346
+ const didSend = relayClient.redoAgent(agentId, sessionId);
347
+ if (!didSend) {
348
+ throw new Error("Failed to send redo request: connection not open");
349
+ }
350
+ return waitForOperationResponse(sessionId);
351
+ };
352
+ return {
353
+ send,
354
+ abort,
355
+ undo,
356
+ redo,
357
+ checkConnection,
358
+ supportsResume: true,
359
+ supportsFollowUp: true
360
+ };
361
+ };
362
+ var defaultRelayClient = null;
363
+ var getDefaultRelayClient = () => {
364
+ if (typeof window === "undefined") {
365
+ return null;
366
+ }
367
+ if (window.__REACT_GRAB_RELAY__) {
368
+ defaultRelayClient = window.__REACT_GRAB_RELAY__;
369
+ return defaultRelayClient;
370
+ }
371
+ if (!defaultRelayClient) {
372
+ defaultRelayClient = createRelayClient();
373
+ window.__REACT_GRAB_RELAY__ = defaultRelayClient;
374
+ }
375
+ return defaultRelayClient;
376
+ };
377
+ var isReactGrabApi = (value) => typeof value === "object" && value !== null && "registerPlugin" in value;
378
+ var createProviderClientPlugin = (config) => {
379
+ const createAgentProvider = (providerOptions = {}) => {
380
+ const relayClient = providerOptions.relayClient ?? getDefaultRelayClient();
381
+ if (!relayClient) {
382
+ throw new Error("RelayClient is required in browser environments");
383
+ }
384
+ return createRelayAgentProvider({
385
+ relayClient,
386
+ agentId: config.agentId
387
+ });
388
+ };
389
+ const attachAgent2 = async () => {
390
+ if (typeof window === "undefined") return;
391
+ const relayClient = getDefaultRelayClient();
392
+ if (!relayClient) return;
393
+ try {
394
+ await relayClient.connect();
395
+ } catch {
396
+ return;
397
+ }
398
+ const provider = createRelayAgentProvider({
399
+ relayClient,
400
+ agentId: config.agentId
401
+ });
402
+ const attach = (api) => {
403
+ const agent = { provider, storage: sessionStorage };
404
+ api.registerPlugin({
405
+ name: config.pluginName,
406
+ actions: [
407
+ {
408
+ id: config.actionId,
409
+ label: config.actionLabel,
410
+ shortcut: "Enter",
411
+ onAction: (actionContext) => {
412
+ actionContext.enterPromptMode?.(agent);
413
+ },
414
+ agent
415
+ }
416
+ ]
417
+ });
418
+ };
419
+ const existingApi = window.__REACT_GRAB__;
420
+ if (isReactGrabApi(existingApi)) {
421
+ attach(existingApi);
422
+ return;
423
+ }
424
+ window.addEventListener(
425
+ "react-grab:init",
426
+ (event) => {
427
+ if (!(event instanceof CustomEvent)) return;
428
+ if (!isReactGrabApi(event.detail)) return;
429
+ attach(event.detail);
430
+ },
431
+ { once: true }
432
+ );
433
+ const apiAfterListener = window.__REACT_GRAB__;
434
+ if (isReactGrabApi(apiAfterListener)) {
435
+ attach(apiAfterListener);
436
+ }
437
+ };
438
+ return { createAgentProvider, attachAgent: attachAgent2 };
439
+ };
440
+
441
+ // src/client.ts
442
+ var { createAgentProvider: createCopilotAgentProvider, attachAgent } = createProviderClientPlugin({
443
+ agentId: "copilot",
444
+ pluginName: "copilot-agent",
445
+ actionId: "edit-with-copilot",
446
+ actionLabel: "Edit with Copilot"
447
+ });
448
+ attachAgent();
449
+
450
+ exports.attachAgent = attachAgent;
451
+ exports.createCopilotAgentProvider = createCopilotAgentProvider;
@@ -0,0 +1,9 @@
1
+ import * as _react_grab_relay_client from '@react-grab/relay/client';
2
+ export { AgentCompleteResult } from 'react-grab/core';
3
+
4
+ declare const createCopilotAgentProvider: (providerOptions?: {
5
+ relayClient?: _react_grab_relay_client.RelayClient;
6
+ }) => _react_grab_relay_client.AgentProvider;
7
+ declare const attachAgent: () => Promise<void>;
8
+
9
+ export { attachAgent, createCopilotAgentProvider };
@@ -0,0 +1,9 @@
1
+ import * as _react_grab_relay_client from '@react-grab/relay/client';
2
+ export { AgentCompleteResult } from 'react-grab/core';
3
+
4
+ declare const createCopilotAgentProvider: (providerOptions?: {
5
+ relayClient?: _react_grab_relay_client.RelayClient;
6
+ }) => _react_grab_relay_client.AgentProvider;
7
+ declare const attachAgent: () => Promise<void>;
8
+
9
+ export { attachAgent, createCopilotAgentProvider };
@@ -0,0 +1,2 @@
1
+ var ReactGrabCopilot=(function(exports){'use strict';var q=4722,O=3e3,D="token",x=(s={})=>{let r=s.serverUrl??`ws://localhost:${q}`,w=s.autoReconnect??true,A=s.reconnectIntervalMs??O,h=s.token,i=null,f=false,p=[],d=null,e=null,t=null,C=false,y=new Set,g=new Set,o=new Set,c=()=>{!w||d||C||(d=setTimeout(()=>{d=null,b().catch(()=>{});},A));},l=n=>{try{let a=JSON.parse(n.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{}},b=()=>i?.readyState===WebSocket.OPEN?Promise.resolve():e||(C=false,e=new Promise((n,a)=>{t=a;let S=h?`${r}?${D}=${encodeURIComponent(h)}`:r;i=new WebSocket(S),i.onopen=()=>{e=null,t=null,f=true;for(let m of o)m(true);n();},i.onmessage=l,i.onclose=()=>{t&&(t(new Error("WebSocket connection closed")),t=null),e=null,f=false,p=[];for(let m of g)m(p);for(let m of o)m(false);c();},i.onerror=()=>{e=null,t=null,f=false,a(new Error("WebSocket connection failed"));};}),e),R=()=>{C=true,d&&(clearTimeout(d),d=null),t&&(t(new Error("Connection aborted")),t=null),e=null,i?.close(),i=null,f=false,p=[];},M=()=>f,v=n=>i?.readyState===WebSocket.OPEN?(i.send(JSON.stringify(n)),true):false;return {connect:b,disconnect:R,isConnected:M,sendAgentRequest:(n,a)=>v({type:"agent-request",agentId:n,sessionId:a.sessionId,context:a}),abortAgent:(n,a)=>{v({type:"agent-abort",agentId:n,sessionId:a});},undoAgent:(n,a)=>v({type:"agent-undo",agentId:n,sessionId:a}),redoAgent:(n,a)=>v({type:"agent-redo",agentId:n,sessionId:a}),onMessage:n=>(y.add(n),()=>y.delete(n)),onHandlersChange:n=>(g.add(n),()=>g.delete(n)),onConnectionChange:n=>(o.add(n),queueMicrotask(()=>{o.has(n)&&n(f);}),()=>o.delete(n)),getAvailableHandlers:()=>p}},L=s=>{let{relayClient:r,agentId:w}=s,A=async()=>{if(!r.isConnected())try{await r.connect();}catch{return false}return r.getAvailableHandlers().includes(w)},h=async function*(e,t){if(t.aborted)throw new DOMException("Aborted","AbortError");yield "Connecting\u2026";let C=e.sessionId??`session-${Date.now()}-${Math.random().toString(36).slice(2)}`,y={...e,sessionId:C},g=[],o=null,c=null,l=false,b=null,R=()=>{r.abortAgent(w,C),l=true,o&&(o({value:void 0,done:true}),o=null,c=null);};t.addEventListener("abort",R,{once:true});let M=u=>{!u&&!l&&(b="Relay connection lost",l=true,c&&(c(new Error(b)),o=null,c=null));},v=r.onConnectionChange(M),I=r.onMessage(u=>{if(u.sessionId===C)if(u.type==="agent-status"&&u.content){if(g.push(u.content),o){let E=g.shift();E!==void 0&&(o({value:E,done:false}),o=null,c=null);}}else u.type==="agent-done"?(l=true,o&&(o({value:void 0,done:true}),o=null,c=null)):u.type==="agent-error"&&(b=u.content??"Unknown error",l=true,c&&(c(new Error(b)),o=null,c=null));});if(!r.isConnected())throw v(),I(),t.removeEventListener("abort",R),new Error("Relay connection is not open");if(!r.sendAgentRequest(w,y))throw v(),I(),t.removeEventListener("abort",R),new Error("Failed to send agent request: connection not open");try{for(;;){if(g.length>0){let E=g.shift();E!==void 0&&(yield E);continue}if(l||t.aborted)break;let u=await new Promise((E,k)=>{o=E,c=k;});if(u.done)break;yield u.value;}if(b)throw new Error(b)}finally{t.removeEventListener("abort",R),v(),I();}},i=async e=>{r.abortAgent(w,e);},f=e=>new Promise((t,C)=>{let y=false,g=()=>{y||(y=true,o(),c());},o=r.onMessage(l=>{l.sessionId===e&&(g(),l.type==="agent-done"?t():l.type==="agent-error"&&C(new Error(l.content??"Operation failed")));}),c=r.onConnectionChange(l=>{l||(g(),C(new Error("Connection lost while waiting for operation response")));});});return {send:h,abort:i,undo:async()=>{let e=`undo-${w}-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!r.undoAgent(w,e))throw new Error("Failed to send undo request: connection not open");return f(e)},redo:async()=>{let e=`redo-${w}-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!r.redoAgent(w,e))throw new Error("Failed to send redo request: connection not open");return f(e)},checkConnection:A,supportsResume:true,supportsFollowUp:true}},_=null,T=()=>typeof window>"u"?null:window.__REACT_GRAB_RELAY__?(_=window.__REACT_GRAB_RELAY__,_):(_||(_=x(),window.__REACT_GRAB_RELAY__=_),_),P=s=>typeof s=="object"&&s!==null&&"registerPlugin"in s,N=s=>({createAgentProvider:(A={})=>{let h=A.relayClient??T();if(!h)throw new Error("RelayClient is required in browser environments");return L({relayClient:h,agentId:s.agentId})},attachAgent:async()=>{if(typeof window>"u")return;let A=T();if(!A)return;try{await A.connect();}catch{return}let h=L({relayClient:A,agentId:s.agentId}),i=d=>{let e={provider:h,storage:sessionStorage};d.registerPlugin({name:s.pluginName,actions:[{id:s.actionId,label:s.actionLabel,shortcut:"Enter",onAction:t=>{t.enterPromptMode?.(e);},agent:e}]});},f=window.__REACT_GRAB__;if(P(f)){i(f);return}window.addEventListener("react-grab:init",d=>{d instanceof CustomEvent&&P(d.detail)&&i(d.detail);},{once:true});let p=window.__REACT_GRAB__;P(p)&&i(p);}});var {createAgentProvider:Y,attachAgent:U}=N({agentId:"copilot",pluginName:"copilot-agent",actionId:"edit-with-copilot",actionLabel:"Edit with Copilot"});U();
2
+ exports.attachAgent=U;exports.createCopilotAgentProvider=Y;return exports;})({});