@react-grab/codex 0.1.0-beta.8 → 0.1.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.
package/dist/cli.cjs CHANGED
@@ -4943,8 +4943,13 @@ ${context.content.join("\n\n")}`;
4943
4943
  signal
4944
4944
  })) {
4945
4945
  if (signal.aborted) break;
4946
+ const getBrowserMessageType = (messageType) => {
4947
+ if (messageType === "status") return "agent-status";
4948
+ if (messageType === "error") return "agent-error";
4949
+ return "agent-done";
4950
+ };
4946
4951
  sendToBrowser(browserSocket, {
4947
- type: message.type === "status" ? "agent-status" : message.type === "error" ? "agent-error" : "agent-done",
4952
+ type: getBrowserMessageType(message.type),
4948
4953
  agentId: handler.agentId,
4949
4954
  sessionId,
4950
4955
  content: message.content
@@ -5147,9 +5152,13 @@ ${context.content.join("\n\n")}`;
5147
5152
  } else if (message.type === "agent-status" || message.type === "agent-done" || message.type === "agent-error") {
5148
5153
  const messageQueue = sessionMessageQueues.get(message.sessionId);
5149
5154
  if (messageQueue) {
5150
- const mappedType = message.type === "agent-status" ? "status" : message.type === "agent-done" ? "done" : "error";
5155
+ const getQueueMessageType = (handlerMessageType) => {
5156
+ if (handlerMessageType === "agent-status") return "status";
5157
+ if (handlerMessageType === "agent-done") return "done";
5158
+ return "error";
5159
+ };
5151
5160
  messageQueue.push({
5152
- type: mappedType,
5161
+ type: getQueueMessageType(message.type),
5153
5162
  content: message.content ?? ""
5154
5163
  });
5155
5164
  if (message.type === "agent-done" || message.type === "agent-error") {
@@ -5172,7 +5181,12 @@ ${context.content.join("\n\n")}`;
5172
5181
  }
5173
5182
  }
5174
5183
  res.writeHead(200, { "Content-Type": "application/json" });
5175
- res.end(JSON.stringify({ status: "ok", handlers: getRegisteredHandlerIds() }));
5184
+ res.end(
5185
+ JSON.stringify({
5186
+ status: "ok",
5187
+ handlers: getRegisteredHandlerIds()
5188
+ })
5189
+ );
5176
5190
  return;
5177
5191
  }
5178
5192
  res.writeHead(404);
@@ -5187,7 +5201,10 @@ ${context.content.join("\n\n")}`;
5187
5201
  });
5188
5202
  webSocketServer.on("connection", (socket, request) => {
5189
5203
  if (token) {
5190
- const connectionUrl = new URL(request.url ?? "", `http://localhost:${port}`);
5204
+ const connectionUrl = new URL(
5205
+ request.url ?? "",
5206
+ `http://localhost:${port}`
5207
+ );
5191
5208
  const clientToken = connectionUrl.searchParams.get(RELAY_TOKEN_PARAM);
5192
5209
  if (clientToken !== token) {
5193
5210
  socket.close(4001, "Unauthorized");
@@ -5228,7 +5245,9 @@ ${context.content.join("\n\n")}`;
5228
5245
  });
5229
5246
  socket.on("message", (data) => {
5230
5247
  try {
5231
- const message = JSON.parse(data.toString());
5248
+ const message = JSON.parse(
5249
+ data.toString()
5250
+ );
5232
5251
  handleBrowserMessage(socket, message);
5233
5252
  } catch {
5234
5253
  }
@@ -5273,7 +5292,10 @@ ${context.content.join("\n\n")}`;
5273
5292
  httpServer?.close();
5274
5293
  };
5275
5294
  const registerHandler = (handler) => {
5276
- registeredHandlers.set(handler.agentId, { agentId: handler.agentId, handler });
5295
+ registeredHandlers.set(handler.agentId, {
5296
+ agentId: handler.agentId,
5297
+ handler
5298
+ });
5277
5299
  broadcastHandlerList();
5278
5300
  };
5279
5301
  const unregisterHandler = (agentId) => {
@@ -7834,7 +7856,7 @@ async function fkill(inputs, options = {}) {
7834
7856
  }
7835
7857
  }
7836
7858
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7837
- var VERSION = "0.1.0-beta.7";
7859
+ var VERSION = "0.1.0";
7838
7860
  var checkIfRelayServerIsRunning = async (port, token) => {
7839
7861
  try {
7840
7862
  const healthUrl = token ? `http://localhost:${port}/health?${RELAY_TOKEN_PARAM}=${encodeURIComponent(token)}` : `http://localhost:${port}/health`;
@@ -7852,7 +7874,10 @@ var connectRelay = async (options) => {
7852
7874
  const { handler, token } = options;
7853
7875
  let relayServer = null;
7854
7876
  let isRelayHost = false;
7855
- const isRelayServerRunning = await checkIfRelayServerIsRunning(relayPort, token);
7877
+ const isRelayServerRunning = await checkIfRelayServerIsRunning(
7878
+ relayPort,
7879
+ token
7880
+ );
7856
7881
  if (isRelayServerRunning) {
7857
7882
  relayServer = await connectToExistingRelay(relayPort, handler, token);
7858
7883
  } else {
package/dist/cli.js CHANGED
@@ -4932,8 +4932,13 @@ ${context.content.join("\n\n")}`;
4932
4932
  signal
4933
4933
  })) {
4934
4934
  if (signal.aborted) break;
4935
+ const getBrowserMessageType = (messageType) => {
4936
+ if (messageType === "status") return "agent-status";
4937
+ if (messageType === "error") return "agent-error";
4938
+ return "agent-done";
4939
+ };
4935
4940
  sendToBrowser(browserSocket, {
4936
- type: message.type === "status" ? "agent-status" : message.type === "error" ? "agent-error" : "agent-done",
4941
+ type: getBrowserMessageType(message.type),
4937
4942
  agentId: handler.agentId,
4938
4943
  sessionId,
4939
4944
  content: message.content
@@ -5136,9 +5141,13 @@ ${context.content.join("\n\n")}`;
5136
5141
  } else if (message.type === "agent-status" || message.type === "agent-done" || message.type === "agent-error") {
5137
5142
  const messageQueue = sessionMessageQueues.get(message.sessionId);
5138
5143
  if (messageQueue) {
5139
- const mappedType = message.type === "agent-status" ? "status" : message.type === "agent-done" ? "done" : "error";
5144
+ const getQueueMessageType = (handlerMessageType) => {
5145
+ if (handlerMessageType === "agent-status") return "status";
5146
+ if (handlerMessageType === "agent-done") return "done";
5147
+ return "error";
5148
+ };
5140
5149
  messageQueue.push({
5141
- type: mappedType,
5150
+ type: getQueueMessageType(message.type),
5142
5151
  content: message.content ?? ""
5143
5152
  });
5144
5153
  if (message.type === "agent-done" || message.type === "agent-error") {
@@ -5161,7 +5170,12 @@ ${context.content.join("\n\n")}`;
5161
5170
  }
5162
5171
  }
5163
5172
  res.writeHead(200, { "Content-Type": "application/json" });
5164
- res.end(JSON.stringify({ status: "ok", handlers: getRegisteredHandlerIds() }));
5173
+ res.end(
5174
+ JSON.stringify({
5175
+ status: "ok",
5176
+ handlers: getRegisteredHandlerIds()
5177
+ })
5178
+ );
5165
5179
  return;
5166
5180
  }
5167
5181
  res.writeHead(404);
@@ -5176,7 +5190,10 @@ ${context.content.join("\n\n")}`;
5176
5190
  });
5177
5191
  webSocketServer.on("connection", (socket, request) => {
5178
5192
  if (token) {
5179
- const connectionUrl = new URL(request.url ?? "", `http://localhost:${port}`);
5193
+ const connectionUrl = new URL(
5194
+ request.url ?? "",
5195
+ `http://localhost:${port}`
5196
+ );
5180
5197
  const clientToken = connectionUrl.searchParams.get(RELAY_TOKEN_PARAM);
5181
5198
  if (clientToken !== token) {
5182
5199
  socket.close(4001, "Unauthorized");
@@ -5217,7 +5234,9 @@ ${context.content.join("\n\n")}`;
5217
5234
  });
5218
5235
  socket.on("message", (data) => {
5219
5236
  try {
5220
- const message = JSON.parse(data.toString());
5237
+ const message = JSON.parse(
5238
+ data.toString()
5239
+ );
5221
5240
  handleBrowserMessage(socket, message);
5222
5241
  } catch {
5223
5242
  }
@@ -5262,7 +5281,10 @@ ${context.content.join("\n\n")}`;
5262
5281
  httpServer?.close();
5263
5282
  };
5264
5283
  const registerHandler = (handler) => {
5265
- registeredHandlers.set(handler.agentId, { agentId: handler.agentId, handler });
5284
+ registeredHandlers.set(handler.agentId, {
5285
+ agentId: handler.agentId,
5286
+ handler
5287
+ });
5266
5288
  broadcastHandlerList();
5267
5289
  };
5268
5290
  const unregisterHandler = (agentId) => {
@@ -7823,7 +7845,7 @@ async function fkill(inputs, options = {}) {
7823
7845
  }
7824
7846
  }
7825
7847
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7826
- var VERSION = "0.1.0-beta.7";
7848
+ var VERSION = "0.1.0";
7827
7849
  var checkIfRelayServerIsRunning = async (port, token) => {
7828
7850
  try {
7829
7851
  const healthUrl = token ? `http://localhost:${port}/health?${RELAY_TOKEN_PARAM}=${encodeURIComponent(token)}` : `http://localhost:${port}/health`;
@@ -7841,7 +7863,10 @@ var connectRelay = async (options) => {
7841
7863
  const { handler, token } = options;
7842
7864
  let relayServer = null;
7843
7865
  let isRelayHost = false;
7844
- const isRelayServerRunning = await checkIfRelayServerIsRunning(relayPort, token);
7866
+ const isRelayServerRunning = await checkIfRelayServerIsRunning(
7867
+ relayPort,
7868
+ token
7869
+ );
7845
7870
  if (isRelayServerRunning) {
7846
7871
  relayServer = await connectToExistingRelay(relayPort, handler, token);
7847
7872
  } else {
package/dist/client.cjs CHANGED
@@ -210,7 +210,7 @@ var createRelayAgentProvider = (options) => {
210
210
  rejectNextMessage = null;
211
211
  }
212
212
  };
213
- signal.addEventListener("abort", handleAbort);
213
+ signal.addEventListener("abort", handleAbort, { once: true });
214
214
  const handleConnectionChange = (connected) => {
215
215
  if (!connected && !isDone) {
216
216
  errorMessage = "Relay connection lost";
@@ -260,7 +260,10 @@ var createRelayAgentProvider = (options) => {
260
260
  signal.removeEventListener("abort", handleAbort);
261
261
  throw new Error("Relay connection is not open");
262
262
  }
263
- const didSendRequest = relayClient.sendAgentRequest(agentId, contextWithSession);
263
+ const didSendRequest = relayClient.sendAgentRequest(
264
+ agentId,
265
+ contextWithSession
266
+ );
264
267
  if (!didSendRequest) {
265
268
  unsubscribeConnection();
266
269
  unsubscribeMessage();
@@ -318,12 +321,16 @@ var createRelayAgentProvider = (options) => {
318
321
  reject(new Error(message.content ?? "Operation failed"));
319
322
  }
320
323
  });
321
- const unsubscribeConnection = relayClient.onConnectionChange((connected) => {
322
- if (!connected) {
323
- cleanup();
324
- reject(new Error("Connection lost while waiting for operation response"));
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
+ }
325
332
  }
326
- });
333
+ );
327
334
  });
328
335
  };
329
336
  const undo = async () => {
@@ -1,2 +1,449 @@
1
- var ReactGrabCodex=(function(exports){'use strict';var $=4722,q=3e3,D="token",G=(i={})=>{let n=i.serverUrl??`ws://localhost:${$}`,c=i.autoReconnect??true,E=i.reconnectIntervalMs??q,h=i.token,s=null,f=false,A=[],C=null,t=null,o=null,w=false,y=new Set,g=new Set,r=new Set,d=()=>{!c||C||w||(C=setTimeout(()=>{C=null,p().catch(()=>{});},E));},l=e=>{try{let a=JSON.parse(e.data);if(a.type==="handlers"&&a.handlers){A=a.handlers;for(let S of g)S(A);}for(let S of y)S(a);}catch{}},p=()=>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,A=[];for(let P of g)P(A);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,C&&(clearTimeout(C),C=null),o&&(o(new Error("Connection aborted")),o=null),t=null,s?.close(),s=null,f=false,A=[];},m=()=>f,R=e=>s?.readyState===WebSocket.OPEN?(s.send(JSON.stringify(e)),true):false;return {connect:p,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:()=>A}},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,p=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&&(p="Relay connection lost",l=true,d&&(d(new Error(p)),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"&&(p=u.content??"Unknown error",l=true,d&&(d(new Error(p)),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,T)=>{r=b,d=T;});if(u.done)break;yield u.value;}if(p)throw new Error(p)}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="codex",x=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},A={name:"codex-agent",actions:[{id:"edit-with-codex",label:"Edit with Codex",shortcut:"Enter",onAction:C=>{C.enterPromptMode?.(f);},agent:f}]};s.registerPlugin(A);},E=window.__REACT_GRAB__;if(x(E)){c(E);return}window.addEventListener("react-grab:init",s=>{s instanceof CustomEvent&&x(s.detail)&&c(s.detail);},{once:true});let h=window.__REACT_GRAB__;x(h)&&c(h);};N();
2
- exports.attachAgent=N;exports.createCodexAgentProvider=Y;return exports;})({});
1
+ var ReactGrabCodex = (function (exports) {
2
+ 'use strict';
3
+
4
+ // ../relay/dist/client.js
5
+ var DEFAULT_RELAY_PORT = 4722;
6
+ var DEFAULT_RECONNECT_INTERVAL_MS = 3e3;
7
+ var RELAY_TOKEN_PARAM = "token";
8
+ var createRelayClient = (options = {}) => {
9
+ const serverUrl = options.serverUrl ?? `ws://localhost:${DEFAULT_RELAY_PORT}`;
10
+ const autoReconnect = options.autoReconnect ?? true;
11
+ const reconnectIntervalMs = options.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS;
12
+ const token = options.token;
13
+ let webSocketConnection = null;
14
+ let isConnectedState = false;
15
+ let availableHandlers = [];
16
+ let reconnectTimeoutId = null;
17
+ let pendingConnectionPromise = null;
18
+ let pendingConnectionReject = null;
19
+ let isIntentionalDisconnect = false;
20
+ const messageCallbacks = /* @__PURE__ */ new Set();
21
+ const handlersChangeCallbacks = /* @__PURE__ */ new Set();
22
+ const connectionChangeCallbacks = /* @__PURE__ */ new Set();
23
+ const scheduleReconnect = () => {
24
+ if (!autoReconnect || reconnectTimeoutId || isIntentionalDisconnect) return;
25
+ reconnectTimeoutId = setTimeout(() => {
26
+ reconnectTimeoutId = null;
27
+ connect().catch(() => {
28
+ });
29
+ }, reconnectIntervalMs);
30
+ };
31
+ const handleMessage = (event) => {
32
+ try {
33
+ const message = JSON.parse(event.data);
34
+ if (message.type === "handlers" && message.handlers) {
35
+ availableHandlers = message.handlers;
36
+ for (const callback of handlersChangeCallbacks) {
37
+ callback(availableHandlers);
38
+ }
39
+ }
40
+ for (const callback of messageCallbacks) {
41
+ callback(message);
42
+ }
43
+ } catch {
44
+ }
45
+ };
46
+ const connect = () => {
47
+ if (webSocketConnection?.readyState === WebSocket.OPEN) {
48
+ return Promise.resolve();
49
+ }
50
+ if (pendingConnectionPromise) {
51
+ return pendingConnectionPromise;
52
+ }
53
+ isIntentionalDisconnect = false;
54
+ pendingConnectionPromise = new Promise((resolve, reject) => {
55
+ pendingConnectionReject = reject;
56
+ const connectionUrl = token ? `${serverUrl}?${RELAY_TOKEN_PARAM}=${encodeURIComponent(token)}` : serverUrl;
57
+ webSocketConnection = new WebSocket(connectionUrl);
58
+ webSocketConnection.onopen = () => {
59
+ pendingConnectionPromise = null;
60
+ pendingConnectionReject = null;
61
+ isConnectedState = true;
62
+ for (const callback of connectionChangeCallbacks) {
63
+ callback(true);
64
+ }
65
+ resolve();
66
+ };
67
+ webSocketConnection.onmessage = handleMessage;
68
+ webSocketConnection.onclose = () => {
69
+ if (pendingConnectionReject) {
70
+ pendingConnectionReject(new Error("WebSocket connection closed"));
71
+ pendingConnectionReject = null;
72
+ }
73
+ pendingConnectionPromise = null;
74
+ isConnectedState = false;
75
+ availableHandlers = [];
76
+ for (const callback of handlersChangeCallbacks) {
77
+ callback(availableHandlers);
78
+ }
79
+ for (const callback of connectionChangeCallbacks) {
80
+ callback(false);
81
+ }
82
+ scheduleReconnect();
83
+ };
84
+ webSocketConnection.onerror = () => {
85
+ pendingConnectionPromise = null;
86
+ pendingConnectionReject = null;
87
+ isConnectedState = false;
88
+ reject(new Error("WebSocket connection failed"));
89
+ };
90
+ });
91
+ return pendingConnectionPromise;
92
+ };
93
+ const disconnect = () => {
94
+ isIntentionalDisconnect = true;
95
+ if (reconnectTimeoutId) {
96
+ clearTimeout(reconnectTimeoutId);
97
+ reconnectTimeoutId = null;
98
+ }
99
+ if (pendingConnectionReject) {
100
+ pendingConnectionReject(new Error("Connection aborted"));
101
+ pendingConnectionReject = null;
102
+ }
103
+ pendingConnectionPromise = null;
104
+ webSocketConnection?.close();
105
+ webSocketConnection = null;
106
+ isConnectedState = false;
107
+ availableHandlers = [];
108
+ };
109
+ const isConnected = () => isConnectedState;
110
+ const sendMessage = (message) => {
111
+ if (webSocketConnection?.readyState === WebSocket.OPEN) {
112
+ webSocketConnection.send(JSON.stringify(message));
113
+ return true;
114
+ }
115
+ return false;
116
+ };
117
+ const sendAgentRequest = (agentId, context) => {
118
+ return sendMessage({
119
+ type: "agent-request",
120
+ agentId,
121
+ sessionId: context.sessionId,
122
+ context
123
+ });
124
+ };
125
+ const abortAgent = (agentId, sessionId) => {
126
+ sendMessage({
127
+ type: "agent-abort",
128
+ agentId,
129
+ sessionId
130
+ });
131
+ };
132
+ const undoAgent = (agentId, sessionId) => {
133
+ return sendMessage({
134
+ type: "agent-undo",
135
+ agentId,
136
+ sessionId
137
+ });
138
+ };
139
+ const redoAgent = (agentId, sessionId) => {
140
+ return sendMessage({
141
+ type: "agent-redo",
142
+ agentId,
143
+ sessionId
144
+ });
145
+ };
146
+ const onMessage = (callback) => {
147
+ messageCallbacks.add(callback);
148
+ return () => messageCallbacks.delete(callback);
149
+ };
150
+ const onHandlersChange = (callback) => {
151
+ handlersChangeCallbacks.add(callback);
152
+ return () => handlersChangeCallbacks.delete(callback);
153
+ };
154
+ const onConnectionChange = (callback) => {
155
+ connectionChangeCallbacks.add(callback);
156
+ queueMicrotask(() => {
157
+ if (connectionChangeCallbacks.has(callback)) {
158
+ callback(isConnectedState);
159
+ }
160
+ });
161
+ return () => connectionChangeCallbacks.delete(callback);
162
+ };
163
+ const getAvailableHandlers = () => availableHandlers;
164
+ return {
165
+ connect,
166
+ disconnect,
167
+ isConnected,
168
+ sendAgentRequest,
169
+ abortAgent,
170
+ undoAgent,
171
+ redoAgent,
172
+ onMessage,
173
+ onHandlersChange,
174
+ onConnectionChange,
175
+ getAvailableHandlers
176
+ };
177
+ };
178
+ var createRelayAgentProvider = (options) => {
179
+ const { relayClient, agentId } = options;
180
+ const checkConnection = async () => {
181
+ if (!relayClient.isConnected()) {
182
+ try {
183
+ await relayClient.connect();
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+ return relayClient.getAvailableHandlers().includes(agentId);
189
+ };
190
+ const send = async function* (context, signal) {
191
+ if (signal.aborted) {
192
+ throw new DOMException("Aborted", "AbortError");
193
+ }
194
+ yield "Connecting\u2026";
195
+ const sessionId = context.sessionId ?? `session-${Date.now()}-${Math.random().toString(36).slice(2)}`;
196
+ const contextWithSession = {
197
+ ...context,
198
+ sessionId
199
+ };
200
+ const messageQueue = [];
201
+ let resolveNextMessage = null;
202
+ let rejectNextMessage = null;
203
+ let isDone = false;
204
+ let errorMessage = null;
205
+ const handleAbort = () => {
206
+ relayClient.abortAgent(agentId, sessionId);
207
+ isDone = true;
208
+ if (resolveNextMessage) {
209
+ resolveNextMessage({ value: void 0, done: true });
210
+ resolveNextMessage = null;
211
+ rejectNextMessage = null;
212
+ }
213
+ };
214
+ signal.addEventListener("abort", handleAbort, { once: true });
215
+ const handleConnectionChange = (connected) => {
216
+ if (!connected && !isDone) {
217
+ errorMessage = "Relay connection lost";
218
+ isDone = true;
219
+ if (rejectNextMessage) {
220
+ rejectNextMessage(new Error(errorMessage));
221
+ resolveNextMessage = null;
222
+ rejectNextMessage = null;
223
+ }
224
+ }
225
+ };
226
+ const unsubscribeConnection = relayClient.onConnectionChange(
227
+ handleConnectionChange
228
+ );
229
+ const unsubscribeMessage = relayClient.onMessage((message) => {
230
+ if (message.sessionId !== sessionId) return;
231
+ if (message.type === "agent-status" && message.content) {
232
+ messageQueue.push(message.content);
233
+ if (resolveNextMessage) {
234
+ const nextMessage = messageQueue.shift();
235
+ if (nextMessage !== void 0) {
236
+ resolveNextMessage({ value: nextMessage, done: false });
237
+ resolveNextMessage = null;
238
+ rejectNextMessage = null;
239
+ }
240
+ }
241
+ } else if (message.type === "agent-done") {
242
+ isDone = true;
243
+ if (resolveNextMessage) {
244
+ resolveNextMessage({ value: void 0, done: true });
245
+ resolveNextMessage = null;
246
+ rejectNextMessage = null;
247
+ }
248
+ } else if (message.type === "agent-error") {
249
+ errorMessage = message.content ?? "Unknown error";
250
+ isDone = true;
251
+ if (rejectNextMessage) {
252
+ rejectNextMessage(new Error(errorMessage));
253
+ resolveNextMessage = null;
254
+ rejectNextMessage = null;
255
+ }
256
+ }
257
+ });
258
+ if (!relayClient.isConnected()) {
259
+ unsubscribeConnection();
260
+ unsubscribeMessage();
261
+ signal.removeEventListener("abort", handleAbort);
262
+ throw new Error("Relay connection is not open");
263
+ }
264
+ const didSendRequest = relayClient.sendAgentRequest(
265
+ agentId,
266
+ contextWithSession
267
+ );
268
+ if (!didSendRequest) {
269
+ unsubscribeConnection();
270
+ unsubscribeMessage();
271
+ signal.removeEventListener("abort", handleAbort);
272
+ throw new Error("Failed to send agent request: connection not open");
273
+ }
274
+ try {
275
+ while (true) {
276
+ if (messageQueue.length > 0) {
277
+ const next = messageQueue.shift();
278
+ if (next !== void 0) {
279
+ yield next;
280
+ }
281
+ continue;
282
+ }
283
+ if (isDone || signal.aborted) {
284
+ break;
285
+ }
286
+ const result = await new Promise(
287
+ (resolve, reject) => {
288
+ resolveNextMessage = resolve;
289
+ rejectNextMessage = reject;
290
+ }
291
+ );
292
+ if (result.done) break;
293
+ yield result.value;
294
+ }
295
+ if (errorMessage) {
296
+ throw new Error(errorMessage);
297
+ }
298
+ } finally {
299
+ signal.removeEventListener("abort", handleAbort);
300
+ unsubscribeConnection();
301
+ unsubscribeMessage();
302
+ }
303
+ };
304
+ const abort = async (sessionId) => {
305
+ relayClient.abortAgent(agentId, sessionId);
306
+ };
307
+ const waitForOperationResponse = (sessionId) => {
308
+ return new Promise((resolve, reject) => {
309
+ let didCleanup = false;
310
+ const cleanup = () => {
311
+ if (didCleanup) return;
312
+ didCleanup = true;
313
+ unsubscribeMessage();
314
+ unsubscribeConnection();
315
+ };
316
+ const unsubscribeMessage = relayClient.onMessage((message) => {
317
+ if (message.sessionId !== sessionId) return;
318
+ cleanup();
319
+ if (message.type === "agent-done") {
320
+ resolve();
321
+ } else if (message.type === "agent-error") {
322
+ reject(new Error(message.content ?? "Operation failed"));
323
+ }
324
+ });
325
+ const unsubscribeConnection = relayClient.onConnectionChange(
326
+ (connected) => {
327
+ if (!connected) {
328
+ cleanup();
329
+ reject(
330
+ new Error("Connection lost while waiting for operation response")
331
+ );
332
+ }
333
+ }
334
+ );
335
+ });
336
+ };
337
+ const undo = async () => {
338
+ const sessionId = `undo-${agentId}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
339
+ const didSend = relayClient.undoAgent(agentId, sessionId);
340
+ if (!didSend) {
341
+ throw new Error("Failed to send undo request: connection not open");
342
+ }
343
+ return waitForOperationResponse(sessionId);
344
+ };
345
+ const redo = async () => {
346
+ const sessionId = `redo-${agentId}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
347
+ const didSend = relayClient.redoAgent(agentId, sessionId);
348
+ if (!didSend) {
349
+ throw new Error("Failed to send redo request: connection not open");
350
+ }
351
+ return waitForOperationResponse(sessionId);
352
+ };
353
+ return {
354
+ send,
355
+ abort,
356
+ undo,
357
+ redo,
358
+ checkConnection,
359
+ supportsResume: true,
360
+ supportsFollowUp: true
361
+ };
362
+ };
363
+ var defaultRelayClient = null;
364
+ var getDefaultRelayClient = () => {
365
+ if (typeof window === "undefined") {
366
+ return null;
367
+ }
368
+ if (window.__REACT_GRAB_RELAY__) {
369
+ defaultRelayClient = window.__REACT_GRAB_RELAY__;
370
+ return defaultRelayClient;
371
+ }
372
+ if (!defaultRelayClient) {
373
+ defaultRelayClient = createRelayClient();
374
+ window.__REACT_GRAB_RELAY__ = defaultRelayClient;
375
+ }
376
+ return defaultRelayClient;
377
+ };
378
+
379
+ // src/client.ts
380
+ var AGENT_ID = "codex";
381
+ var isReactGrabApi = (value) => typeof value === "object" && value !== null && "registerPlugin" in value;
382
+ var createCodexAgentProvider = (providerOptions = {}) => {
383
+ const relayClient = providerOptions.relayClient ?? getDefaultRelayClient();
384
+ if (!relayClient) {
385
+ throw new Error("RelayClient is required in browser environments");
386
+ }
387
+ return createRelayAgentProvider({
388
+ relayClient,
389
+ agentId: AGENT_ID
390
+ });
391
+ };
392
+ var attachAgent = async () => {
393
+ if (typeof window === "undefined") return;
394
+ const relayClient = getDefaultRelayClient();
395
+ if (!relayClient) return;
396
+ try {
397
+ await relayClient.connect();
398
+ } catch {
399
+ return;
400
+ }
401
+ const provider = createRelayAgentProvider({
402
+ relayClient,
403
+ agentId: AGENT_ID
404
+ });
405
+ const attach = (api) => {
406
+ const agent = { provider, storage: sessionStorage };
407
+ const plugin = {
408
+ name: "codex-agent",
409
+ actions: [
410
+ {
411
+ id: "edit-with-codex",
412
+ label: "Edit with Codex",
413
+ shortcut: "Enter",
414
+ onAction: (actionContext) => {
415
+ actionContext.enterPromptMode?.(agent);
416
+ },
417
+ agent
418
+ }
419
+ ]
420
+ };
421
+ api.registerPlugin(plugin);
422
+ };
423
+ const existingApi = window.__REACT_GRAB__;
424
+ if (isReactGrabApi(existingApi)) {
425
+ attach(existingApi);
426
+ return;
427
+ }
428
+ window.addEventListener(
429
+ "react-grab:init",
430
+ (event) => {
431
+ if (!(event instanceof CustomEvent)) return;
432
+ if (!isReactGrabApi(event.detail)) return;
433
+ attach(event.detail);
434
+ },
435
+ { once: true }
436
+ );
437
+ const apiAfterListener = window.__REACT_GRAB__;
438
+ if (isReactGrabApi(apiAfterListener)) {
439
+ attach(apiAfterListener);
440
+ }
441
+ };
442
+ attachAgent();
443
+
444
+ exports.attachAgent = attachAgent;
445
+ exports.createCodexAgentProvider = createCodexAgentProvider;
446
+
447
+ return exports;
448
+
449
+ })({});
package/dist/client.js CHANGED
@@ -208,7 +208,7 @@ var createRelayAgentProvider = (options) => {
208
208
  rejectNextMessage = null;
209
209
  }
210
210
  };
211
- signal.addEventListener("abort", handleAbort);
211
+ signal.addEventListener("abort", handleAbort, { once: true });
212
212
  const handleConnectionChange = (connected) => {
213
213
  if (!connected && !isDone) {
214
214
  errorMessage = "Relay connection lost";
@@ -258,7 +258,10 @@ var createRelayAgentProvider = (options) => {
258
258
  signal.removeEventListener("abort", handleAbort);
259
259
  throw new Error("Relay connection is not open");
260
260
  }
261
- const didSendRequest = relayClient.sendAgentRequest(agentId, contextWithSession);
261
+ const didSendRequest = relayClient.sendAgentRequest(
262
+ agentId,
263
+ contextWithSession
264
+ );
262
265
  if (!didSendRequest) {
263
266
  unsubscribeConnection();
264
267
  unsubscribeMessage();
@@ -316,12 +319,16 @@ var createRelayAgentProvider = (options) => {
316
319
  reject(new Error(message.content ?? "Operation failed"));
317
320
  }
318
321
  });
319
- const unsubscribeConnection = relayClient.onConnectionChange((connected) => {
320
- if (!connected) {
321
- cleanup();
322
- reject(new Error("Connection lost while waiting for operation response"));
322
+ const unsubscribeConnection = relayClient.onConnectionChange(
323
+ (connected) => {
324
+ if (!connected) {
325
+ cleanup();
326
+ reject(
327
+ new Error("Connection lost while waiting for operation response")
328
+ );
329
+ }
323
330
  }
324
- });
331
+ );
325
332
  });
326
333
  };
327
334
  const undo = async () => {
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "@react-grab/codex",
3
- "version": "0.1.0-beta.8",
4
- "type": "module",
3
+ "version": "0.1.0",
5
4
  "bin": {
6
5
  "react-grab-codex": "./dist/cli.cjs"
7
6
  },
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "type": "module",
11
+ "browser": "dist/client.global.js",
8
12
  "exports": {
9
13
  "./client": {
10
14
  "types": "./dist/client.d.ts",
@@ -19,19 +23,15 @@
19
23
  "./dist/*": "./dist/*.js",
20
24
  "./dist/*.js": "./dist/*.js"
21
25
  },
22
- "browser": "dist/client.global.js",
23
- "files": [
24
- "dist"
25
- ],
26
+ "dependencies": {
27
+ "@openai/codex-sdk": "^0.66.0",
28
+ "@react-grab/relay": "0.1.0",
29
+ "react-grab": "0.1.0"
30
+ },
26
31
  "devDependencies": {
27
32
  "@types/node": "^22.10.7",
28
33
  "tsup": "^8.4.0",
29
- "@react-grab/utils": "0.1.0-beta.8"
30
- },
31
- "dependencies": {
32
- "@openai/codex-sdk": "^0.66.0",
33
- "@react-grab/relay": "0.1.0-beta.8",
34
- "react-grab": "0.1.0-beta.8"
34
+ "@react-grab/utils": "0.1.0"
35
35
  },
36
36
  "scripts": {
37
37
  "dev": "tsup --watch",