@mitralab.io/sdk-core 0.2.8 → 0.2.9-beta.1

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,729 @@ 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 {
3336
+ ok: response.ok,
3337
+ status: response.status,
3338
+ headers: response.headers,
3339
+ body: response.body,
3340
+ json: async () => body
3341
+ };
3342
+ }
3343
+ var AgentDirectChannel = class {
3344
+ constructor(tasks, fallback, options = {}) {
3345
+ this.tasks = tasks;
3346
+ this.fallback = fallback;
3347
+ this.options = options;
3348
+ }
3349
+ links = /* @__PURE__ */ new Map();
3350
+ /** Whether an open would try the box at all: the Copilot can be asked and the box reached. */
3351
+ canDial(transport) {
3352
+ return this.enabled() && this.modeFor(transport) !== null;
3353
+ }
3354
+ /**
3355
+ * Off until the SDK says where it talks to: without `apiUrl` the host of an offer cannot be
3356
+ * checked, and asking for a channel that will not be followed would still move the chat to a
3357
+ * box. The session then stays exactly as before the direct channel.
3358
+ */
3359
+ enabled() {
3360
+ return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
3361
+ }
3362
+ async open(taskId, observer, signal, transport) {
3363
+ if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
3364
+ const mode = this.modeFor(transport);
3365
+ const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
3366
+ if (signal?.aborted) throw signal.reason ?? new Error("Agent channel request aborted.");
3367
+ if ("declined" in answer || !mode) {
3368
+ if ("declined" in answer) observer.onEvent(channelEvent("channelDeclined", answer.declined));
3369
+ return this.fallback.open(taskId, observer, signal, transport);
3370
+ }
3371
+ try {
3372
+ return await this.openDirect(taskId, mode, answer, observer, signal);
3373
+ } catch (error) {
3374
+ if (signal?.aborted) throw error;
3375
+ observer.onEvent(
3376
+ channelEvent("channelDeclined", {
3377
+ reason: error instanceof HttpUnsupportedError ? "http_unsupported" : "unavailable",
3378
+ error: errorMessage(error)
3379
+ })
3380
+ );
3381
+ return this.fallback.open(taskId, observer, signal, transport);
3382
+ }
3383
+ }
3384
+ /**
3385
+ * Hands a message or an interrupt to the box when the chat is on the direct channel and its
3386
+ * wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3387
+ * mid-redial, or an approval, which stays on REST.
3388
+ *
3389
+ * A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
3390
+ * the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
3391
+ * and reaches the Copilot's log whether or not this process is still around, so a Serverless
3392
+ * Function may return. An `error` frame is a refusal the session already reports from the
3393
+ * stream, and resolves false; a refusal in the HTTP answer rejects with `AgentTaskTurnError`.
3394
+ * A channel lost for good, or closed, before the box answered rejects with that cause.
3395
+ *
3396
+ * A message whose wire drops before the box answers is not sent again over REST: the box may
3397
+ * have admitted the turn, and a second copy would start it twice. The redial replays the box
3398
+ * log, where the `stepStart` of an admitted turn is.
3399
+ */
3400
+ send(taskId, input) {
3401
+ if (input.type === "approval_response") return null;
3402
+ const link = this.links.get(taskId);
3403
+ if (!link?.wire) return null;
3404
+ if (input.type !== "message") return link.wire.interrupt(input);
3405
+ link.admission?.fail(new Error("A newer message replaced the one waiting for the box."));
3406
+ let admission;
3407
+ const admitted = new Promise((resolve, reject) => {
3408
+ let timer;
3409
+ const arm = () => {
3410
+ clearTimeout(timer);
3411
+ timer = setTimeout(() => {
3412
+ admission.fail(
3413
+ new Error(
3414
+ `The Agent box did not confirm the turn within ${ADMISSION_TIMEOUT_MS / 1e3}s.`
3415
+ )
3416
+ );
3417
+ }, ADMISSION_TIMEOUT_MS);
3418
+ };
3419
+ const done = () => {
3420
+ clearTimeout(timer);
3421
+ if (link.admission === admission) link.admission = null;
3422
+ };
3423
+ admission = {
3424
+ settle: (value) => {
3425
+ done();
3426
+ resolve(value);
3427
+ },
3428
+ fail: (error) => {
3429
+ done();
3430
+ reject(error);
3431
+ },
3432
+ hold: () => clearTimeout(timer),
3433
+ rearm: arm
3434
+ };
3435
+ arm();
3436
+ });
3437
+ link.admission = admission;
3438
+ if (!link.wire.message(input, admission)) {
3439
+ admission.settle(false);
3440
+ return null;
3441
+ }
3442
+ link.inTurn = true;
3443
+ return admitted;
3444
+ }
3445
+ /** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
3446
+ modeFor(transport) {
3447
+ const socket = this.webSocket() !== null;
3448
+ const http = this.fetcher() !== null;
3449
+ if (transport === "websocket") return socket ? "websocket" : null;
3450
+ if (transport === "http") return http ? "http" : null;
3451
+ if (socket) return "websocket";
3452
+ return http ? "http" : null;
3453
+ }
3454
+ webSocket() {
3455
+ if (this.options.WebSocket) return this.options.WebSocket;
3456
+ const global = globalThis.WebSocket;
3457
+ return typeof global === "function" ? global : null;
3458
+ }
3459
+ fetcher() {
3460
+ if (this.options.fetch) return this.options.fetch;
3461
+ const global = globalThis.fetch;
3462
+ return typeof global === "function" ? global : null;
3463
+ }
3464
+ /**
3465
+ * One request. The Copilot holds it while the box boots and answers with the channel, or an
3466
+ * error once the box cannot be had. A 202 comes only from a Copilot that offers no channel.
3467
+ */
3468
+ async requestChannel(taskId) {
3469
+ let channel;
3470
+ try {
3471
+ channel = await this.tasks.channel(taskId);
3472
+ } catch (error) {
3473
+ const code = error?.code;
3474
+ return {
3475
+ declined: {
3476
+ reason: code === "INVALID_RESPONSE" ? "body" : "unavailable",
3477
+ error: errorMessage(error)
3478
+ }
3479
+ };
3480
+ }
3481
+ if (!channel) return { declined: { reason: "unavailable" } };
3482
+ if (!isChannelHostAllowed(channel.wsUrl, this.options.apiUrl)) {
3483
+ const host = hostOf(channel.wsUrl);
3484
+ return { declined: { reason: "host", ...host === void 0 ? {} : { host } } };
3485
+ }
3486
+ return channel;
3487
+ }
3488
+ /**
3489
+ * The box path. A drop in the middle of a turn is redialed from here, with the replay the box
3490
+ * offers, so the session keeps one connection and one stream. The session hears a disconnect
3491
+ * only when the redial gives up, when the Copilot no longer offers the box, or when there is
3492
+ * no turn to resume: dialing an idle box again would wake it for nobody.
3493
+ *
3494
+ * Opening never asks for an older replay. What an idle chat missed is history, which the
3495
+ * session loads by REST; replaying from an older cursor would put old turns on screen as live
3496
+ * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3497
+ */
3498
+ async openDirect(taskId, mode, channel, observer, signal) {
3499
+ const link = { wire: null, inTurn: false, admission: null };
3500
+ let box = boxAddress(channel.wsUrl);
3501
+ let cursor = channel.lastSequence;
3502
+ const abort = new AbortController();
3503
+ const onAbort = () => abort.abort(signal?.reason);
3504
+ signal?.addEventListener("abort", onAbort, { once: true });
3505
+ const onFrame = (event) => {
3506
+ if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3507
+ link.inTurn = turnAfter(event, link.inTurn);
3508
+ observer.onEvent(event);
3509
+ if (event.type === "stepStart") link.admission?.settle(true);
3510
+ else if (event.type === "error") link.admission?.settle(false);
3511
+ };
3512
+ const onLost = (error, code) => {
3513
+ link.wire = null;
3514
+ if (abort.signal.aborted) return;
3515
+ if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
3516
+ link.admission?.fail(error);
3517
+ observer.onDisconnect(error);
3518
+ return;
3519
+ }
3520
+ link.admission?.hold();
3521
+ void this.redial(taskId, mode, error, abort.signal, observer, {
3522
+ onFrame,
3523
+ onLost,
3524
+ replayFrom: (next) => {
3525
+ const nextBox = boxAddress(next.wsUrl);
3526
+ if (nextBox === box) return cursor;
3527
+ box = nextBox;
3528
+ cursor = next.lastSequence;
3529
+ return void 0;
3530
+ }
3531
+ }).then((outcome) => {
3532
+ if (outcome instanceof Error) link.admission?.fail(outcome);
3533
+ else if (outcome) {
3534
+ link.wire = outcome;
3535
+ link.admission?.rearm();
3536
+ }
3537
+ });
3538
+ };
3539
+ try {
3540
+ link.wire = await this.connect(taskId, mode, channel, {
3541
+ signal: abort.signal,
3542
+ onFrame,
3543
+ onLost
3544
+ });
3545
+ } catch (error) {
3546
+ signal?.removeEventListener("abort", onAbort);
3547
+ throw error;
3548
+ }
3549
+ this.links.set(taskId, link);
3550
+ return {
3551
+ close: () => {
3552
+ signal?.removeEventListener("abort", onAbort);
3553
+ abort.abort();
3554
+ link.wire?.close();
3555
+ link.wire = null;
3556
+ link.admission?.fail(
3557
+ new Error("The Agent session closed before the box confirmed the turn.")
3558
+ );
3559
+ if (this.links.get(taskId) === link) this.links.delete(taskId);
3560
+ }
3561
+ };
3562
+ }
3563
+ async connect(taskId, mode, channel, options) {
3564
+ if (mode === "http") return this.openHttp(taskId, channel, options);
3565
+ const socket = await this.dial(channel.wsUrl, options);
3566
+ return {
3567
+ close: () => socket.close(),
3568
+ interrupt: (input) => socket.send(JSON.stringify(input)) ? Promise.resolve(true) : null,
3569
+ message: (input) => socket.send(JSON.stringify(input))
3570
+ };
3571
+ }
3572
+ async redial(taskId, mode, cause, signal, observer, handlers) {
3573
+ let lastError = cause;
3574
+ for (const [index, delayMs] of RECONNECT_DELAYS_MS.entries()) {
3575
+ const attempt = index + 1;
3576
+ observer.onEvent(
3577
+ channelEvent("channelReconnecting", {
3578
+ attempt,
3579
+ maxAttempts: RECONNECT_DELAYS_MS.length,
3580
+ reason: lastError.message
3581
+ })
3582
+ );
3583
+ await sleep(delayMs, signal);
3584
+ if (signal.aborted) return null;
3585
+ const outcome = await this.reopenOnce(taskId, mode, signal, handlers);
3586
+ if (signal.aborted) {
3587
+ if (outcome.kind === "wire") outcome.wire.close();
3588
+ return null;
3589
+ }
3590
+ if (outcome.kind === "wire") {
3591
+ observer.onEvent(channelEvent("channelConnected", { attempt }));
3592
+ return outcome.wire;
3593
+ }
3594
+ if (outcome.kind === "refused") {
3595
+ const refused = new Error(
3596
+ `The Copilot no longer offers the box channel (after: ${cause.message})`
3597
+ );
3598
+ observer.onDisconnect(refused);
3599
+ return refused;
3600
+ }
3601
+ lastError = outcome.error;
3602
+ }
3603
+ const exhausted = new Error(
3604
+ `Agent box channel could not be reopened after ${RECONNECT_DELAYS_MS.length} attempts: ${lastError.message}`
3605
+ );
3606
+ observer.onDisconnect(exhausted);
3607
+ return exhausted;
3608
+ }
3609
+ // One attempt to get the box back: the channel request, then the dial. A failure is returned
3610
+ // rather than thrown, so the caller decides between another attempt and giving up.
3611
+ async reopenOnce(taskId, mode, signal, handlers) {
3612
+ let channel;
3613
+ try {
3614
+ channel = await this.tasks.channel(taskId);
3615
+ } catch (error) {
3616
+ return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
3617
+ }
3618
+ if (!channel || !isChannelHostAllowed(channel.wsUrl, this.options.apiUrl)) {
3619
+ return { kind: "refused" };
3620
+ }
3621
+ try {
3622
+ const replayFrom = handlers.replayFrom(channel);
3623
+ const wire = await this.connect(taskId, mode, channel, {
3624
+ onFrame: handlers.onFrame,
3625
+ onLost: handlers.onLost,
3626
+ signal,
3627
+ ...replayFrom === void 0 ? {} : { replayFrom }
3628
+ });
3629
+ return { kind: "wire", wire };
3630
+ } catch (error) {
3631
+ if (error instanceof HttpUnsupportedError) return { kind: "refused" };
3632
+ return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
3633
+ }
3634
+ }
3635
+ /**
3636
+ * The box over HTTP: the event stream reads what the socket would carry, from the sequence
3637
+ * asked, and each message is a POST the box answers once the turn was admitted.
3638
+ *
3639
+ * The URLs carry a grant that lasts 10 minutes and, behind the dev proxy, a ticket that lasts
3640
+ * 60 seconds. A 401 or 403 without an `error_code` is that grant gone stale: the Copilot is
3641
+ * asked for the channel again and the request goes once more on the fresh URLs. A second
3642
+ * rejection is an error. With an `error_code` it is a refusal, answered once as it came.
3643
+ */
3644
+ async openHttp(taskId, channel, options) {
3645
+ const fetch = this.fetcher();
3646
+ if (!fetch) throw new TypeError("fetch is not available.");
3647
+ const fromSequence = String(options.replayFrom ?? channel.lastSequence);
3648
+ let current = channel;
3649
+ const renew = async () => {
3650
+ let next;
3651
+ try {
3652
+ next = await this.tasks.channel(taskId);
3653
+ } catch (error) {
3654
+ throw new ChannelRenewalError(
3655
+ `The Agent box channel could not be renewed: ${errorMessage(error)}`
3656
+ );
3657
+ }
3658
+ if (!next || !isChannelHostAllowed(next.wsUrl, this.options.apiUrl)) {
3659
+ throw new ChannelRenewalError("The Copilot no longer offers the box channel.");
3660
+ }
3661
+ current = next;
3662
+ };
3663
+ const eventsUrl = () => {
3664
+ const url = new URL(boxRoute(current.wsUrl, "events"));
3665
+ url.searchParams.set("fromSequence", fromSequence);
3666
+ return url.toString();
3667
+ };
3668
+ let close;
3669
+ try {
3670
+ close = await this.readEvents(fetch, eventsUrl(), options);
3671
+ } catch (error) {
3672
+ if (!(error instanceof GrantRejectedError)) throw error;
3673
+ await renew();
3674
+ close = await this.readEvents(fetch, eventsUrl(), options);
3675
+ }
3676
+ const postOnce = (input) => fetch(boxRoute(current.wsUrl, "messages"), {
3677
+ method: "POST",
3678
+ headers: { "Content-Type": "application/json" },
3679
+ body: JSON.stringify(input),
3680
+ // The URL carries the grant: a redirect would hand it to wherever it points.
3681
+ redirect: "error"
3682
+ });
3683
+ const post = async (input) => {
3684
+ const response = await postOnce(input);
3685
+ if (!isGrantRejection(response.status)) return response;
3686
+ const body = await response.json().catch(() => null);
3687
+ if (errorCodeOf(body) !== void 0) return withBody(response, body);
3688
+ await renew();
3689
+ return postOnce(input);
3690
+ };
3691
+ return {
3692
+ close,
3693
+ interrupt: (input) => post(input).then((response) => {
3694
+ if (!response.ok) {
3695
+ throw new Error(`The Agent box refused the interrupt (${response.status}).`);
3696
+ }
3697
+ return true;
3698
+ }),
3699
+ message: (input, admission) => {
3700
+ post(input).then(
3701
+ async (response) => {
3702
+ if (response.ok) {
3703
+ admission.settle(true);
3704
+ return;
3705
+ }
3706
+ const body = asObject(await response.json().catch(() => null));
3707
+ const code = errorCodeOf(body);
3708
+ if (isGrantRejection(response.status) && code === void 0) {
3709
+ admission.fail(new GrantRejectedError(response.status));
3710
+ return;
3711
+ }
3712
+ const fallback = response.status === 504 ? "The Agent box got no admission for the turn (504)." : `The Agent box refused the message (${response.status}).`;
3713
+ const message = typeof body?.message === "string" ? body.message : fallback;
3714
+ admission.fail(new AgentTaskTurnError(message, code));
3715
+ },
3716
+ (error) => {
3717
+ if (error instanceof ChannelRenewalError) admission.fail(error);
3718
+ }
3719
+ );
3720
+ return true;
3721
+ }
3722
+ };
3723
+ }
3724
+ /** Opens the box event stream; resolves once the box answered, with the way to close it. */
3725
+ async readEvents(fetch, url, options) {
3726
+ if (options.signal?.aborted) throw new Error("Agent box event stream aborted.");
3727
+ const abort = new AbortController();
3728
+ let intentionalClose = false;
3729
+ const close = () => {
3730
+ if (intentionalClose) return;
3731
+ intentionalClose = true;
3732
+ options.signal?.removeEventListener("abort", close);
3733
+ abort.abort();
3734
+ };
3735
+ options.signal?.addEventListener("abort", close, { once: true });
3736
+ const handshake = setTimeout(() => abort.abort(), CONNECT_TIMEOUT_MS);
3737
+ let response;
3738
+ try {
3739
+ response = await fetch(url, {
3740
+ headers: { Accept: "text/event-stream" },
3741
+ signal: abort.signal,
3742
+ redirect: "error"
3743
+ });
3744
+ } catch (error) {
3745
+ close();
3746
+ throw error instanceof Error ? error : new Error(String(error));
3747
+ } finally {
3748
+ clearTimeout(handshake);
3749
+ }
3750
+ if (!response.ok || !response.body) {
3751
+ close();
3752
+ if (response.status === 404) throw new HttpUnsupportedError(response.status);
3753
+ if (isGrantRejection(response.status)) {
3754
+ const body = await response.json().catch(() => null);
3755
+ if (errorCodeOf(body) === void 0) throw new GrantRejectedError(response.status);
3756
+ }
3757
+ throw new Error(`Agent box event stream failed (${response.status}).`);
3758
+ }
3759
+ const contentType = response.headers.get("content-type") ?? "";
3760
+ if (!/^text\/event-stream\b/i.test(contentType)) {
3761
+ close();
3762
+ throw new HttpUnsupportedError(contentType || "no content type");
3763
+ }
3764
+ const lost = (error) => {
3765
+ if (intentionalClose) return;
3766
+ close();
3767
+ options.onLost(error);
3768
+ };
3769
+ 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))));
3770
+ return close;
3771
+ }
3772
+ dial(url, options) {
3773
+ const Socket = this.webSocket();
3774
+ if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
3775
+ const { signal, replayFrom } = options;
3776
+ return new Promise((resolve, reject) => {
3777
+ const socket = new Socket(url);
3778
+ let opened = false;
3779
+ let intentionalClose = false;
3780
+ let settled = false;
3781
+ let silence = null;
3782
+ const clearSilence = () => {
3783
+ if (silence !== null) clearTimeout(silence);
3784
+ silence = null;
3785
+ };
3786
+ const removeAbortListener = () => signal?.removeEventListener("abort", onAbort);
3787
+ const rejectHandshake = (error) => {
3788
+ if (settled) return;
3789
+ settled = true;
3790
+ intentionalClose = true;
3791
+ clearTimeout(timer);
3792
+ removeAbortListener();
3793
+ socket.close();
3794
+ reject(error);
3795
+ };
3796
+ const touch = () => {
3797
+ clearSilence();
3798
+ silence = setTimeout(() => {
3799
+ if (intentionalClose) return;
3800
+ intentionalClose = true;
3801
+ removeAbortListener();
3802
+ options.onLost(
3803
+ new Error(`Agent WebSocket went silent for ${SILENCE_TIMEOUT_MS / 1e3}s.`)
3804
+ );
3805
+ socket.close(1e3, "Client closed");
3806
+ }, SILENCE_TIMEOUT_MS);
3807
+ };
3808
+ const close = () => {
3809
+ if (intentionalClose) return;
3810
+ intentionalClose = true;
3811
+ clearSilence();
3812
+ removeAbortListener();
3813
+ socket.close(1e3, "Client closed");
3814
+ };
3815
+ const send = (frame) => {
3816
+ if (intentionalClose || socket.readyState !== SOCKET_OPEN) return false;
3817
+ try {
3818
+ socket.send(frame);
3819
+ return true;
3820
+ } catch {
3821
+ return false;
3822
+ }
3823
+ };
3824
+ const onAbort = () => {
3825
+ if (!opened) {
3826
+ rejectHandshake(
3827
+ signal?.reason instanceof Error ? signal.reason : new Error("Agent WebSocket connection aborted.")
3828
+ );
3829
+ return;
3830
+ }
3831
+ close();
3832
+ };
3833
+ const timer = setTimeout(() => {
3834
+ rejectHandshake(new Error("Timed out connecting to the Agent WebSocket."));
3835
+ }, CONNECT_TIMEOUT_MS);
3836
+ signal?.addEventListener("abort", onAbort, { once: true });
3837
+ const handlers = socket;
3838
+ handlers.onopen = () => {
3839
+ if (settled) return;
3840
+ opened = true;
3841
+ settled = true;
3842
+ clearTimeout(timer);
3843
+ touch();
3844
+ if (replayFrom !== void 0) {
3845
+ try {
3846
+ socket.send(JSON.stringify({ type: "replay", fromSequence: replayFrom }));
3847
+ } catch {
3848
+ }
3849
+ }
3850
+ resolve({ close, send });
3851
+ };
3852
+ handlers.onerror = () => {
3853
+ if (!opened) rejectHandshake(new Error("Failed to connect to the Agent WebSocket."));
3854
+ };
3855
+ handlers.onmessage = (message) => {
3856
+ touch();
3857
+ const event = parseEvent(message.data);
3858
+ if (event) options.onFrame(asDelta(event));
3859
+ };
3860
+ handlers.onclose = (event) => {
3861
+ clearTimeout(timer);
3862
+ clearSilence();
3863
+ removeAbortListener();
3864
+ if (!opened) {
3865
+ rejectHandshake(new Error(`Agent WebSocket closed during handshake (${event.code}).`));
3866
+ return;
3867
+ }
3868
+ if (!intentionalClose) {
3869
+ options.onLost(new Error(`Agent WebSocket closed (${event.code}).`), event.code);
3870
+ }
3871
+ };
3872
+ });
3873
+ }
3874
+ };
3875
+
3876
+ // src/agentSession.ts
3877
+ var AGENT_QUEUE_LIMIT = 10;
3878
+ var CANCEL_SAFETY_MS = 1e4;
3879
+ var RECONCILE_DELAY_MS = 1e3;
3880
+ function asObject2(value) {
3881
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3882
+ }
3883
+ function errorMessage2(error) {
3152
3884
  if (error instanceof Error) return error.message;
3153
3885
  if (error && typeof error === "object" && "message" in error) {
3154
3886
  return String(error.message);
@@ -3194,14 +3926,18 @@ function toAgentTimelineItem(message) {
3194
3926
  }
3195
3927
  function createAgentTaskSessionManager(options) {
3196
3928
  const sessions = /* @__PURE__ */ new Map();
3929
+ const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
3197
3930
  return {
3198
- session(sessionOptions) {
3199
- if ("taskId" in sessionOptions) {
3200
- const current = sessions.get(sessionOptions.taskId);
3931
+ session(requested) {
3932
+ if ("taskId" in requested) {
3933
+ const current = sessions.get(requested.taskId);
3201
3934
  if (current && current.status !== "closed") return current;
3202
3935
  }
3936
+ const sessionOptions = "create" in requested && requested.agentId && !requested.runtime && channel.canDial(requested.transport) ? { ...requested, runtime: "T3" } : requested;
3203
3937
  const session = new CoreAgentTaskSession(sessionOptions, {
3204
- ...options,
3938
+ tasks: options.tasks,
3939
+ eventSource: options.eventSource,
3940
+ channel,
3205
3941
  onTaskId: (taskId, value) => sessions.set(taskId, value),
3206
3942
  onClose: (taskId, value) => {
3207
3943
  if (sessions.get(taskId) === value) sessions.delete(taskId);
@@ -3449,7 +4185,7 @@ var CoreAgentTaskSession = class {
3449
4185
  this.activeWaiter = waiter;
3450
4186
  this.setStatus("streaming");
3451
4187
  this.emit("turnStart", {});
3452
- await this.sendInput(input);
4188
+ if (await this.sendInput(input)) this.emit("accepted", {});
3453
4189
  }
3454
4190
  async ensureTask() {
3455
4191
  if (this._taskId) return;
@@ -3481,7 +4217,8 @@ var CoreAgentTaskSession = class {
3481
4217
  if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3482
4218
  const abort = new AbortController();
3483
4219
  this.connectionAbort = abort;
3484
- this.connectionPromise = this.dependencies.eventSource.open(
4220
+ const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
4221
+ this.connectionPromise = source.open(
3485
4222
  this._taskId,
3486
4223
  {
3487
4224
  onEvent: (event) => this.handleEvent(event),
@@ -3528,7 +4265,7 @@ var CoreAgentTaskSession = class {
3528
4265
  }
3529
4266
  } catch (error) {
3530
4267
  if (this.isClosed()) return;
3531
- const recoveryError = error instanceof Error ? error : new Error(errorMessage(error));
4268
+ const recoveryError = error instanceof Error ? error : new Error(errorMessage2(error));
3532
4269
  this.failLiveChannel(error, recoveryError);
3533
4270
  }
3534
4271
  }
@@ -3562,13 +4299,17 @@ var CoreAgentTaskSession = class {
3562
4299
  this.finishTurn(reason);
3563
4300
  return true;
3564
4301
  }
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);
4302
+ /** True once the server took the input; false when the box refused it on the stream. */
4303
+ async sendInput(input) {
4304
+ if (!this._taskId) throw new Error("Agent task has not been created.");
4305
+ const direct = this.dependencies.channel.send(this._taskId, input);
4306
+ if (direct) return direct;
4307
+ await this.dependencies.tasks.sendInput(this._taskId, input);
4308
+ return true;
3568
4309
  }
3569
4310
  handleEvent(event) {
3570
4311
  this.emit("raw", event);
3571
- const payload = asObject(event.payload);
4312
+ const payload = asObject2(event.payload);
3572
4313
  switch (event.type) {
3573
4314
  // A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
3574
4315
  // como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
@@ -3633,7 +4374,7 @@ var CoreAgentTaskSession = class {
3633
4374
  if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
3634
4375
  }
3635
4376
  consumeDelta(payload, kind) {
3636
- const lifecycle = asObject(payload?.lifecycle);
4377
+ const lifecycle = asObject2(payload?.lifecycle);
3637
4378
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
3638
4379
  if (turnId && this.finishedTurnIds.includes(turnId)) return;
3639
4380
  const idle = this._status !== "streaming" && this._status !== "cancelled";
@@ -3791,7 +4532,7 @@ var CoreAgentTaskSession = class {
3791
4532
  const code = errorCode(error);
3792
4533
  this.emit("error", {
3793
4534
  ...code ? { code } : {},
3794
- error: `${prefix}: ${errorMessage(error)}`
4535
+ error: `${prefix}: ${errorMessage2(error)}`
3795
4536
  });
3796
4537
  }
3797
4538
  setStatus(status) {