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