@mitralab.io/platform-sdk 1.2.0 → 1.3.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 1.3.0-beta.0
6
+
7
+ - The direct channel to the chat's box now comes from `@mitralab.io/sdk-core@0.2.9-beta.1`. This
8
+ package passes it the API URL and keeps only the Copilot WebSocket and SSE streams a chat falls
9
+ back to, and the offline outbox for what is sent over REST. The browser behavior is the same:
10
+ same host rule, redial with replay, `channelDeclined`, `channelReconnecting` and
11
+ `channelConnected` events, and message and interrupt on the box.
12
+ - Only a business agent's chat (one with an `agentId`) is born on the box (`runtime: "T3"`) and
13
+ asks for the channel. Any other chat is created without `runtime` and stays on the Copilot
14
+ stream, since the Copilot refuses T3 outside an agent chat.
15
+ - `transport: "http"` changes meaning: it now reaches the box over its HTTP routes (POST to send,
16
+ SSE to read) instead of the Copilot SSE, which becomes its fallback, and an agent chat created
17
+ with it is also born on the box. This is why the minor version moves.
18
+ - A message sent on the box counts as sent only when the box starts the admitted turn; the session
19
+ emits `accepted` then. A box that confirms nothing within 35 seconds fails the send, and a box
20
+ refusal rejects with the box's `error_code` and message.
21
+ - `channelDeclined` is emitted for every fallback, with the reasons `unavailable`, `body`, `host`,
22
+ `websocket` and `http_unsupported`.
23
+ - The channel request is not reported to the client's global `onError`, and
24
+ `agentTasks.channel(taskId)` is not part of the public surface: its answer carries the box grant.
25
+ - `inputUnsent`, `inputSent` and the `INPUT_UNSENT` error reach the session's `raw` and `error`
26
+ listeners on a chat served by the box too, and a listener that throws no longer stops the outbox
27
+ nor the session's `close()`.
28
+
5
29
  ## 1.2.0
6
30
 
7
31
  Stable release of the 1.1.4-beta.0 to 1.2.0-beta.6 line. Everything below is already on the
package/README.md CHANGED
@@ -59,9 +59,9 @@ The Platform SDK owns:
59
59
  - proactive token refresh before authenticated native requests
60
60
  - one retry after reactive `401` recovery with the current session
61
61
  - browser HTTP transport and public application initialization
62
- - Agent WebSocket and HTTP/SSE live channels
62
+ - the Copilot WebSocket and HTTP/SSE streams an Agent chat falls back to, and the offline outbox for its prompts
63
63
 
64
- `@mitralab.io/sdk-core` owns the shared entities, custom queries, Functions, integrations, Agent task lifecycle, `auth.me`, safe paths, and structural response validation. Server Function code should use `@mitralab.io/functions-sdk` instead of this browser SDK.
64
+ `@mitralab.io/sdk-core` owns the shared entities, custom queries, Functions, integrations, Agent task lifecycle and the direct channel to the chat's box, `auth.me`, safe paths, and structural response validation. Server Function code should use `@mitralab.io/functions-sdk` instead of this browser SDK.
65
65
 
66
66
  ## Authentication
67
67
 
@@ -384,7 +384,7 @@ authenticated `functions.executeAsync` plus `functions.getExecution` flow after
384
384
 
385
385
  ## Agent tasks and credentials
386
386
 
387
- The browser-safe Copilot modules call the native service directly. `agentTasks` provides list, read, create, rename, archive, HTTP input, history, and live sessions. These direct primitives match the Copilot producer and MCP contract. Core owns session state, queueing, recovery, and reconciliation; Platform supplies only authenticated browser WebSocket/SSE channels. `agentCredentials` provides safe credential status, model discovery, API key, OAuth, and device authorization flows. Raw credentials are write-only.
387
+ The browser-safe Copilot modules call the native service directly. `agentTasks` provides list, read, create, rename, archive, HTTP input, history, and live sessions. These direct primitives match the Copilot producer and MCP contract. Core owns session state, queueing, recovery, reconciliation, and the direct channel to the chat's box; Platform supplies the authenticated Copilot WebSocket/SSE streams a chat falls back to and the offline outbox. `agentCredentials` provides safe credential status, model discovery, API key, OAuth, and device authorization flows. Raw credentials are write-only.
388
388
 
389
389
  ```typescript
390
390
  const credentials = await mitra.agentCredentials.list()
@@ -392,11 +392,12 @@ const models = await mitra.agentCredentials.listModels()
392
392
  const chats = await mitra.agentTasks.list({ archived: false, size: 20 })
393
393
  ```
394
394
 
395
- Create a live task lazily on the first message:
395
+ Create a live task lazily on the first message. `agentId` names the business agent the chat belongs to; without it the chat is a plain Copilot chat:
396
396
 
397
397
  ```typescript
398
398
  const session = mitra.agentTasks.session({
399
399
  create: true,
400
+ agentId,
400
401
  agentType: models[0].agentType,
401
402
  reasoningEffort: models[0].reasoningOptions[0],
402
403
  })
@@ -412,13 +413,19 @@ unsubscribe()
412
413
  session.close()
413
414
  ```
414
415
 
415
- A chat created with `create: true` over the `auto` or `websocket` transport is born on the T3 box (`runtime: "T3"` in the create request), so the first open does not wait for the box to adopt it; a chat created with `transport: "http"` stays on the Copilot runner. Pass `runtime: "RUNNER"` or `runtime: "T3"` to decide explicitly.
416
+ A business agent's chat (`create: true` with an `agentId`) is born on the T3 box (`runtime: "T3"` in the create request) whenever the session can reach the box, over any transport, `http` included, so the first open does not wait for the box to adopt it. A chat without `agentId` is created without `runtime` and never asks for the direct channel: the Copilot refuses T3 outside an agent chat (`RUNTIME_REQUIRES_AGENT_APP`). Pass `runtime: "RUNNER"` or `runtime: "T3"` to decide explicitly.
416
417
 
417
418
  `session({ create: true, agentId, scope: "ACCOUNT" })` and `agentTasks.create({ agentType, agentId, scope: "ACCOUNT" })` send `scope` in the create body, so the chat runs on the credential the person connected to their own account, the one the IDE and the builder read, instead of the agent's connection. The Copilot honors `ACCOUNT` only for apps listed by flag and answers `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise; a turn without a credential on the account fails with `ACCOUNT_CREDENTIAL_MISSING`. Through `agentTasks.session(...)` those refusals reach the session `error` event with the message and code the Copilot sends; through `agentTasks.create()` and the `agentCredentials` methods they reject the promise with a `MitraApiError` carrying status and code. No platform session is involved: the app token is used as always. Without `scope` nothing changes.
418
419
 
419
- Open an existing task with `session({ taskId })`. The default `auto` transport refreshes before connecting, asks the Copilot once where the chat is served, and opens whichever channel it names: the box that runs the agent when one is offered, `/copilot/ws/tasks/{taskId}` otherwise. The box is followed only when its `wss:` address is on the API host (proxy mode, `/__ide/<box>/...`) or on a fleet box host (direct mode, `<port>-<box>.e2b.app` or `<port>-<box>.e2b-<fleet>.mitralab.ai`), the same allowlist the gateway trusts on `/__ide`; an offer the SDK refuses, because of its host or an unreadable body, emits a `raw` event of type `channelDeclined` (payload `reason`, `host`) and the chat follows the Copilot socket. The Copilot holds that request while the box boots and answers only once the box is ready or cannot be had; the SDK does not poll. The choice belongs to the server, never to application configuration, so a Copilot that stops offering the box leaves every application on the Copilot socket without a republish. Opening the box never asks it to replay, whether the conversation is new to the session or is being opened again after an idle close: what an idle conversation missed is history, which the application loads over REST. A box socket that drops in the middle of a turn is redialed by the SDK itself, with a bounded backoff (1, 2, 4, 8 and 16 seconds) and the replay from the last position seen on that socket, so the answer keeps streaming; a position taken on one box is forgotten when the Copilot points the conversation to another box; replayed `textChunk` frames reach the `delta` event like live text. While that happens the session emits `raw` events of type `channelReconnecting` (payload `attempt`, `maxAttempts`, `reason`) and `channelConnected` (payload `attempt`); the session `status` stays `streaming`, because Core has no reconnecting status. The disconnect reaches Core, and with it the `error` event, only when the attempts run out or the Copilot no longer offers the box. A drop with no turn in flight, a channel taken over by another tab (close code 4409), and any close of the Copilot socket the session did not ask for are reported at once, whatever the code, so the next send reopens the channel instead of waiting on a socket that is gone. Recovery through persisted history plus the HTTP/SSE channel is unchanged. Set `transport: "http"` when WebSockets are unavailable. Messages sent during a turn enter a FIFO queue with a maximum of 10 items; the session also exposes edit, remove, clear, approval, cancel, history, close, and typed events.
420
+ Open an existing task with `session({ taskId })`. A session on a business agent's chat (a task with an `agentId`) asks the Copilot once where the chat is served (`POST /copilot/api/v1/tasks/{taskId}/channel`) and talks to the box that runs the agent when one is offered; any other chat never asks and stays on the Copilot stream described below. This direct channel lives in `@mitralab.io/sdk-core` (0.2.9 and later); this package passes it the API URL and nothing else, so the rules below are Core's. The Copilot holds that request while the box boots and answers only once the box is ready or cannot be had; the SDK does not poll. The choice belongs to the server, never to application configuration, so a Copilot that stops offering the box leaves every application on the Copilot stream without a republish.
420
421
 
421
- On the direct channel the message and the interrupt are written on the box socket itself, as the frames the box reads from a client: `{ "type": "message", "content", "agentType"?, "reasoningEffort"? }` and `{ "type": "interrupt" }`. The box asks the Copilot to admit the turn and the Copilot records the history; the admission, its refusal and the turn itself come back on that same socket as the events the session already handles, so a message the box refuses surfaces through the `error` event with the box's code. `POST /copilot/api/v1/tasks/{taskId}/inputs` is the path when there is no box socket: a chat served by the Copilot socket or by SSE, a box socket that is not open at the moment of the send (a drop being redialed included), and every approval answer. A frame written on a socket that closes before the box acknowledges it is not sent again over REST, because the box may already have admitted the turn; the redial replays the box log, as it does for a turn started over REST.
422
+ - **Transport.** `auto`, the default, uses the box socket in the browser. `websocket` uses the box socket. `http` uses the box's HTTP routes next to the socket path (`POST .../api/mitra/chat/messages` to send, `GET .../api/mitra/chat/events` as SSE to read), for browsers or proxies where WebSockets are unavailable; before 1.3.0 it meant the Copilot SSE, which is now only its fallback. A business agent's new chat is created with `runtime: "T3"` so it is born on its box, unless the session names a runtime.
423
+ - **Host rule.** The box is followed only when its address is on the API host (proxy mode, `/__ide/<box>/...`) or on a fleet box host over `wss:` (direct mode, `<port>-<box>.e2b.app` or `<port>-<box>.e2b-<fleet>.mitralab.ai`), the same allowlist the gateway trusts on `/__ide`.
424
+ - **Fallback, always visible.** When the Copilot offers no box (a `202` or an error), the body has no address, the host is outside the rule, the box cannot be reached, or the box has no HTTP routes, the chat follows the Copilot stream (`/copilot/ws/tasks/{taskId}`, falling back to `/copilot/api/v1/tasks/{taskId}/events` for `auto`) and the session first emits a `raw` event of type `channelDeclined` with `reason` `unavailable`, `body`, `host`, `websocket` or `http_unsupported` (and `host` or `error` when known). A channel request that fails is not reported to the client's global `onError`: it is not an error for the application.
425
+ - **Sending.** On the box, the message and the interrupt go to the box itself, as the frames it reads from a client: `{ "type": "message", "content", "agentType"?, "reasoningEffort"? }` and `{ "type": "interrupt" }`. The box asks the Copilot to admit the turn and the Copilot records the history. The session emits `accepted` once the box starts the admitted turn, or once the Copilot accepts a REST send; a message the box refuses surfaces through the `error` event with the box's code, and a box that confirms nothing within 35 seconds fails the send. `POST /copilot/api/v1/tasks/{taskId}/inputs` is the path when there is no box wire: a chat on the Copilot stream, a box wire that is down at the moment of the send (a drop being redialed included), and every approval answer. A message whose wire drops before the box answers is not sent again over REST, because the box may already have admitted the turn; the redial replays the box log.
426
+ - **Drops.** Opening the box never asks it to replay: what an idle chat missed is history, which the application loads over REST. A box wire that drops in the middle of a turn is redialed with a bounded backoff (1, 2, 4, 8 and 16 seconds) and the replay from the last position seen on that box, so the answer keeps streaming; replayed `textChunk` frames reach the `delta` event like live text. While that happens the session emits `raw` events of type `channelReconnecting` (payload `attempt`, `maxAttempts`, `reason`) and `channelConnected` (payload `attempt`); the session `status` stays `streaming`. The disconnect reaches the session, and with it the `error` event, only when the attempts run out or the Copilot no longer offers the box. A drop with no turn in flight, a channel taken over by another tab (close code 4409), and any close of the Copilot socket the session did not ask for are reported at once, so the next send reopens the channel. Recovery through persisted history is unchanged.
427
+
428
+ Messages sent during a turn enter a FIFO queue with a maximum of 10 items; the session also exposes edit, remove, clear, approval, cancel, history, close, and typed events.
422
429
 
423
430
  A prompt sent while the browser says it is offline (`navigator.onLine === false`) does not enter Core at all, because Core opens the channel and reads the turn baseline before the prompt goes out and every one of those requests would fail first: the session keeps the prompt in an outbox, emits a `raw` event of type `inputUnsent` (payload `attempt` 0, `reason`, `waitingForOnline` true) and hands it to Core, in order, when the browser fires `online`; the turn starts then. A prompt whose `POST /inputs` went out but got no response at all is kept the same way: the session sends the same request again when the browser fires `online` or on a bounded backoff (2, 5, 10, 20 and 40 seconds), while the turn stays `streaming`, with `inputUnsent` events (payload `attempt`, `reason`, `waitingForOnline`, `retryInMs` when a timer is armed) and, once it goes through, `inputSent` (payload `attempts`). A response from the server, an error included, is never retried: the prompt fails through the `error` event as before. A session closed with a prompt still waiting emits `error` with code `INPUT_UNSENT` before it goes quiet, and `sendAndWait` rejects. The retry cannot tell a request the server never received from one whose response was lost on the way back, so a prompt may reach the server twice in that case; the Copilot's `/inputs` accepts no client message id yet. The public `agentTasks.sendInput` primitive is not held back: it fails immediately, as it always did.
424
431
 
package/dist/index.cjs CHANGED
@@ -1994,13 +1994,23 @@ function neverSent(pending) {
1994
1994
  );
1995
1995
  }
1996
1996
  var AgentInputOutbox = class {
1997
- constructor(tasks, announce, network = browserNetwork) {
1997
+ constructor(tasks, network = browserNetwork) {
1998
1998
  this.tasks = tasks;
1999
- this.announce = announce;
2000
1999
  this.network = network;
2001
2000
  }
2002
2001
  held = /* @__PURE__ */ new Map();
2003
2002
  gated = /* @__PURE__ */ new Map();
2003
+ hearers = /* @__PURE__ */ new Set();
2004
+ /** Returns the way to stop hearing. */
2005
+ listen(hearer) {
2006
+ this.hearers.add(hearer);
2007
+ return () => this.hearers.delete(hearer);
2008
+ }
2009
+ announce(taskId, event) {
2010
+ for (const hearer of this.hearers) {
2011
+ if (hearer.taskId() === taskId) hearer.hear(event);
2012
+ }
2013
+ }
2004
2014
  async sendInput(taskId, input) {
2005
2015
  try {
2006
2016
  await this.tasks.sendInput(taskId, input);
@@ -2142,9 +2152,40 @@ var AgentInputOutbox = class {
2142
2152
  else this.held.delete(taskId);
2143
2153
  }
2144
2154
  };
2155
+ function notify(listeners, payload) {
2156
+ for (const listener of listeners) {
2157
+ try {
2158
+ listener(payload);
2159
+ } catch {
2160
+ }
2161
+ }
2162
+ }
2145
2163
  function holdSendsWhileOffline(session, outbox) {
2146
2164
  const passThrough = (prompt) => !outbox.offline || !prompt.trim() || session.status === "closed";
2165
+ const raws = /* @__PURE__ */ new Set();
2166
+ const errors = /* @__PURE__ */ new Set();
2167
+ const outboxListeners = { raw: raws, error: errors };
2168
+ const stopHearing = outbox.listen({
2169
+ taskId: () => session.taskId,
2170
+ hear: (event) => {
2171
+ if (session.status === "closed") return;
2172
+ notify(raws, event);
2173
+ if (event.type !== "error") return;
2174
+ const payload = event.payload;
2175
+ notify(errors, { code: payload.code, error: payload.message });
2176
+ }
2177
+ });
2147
2178
  const gated = {
2179
+ on: (event, handler) => {
2180
+ const off = session.on(event, handler);
2181
+ const own = outboxListeners[event];
2182
+ if (!own) return off;
2183
+ own.add(handler);
2184
+ return () => {
2185
+ own.delete(handler);
2186
+ off();
2187
+ };
2188
+ },
2148
2189
  send: (prompt, options) => {
2149
2190
  if (passThrough(prompt)) {
2150
2191
  session.send(prompt, options);
@@ -2160,7 +2201,13 @@ function holdSendsWhileOffline(session, outbox) {
2160
2201
  }).then(() => turn);
2161
2202
  },
2162
2203
  close: () => {
2163
- outbox.abandonGated(session, session.taskId);
2204
+ if (session.status !== "closed") {
2205
+ outbox.abandonGated(session, session.taskId);
2206
+ if (session.taskId) outbox.abandon(session.taskId);
2207
+ }
2208
+ stopHearing();
2209
+ raws.clear();
2210
+ errors.clear();
2164
2211
  session.close();
2165
2212
  }
2166
2213
  };
@@ -2172,9 +2219,6 @@ function holdSendsWhileOffline(session, outbox) {
2172
2219
  // src/modules/agent-session.ts
2173
2220
  var CONNECT_TIMEOUT_MS = 15e3;
2174
2221
  var SILENCE_TIMEOUT_MS = 6e4;
2175
- var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3];
2176
- var SUPERSEDED_CLOSE_CODE = 4409;
2177
- var SOCKET_OPEN = 1;
2178
2222
  var SilenceWatchdog = class {
2179
2223
  constructor(onSilence) {
2180
2224
  this.onSilence = onSilence;
@@ -2212,50 +2256,6 @@ function expectEvent(value) {
2212
2256
  ...typeof event.sequence === "number" ? { sequence: event.sequence } : {}
2213
2257
  };
2214
2258
  }
2215
- var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
2216
- function isSameGateway(candidate, apiUrl) {
2217
- try {
2218
- const target = new URL(candidate);
2219
- if (target.protocol !== "ws:" && target.protocol !== "wss:") return false;
2220
- if (target.host === new URL(apiUrl).host) return true;
2221
- return target.protocol === "wss:" && FLEET_BOX_HOST.test(target.host);
2222
- } catch {
2223
- return false;
2224
- }
2225
- }
2226
- function hostOf(url) {
2227
- try {
2228
- return new URL(url).host;
2229
- } catch {
2230
- return void 0;
2231
- }
2232
- }
2233
- function boxAddress(wsUrl) {
2234
- const url = new URL(wsUrl);
2235
- return `${url.origin}${url.pathname}`;
2236
- }
2237
- function toDirectChannel(body, apiUrl) {
2238
- if (typeof body !== "object" || body === null) return { declined: { reason: "body" } };
2239
- const channel = body;
2240
- if (typeof channel.wsUrl !== "string") return { declined: { reason: "body" } };
2241
- if (!isSameGateway(channel.wsUrl, apiUrl)) {
2242
- const host = hostOf(channel.wsUrl);
2243
- return { declined: { reason: "host", ...host === void 0 ? {} : { host } } };
2244
- }
2245
- return {
2246
- wsUrl: channel.wsUrl,
2247
- lastSequence: typeof channel.lastSequence === "number" && channel.lastSequence > 0 ? channel.lastSequence : 0
2248
- };
2249
- }
2250
- function sleep(ms, signal) {
2251
- return new Promise((resolve) => {
2252
- const timer = globalThis.setTimeout(resolve, ms);
2253
- signal?.addEventListener("abort", () => {
2254
- globalThis.clearTimeout(timer);
2255
- resolve();
2256
- }, { once: true });
2257
- });
2258
- }
2259
2259
  function parseEvent(raw) {
2260
2260
  if (typeof raw !== "string") return expectEvent(raw);
2261
2261
  try {
@@ -2264,26 +2264,6 @@ function parseEvent(raw) {
2264
2264
  return null;
2265
2265
  }
2266
2266
  }
2267
- function asDelta(event) {
2268
- if (event.type !== "textChunk") return event;
2269
- const kind = asObject(event.payload)?.kind;
2270
- return { ...event, type: kind === "thinking" ? "thinking" : "textDelta" };
2271
- }
2272
- var TURN_FRAME_TYPES = /* @__PURE__ */ new Set(["textDelta", "thinking", "toolCall", "toolResult"]);
2273
- var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
2274
- function turnAfter(event, inTurn) {
2275
- if (TURN_FRAME_TYPES.has(event.type)) return true;
2276
- if (event.type === "error") return false;
2277
- if (event.type === "stepFinish") {
2278
- const payload = asObject(event.payload);
2279
- if (TURN_END_REASONS.has(payload?.reason)) return false;
2280
- return asObject(payload?.lifecycle)?.interruptTerminal !== true;
2281
- }
2282
- return inTurn;
2283
- }
2284
- function channelEvent(type, payload) {
2285
- return { type, payload, timestamp: Date.now() };
2286
- }
2287
2267
  var BrowserAgentTaskEventSource = class {
2288
2268
  constructor(auth, apiUrl) {
2289
2269
  this.auth = auth;
@@ -2291,20 +2271,6 @@ var BrowserAgentTaskEventSource = class {
2291
2271
  }
2292
2272
  apiUrl;
2293
2273
  sseFallbackTasks = /* @__PURE__ */ new Set();
2294
- // Tasks whose last WebSocket was the box itself. A box socket that closes says nothing about
2295
- // WebSockets: the box went idle or the channel was superseded, and the answer is to ask the
2296
- // copilot for the channel again. Only the copilot's own socket failing sends a task to SSE.
2297
- directTasks = /* @__PURE__ */ new Set();
2298
- /**
2299
- * Ate onde esta sessao ja viu o log da caixa, por conversa, e de qual caixa esse log e. So o
2300
- * redial no meio de um turno pede repeticao a partir daqui; abrir a conversa de novo nunca
2301
- * pede. O cursor vale para uma caixa: outra caixa tem outro log, e um cursor da anterior
2302
- * repetiria turnos antigos como se fossem texto ao vivo.
2303
- */
2304
- boxCursors = /* @__PURE__ */ new Map();
2305
- boxAddresses = /* @__PURE__ */ new Map();
2306
- /** The box socket a task is talking on right now; absent while it is lost or being redialed. */
2307
- directSockets = /* @__PURE__ */ new Map();
2308
2274
  async open(taskId, observer, signal, transport = "auto") {
2309
2275
  if (transport === "http") return this.openSse(taskId, observer, signal);
2310
2276
  if (transport === "websocket") return this.openWebSocket(taskId, observer, signal);
@@ -2315,13 +2281,13 @@ var BrowserAgentTaskEventSource = class {
2315
2281
  const connection = await this.openWebSocket(taskId, {
2316
2282
  ...observer,
2317
2283
  onDisconnect: (error) => {
2318
- if (!this.directTasks.has(taskId)) this.sseFallbackTasks.add(taskId);
2284
+ this.sseFallbackTasks.add(taskId);
2319
2285
  observer.onDisconnect(error);
2320
2286
  }
2321
2287
  }, signal);
2322
2288
  return this.wrapAutoConnection(taskId, connection);
2323
2289
  } catch {
2324
- if (!this.directTasks.has(taskId)) this.sseFallbackTasks.add(taskId);
2290
+ this.sseFallbackTasks.add(taskId);
2325
2291
  return this.wrapAutoConnection(taskId, await this.openSse(taskId, observer, signal));
2326
2292
  }
2327
2293
  }
@@ -2329,30 +2295,10 @@ var BrowserAgentTaskEventSource = class {
2329
2295
  return {
2330
2296
  close: () => {
2331
2297
  this.sseFallbackTasks.delete(taskId);
2332
- this.directTasks.delete(taskId);
2333
- this.boxCursors.delete(taskId);
2334
- this.boxAddresses.delete(taskId);
2335
2298
  connection.close();
2336
2299
  }
2337
2300
  };
2338
2301
  }
2339
- /**
2340
- * Writes a message or an interrupt on the box socket when the task is on the direct channel
2341
- * and that socket is open right now. The box accepts the core's input as its own inbound
2342
- * frame, asks the copilot for admission itself and answers on this same socket with the
2343
- * frames the observer already reads, so the copilot's host socket is off the message path.
2344
- * False sends the caller to REST: no direct channel, a socket lost or mid-redial, or an
2345
- * approval, which stays on REST as it is.
2346
- *
2347
- * A frame written on a socket that closes before the box acknowledges it is not sent again
2348
- * over REST: the box may have admitted the turn already, and a second copy would start it
2349
- * twice. The redial replays the box log, which is the same recovery a REST 202 gets when its
2350
- * turn is lost.
2351
- */
2352
- sendOnChannel(taskId, input) {
2353
- if (input.type === "approval_response") return false;
2354
- return this.directSockets.get(taskId)?.send(JSON.stringify(input)) ?? false;
2355
- }
2356
2302
  async requireFreshToken() {
2357
2303
  const fresh = await this.auth.ensureFreshSession();
2358
2304
  const token = this.auth.accessToken;
@@ -2361,167 +2307,16 @@ var BrowserAgentTaskEventSource = class {
2361
2307
  }
2362
2308
  return token;
2363
2309
  }
2364
- /**
2365
- * Pergunta ao copilot onde esta conversa e servida. Nada aqui e fatal: uma recusa, uma
2366
- * resposta que nao entendemos ou uma rede que falhou significam apenas que a conversa segue
2367
- * pelo socket do copilot, que e como toda conversa era servida antes da caixa existir.
2368
- */
2369
- requestDirectChannel(taskId, token, signal) {
2370
- return this.askDirectChannel(taskId, token, signal).catch(() => null);
2371
- }
2372
- /**
2373
- * Like `requestDirectChannel`, but a request the network lost is thrown, not a refusal.
2374
- *
2375
- * One request. The copilot holds it while the box boots and answers 200 with the channel, or
2376
- * an error status once the box cannot be had. A 202 comes only from a copilot older than that
2377
- * contract, which used to mean "still booting, ask again": there is no channel to open, and
2378
- * the conversation follows the copilot socket. Polling here again would put the wait back on
2379
- * the client that the server now owns.
2380
- */
2381
- async askDirectChannel(taskId, token, signal) {
2382
- if (signal?.aborted) return null;
2383
- const url = `${this.apiUrl}/copilot/api/v1/tasks/${encodeURIComponent(taskId)}/channel`;
2384
- const response = await globalThis.fetch(url, {
2385
- method: "POST",
2386
- headers: { Authorization: `Bearer ${stripBearer2(token)}` },
2387
- ...signal ? { signal } : {}
2388
- });
2389
- if (response.status === 202 || !response.ok) return null;
2390
- try {
2391
- return toDirectChannel(await response.json(), this.apiUrl);
2392
- } catch {
2393
- return { declined: { reason: "body" } };
2394
- }
2395
- }
2396
2310
  async openWebSocket(taskId, observer, signal) {
2397
2311
  if (typeof globalThis.WebSocket !== "function") {
2398
2312
  throw new TypeError("WebSocket is not available.");
2399
2313
  }
2400
2314
  if (signal?.aborted) throw signal.reason ?? new Error("Agent WebSocket connection aborted.");
2401
2315
  const token = await this.requireFreshToken();
2402
- const answer = await this.requestDirectChannel(taskId, token, signal);
2403
- if (answer && "declined" in answer) observer.onEvent(channelEvent("channelDeclined", answer.declined));
2404
- const direct = answer && !("declined" in answer) ? answer : null;
2405
- if (direct) this.directTasks.add(taskId);
2406
- else this.directTasks.delete(taskId);
2407
- if (direct) return this.openDirect(taskId, direct, observer, signal);
2408
2316
  const url = `${this.apiUrl.replace(/^http/i, "ws")}/copilot/ws/tasks/${encodeURIComponent(taskId)}?token=${encodeURIComponent(stripBearer2(token))}`;
2409
- const socket = await this.dial(url, {
2410
- signal,
2411
- onFrame: (event) => observer.onEvent(event),
2412
- onLost: (error) => observer.onDisconnect(error)
2413
- });
2414
- return { close: () => socket.close() };
2415
- }
2416
- /** Forgets the cursor when the copilot points the conversation to a box other than the last dialed. */
2417
- adoptBox(taskId, channel) {
2418
- const box = boxAddress(channel.wsUrl);
2419
- if (this.boxAddresses.get(taskId) === box) return;
2420
- this.boxAddresses.set(taskId, box);
2421
- this.boxCursors.delete(taskId);
2422
- }
2423
- /**
2424
- * The box path. A drop in the middle of a turn is redialed from here, with the replay the
2425
- * box offers, so the core keeps one connection and one stream: reporting the drop instead
2426
- * would make it reconcile the turn from persisted history, which is the screen freezing and
2427
- * the rest of the answer landing at once. The core hears a disconnect only when the redial
2428
- * gives up, when the copilot no longer offers the box, or when there is no turn to resume:
2429
- * the sandbox pauses an idle box, and dialing it again would wake it for nobody.
2430
- *
2431
- * Opening never asks for a replay, whether the conversation is new to this session or was
2432
- * open before. What an idle conversation missed is history, which the app loads by REST. Beta
2433
- * 2026-09-14: a tab open overnight had its box replaced, and the open that followed replayed
2434
- * the old box's cursor against the new log, which put every old turn on screen as live text.
2435
- */
2436
- async openDirect(taskId, channel, observer, signal) {
2437
- this.adoptBox(taskId, channel);
2438
- this.boxCursors.set(taskId, channel.lastSequence);
2439
- const link = new AbortController();
2440
- const onAbort = () => link.abort(signal?.reason);
2441
- signal?.addEventListener("abort", onAbort, { once: true });
2442
- let inTurn = false;
2443
- let current = null;
2444
- const track = (socket) => {
2445
- if (socket) this.directSockets.set(taskId, socket);
2446
- else if (current && this.directSockets.get(taskId) === current) this.directSockets.delete(taskId);
2447
- current = socket;
2448
- };
2449
- const onFrame = (event) => {
2450
- if (typeof event.sequence === "number") {
2451
- const seen = this.boxCursors.get(taskId) ?? 0;
2452
- if (event.sequence > seen) this.boxCursors.set(taskId, event.sequence);
2453
- }
2454
- inTurn = turnAfter(event, inTurn);
2455
- observer.onEvent(event);
2456
- };
2457
- const onLost = (error, code) => {
2458
- track(null);
2459
- if (link.signal.aborted) return;
2460
- if (!inTurn || code === SUPERSEDED_CLOSE_CODE) {
2461
- observer.onDisconnect(error);
2462
- return;
2463
- }
2464
- void this.redial(taskId, error, link.signal, observer, { onFrame, onLost }).then(track);
2465
- };
2466
- track(await this.dial(channel.wsUrl, { signal: link.signal, onFrame, onLost }));
2467
- return {
2468
- close: () => {
2469
- signal?.removeEventListener("abort", onAbort);
2470
- link.abort();
2471
- current?.close();
2472
- track(null);
2473
- }
2474
- };
2317
+ return this.dial(url, observer, signal);
2475
2318
  }
2476
- async redial(taskId, cause, signal, observer, handlers) {
2477
- let lastError = cause;
2478
- for (const [index, delayMs] of RECONNECT_DELAYS_MS.entries()) {
2479
- const attempt = index + 1;
2480
- observer.onEvent(channelEvent("channelReconnecting", {
2481
- attempt,
2482
- maxAttempts: RECONNECT_DELAYS_MS.length,
2483
- reason: lastError.message
2484
- }));
2485
- await sleep(delayMs, signal);
2486
- if (signal.aborted) return null;
2487
- const outcome = await this.reopenOnce(taskId, signal, handlers);
2488
- if (signal.aborted) return null;
2489
- if (outcome.kind === "socket") {
2490
- observer.onEvent(channelEvent("channelConnected", { attempt }));
2491
- return outcome.socket;
2492
- }
2493
- if (outcome.kind === "refused") {
2494
- observer.onDisconnect(new Error(
2495
- `The copilot no longer offers the box channel (after: ${cause.message})`
2496
- ));
2497
- return null;
2498
- }
2499
- lastError = outcome.error;
2500
- }
2501
- observer.onDisconnect(new Error(
2502
- `Agent box channel could not be reopened after ${RECONNECT_DELAYS_MS.length} attempts: ${lastError.message}`
2503
- ));
2504
- return null;
2505
- }
2506
- // One attempt to get the box back: a fresh token, the channel request, the dial. A failure is
2507
- // returned rather than thrown, so the caller decides between another attempt and giving up.
2508
- async reopenOnce(taskId, signal, handlers) {
2509
- try {
2510
- const token = await this.requireFreshToken();
2511
- const channel = await this.askDirectChannel(taskId, token, signal);
2512
- if (signal.aborted) return { kind: "failed", error: new Error("Agent box redial aborted.") };
2513
- if (!channel || "declined" in channel) return { kind: "refused" };
2514
- this.adoptBox(taskId, channel);
2515
- const replayFrom = this.boxCursors.get(taskId);
2516
- if (replayFrom === void 0) this.boxCursors.set(taskId, channel.lastSequence);
2517
- const socket = await this.dial(channel.wsUrl, { ...handlers, signal, replayFrom });
2518
- return { kind: "socket", socket };
2519
- } catch (error) {
2520
- return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
2521
- }
2522
- }
2523
- dial(url, options) {
2524
- const { signal, replayFrom } = options;
2319
+ dial(url, observer, signal) {
2525
2320
  return new Promise((resolve, reject) => {
2526
2321
  const socket = new globalThis.WebSocket(url);
2527
2322
  let opened = false;
@@ -2544,7 +2339,7 @@ var BrowserAgentTaskEventSource = class {
2544
2339
  if (intentionalClose) return;
2545
2340
  intentionalClose = true;
2546
2341
  removeAbortListener();
2547
- options.onLost(silenceError("WebSocket"));
2342
+ observer.onDisconnect(silenceError("WebSocket"));
2548
2343
  socket.close(1e3, "Client closed");
2549
2344
  });
2550
2345
  const close = () => {
@@ -2554,15 +2349,6 @@ var BrowserAgentTaskEventSource = class {
2554
2349
  removeAbortListener();
2555
2350
  socket.close(1e3, "Client closed");
2556
2351
  };
2557
- const send = (frame) => {
2558
- if (intentionalClose || socket.readyState !== SOCKET_OPEN) return false;
2559
- try {
2560
- socket.send(frame);
2561
- return true;
2562
- } catch {
2563
- return false;
2564
- }
2565
- };
2566
2352
  const onAbort = () => {
2567
2353
  if (!opened) {
2568
2354
  rejectHandshake(signal?.reason instanceof Error ? signal.reason : new Error("Agent WebSocket connection aborted."));
@@ -2580,13 +2366,7 @@ var BrowserAgentTaskEventSource = class {
2580
2366
  settled = true;
2581
2367
  globalThis.clearTimeout(timer);
2582
2368
  watchdog.touch();
2583
- if (replayFrom !== void 0) {
2584
- try {
2585
- socket.send(JSON.stringify({ type: "replay", fromSequence: replayFrom }));
2586
- } catch {
2587
- }
2588
- }
2589
- resolve({ close, send });
2369
+ resolve({ close });
2590
2370
  };
2591
2371
  socket.onerror = () => {
2592
2372
  if (!opened) rejectHandshake(new Error("Failed to connect to the Agent WebSocket."));
@@ -2594,7 +2374,7 @@ var BrowserAgentTaskEventSource = class {
2594
2374
  socket.onmessage = (message) => {
2595
2375
  watchdog.touch();
2596
2376
  const event = parseEvent(message.data);
2597
- if (event) options.onFrame(asDelta(event));
2377
+ if (event) observer.onEvent(event);
2598
2378
  };
2599
2379
  socket.onclose = (event) => {
2600
2380
  globalThis.clearTimeout(timer);
@@ -2605,7 +2385,7 @@ var BrowserAgentTaskEventSource = class {
2605
2385
  return;
2606
2386
  }
2607
2387
  if (!intentionalClose) {
2608
- options.onLost(new Error(`Agent WebSocket closed (${event.code}).`), event.code);
2388
+ observer.onDisconnect(new Error(`Agent WebSocket closed (${event.code}).`));
2609
2389
  }
2610
2390
  };
2611
2391
  });
@@ -2693,43 +2473,22 @@ var BrowserAgentTaskEventSource = class {
2693
2473
  };
2694
2474
 
2695
2475
  // src/modules/agent-tasks.ts
2696
- function bornOnBox(options) {
2697
- if (!("create" in options) || options.runtime || options.transport === "http") return options;
2698
- return { ...options, runtime: "T3" };
2699
- }
2700
- function createBrowserAgentTasksModule(httpClient, auth, apiUrl) {
2476
+ function createBrowserAgentTasksModule(httpClient, auth, apiUrl, channelHttpClient = httpClient) {
2701
2477
  const tasks = (0, import_sdk_core9.createAgentTasksModule)(httpClient, coreErrors);
2702
- const source = new BrowserAgentTaskEventSource(auth, apiUrl);
2703
- const observers = /* @__PURE__ */ new Map();
2704
- const outbox = new AgentInputOutbox(tasks, (taskId, event) => observers.get(taskId)?.onEvent(event));
2705
- const eventSource = {
2706
- async open(taskId, observer, signal, transport) {
2707
- observers.set(taskId, observer);
2708
- let connection;
2709
- try {
2710
- connection = await source.open(taskId, observer, signal, transport);
2711
- } catch (error) {
2712
- observers.delete(taskId);
2713
- throw error;
2714
- }
2715
- return {
2716
- close: () => {
2717
- outbox.abandon(taskId);
2718
- observers.delete(taskId);
2719
- connection.close();
2720
- }
2721
- };
2722
- }
2723
- };
2478
+ const outbox = new AgentInputOutbox(tasks);
2724
2479
  const manager = (0, import_sdk_core9.createAgentTaskSessionManager)({
2725
2480
  tasks: {
2726
2481
  ...tasks,
2727
- sendInput: (taskId, input) => source.sendOnChannel(taskId, input) ? Promise.resolve() : outbox.sendInput(taskId, input)
2482
+ channel: (0, import_sdk_core9.createAgentTasksModule)(channelHttpClient, coreErrors).channel,
2483
+ sendInput: (taskId, input) => outbox.sendInput(taskId, input)
2728
2484
  },
2729
- eventSource
2485
+ eventSource: new BrowserAgentTaskEventSource(auth, apiUrl),
2486
+ directChannel: { apiUrl }
2730
2487
  });
2731
- return (0, import_sdk_core9.withAgentTaskSessions)(tasks, {
2732
- session: (options) => holdSendsWhileOffline(manager.session(bornOnBox(options)), outbox)
2488
+ const publicTasks = { ...tasks };
2489
+ delete publicTasks.channel;
2490
+ return (0, import_sdk_core9.withAgentTaskSessions)(publicTasks, {
2491
+ session: (options) => holdSendsWhileOffline(manager.session(options), outbox)
2733
2492
  });
2734
2493
  }
2735
2494
 
@@ -2852,7 +2611,14 @@ function createClient(config) {
2852
2611
  const agentTasksModule = createBrowserAgentTasksModule(
2853
2612
  copilotHttpClient,
2854
2613
  authSession,
2855
- gatewayUrl
2614
+ gatewayUrl,
2615
+ new HttpClient({
2616
+ baseUrl: copilotUrl,
2617
+ getToken: () => authModule.accessToken,
2618
+ beforeAuthenticatedRequest,
2619
+ onUnauthorized,
2620
+ defaultHeaders
2621
+ })
2856
2622
  );
2857
2623
  const agentCredentialsModule = createBrowserAgentCredentialsModule(copilotHttpClient);
2858
2624
  const integrationHttpClient = new HttpClient({
package/dist/index.js CHANGED
@@ -1957,13 +1957,23 @@ function neverSent(pending) {
1957
1957
  );
1958
1958
  }
1959
1959
  var AgentInputOutbox = class {
1960
- constructor(tasks, announce, network = browserNetwork) {
1960
+ constructor(tasks, network = browserNetwork) {
1961
1961
  this.tasks = tasks;
1962
- this.announce = announce;
1963
1962
  this.network = network;
1964
1963
  }
1965
1964
  held = /* @__PURE__ */ new Map();
1966
1965
  gated = /* @__PURE__ */ new Map();
1966
+ hearers = /* @__PURE__ */ new Set();
1967
+ /** Returns the way to stop hearing. */
1968
+ listen(hearer) {
1969
+ this.hearers.add(hearer);
1970
+ return () => this.hearers.delete(hearer);
1971
+ }
1972
+ announce(taskId, event) {
1973
+ for (const hearer of this.hearers) {
1974
+ if (hearer.taskId() === taskId) hearer.hear(event);
1975
+ }
1976
+ }
1967
1977
  async sendInput(taskId, input) {
1968
1978
  try {
1969
1979
  await this.tasks.sendInput(taskId, input);
@@ -2105,9 +2115,40 @@ var AgentInputOutbox = class {
2105
2115
  else this.held.delete(taskId);
2106
2116
  }
2107
2117
  };
2118
+ function notify(listeners, payload) {
2119
+ for (const listener of listeners) {
2120
+ try {
2121
+ listener(payload);
2122
+ } catch {
2123
+ }
2124
+ }
2125
+ }
2108
2126
  function holdSendsWhileOffline(session, outbox) {
2109
2127
  const passThrough = (prompt) => !outbox.offline || !prompt.trim() || session.status === "closed";
2128
+ const raws = /* @__PURE__ */ new Set();
2129
+ const errors = /* @__PURE__ */ new Set();
2130
+ const outboxListeners = { raw: raws, error: errors };
2131
+ const stopHearing = outbox.listen({
2132
+ taskId: () => session.taskId,
2133
+ hear: (event) => {
2134
+ if (session.status === "closed") return;
2135
+ notify(raws, event);
2136
+ if (event.type !== "error") return;
2137
+ const payload = event.payload;
2138
+ notify(errors, { code: payload.code, error: payload.message });
2139
+ }
2140
+ });
2110
2141
  const gated = {
2142
+ on: (event, handler) => {
2143
+ const off = session.on(event, handler);
2144
+ const own = outboxListeners[event];
2145
+ if (!own) return off;
2146
+ own.add(handler);
2147
+ return () => {
2148
+ own.delete(handler);
2149
+ off();
2150
+ };
2151
+ },
2111
2152
  send: (prompt, options) => {
2112
2153
  if (passThrough(prompt)) {
2113
2154
  session.send(prompt, options);
@@ -2123,7 +2164,13 @@ function holdSendsWhileOffline(session, outbox) {
2123
2164
  }).then(() => turn);
2124
2165
  },
2125
2166
  close: () => {
2126
- outbox.abandonGated(session, session.taskId);
2167
+ if (session.status !== "closed") {
2168
+ outbox.abandonGated(session, session.taskId);
2169
+ if (session.taskId) outbox.abandon(session.taskId);
2170
+ }
2171
+ stopHearing();
2172
+ raws.clear();
2173
+ errors.clear();
2127
2174
  session.close();
2128
2175
  }
2129
2176
  };
@@ -2135,9 +2182,6 @@ function holdSendsWhileOffline(session, outbox) {
2135
2182
  // src/modules/agent-session.ts
2136
2183
  var CONNECT_TIMEOUT_MS = 15e3;
2137
2184
  var SILENCE_TIMEOUT_MS = 6e4;
2138
- var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3];
2139
- var SUPERSEDED_CLOSE_CODE = 4409;
2140
- var SOCKET_OPEN = 1;
2141
2185
  var SilenceWatchdog = class {
2142
2186
  constructor(onSilence) {
2143
2187
  this.onSilence = onSilence;
@@ -2175,50 +2219,6 @@ function expectEvent(value) {
2175
2219
  ...typeof event.sequence === "number" ? { sequence: event.sequence } : {}
2176
2220
  };
2177
2221
  }
2178
- var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
2179
- function isSameGateway(candidate, apiUrl) {
2180
- try {
2181
- const target = new URL(candidate);
2182
- if (target.protocol !== "ws:" && target.protocol !== "wss:") return false;
2183
- if (target.host === new URL(apiUrl).host) return true;
2184
- return target.protocol === "wss:" && FLEET_BOX_HOST.test(target.host);
2185
- } catch {
2186
- return false;
2187
- }
2188
- }
2189
- function hostOf(url) {
2190
- try {
2191
- return new URL(url).host;
2192
- } catch {
2193
- return void 0;
2194
- }
2195
- }
2196
- function boxAddress(wsUrl) {
2197
- const url = new URL(wsUrl);
2198
- return `${url.origin}${url.pathname}`;
2199
- }
2200
- function toDirectChannel(body, apiUrl) {
2201
- if (typeof body !== "object" || body === null) return { declined: { reason: "body" } };
2202
- const channel = body;
2203
- if (typeof channel.wsUrl !== "string") return { declined: { reason: "body" } };
2204
- if (!isSameGateway(channel.wsUrl, apiUrl)) {
2205
- const host = hostOf(channel.wsUrl);
2206
- return { declined: { reason: "host", ...host === void 0 ? {} : { host } } };
2207
- }
2208
- return {
2209
- wsUrl: channel.wsUrl,
2210
- lastSequence: typeof channel.lastSequence === "number" && channel.lastSequence > 0 ? channel.lastSequence : 0
2211
- };
2212
- }
2213
- function sleep(ms, signal) {
2214
- return new Promise((resolve) => {
2215
- const timer = globalThis.setTimeout(resolve, ms);
2216
- signal?.addEventListener("abort", () => {
2217
- globalThis.clearTimeout(timer);
2218
- resolve();
2219
- }, { once: true });
2220
- });
2221
- }
2222
2222
  function parseEvent(raw) {
2223
2223
  if (typeof raw !== "string") return expectEvent(raw);
2224
2224
  try {
@@ -2227,26 +2227,6 @@ function parseEvent(raw) {
2227
2227
  return null;
2228
2228
  }
2229
2229
  }
2230
- function asDelta(event) {
2231
- if (event.type !== "textChunk") return event;
2232
- const kind = asObject(event.payload)?.kind;
2233
- return { ...event, type: kind === "thinking" ? "thinking" : "textDelta" };
2234
- }
2235
- var TURN_FRAME_TYPES = /* @__PURE__ */ new Set(["textDelta", "thinking", "toolCall", "toolResult"]);
2236
- var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
2237
- function turnAfter(event, inTurn) {
2238
- if (TURN_FRAME_TYPES.has(event.type)) return true;
2239
- if (event.type === "error") return false;
2240
- if (event.type === "stepFinish") {
2241
- const payload = asObject(event.payload);
2242
- if (TURN_END_REASONS.has(payload?.reason)) return false;
2243
- return asObject(payload?.lifecycle)?.interruptTerminal !== true;
2244
- }
2245
- return inTurn;
2246
- }
2247
- function channelEvent(type, payload) {
2248
- return { type, payload, timestamp: Date.now() };
2249
- }
2250
2230
  var BrowserAgentTaskEventSource = class {
2251
2231
  constructor(auth, apiUrl) {
2252
2232
  this.auth = auth;
@@ -2254,20 +2234,6 @@ var BrowserAgentTaskEventSource = class {
2254
2234
  }
2255
2235
  apiUrl;
2256
2236
  sseFallbackTasks = /* @__PURE__ */ new Set();
2257
- // Tasks whose last WebSocket was the box itself. A box socket that closes says nothing about
2258
- // WebSockets: the box went idle or the channel was superseded, and the answer is to ask the
2259
- // copilot for the channel again. Only the copilot's own socket failing sends a task to SSE.
2260
- directTasks = /* @__PURE__ */ new Set();
2261
- /**
2262
- * Ate onde esta sessao ja viu o log da caixa, por conversa, e de qual caixa esse log e. So o
2263
- * redial no meio de um turno pede repeticao a partir daqui; abrir a conversa de novo nunca
2264
- * pede. O cursor vale para uma caixa: outra caixa tem outro log, e um cursor da anterior
2265
- * repetiria turnos antigos como se fossem texto ao vivo.
2266
- */
2267
- boxCursors = /* @__PURE__ */ new Map();
2268
- boxAddresses = /* @__PURE__ */ new Map();
2269
- /** The box socket a task is talking on right now; absent while it is lost or being redialed. */
2270
- directSockets = /* @__PURE__ */ new Map();
2271
2237
  async open(taskId, observer, signal, transport = "auto") {
2272
2238
  if (transport === "http") return this.openSse(taskId, observer, signal);
2273
2239
  if (transport === "websocket") return this.openWebSocket(taskId, observer, signal);
@@ -2278,13 +2244,13 @@ var BrowserAgentTaskEventSource = class {
2278
2244
  const connection = await this.openWebSocket(taskId, {
2279
2245
  ...observer,
2280
2246
  onDisconnect: (error) => {
2281
- if (!this.directTasks.has(taskId)) this.sseFallbackTasks.add(taskId);
2247
+ this.sseFallbackTasks.add(taskId);
2282
2248
  observer.onDisconnect(error);
2283
2249
  }
2284
2250
  }, signal);
2285
2251
  return this.wrapAutoConnection(taskId, connection);
2286
2252
  } catch {
2287
- if (!this.directTasks.has(taskId)) this.sseFallbackTasks.add(taskId);
2253
+ this.sseFallbackTasks.add(taskId);
2288
2254
  return this.wrapAutoConnection(taskId, await this.openSse(taskId, observer, signal));
2289
2255
  }
2290
2256
  }
@@ -2292,30 +2258,10 @@ var BrowserAgentTaskEventSource = class {
2292
2258
  return {
2293
2259
  close: () => {
2294
2260
  this.sseFallbackTasks.delete(taskId);
2295
- this.directTasks.delete(taskId);
2296
- this.boxCursors.delete(taskId);
2297
- this.boxAddresses.delete(taskId);
2298
2261
  connection.close();
2299
2262
  }
2300
2263
  };
2301
2264
  }
2302
- /**
2303
- * Writes a message or an interrupt on the box socket when the task is on the direct channel
2304
- * and that socket is open right now. The box accepts the core's input as its own inbound
2305
- * frame, asks the copilot for admission itself and answers on this same socket with the
2306
- * frames the observer already reads, so the copilot's host socket is off the message path.
2307
- * False sends the caller to REST: no direct channel, a socket lost or mid-redial, or an
2308
- * approval, which stays on REST as it is.
2309
- *
2310
- * A frame written on a socket that closes before the box acknowledges it is not sent again
2311
- * over REST: the box may have admitted the turn already, and a second copy would start it
2312
- * twice. The redial replays the box log, which is the same recovery a REST 202 gets when its
2313
- * turn is lost.
2314
- */
2315
- sendOnChannel(taskId, input) {
2316
- if (input.type === "approval_response") return false;
2317
- return this.directSockets.get(taskId)?.send(JSON.stringify(input)) ?? false;
2318
- }
2319
2265
  async requireFreshToken() {
2320
2266
  const fresh = await this.auth.ensureFreshSession();
2321
2267
  const token = this.auth.accessToken;
@@ -2324,167 +2270,16 @@ var BrowserAgentTaskEventSource = class {
2324
2270
  }
2325
2271
  return token;
2326
2272
  }
2327
- /**
2328
- * Pergunta ao copilot onde esta conversa e servida. Nada aqui e fatal: uma recusa, uma
2329
- * resposta que nao entendemos ou uma rede que falhou significam apenas que a conversa segue
2330
- * pelo socket do copilot, que e como toda conversa era servida antes da caixa existir.
2331
- */
2332
- requestDirectChannel(taskId, token, signal) {
2333
- return this.askDirectChannel(taskId, token, signal).catch(() => null);
2334
- }
2335
- /**
2336
- * Like `requestDirectChannel`, but a request the network lost is thrown, not a refusal.
2337
- *
2338
- * One request. The copilot holds it while the box boots and answers 200 with the channel, or
2339
- * an error status once the box cannot be had. A 202 comes only from a copilot older than that
2340
- * contract, which used to mean "still booting, ask again": there is no channel to open, and
2341
- * the conversation follows the copilot socket. Polling here again would put the wait back on
2342
- * the client that the server now owns.
2343
- */
2344
- async askDirectChannel(taskId, token, signal) {
2345
- if (signal?.aborted) return null;
2346
- const url = `${this.apiUrl}/copilot/api/v1/tasks/${encodeURIComponent(taskId)}/channel`;
2347
- const response = await globalThis.fetch(url, {
2348
- method: "POST",
2349
- headers: { Authorization: `Bearer ${stripBearer2(token)}` },
2350
- ...signal ? { signal } : {}
2351
- });
2352
- if (response.status === 202 || !response.ok) return null;
2353
- try {
2354
- return toDirectChannel(await response.json(), this.apiUrl);
2355
- } catch {
2356
- return { declined: { reason: "body" } };
2357
- }
2358
- }
2359
2273
  async openWebSocket(taskId, observer, signal) {
2360
2274
  if (typeof globalThis.WebSocket !== "function") {
2361
2275
  throw new TypeError("WebSocket is not available.");
2362
2276
  }
2363
2277
  if (signal?.aborted) throw signal.reason ?? new Error("Agent WebSocket connection aborted.");
2364
2278
  const token = await this.requireFreshToken();
2365
- const answer = await this.requestDirectChannel(taskId, token, signal);
2366
- if (answer && "declined" in answer) observer.onEvent(channelEvent("channelDeclined", answer.declined));
2367
- const direct = answer && !("declined" in answer) ? answer : null;
2368
- if (direct) this.directTasks.add(taskId);
2369
- else this.directTasks.delete(taskId);
2370
- if (direct) return this.openDirect(taskId, direct, observer, signal);
2371
2279
  const url = `${this.apiUrl.replace(/^http/i, "ws")}/copilot/ws/tasks/${encodeURIComponent(taskId)}?token=${encodeURIComponent(stripBearer2(token))}`;
2372
- const socket = await this.dial(url, {
2373
- signal,
2374
- onFrame: (event) => observer.onEvent(event),
2375
- onLost: (error) => observer.onDisconnect(error)
2376
- });
2377
- return { close: () => socket.close() };
2378
- }
2379
- /** Forgets the cursor when the copilot points the conversation to a box other than the last dialed. */
2380
- adoptBox(taskId, channel) {
2381
- const box = boxAddress(channel.wsUrl);
2382
- if (this.boxAddresses.get(taskId) === box) return;
2383
- this.boxAddresses.set(taskId, box);
2384
- this.boxCursors.delete(taskId);
2385
- }
2386
- /**
2387
- * The box path. A drop in the middle of a turn is redialed from here, with the replay the
2388
- * box offers, so the core keeps one connection and one stream: reporting the drop instead
2389
- * would make it reconcile the turn from persisted history, which is the screen freezing and
2390
- * the rest of the answer landing at once. The core hears a disconnect only when the redial
2391
- * gives up, when the copilot no longer offers the box, or when there is no turn to resume:
2392
- * the sandbox pauses an idle box, and dialing it again would wake it for nobody.
2393
- *
2394
- * Opening never asks for a replay, whether the conversation is new to this session or was
2395
- * open before. What an idle conversation missed is history, which the app loads by REST. Beta
2396
- * 2026-09-14: a tab open overnight had its box replaced, and the open that followed replayed
2397
- * the old box's cursor against the new log, which put every old turn on screen as live text.
2398
- */
2399
- async openDirect(taskId, channel, observer, signal) {
2400
- this.adoptBox(taskId, channel);
2401
- this.boxCursors.set(taskId, channel.lastSequence);
2402
- const link = new AbortController();
2403
- const onAbort = () => link.abort(signal?.reason);
2404
- signal?.addEventListener("abort", onAbort, { once: true });
2405
- let inTurn = false;
2406
- let current = null;
2407
- const track = (socket) => {
2408
- if (socket) this.directSockets.set(taskId, socket);
2409
- else if (current && this.directSockets.get(taskId) === current) this.directSockets.delete(taskId);
2410
- current = socket;
2411
- };
2412
- const onFrame = (event) => {
2413
- if (typeof event.sequence === "number") {
2414
- const seen = this.boxCursors.get(taskId) ?? 0;
2415
- if (event.sequence > seen) this.boxCursors.set(taskId, event.sequence);
2416
- }
2417
- inTurn = turnAfter(event, inTurn);
2418
- observer.onEvent(event);
2419
- };
2420
- const onLost = (error, code) => {
2421
- track(null);
2422
- if (link.signal.aborted) return;
2423
- if (!inTurn || code === SUPERSEDED_CLOSE_CODE) {
2424
- observer.onDisconnect(error);
2425
- return;
2426
- }
2427
- void this.redial(taskId, error, link.signal, observer, { onFrame, onLost }).then(track);
2428
- };
2429
- track(await this.dial(channel.wsUrl, { signal: link.signal, onFrame, onLost }));
2430
- return {
2431
- close: () => {
2432
- signal?.removeEventListener("abort", onAbort);
2433
- link.abort();
2434
- current?.close();
2435
- track(null);
2436
- }
2437
- };
2280
+ return this.dial(url, observer, signal);
2438
2281
  }
2439
- async redial(taskId, cause, signal, observer, handlers) {
2440
- let lastError = cause;
2441
- for (const [index, delayMs] of RECONNECT_DELAYS_MS.entries()) {
2442
- const attempt = index + 1;
2443
- observer.onEvent(channelEvent("channelReconnecting", {
2444
- attempt,
2445
- maxAttempts: RECONNECT_DELAYS_MS.length,
2446
- reason: lastError.message
2447
- }));
2448
- await sleep(delayMs, signal);
2449
- if (signal.aborted) return null;
2450
- const outcome = await this.reopenOnce(taskId, signal, handlers);
2451
- if (signal.aborted) return null;
2452
- if (outcome.kind === "socket") {
2453
- observer.onEvent(channelEvent("channelConnected", { attempt }));
2454
- return outcome.socket;
2455
- }
2456
- if (outcome.kind === "refused") {
2457
- observer.onDisconnect(new Error(
2458
- `The copilot no longer offers the box channel (after: ${cause.message})`
2459
- ));
2460
- return null;
2461
- }
2462
- lastError = outcome.error;
2463
- }
2464
- observer.onDisconnect(new Error(
2465
- `Agent box channel could not be reopened after ${RECONNECT_DELAYS_MS.length} attempts: ${lastError.message}`
2466
- ));
2467
- return null;
2468
- }
2469
- // One attempt to get the box back: a fresh token, the channel request, the dial. A failure is
2470
- // returned rather than thrown, so the caller decides between another attempt and giving up.
2471
- async reopenOnce(taskId, signal, handlers) {
2472
- try {
2473
- const token = await this.requireFreshToken();
2474
- const channel = await this.askDirectChannel(taskId, token, signal);
2475
- if (signal.aborted) return { kind: "failed", error: new Error("Agent box redial aborted.") };
2476
- if (!channel || "declined" in channel) return { kind: "refused" };
2477
- this.adoptBox(taskId, channel);
2478
- const replayFrom = this.boxCursors.get(taskId);
2479
- if (replayFrom === void 0) this.boxCursors.set(taskId, channel.lastSequence);
2480
- const socket = await this.dial(channel.wsUrl, { ...handlers, signal, replayFrom });
2481
- return { kind: "socket", socket };
2482
- } catch (error) {
2483
- return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
2484
- }
2485
- }
2486
- dial(url, options) {
2487
- const { signal, replayFrom } = options;
2282
+ dial(url, observer, signal) {
2488
2283
  return new Promise((resolve, reject) => {
2489
2284
  const socket = new globalThis.WebSocket(url);
2490
2285
  let opened = false;
@@ -2507,7 +2302,7 @@ var BrowserAgentTaskEventSource = class {
2507
2302
  if (intentionalClose) return;
2508
2303
  intentionalClose = true;
2509
2304
  removeAbortListener();
2510
- options.onLost(silenceError("WebSocket"));
2305
+ observer.onDisconnect(silenceError("WebSocket"));
2511
2306
  socket.close(1e3, "Client closed");
2512
2307
  });
2513
2308
  const close = () => {
@@ -2517,15 +2312,6 @@ var BrowserAgentTaskEventSource = class {
2517
2312
  removeAbortListener();
2518
2313
  socket.close(1e3, "Client closed");
2519
2314
  };
2520
- const send = (frame) => {
2521
- if (intentionalClose || socket.readyState !== SOCKET_OPEN) return false;
2522
- try {
2523
- socket.send(frame);
2524
- return true;
2525
- } catch {
2526
- return false;
2527
- }
2528
- };
2529
2315
  const onAbort = () => {
2530
2316
  if (!opened) {
2531
2317
  rejectHandshake(signal?.reason instanceof Error ? signal.reason : new Error("Agent WebSocket connection aborted."));
@@ -2543,13 +2329,7 @@ var BrowserAgentTaskEventSource = class {
2543
2329
  settled = true;
2544
2330
  globalThis.clearTimeout(timer);
2545
2331
  watchdog.touch();
2546
- if (replayFrom !== void 0) {
2547
- try {
2548
- socket.send(JSON.stringify({ type: "replay", fromSequence: replayFrom }));
2549
- } catch {
2550
- }
2551
- }
2552
- resolve({ close, send });
2332
+ resolve({ close });
2553
2333
  };
2554
2334
  socket.onerror = () => {
2555
2335
  if (!opened) rejectHandshake(new Error("Failed to connect to the Agent WebSocket."));
@@ -2557,7 +2337,7 @@ var BrowserAgentTaskEventSource = class {
2557
2337
  socket.onmessage = (message) => {
2558
2338
  watchdog.touch();
2559
2339
  const event = parseEvent(message.data);
2560
- if (event) options.onFrame(asDelta(event));
2340
+ if (event) observer.onEvent(event);
2561
2341
  };
2562
2342
  socket.onclose = (event) => {
2563
2343
  globalThis.clearTimeout(timer);
@@ -2568,7 +2348,7 @@ var BrowserAgentTaskEventSource = class {
2568
2348
  return;
2569
2349
  }
2570
2350
  if (!intentionalClose) {
2571
- options.onLost(new Error(`Agent WebSocket closed (${event.code}).`), event.code);
2351
+ observer.onDisconnect(new Error(`Agent WebSocket closed (${event.code}).`));
2572
2352
  }
2573
2353
  };
2574
2354
  });
@@ -2656,43 +2436,22 @@ var BrowserAgentTaskEventSource = class {
2656
2436
  };
2657
2437
 
2658
2438
  // src/modules/agent-tasks.ts
2659
- function bornOnBox(options) {
2660
- if (!("create" in options) || options.runtime || options.transport === "http") return options;
2661
- return { ...options, runtime: "T3" };
2662
- }
2663
- function createBrowserAgentTasksModule(httpClient, auth, apiUrl) {
2439
+ function createBrowserAgentTasksModule(httpClient, auth, apiUrl, channelHttpClient = httpClient) {
2664
2440
  const tasks = createAgentTasksModule(httpClient, coreErrors);
2665
- const source = new BrowserAgentTaskEventSource(auth, apiUrl);
2666
- const observers = /* @__PURE__ */ new Map();
2667
- const outbox = new AgentInputOutbox(tasks, (taskId, event) => observers.get(taskId)?.onEvent(event));
2668
- const eventSource = {
2669
- async open(taskId, observer, signal, transport) {
2670
- observers.set(taskId, observer);
2671
- let connection;
2672
- try {
2673
- connection = await source.open(taskId, observer, signal, transport);
2674
- } catch (error) {
2675
- observers.delete(taskId);
2676
- throw error;
2677
- }
2678
- return {
2679
- close: () => {
2680
- outbox.abandon(taskId);
2681
- observers.delete(taskId);
2682
- connection.close();
2683
- }
2684
- };
2685
- }
2686
- };
2441
+ const outbox = new AgentInputOutbox(tasks);
2687
2442
  const manager = createAgentTaskSessionManager({
2688
2443
  tasks: {
2689
2444
  ...tasks,
2690
- sendInput: (taskId, input) => source.sendOnChannel(taskId, input) ? Promise.resolve() : outbox.sendInput(taskId, input)
2445
+ channel: createAgentTasksModule(channelHttpClient, coreErrors).channel,
2446
+ sendInput: (taskId, input) => outbox.sendInput(taskId, input)
2691
2447
  },
2692
- eventSource
2448
+ eventSource: new BrowserAgentTaskEventSource(auth, apiUrl),
2449
+ directChannel: { apiUrl }
2693
2450
  });
2694
- return withAgentTaskSessions(tasks, {
2695
- session: (options) => holdSendsWhileOffline(manager.session(bornOnBox(options)), outbox)
2451
+ const publicTasks = { ...tasks };
2452
+ delete publicTasks.channel;
2453
+ return withAgentTaskSessions(publicTasks, {
2454
+ session: (options) => holdSendsWhileOffline(manager.session(options), outbox)
2696
2455
  });
2697
2456
  }
2698
2457
 
@@ -2817,7 +2576,14 @@ function createClient(config) {
2817
2576
  const agentTasksModule = createBrowserAgentTasksModule(
2818
2577
  copilotHttpClient,
2819
2578
  authSession,
2820
- gatewayUrl
2579
+ gatewayUrl,
2580
+ new HttpClient({
2581
+ baseUrl: copilotUrl,
2582
+ getToken: () => authModule.accessToken,
2583
+ beforeAuthenticatedRequest,
2584
+ onUnauthorized,
2585
+ defaultHeaders
2586
+ })
2821
2587
  );
2822
2588
  const agentCredentialsModule = createBrowserAgentCredentialsModule(copilotHttpClient);
2823
2589
  const integrationHttpClient = new HttpClient({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/platform-sdk",
3
- "version": "1.2.0",
3
+ "version": "1.3.0-beta.0",
4
4
  "description": "JavaScript/TypeScript SDK for building apps on the Mitra Platform",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -62,7 +62,7 @@
62
62
  "url": "https://github.com/mitralab-dev/mitra-platform-sdk/issues"
63
63
  },
64
64
  "dependencies": {
65
- "@mitralab.io/sdk-core": "0.2.8",
65
+ "@mitralab.io/sdk-core": "0.2.9-beta.1",
66
66
  "mitra-interactions-sdk": "1.0.60-beta.48"
67
67
  },
68
68
  "devDependencies": {