@mitralab.io/sdk-core 0.2.8-beta.0 → 0.2.9-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/dist/index.cjs CHANGED
@@ -1002,6 +1002,15 @@ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
1002
1002
  if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
1003
1003
  return task;
1004
1004
  }
1005
+ function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFactory) {
1006
+ if (value === void 0 || value === null || value === "") return null;
1007
+ const channel = expectObject(value, context, errors);
1008
+ if (typeof channel.wsUrl !== "string" || !channel.wsUrl) invalidField(context, "wsUrl", errors);
1009
+ return {
1010
+ wsUrl: channel.wsUrl,
1011
+ lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0
1012
+ };
1013
+ }
1005
1014
  function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
1006
1015
  const message = expectObject(value, context, errors);
1007
1016
  for (const field of ["id", "sender", "type", "content", "createdAt"]) {
@@ -1566,6 +1575,13 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1566
1575
  errors,
1567
1576
  expectAgentMessage
1568
1577
  );
1578
+ },
1579
+ async channel(id) {
1580
+ return expectAgentTaskChannel(
1581
+ await transport.request(`${path(id)}/channel`, { method: "POST" }),
1582
+ "Agent task channel response",
1583
+ errors
1584
+ );
1569
1585
  }
1570
1586
  };
1571
1587
  }
@@ -3133,10 +3149,7 @@ function unavailableTransport(name, errors) {
3133
3149
  };
3134
3150
  }
3135
3151
 
3136
- // src/agentSession.ts
3137
- var AGENT_QUEUE_LIMIT = 10;
3138
- var CANCEL_SAFETY_MS = 1e4;
3139
- var RECONCILE_DELAY_MS = 1e3;
3152
+ // src/agentTurnError.ts
3140
3153
  var AgentTaskTurnError = class extends Error {
3141
3154
  code;
3142
3155
  constructor(message, code) {
@@ -3145,10 +3158,721 @@ var AgentTaskTurnError = class extends Error {
3145
3158
  this.code = code;
3146
3159
  }
3147
3160
  };
3161
+
3162
+ // src/agentChannel.ts
3163
+ var CONNECT_TIMEOUT_MS = 15e3;
3164
+ var SILENCE_TIMEOUT_MS = 6e4;
3165
+ var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3];
3166
+ var ADMISSION_TIMEOUT_MS = 35e3;
3167
+ var SUPERSEDED_CLOSE_CODE = 4409;
3168
+ var SOCKET_OPEN = 1;
3169
+ var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
3148
3170
  function asObject(value) {
3149
3171
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3150
3172
  }
3151
3173
  function errorMessage(error) {
3174
+ return error instanceof Error ? error.message : String(error);
3175
+ }
3176
+ function hostOf(url) {
3177
+ try {
3178
+ return new URL(url).host;
3179
+ } catch {
3180
+ return void 0;
3181
+ }
3182
+ }
3183
+ function isChannelHostAllowed(candidate, apiUrl) {
3184
+ try {
3185
+ const target = new URL(candidate);
3186
+ if (target.protocol !== "ws:" && target.protocol !== "wss:") return false;
3187
+ const api = apiUrl === void 0 ? void 0 : new URL(apiUrl);
3188
+ if (api && target.host === api.host) {
3189
+ return api.protocol !== "https:" || target.protocol === "wss:";
3190
+ }
3191
+ return target.protocol === "wss:" && FLEET_BOX_HOST.test(target.host);
3192
+ } catch {
3193
+ return false;
3194
+ }
3195
+ }
3196
+ function boxAddress(wsUrl) {
3197
+ const url = new URL(wsUrl);
3198
+ return `${url.origin}${url.pathname}`;
3199
+ }
3200
+ function boxRoute(wsUrl, route) {
3201
+ const url = new URL(wsUrl);
3202
+ url.protocol = url.protocol === "wss:" ? "https:" : "http:";
3203
+ url.pathname = `${url.pathname.replace(/\/api\/mitra\/chat\/ws\/?$/, "")}/api/mitra/chat/${route}`;
3204
+ return url.toString();
3205
+ }
3206
+ async function readSse(reader, onFrame) {
3207
+ const decoder = new TextDecoder();
3208
+ let buffer = "";
3209
+ let timer;
3210
+ const silence = () => new Promise((_, reject) => {
3211
+ timer = setTimeout(
3212
+ () => reject(
3213
+ new Error(`Agent box event stream went silent for ${SILENCE_TIMEOUT_MS / 1e3}s.`)
3214
+ ),
3215
+ SILENCE_TIMEOUT_MS
3216
+ );
3217
+ });
3218
+ try {
3219
+ for (; ; ) {
3220
+ let chunk;
3221
+ try {
3222
+ chunk = await Promise.race([reader.read(), silence()]);
3223
+ } catch (error) {
3224
+ await reader.cancel().catch(() => void 0);
3225
+ throw error;
3226
+ } finally {
3227
+ clearTimeout(timer);
3228
+ }
3229
+ if (chunk.done) return;
3230
+ buffer += decoder.decode(chunk.value, { stream: true });
3231
+ let separator = /\r?\n\r?\n/.exec(buffer);
3232
+ while (separator) {
3233
+ const block = buffer.slice(0, separator.index);
3234
+ buffer = buffer.slice(separator.index + separator[0].length);
3235
+ const data = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
3236
+ const event = data ? parseEvent(data) : null;
3237
+ if (event) onFrame(event);
3238
+ separator = /\r?\n\r?\n/.exec(buffer);
3239
+ }
3240
+ }
3241
+ } finally {
3242
+ reader.releaseLock();
3243
+ }
3244
+ }
3245
+ function sleep(ms, signal) {
3246
+ return new Promise((resolve) => {
3247
+ const timer = setTimeout(resolve, ms);
3248
+ signal.addEventListener(
3249
+ "abort",
3250
+ () => {
3251
+ clearTimeout(timer);
3252
+ resolve();
3253
+ },
3254
+ { once: true }
3255
+ );
3256
+ });
3257
+ }
3258
+ function parseEvent(raw) {
3259
+ let text;
3260
+ if (typeof raw === "string") text = raw;
3261
+ else if (raw instanceof ArrayBuffer || raw instanceof Uint8Array) {
3262
+ text = new TextDecoder().decode(raw);
3263
+ } else return null;
3264
+ let value;
3265
+ try {
3266
+ value = JSON.parse(text);
3267
+ } catch {
3268
+ return null;
3269
+ }
3270
+ const event = asObject(value);
3271
+ if (!event || typeof event.type !== "string" || !event.type) return null;
3272
+ if (typeof event.timestamp !== "number" || !Number.isFinite(event.timestamp)) return null;
3273
+ if (event.sequence !== void 0 && (typeof event.sequence !== "number" || !Number.isSafeInteger(event.sequence) || event.sequence < 0)) {
3274
+ return null;
3275
+ }
3276
+ return {
3277
+ type: event.type,
3278
+ payload: event.payload,
3279
+ timestamp: event.timestamp,
3280
+ ...typeof event.sequence === "number" ? { sequence: event.sequence } : {}
3281
+ };
3282
+ }
3283
+ function asDelta(event) {
3284
+ if (event.type !== "textChunk") return event;
3285
+ const kind = asObject(event.payload)?.kind;
3286
+ return { ...event, type: kind === "thinking" ? "thinking" : "textDelta" };
3287
+ }
3288
+ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3289
+ "stepStart",
3290
+ "textDelta",
3291
+ "thinking",
3292
+ "toolCall",
3293
+ "toolResult"
3294
+ ]);
3295
+ var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3296
+ function turnAfter(event, inTurn) {
3297
+ if (TURN_FRAME_TYPES.has(event.type)) return true;
3298
+ if (event.type === "error") return false;
3299
+ if (event.type === "stepFinish") {
3300
+ const payload = asObject(event.payload);
3301
+ if (TURN_END_REASONS.has(payload?.reason)) return false;
3302
+ return asObject(payload?.lifecycle)?.interruptTerminal !== true;
3303
+ }
3304
+ return inTurn;
3305
+ }
3306
+ function channelEvent(type, payload) {
3307
+ return { type, payload, timestamp: Date.now() };
3308
+ }
3309
+ var HttpUnsupportedError = class extends Error {
3310
+ constructor(status) {
3311
+ super(`The Agent box has no HTTP chat routes (${status}).`);
3312
+ this.name = "HttpUnsupportedError";
3313
+ }
3314
+ };
3315
+ var GrantRejectedError = class extends Error {
3316
+ constructor(status) {
3317
+ super(`The Agent box rejected the channel grant (${status}).`);
3318
+ this.name = "GrantRejectedError";
3319
+ }
3320
+ };
3321
+ var ChannelRenewalError = class extends Error {
3322
+ constructor(message) {
3323
+ super(message);
3324
+ this.name = "ChannelRenewalError";
3325
+ }
3326
+ };
3327
+ function isGrantRejection(status) {
3328
+ return status === 401 || status === 403;
3329
+ }
3330
+ function errorCodeOf(body) {
3331
+ const code = asObject(body)?.error_code;
3332
+ return typeof code === "string" ? code : void 0;
3333
+ }
3334
+ function withBody(response, body) {
3335
+ return { ok: response.ok, status: response.status, body: response.body, json: async () => body };
3336
+ }
3337
+ var AgentDirectChannel = class {
3338
+ constructor(tasks, fallback, options = {}) {
3339
+ this.tasks = tasks;
3340
+ this.fallback = fallback;
3341
+ this.options = options;
3342
+ }
3343
+ links = /* @__PURE__ */ new Map();
3344
+ /** Whether an open would try the box at all: the Copilot can be asked and the box reached. */
3345
+ canDial(transport) {
3346
+ return this.enabled() && this.modeFor(transport) !== null;
3347
+ }
3348
+ /**
3349
+ * Off until the SDK says where it talks to: without `apiUrl` the host of an offer cannot be
3350
+ * checked, and asking for a channel that will not be followed would still move the chat to a
3351
+ * box. The session then stays exactly as before the direct channel.
3352
+ */
3353
+ enabled() {
3354
+ return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
3355
+ }
3356
+ async open(taskId, observer, signal, transport) {
3357
+ if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
3358
+ const mode = this.modeFor(transport);
3359
+ const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
3360
+ if (signal?.aborted) throw signal.reason ?? new Error("Agent channel request aborted.");
3361
+ if ("declined" in answer || !mode) {
3362
+ if ("declined" in answer) observer.onEvent(channelEvent("channelDeclined", answer.declined));
3363
+ return this.fallback.open(taskId, observer, signal, transport);
3364
+ }
3365
+ try {
3366
+ return await this.openDirect(taskId, mode, answer, observer, signal);
3367
+ } catch (error) {
3368
+ if (signal?.aborted) throw error;
3369
+ observer.onEvent(
3370
+ channelEvent("channelDeclined", {
3371
+ reason: error instanceof HttpUnsupportedError ? "http_unsupported" : "unavailable",
3372
+ error: errorMessage(error)
3373
+ })
3374
+ );
3375
+ return this.fallback.open(taskId, observer, signal, transport);
3376
+ }
3377
+ }
3378
+ /**
3379
+ * Hands a message or an interrupt to the box when the chat is on the direct channel and its
3380
+ * wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3381
+ * mid-redial, or an approval, which stays on REST.
3382
+ *
3383
+ * A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
3384
+ * the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
3385
+ * and reaches the Copilot's log whether or not this process is still around, so a Serverless
3386
+ * Function may return. An `error` frame is a refusal the session already reports from the
3387
+ * stream, and resolves false; a refusal in the HTTP answer rejects with `AgentTaskTurnError`.
3388
+ * A channel lost for good, or closed, before the box answered rejects with that cause.
3389
+ *
3390
+ * A message whose wire drops before the box answers is not sent again over REST: the box may
3391
+ * have admitted the turn, and a second copy would start it twice. The redial replays the box
3392
+ * log, where the `stepStart` of an admitted turn is.
3393
+ */
3394
+ send(taskId, input) {
3395
+ if (input.type === "approval_response") return null;
3396
+ const link = this.links.get(taskId);
3397
+ if (!link?.wire) return null;
3398
+ if (input.type !== "message") return link.wire.interrupt(input);
3399
+ link.admission?.fail(new Error("A newer message replaced the one waiting for the box."));
3400
+ let admission;
3401
+ const admitted = new Promise((resolve, reject) => {
3402
+ let timer;
3403
+ const arm = () => {
3404
+ clearTimeout(timer);
3405
+ timer = setTimeout(() => {
3406
+ admission.fail(
3407
+ new Error(
3408
+ `The Agent box did not confirm the turn within ${ADMISSION_TIMEOUT_MS / 1e3}s.`
3409
+ )
3410
+ );
3411
+ }, ADMISSION_TIMEOUT_MS);
3412
+ };
3413
+ const done = () => {
3414
+ clearTimeout(timer);
3415
+ if (link.admission === admission) link.admission = null;
3416
+ };
3417
+ admission = {
3418
+ settle: (value) => {
3419
+ done();
3420
+ resolve(value);
3421
+ },
3422
+ fail: (error) => {
3423
+ done();
3424
+ reject(error);
3425
+ },
3426
+ hold: () => clearTimeout(timer),
3427
+ rearm: arm
3428
+ };
3429
+ arm();
3430
+ });
3431
+ link.admission = admission;
3432
+ if (!link.wire.message(input, admission)) {
3433
+ admission.settle(false);
3434
+ return null;
3435
+ }
3436
+ link.inTurn = true;
3437
+ return admitted;
3438
+ }
3439
+ /** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
3440
+ modeFor(transport) {
3441
+ const socket = this.webSocket() !== null;
3442
+ const http = this.fetcher() !== null;
3443
+ if (transport === "websocket") return socket ? "websocket" : null;
3444
+ if (transport === "http") return http ? "http" : null;
3445
+ if (socket) return "websocket";
3446
+ return http ? "http" : null;
3447
+ }
3448
+ webSocket() {
3449
+ if (this.options.WebSocket) return this.options.WebSocket;
3450
+ const global = globalThis.WebSocket;
3451
+ return typeof global === "function" ? global : null;
3452
+ }
3453
+ fetcher() {
3454
+ if (this.options.fetch) return this.options.fetch;
3455
+ const global = globalThis.fetch;
3456
+ return typeof global === "function" ? global : null;
3457
+ }
3458
+ /**
3459
+ * One request. The Copilot holds it while the box boots and answers with the channel, or an
3460
+ * error once the box cannot be had. A 202 comes only from a Copilot that offers no channel.
3461
+ */
3462
+ async requestChannel(taskId) {
3463
+ let channel;
3464
+ try {
3465
+ channel = await this.tasks.channel(taskId);
3466
+ } catch (error) {
3467
+ const code = error?.code;
3468
+ return {
3469
+ declined: {
3470
+ reason: code === "INVALID_RESPONSE" ? "body" : "unavailable",
3471
+ error: errorMessage(error)
3472
+ }
3473
+ };
3474
+ }
3475
+ if (!channel) return { declined: { reason: "unavailable" } };
3476
+ if (!isChannelHostAllowed(channel.wsUrl, this.options.apiUrl)) {
3477
+ const host = hostOf(channel.wsUrl);
3478
+ return { declined: { reason: "host", ...host === void 0 ? {} : { host } } };
3479
+ }
3480
+ return channel;
3481
+ }
3482
+ /**
3483
+ * The box path. A drop in the middle of a turn is redialed from here, with the replay the box
3484
+ * offers, so the session keeps one connection and one stream. The session hears a disconnect
3485
+ * only when the redial gives up, when the Copilot no longer offers the box, or when there is
3486
+ * no turn to resume: dialing an idle box again would wake it for nobody.
3487
+ *
3488
+ * Opening never asks for an older replay. What an idle chat missed is history, which the
3489
+ * session loads by REST; replaying from an older cursor would put old turns on screen as live
3490
+ * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3491
+ */
3492
+ async openDirect(taskId, mode, channel, observer, signal) {
3493
+ const link = { wire: null, inTurn: false, admission: null };
3494
+ let box = boxAddress(channel.wsUrl);
3495
+ let cursor = channel.lastSequence;
3496
+ const abort = new AbortController();
3497
+ const onAbort = () => abort.abort(signal?.reason);
3498
+ signal?.addEventListener("abort", onAbort, { once: true });
3499
+ const onFrame = (event) => {
3500
+ if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3501
+ link.inTurn = turnAfter(event, link.inTurn);
3502
+ observer.onEvent(event);
3503
+ if (event.type === "stepStart") link.admission?.settle(true);
3504
+ else if (event.type === "error") link.admission?.settle(false);
3505
+ };
3506
+ const onLost = (error, code) => {
3507
+ link.wire = null;
3508
+ if (abort.signal.aborted) return;
3509
+ if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
3510
+ link.admission?.fail(error);
3511
+ observer.onDisconnect(error);
3512
+ return;
3513
+ }
3514
+ link.admission?.hold();
3515
+ void this.redial(taskId, mode, error, abort.signal, observer, {
3516
+ onFrame,
3517
+ onLost,
3518
+ replayFrom: (next) => {
3519
+ const nextBox = boxAddress(next.wsUrl);
3520
+ if (nextBox === box) return cursor;
3521
+ box = nextBox;
3522
+ cursor = next.lastSequence;
3523
+ return void 0;
3524
+ }
3525
+ }).then((outcome) => {
3526
+ if (outcome instanceof Error) link.admission?.fail(outcome);
3527
+ else if (outcome) {
3528
+ link.wire = outcome;
3529
+ link.admission?.rearm();
3530
+ }
3531
+ });
3532
+ };
3533
+ try {
3534
+ link.wire = await this.connect(taskId, mode, channel, {
3535
+ signal: abort.signal,
3536
+ onFrame,
3537
+ onLost
3538
+ });
3539
+ } catch (error) {
3540
+ signal?.removeEventListener("abort", onAbort);
3541
+ throw error;
3542
+ }
3543
+ this.links.set(taskId, link);
3544
+ return {
3545
+ close: () => {
3546
+ signal?.removeEventListener("abort", onAbort);
3547
+ abort.abort();
3548
+ link.wire?.close();
3549
+ link.wire = null;
3550
+ link.admission?.fail(
3551
+ new Error("The Agent session closed before the box confirmed the turn.")
3552
+ );
3553
+ if (this.links.get(taskId) === link) this.links.delete(taskId);
3554
+ }
3555
+ };
3556
+ }
3557
+ async connect(taskId, mode, channel, options) {
3558
+ if (mode === "http") return this.openHttp(taskId, channel, options);
3559
+ const socket = await this.dial(channel.wsUrl, options);
3560
+ return {
3561
+ close: () => socket.close(),
3562
+ interrupt: (input) => socket.send(JSON.stringify(input)) ? Promise.resolve(true) : null,
3563
+ message: (input) => socket.send(JSON.stringify(input))
3564
+ };
3565
+ }
3566
+ async redial(taskId, mode, cause, signal, observer, handlers) {
3567
+ let lastError = cause;
3568
+ for (const [index, delayMs] of RECONNECT_DELAYS_MS.entries()) {
3569
+ const attempt = index + 1;
3570
+ observer.onEvent(
3571
+ channelEvent("channelReconnecting", {
3572
+ attempt,
3573
+ maxAttempts: RECONNECT_DELAYS_MS.length,
3574
+ reason: lastError.message
3575
+ })
3576
+ );
3577
+ await sleep(delayMs, signal);
3578
+ if (signal.aborted) return null;
3579
+ const outcome = await this.reopenOnce(taskId, mode, signal, handlers);
3580
+ if (signal.aborted) {
3581
+ if (outcome.kind === "wire") outcome.wire.close();
3582
+ return null;
3583
+ }
3584
+ if (outcome.kind === "wire") {
3585
+ observer.onEvent(channelEvent("channelConnected", { attempt }));
3586
+ return outcome.wire;
3587
+ }
3588
+ if (outcome.kind === "refused") {
3589
+ const refused = new Error(
3590
+ `The Copilot no longer offers the box channel (after: ${cause.message})`
3591
+ );
3592
+ observer.onDisconnect(refused);
3593
+ return refused;
3594
+ }
3595
+ lastError = outcome.error;
3596
+ }
3597
+ const exhausted = new Error(
3598
+ `Agent box channel could not be reopened after ${RECONNECT_DELAYS_MS.length} attempts: ${lastError.message}`
3599
+ );
3600
+ observer.onDisconnect(exhausted);
3601
+ return exhausted;
3602
+ }
3603
+ // One attempt to get the box back: the channel request, then the dial. A failure is returned
3604
+ // rather than thrown, so the caller decides between another attempt and giving up.
3605
+ async reopenOnce(taskId, mode, signal, handlers) {
3606
+ let channel;
3607
+ try {
3608
+ channel = await this.tasks.channel(taskId);
3609
+ } catch (error) {
3610
+ return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
3611
+ }
3612
+ if (!channel || !isChannelHostAllowed(channel.wsUrl, this.options.apiUrl)) {
3613
+ return { kind: "refused" };
3614
+ }
3615
+ try {
3616
+ const replayFrom = handlers.replayFrom(channel);
3617
+ const wire = await this.connect(taskId, mode, channel, {
3618
+ onFrame: handlers.onFrame,
3619
+ onLost: handlers.onLost,
3620
+ signal,
3621
+ ...replayFrom === void 0 ? {} : { replayFrom }
3622
+ });
3623
+ return { kind: "wire", wire };
3624
+ } catch (error) {
3625
+ if (error instanceof HttpUnsupportedError) return { kind: "refused" };
3626
+ return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
3627
+ }
3628
+ }
3629
+ /**
3630
+ * The box over HTTP: the event stream reads what the socket would carry, from the sequence
3631
+ * asked, and each message is a POST the box answers once the turn was admitted.
3632
+ *
3633
+ * The URLs carry a grant that lasts 10 minutes and, behind the dev proxy, a ticket that lasts
3634
+ * 60 seconds. A 401 or 403 without an `error_code` is that grant gone stale: the Copilot is
3635
+ * asked for the channel again and the request goes once more on the fresh URLs. A second
3636
+ * rejection is an error. With an `error_code` it is a refusal, answered once as it came.
3637
+ */
3638
+ async openHttp(taskId, channel, options) {
3639
+ const fetch = this.fetcher();
3640
+ if (!fetch) throw new TypeError("fetch is not available.");
3641
+ const fromSequence = String(options.replayFrom ?? channel.lastSequence);
3642
+ let current = channel;
3643
+ const renew = async () => {
3644
+ let next;
3645
+ try {
3646
+ next = await this.tasks.channel(taskId);
3647
+ } catch (error) {
3648
+ throw new ChannelRenewalError(
3649
+ `The Agent box channel could not be renewed: ${errorMessage(error)}`
3650
+ );
3651
+ }
3652
+ if (!next || !isChannelHostAllowed(next.wsUrl, this.options.apiUrl)) {
3653
+ throw new ChannelRenewalError("The Copilot no longer offers the box channel.");
3654
+ }
3655
+ current = next;
3656
+ };
3657
+ const eventsUrl = () => {
3658
+ const url = new URL(boxRoute(current.wsUrl, "events"));
3659
+ url.searchParams.set("fromSequence", fromSequence);
3660
+ return url.toString();
3661
+ };
3662
+ let close;
3663
+ try {
3664
+ close = await this.readEvents(fetch, eventsUrl(), options);
3665
+ } catch (error) {
3666
+ if (!(error instanceof GrantRejectedError)) throw error;
3667
+ await renew();
3668
+ close = await this.readEvents(fetch, eventsUrl(), options);
3669
+ }
3670
+ const postOnce = (input) => fetch(boxRoute(current.wsUrl, "messages"), {
3671
+ method: "POST",
3672
+ headers: { "Content-Type": "application/json" },
3673
+ body: JSON.stringify(input),
3674
+ // The URL carries the grant: a redirect would hand it to wherever it points.
3675
+ redirect: "error"
3676
+ });
3677
+ const post = async (input) => {
3678
+ const response = await postOnce(input);
3679
+ if (!isGrantRejection(response.status)) return response;
3680
+ const body = await response.json().catch(() => null);
3681
+ if (errorCodeOf(body) !== void 0) return withBody(response, body);
3682
+ await renew();
3683
+ return postOnce(input);
3684
+ };
3685
+ return {
3686
+ close,
3687
+ interrupt: (input) => post(input).then((response) => {
3688
+ if (!response.ok) {
3689
+ throw new Error(`The Agent box refused the interrupt (${response.status}).`);
3690
+ }
3691
+ return true;
3692
+ }),
3693
+ message: (input, admission) => {
3694
+ post(input).then(
3695
+ async (response) => {
3696
+ if (response.ok) {
3697
+ admission.settle(true);
3698
+ return;
3699
+ }
3700
+ if (response.status === 504) {
3701
+ admission.fail(new Error("The Agent box got no admission for the turn (504)."));
3702
+ return;
3703
+ }
3704
+ const body = asObject(await response.json().catch(() => null));
3705
+ const code = errorCodeOf(body);
3706
+ if (isGrantRejection(response.status) && code === void 0) {
3707
+ admission.fail(new GrantRejectedError(response.status));
3708
+ return;
3709
+ }
3710
+ const message = typeof body?.message === "string" ? body.message : `The Agent box refused the message (${response.status}).`;
3711
+ admission.fail(new AgentTaskTurnError(message, code));
3712
+ },
3713
+ (error) => {
3714
+ if (error instanceof ChannelRenewalError) admission.fail(error);
3715
+ }
3716
+ );
3717
+ return true;
3718
+ }
3719
+ };
3720
+ }
3721
+ /** Opens the box event stream; resolves once the box answered, with the way to close it. */
3722
+ async readEvents(fetch, url, options) {
3723
+ if (options.signal?.aborted) throw new Error("Agent box event stream aborted.");
3724
+ const abort = new AbortController();
3725
+ let intentionalClose = false;
3726
+ const close = () => {
3727
+ if (intentionalClose) return;
3728
+ intentionalClose = true;
3729
+ options.signal?.removeEventListener("abort", close);
3730
+ abort.abort();
3731
+ };
3732
+ options.signal?.addEventListener("abort", close, { once: true });
3733
+ const handshake = setTimeout(() => abort.abort(), CONNECT_TIMEOUT_MS);
3734
+ let response;
3735
+ try {
3736
+ response = await fetch(url, {
3737
+ headers: { Accept: "text/event-stream" },
3738
+ signal: abort.signal,
3739
+ redirect: "error"
3740
+ });
3741
+ } catch (error) {
3742
+ close();
3743
+ throw error instanceof Error ? error : new Error(String(error));
3744
+ } finally {
3745
+ clearTimeout(handshake);
3746
+ }
3747
+ if (!response.ok || !response.body) {
3748
+ close();
3749
+ if (response.status === 404) throw new HttpUnsupportedError(response.status);
3750
+ if (isGrantRejection(response.status)) {
3751
+ const body = await response.json().catch(() => null);
3752
+ if (errorCodeOf(body) === void 0) throw new GrantRejectedError(response.status);
3753
+ }
3754
+ throw new Error(`Agent box event stream failed (${response.status}).`);
3755
+ }
3756
+ const lost = (error) => {
3757
+ if (intentionalClose) return;
3758
+ close();
3759
+ options.onLost(error);
3760
+ };
3761
+ void readSse(response.body.getReader(), (event) => options.onFrame(asDelta(event))).then(() => lost(new Error("Agent box event stream ended."))).catch((error) => lost(error instanceof Error ? error : new Error(String(error))));
3762
+ return close;
3763
+ }
3764
+ dial(url, options) {
3765
+ const Socket = this.webSocket();
3766
+ if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
3767
+ const { signal, replayFrom } = options;
3768
+ return new Promise((resolve, reject) => {
3769
+ const socket = new Socket(url);
3770
+ let opened = false;
3771
+ let intentionalClose = false;
3772
+ let settled = false;
3773
+ let silence = null;
3774
+ const clearSilence = () => {
3775
+ if (silence !== null) clearTimeout(silence);
3776
+ silence = null;
3777
+ };
3778
+ const removeAbortListener = () => signal?.removeEventListener("abort", onAbort);
3779
+ const rejectHandshake = (error) => {
3780
+ if (settled) return;
3781
+ settled = true;
3782
+ intentionalClose = true;
3783
+ clearTimeout(timer);
3784
+ removeAbortListener();
3785
+ socket.close();
3786
+ reject(error);
3787
+ };
3788
+ const touch = () => {
3789
+ clearSilence();
3790
+ silence = setTimeout(() => {
3791
+ if (intentionalClose) return;
3792
+ intentionalClose = true;
3793
+ removeAbortListener();
3794
+ options.onLost(
3795
+ new Error(`Agent WebSocket went silent for ${SILENCE_TIMEOUT_MS / 1e3}s.`)
3796
+ );
3797
+ socket.close(1e3, "Client closed");
3798
+ }, SILENCE_TIMEOUT_MS);
3799
+ };
3800
+ const close = () => {
3801
+ if (intentionalClose) return;
3802
+ intentionalClose = true;
3803
+ clearSilence();
3804
+ removeAbortListener();
3805
+ socket.close(1e3, "Client closed");
3806
+ };
3807
+ const send = (frame) => {
3808
+ if (intentionalClose || socket.readyState !== SOCKET_OPEN) return false;
3809
+ try {
3810
+ socket.send(frame);
3811
+ return true;
3812
+ } catch {
3813
+ return false;
3814
+ }
3815
+ };
3816
+ const onAbort = () => {
3817
+ if (!opened) {
3818
+ rejectHandshake(
3819
+ signal?.reason instanceof Error ? signal.reason : new Error("Agent WebSocket connection aborted.")
3820
+ );
3821
+ return;
3822
+ }
3823
+ close();
3824
+ };
3825
+ const timer = setTimeout(() => {
3826
+ rejectHandshake(new Error("Timed out connecting to the Agent WebSocket."));
3827
+ }, CONNECT_TIMEOUT_MS);
3828
+ signal?.addEventListener("abort", onAbort, { once: true });
3829
+ const handlers = socket;
3830
+ handlers.onopen = () => {
3831
+ if (settled) return;
3832
+ opened = true;
3833
+ settled = true;
3834
+ clearTimeout(timer);
3835
+ touch();
3836
+ if (replayFrom !== void 0) {
3837
+ try {
3838
+ socket.send(JSON.stringify({ type: "replay", fromSequence: replayFrom }));
3839
+ } catch {
3840
+ }
3841
+ }
3842
+ resolve({ close, send });
3843
+ };
3844
+ handlers.onerror = () => {
3845
+ if (!opened) rejectHandshake(new Error("Failed to connect to the Agent WebSocket."));
3846
+ };
3847
+ handlers.onmessage = (message) => {
3848
+ touch();
3849
+ const event = parseEvent(message.data);
3850
+ if (event) options.onFrame(asDelta(event));
3851
+ };
3852
+ handlers.onclose = (event) => {
3853
+ clearTimeout(timer);
3854
+ clearSilence();
3855
+ removeAbortListener();
3856
+ if (!opened) {
3857
+ rejectHandshake(new Error(`Agent WebSocket closed during handshake (${event.code}).`));
3858
+ return;
3859
+ }
3860
+ if (!intentionalClose) {
3861
+ options.onLost(new Error(`Agent WebSocket closed (${event.code}).`), event.code);
3862
+ }
3863
+ };
3864
+ });
3865
+ }
3866
+ };
3867
+
3868
+ // src/agentSession.ts
3869
+ var AGENT_QUEUE_LIMIT = 10;
3870
+ var CANCEL_SAFETY_MS = 1e4;
3871
+ var RECONCILE_DELAY_MS = 1e3;
3872
+ function asObject2(value) {
3873
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3874
+ }
3875
+ function errorMessage2(error) {
3152
3876
  if (error instanceof Error) return error.message;
3153
3877
  if (error && typeof error === "object" && "message" in error) {
3154
3878
  return String(error.message);
@@ -3194,14 +3918,18 @@ function toAgentTimelineItem(message) {
3194
3918
  }
3195
3919
  function createAgentTaskSessionManager(options) {
3196
3920
  const sessions = /* @__PURE__ */ new Map();
3921
+ const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
3197
3922
  return {
3198
- session(sessionOptions) {
3199
- if ("taskId" in sessionOptions) {
3200
- const current = sessions.get(sessionOptions.taskId);
3923
+ session(requested) {
3924
+ if ("taskId" in requested) {
3925
+ const current = sessions.get(requested.taskId);
3201
3926
  if (current && current.status !== "closed") return current;
3202
3927
  }
3928
+ const sessionOptions = "create" in requested && !requested.runtime && channel.canDial(requested.transport) ? { ...requested, runtime: "T3" } : requested;
3203
3929
  const session = new CoreAgentTaskSession(sessionOptions, {
3204
- ...options,
3930
+ tasks: options.tasks,
3931
+ eventSource: channel,
3932
+ channel,
3205
3933
  onTaskId: (taskId, value) => sessions.set(taskId, value),
3206
3934
  onClose: (taskId, value) => {
3207
3935
  if (sessions.get(taskId) === value) sessions.delete(taskId);
@@ -3449,7 +4177,7 @@ var CoreAgentTaskSession = class {
3449
4177
  this.activeWaiter = waiter;
3450
4178
  this.setStatus("streaming");
3451
4179
  this.emit("turnStart", {});
3452
- await this.sendInput(input);
4180
+ if (await this.sendInput(input)) this.emit("accepted", {});
3453
4181
  }
3454
4182
  async ensureTask() {
3455
4183
  if (this._taskId) return;
@@ -3528,7 +4256,7 @@ var CoreAgentTaskSession = class {
3528
4256
  }
3529
4257
  } catch (error) {
3530
4258
  if (this.isClosed()) return;
3531
- const recoveryError = error instanceof Error ? error : new Error(errorMessage(error));
4259
+ const recoveryError = error instanceof Error ? error : new Error(errorMessage2(error));
3532
4260
  this.failLiveChannel(error, recoveryError);
3533
4261
  }
3534
4262
  }
@@ -3562,13 +4290,17 @@ var CoreAgentTaskSession = class {
3562
4290
  this.finishTurn(reason);
3563
4291
  return true;
3564
4292
  }
3565
- sendInput(input) {
3566
- if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3567
- return this.dependencies.tasks.sendInput(this._taskId, input);
4293
+ /** True once the server took the input; false when the box refused it on the stream. */
4294
+ async sendInput(input) {
4295
+ if (!this._taskId) throw new Error("Agent task has not been created.");
4296
+ const direct = this.dependencies.channel.send(this._taskId, input);
4297
+ if (direct) return direct;
4298
+ await this.dependencies.tasks.sendInput(this._taskId, input);
4299
+ return true;
3568
4300
  }
3569
4301
  handleEvent(event) {
3570
4302
  this.emit("raw", event);
3571
- const payload = asObject(event.payload);
4303
+ const payload = asObject2(event.payload);
3572
4304
  switch (event.type) {
3573
4305
  // A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
3574
4306
  // como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
@@ -3633,7 +4365,7 @@ var CoreAgentTaskSession = class {
3633
4365
  if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
3634
4366
  }
3635
4367
  consumeDelta(payload, kind) {
3636
- const lifecycle = asObject(payload?.lifecycle);
4368
+ const lifecycle = asObject2(payload?.lifecycle);
3637
4369
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
3638
4370
  if (turnId && this.finishedTurnIds.includes(turnId)) return;
3639
4371
  const idle = this._status !== "streaming" && this._status !== "cancelled";
@@ -3791,7 +4523,7 @@ var CoreAgentTaskSession = class {
3791
4523
  const code = errorCode(error);
3792
4524
  this.emit("error", {
3793
4525
  ...code ? { code } : {},
3794
- error: `${prefix}: ${errorMessage(error)}`
4526
+ error: `${prefix}: ${errorMessage2(error)}`
3795
4527
  });
3796
4528
  }
3797
4529
  setStatus(status) {