@mitralab.io/sdk-core 0.2.14 → 0.3.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
@@ -942,7 +942,8 @@ function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFact
942
942
  if (typeof channel.wsUrl !== "string" || !channel.wsUrl) invalidField(context, "wsUrl", errors);
943
943
  return {
944
944
  wsUrl: channel.wsUrl,
945
- lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0
945
+ lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0,
946
+ ...isInteger(channel.boxLog) ? { boxLog: channel.boxLog } : {}
946
947
  };
947
948
  }
948
949
  function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
@@ -1614,7 +1615,12 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1614
1615
  const page = expectPage(
1615
1616
  await transport.request(`${path(id)}/messages`, {
1616
1617
  method: "GET",
1617
- params: { page: options.page, size: options.size, sort: options.sort }
1618
+ params: {
1619
+ page: options.page,
1620
+ size: options.size,
1621
+ sort: options.sort,
1622
+ kinds: options.kinds
1623
+ }
1618
1624
  }),
1619
1625
  context,
1620
1626
  errors
@@ -3239,6 +3245,29 @@ var ADMISSION_TIMEOUT_MS = 35e3;
3239
3245
  var SUPERSEDED_CLOSE_CODE = 4409;
3240
3246
  var SOCKET_OPEN = 1;
3241
3247
  var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
3248
+ var clientMessageSequence = 0;
3249
+ function newClientMessageId() {
3250
+ const random = globalThis.crypto?.randomUUID;
3251
+ return random ? random.call(globalThis.crypto) : `m-${Date.now()}-${++clientMessageSequence}`;
3252
+ }
3253
+ function admissionFor(link, event) {
3254
+ const payload = asObject(event.payload);
3255
+ if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0 || payload?.command !== void 0)) {
3256
+ return void 0;
3257
+ }
3258
+ const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
3259
+ if (typeof id === "string")
3260
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3261
+ return link.admissions[0];
3262
+ }
3263
+ function queuedAdmission(link, event) {
3264
+ const id = asObject(asObject(event.payload)?.lifecycle)?.clientMessageId;
3265
+ if (typeof id !== "string") return void 0;
3266
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3267
+ }
3268
+ function isSubagentFrame(event) {
3269
+ return typeof asObject(event.payload)?.parentToolId === "string";
3270
+ }
3242
3271
  function asObject(value) {
3243
3272
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3244
3273
  }
@@ -3269,6 +3298,14 @@ function boxAddress(wsUrl) {
3269
3298
  const url = new URL(wsUrl);
3270
3299
  return `${url.origin}${url.pathname}`;
3271
3300
  }
3301
+ function helloOf(event) {
3302
+ if (event.type !== "hello") return void 0;
3303
+ const payload = asObject(event.payload);
3304
+ const threadId = payload?.threadId;
3305
+ const lastSequence = payload?.lastSequence;
3306
+ if (typeof threadId !== "string" || typeof lastSequence !== "number") return void 0;
3307
+ return { threadId, lastSequence };
3308
+ }
3272
3309
  function boxRoute(wsUrl, route) {
3273
3310
  const url = new URL(wsUrl);
3274
3311
  url.protocol = url.protocol === "wss:" ? "https:" : "http:";
@@ -3359,15 +3396,15 @@ function asDelta(event) {
3359
3396
  }
3360
3397
  var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3361
3398
  "stepStart",
3399
+ "steer",
3362
3400
  "textDelta",
3363
3401
  "thinking",
3364
- "toolCall",
3365
- "toolResult"
3402
+ "toolCall"
3366
3403
  ]);
3367
3404
  var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3368
3405
  function turnAfter(event, inTurn) {
3369
3406
  if (TURN_FRAME_TYPES.has(event.type)) return true;
3370
- if (event.type === "error") return false;
3407
+ if (event.type === "error") return asObject(event.payload)?.lifecycle ? false : inTurn;
3371
3408
  if (event.type === "stepFinish") {
3372
3409
  const payload = asObject(event.payload);
3373
3410
  if (TURN_END_REASONS.has(payload?.reason)) return false;
@@ -3375,6 +3412,27 @@ function turnAfter(event, inTurn) {
3375
3412
  }
3376
3413
  return inTurn;
3377
3414
  }
3415
+ function followsTurn(link, event) {
3416
+ if (event.type === "messageQueued") return false;
3417
+ if (event.type !== "stepFinish" && event.type !== "error") return true;
3418
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3419
+ return typeof turnId !== "string" || link.turnId === void 0 || turnId === link.turnId;
3420
+ }
3421
+ function lostTurnFrame(turnId) {
3422
+ return {
3423
+ type: "stepFinish",
3424
+ payload: {
3425
+ reason: "interrupted",
3426
+ lifecycle: {
3427
+ ...turnId === void 0 ? {} : { turnId },
3428
+ terminal: true,
3429
+ sessionIdle: true,
3430
+ interruptTerminal: true
3431
+ }
3432
+ },
3433
+ timestamp: Date.now()
3434
+ };
3435
+ }
3378
3436
  function channelEvent(type, payload) {
3379
3437
  return { type, payload, timestamp: Date.now() };
3380
3438
  }
@@ -3431,7 +3489,7 @@ var AgentDirectChannel = class {
3431
3489
  enabled() {
3432
3490
  return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
3433
3491
  }
3434
- async open(taskId, observer, signal, transport) {
3492
+ async open(taskId, observer, signal, transport, historyCursor) {
3435
3493
  if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
3436
3494
  const mode = this.modeFor(transport);
3437
3495
  const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
@@ -3441,7 +3499,7 @@ var AgentDirectChannel = class {
3441
3499
  return this.fallback.open(taskId, observer, signal, transport);
3442
3500
  }
3443
3501
  try {
3444
- return await this.openDirect(taskId, mode, answer, observer, signal);
3502
+ return await this.openDirect(taskId, mode, answer, observer, signal, historyCursor);
3445
3503
  } catch (error) {
3446
3504
  if (signal?.aborted) throw error;
3447
3505
  observer.onEvent(
@@ -3454,9 +3512,11 @@ var AgentDirectChannel = class {
3454
3512
  }
3455
3513
  }
3456
3514
  /**
3457
- * Hands a message or an interrupt to the box when the chat is on the direct channel and its
3458
- * wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3459
- * mid-redial, or an approval, which stays on REST.
3515
+ * Hands a message, an interrupt, a subagent stop or an answer to a T3 input request to the box
3516
+ * when the chat is on the direct channel and its wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3517
+ * mid-redial, or an approval, which stays on REST. Mid-redial the Copilot is the durable path:
3518
+ * the box URL kept from the last channel carries a proxy ticket that lasts 60 seconds, and a
3519
+ * box that dropped the socket is often the one that went away.
3460
3520
  *
3461
3521
  * A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
3462
3522
  * the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
@@ -3469,12 +3529,12 @@ var AgentDirectChannel = class {
3469
3529
  * have admitted the turn, and a second copy would start it twice. The redial replays the box
3470
3530
  * log, where the `stepStart` of an admitted turn is.
3471
3531
  */
3472
- send(taskId, input) {
3532
+ send(taskId, input, clientMessageId) {
3473
3533
  if (input.type === "approval_response") return null;
3474
3534
  const link = this.links.get(taskId);
3475
3535
  if (!link?.wire) return null;
3476
3536
  if (input.type !== "message") return link.wire.interrupt(input);
3477
- link.admission?.fail(new Error("A newer message replaced the one waiting for the box."));
3537
+ const messageId = clientMessageId ?? newClientMessageId();
3478
3538
  let admission;
3479
3539
  const admitted = new Promise((resolve, reject) => {
3480
3540
  let timer;
@@ -3490,11 +3550,13 @@ var AgentDirectChannel = class {
3490
3550
  };
3491
3551
  const done = () => {
3492
3552
  clearTimeout(timer);
3493
- if (link.admission === admission) link.admission = null;
3553
+ link.admissions = link.admissions.filter((pending) => pending !== admission);
3494
3554
  };
3495
3555
  admission = {
3556
+ clientMessageId: messageId,
3496
3557
  settle: (value) => {
3497
3558
  done();
3559
+ if (value) link.inTurn = true;
3498
3560
  resolve(value);
3499
3561
  },
3500
3562
  fail: (error) => {
@@ -3506,12 +3568,11 @@ var AgentDirectChannel = class {
3506
3568
  };
3507
3569
  arm();
3508
3570
  });
3509
- link.admission = admission;
3510
- if (!link.wire.message(input, admission)) {
3571
+ link.admissions = [...link.admissions, admission];
3572
+ if (!link.wire.message({ ...input, clientMessageId: messageId }, admission)) {
3511
3573
  admission.settle(false);
3512
3574
  return null;
3513
3575
  }
3514
- link.inTurn = true;
3515
3576
  return admitted;
3516
3577
  }
3517
3578
  /** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
@@ -3563,56 +3624,91 @@ var AgentDirectChannel = class {
3563
3624
  * only when the redial gives up, when the Copilot no longer offers the box, or when there is
3564
3625
  * no turn to resume: dialing an idle box again would wake it for nobody.
3565
3626
  *
3566
- * Opening never asks for an older replay. What an idle chat missed is history, which the
3567
- * session loads by REST; replaying from an older cursor would put old turns on screen as live
3568
- * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3627
+ * Opening asks for the replay from where the session's history ends, with the same request the
3628
+ * redial makes: what the history has, the replay does not repeat, and what the Copilot has not
3629
+ * recorded yet (the turn running now, or one it is still behind on) comes in the replay before
3630
+ * any live frame. When the Copilot says the box log is another one than the history's newest,
3631
+ * nothing of it is in the history and the replay starts at its beginning. A history with no
3632
+ * box sequence asks for nothing, and the open starts at the sequence the Copilot reported.
3569
3633
  */
3570
- async openDirect(taskId, mode, channel, observer, signal) {
3571
- const link = { wire: null, inTurn: false, admission: null };
3634
+ async openDirect(taskId, mode, channel, observer, signal, historyCursor) {
3635
+ const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
3572
3636
  let box = boxAddress(channel.wsUrl);
3573
- let cursor = channel.lastSequence;
3637
+ let thread;
3638
+ const otherLog = historyCursor?.boxLog !== void 0 && channel.boxLog !== void 0 && historyCursor.boxLog !== channel.boxLog;
3639
+ const historyFrom = historyCursor === void 0 ? void 0 : otherLog ? 0 : historyCursor.sequence;
3640
+ let cursor = historyFrom ?? channel.lastSequence;
3574
3641
  const abort = new AbortController();
3575
3642
  const onAbort = () => abort.abort(signal?.reason);
3576
3643
  signal?.addEventListener("abort", onAbort, { once: true });
3577
3644
  const onFrame = (event) => {
3645
+ const hello = helloOf(event);
3646
+ if (hello) thread = hello.threadId;
3578
3647
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3579
- link.inTurn = turnAfter(event, link.inTurn);
3648
+ if (isSubagentFrame(event)) {
3649
+ observer.onEvent(event);
3650
+ return;
3651
+ }
3652
+ if (followsTurn(link, event)) {
3653
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3654
+ if (typeof turnId === "string" && event.type !== "toolResult") link.turnId = turnId;
3655
+ link.inTurn = turnAfter(event, link.inTurn);
3656
+ }
3580
3657
  observer.onEvent(event);
3581
- if (event.type === "stepStart") link.admission?.settle(true);
3582
- else if (event.type === "error") link.admission?.settle(false);
3658
+ if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
3659
+ else if (event.type === "error") admissionFor(link, event)?.settle(false);
3660
+ else if (event.type === "messageQueued" || event.type === "steer") {
3661
+ queuedAdmission(link, event)?.settle(true);
3662
+ }
3583
3663
  };
3584
3664
  const onLost = (error, code) => {
3585
3665
  link.wire = null;
3586
3666
  if (abort.signal.aborted) return;
3587
- if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
3588
- link.admission?.fail(error);
3667
+ if (!link.inTurn && link.admissions.length === 0 || code === SUPERSEDED_CLOSE_CODE) {
3668
+ for (const pending of link.admissions) pending.fail(error);
3589
3669
  observer.onDisconnect(error);
3590
3670
  return;
3591
3671
  }
3592
- link.admission?.hold();
3672
+ for (const pending of link.admissions) pending.hold();
3593
3673
  void this.redial(taskId, mode, error, abort.signal, observer, {
3594
3674
  onFrame,
3595
3675
  onLost,
3596
3676
  replayFrom: (next) => {
3597
- const nextBox = boxAddress(next.wsUrl);
3598
- if (nextBox === box) return cursor;
3599
- box = nextBox;
3600
- cursor = next.lastSequence;
3601
- return void 0;
3677
+ const decide = (hello) => {
3678
+ const nextBox = boxAddress(next.wsUrl);
3679
+ const zeroed = next.lastSequence === 0 && cursor > 0;
3680
+ const otherBox = hello !== void 0 && (hello.threadId !== thread || hello.lastSequence < cursor);
3681
+ if (nextBox === box && !zeroed && !otherBox) return cursor;
3682
+ if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3683
+ box = nextBox;
3684
+ if (mode === "websocket") {
3685
+ cursor = 0;
3686
+ return 0;
3687
+ }
3688
+ cursor = next.lastSequence;
3689
+ return void 0;
3690
+ };
3691
+ return mode === "websocket" && thread !== void 0 ? decide : decide(void 0);
3602
3692
  }
3603
3693
  }).then((outcome) => {
3604
- if (outcome instanceof Error) link.admission?.fail(outcome);
3694
+ if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
3605
3695
  else if (outcome) {
3606
3696
  link.wire = outcome;
3607
- link.admission?.rearm();
3697
+ for (const pending of link.admissions) pending.rearm();
3608
3698
  }
3609
3699
  });
3610
3700
  };
3701
+ const afterHello = (hello) => {
3702
+ if (hello !== void 0 && hello.lastSequence < cursor) cursor = 0;
3703
+ return cursor;
3704
+ };
3705
+ const replay = historyFrom === void 0 ? {} : mode === "websocket" ? { replayAfterHello: afterHello } : { replayFrom: historyFrom };
3611
3706
  try {
3612
3707
  link.wire = await this.connect(taskId, mode, channel, {
3613
3708
  signal: abort.signal,
3614
3709
  onFrame,
3615
- onLost
3710
+ onLost,
3711
+ ...replay
3616
3712
  });
3617
3713
  } catch (error) {
3618
3714
  signal?.removeEventListener("abort", onAbort);
@@ -3625,9 +3721,8 @@ var AgentDirectChannel = class {
3625
3721
  abort.abort();
3626
3722
  link.wire?.close();
3627
3723
  link.wire = null;
3628
- link.admission?.fail(
3629
- new Error("The Agent session closed before the box confirmed the turn.")
3630
- );
3724
+ const closed = new Error("The Agent session closed before the box confirmed the turn.");
3725
+ for (const pending of link.admissions) pending.fail(closed);
3631
3726
  if (this.links.get(taskId) === link) this.links.delete(taskId);
3632
3727
  }
3633
3728
  };
@@ -3696,7 +3791,8 @@ var AgentDirectChannel = class {
3696
3791
  onFrame: handlers.onFrame,
3697
3792
  onLost: handlers.onLost,
3698
3793
  signal,
3699
- ...replayFrom === void 0 ? {} : { replayFrom }
3794
+ ...typeof replayFrom === "function" ? { replayAfterHello: replayFrom } : {},
3795
+ ...typeof replayFrom === "number" ? { replayFrom } : {}
3700
3796
  });
3701
3797
  return { kind: "wire", wire };
3702
3798
  } catch (error) {
@@ -3764,7 +3860,7 @@ var AgentDirectChannel = class {
3764
3860
  close,
3765
3861
  interrupt: (input) => post(input).then((response) => {
3766
3862
  if (!response.ok) {
3767
- throw new Error(`The Agent box refused the interrupt (${response.status}).`);
3863
+ throw new Error(`The Agent box refused the ${input.type} (${response.status}).`);
3768
3864
  }
3769
3865
  return true;
3770
3866
  }),
@@ -3845,6 +3941,7 @@ var AgentDirectChannel = class {
3845
3941
  const Socket = this.webSocket();
3846
3942
  if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
3847
3943
  const { signal, replayFrom } = options;
3944
+ let replayAfterHello = options.replayAfterHello;
3848
3945
  return new Promise((resolve, reject) => {
3849
3946
  const socket = new Socket(url);
3850
3947
  let opened = false;
@@ -3927,7 +4024,13 @@ var AgentDirectChannel = class {
3927
4024
  handlers.onmessage = (message) => {
3928
4025
  touch();
3929
4026
  const event = parseEvent(message.data);
3930
- if (event) options.onFrame(asDelta(event));
4027
+ if (!event) return;
4028
+ if (replayAfterHello) {
4029
+ const fromSequence = replayAfterHello(helloOf(event));
4030
+ replayAfterHello = void 0;
4031
+ if (fromSequence !== void 0) send(JSON.stringify({ type: "replay", fromSequence }));
4032
+ }
4033
+ options.onFrame(asDelta(event));
3931
4034
  };
3932
4035
  handlers.onclose = (event) => {
3933
4036
  clearTimeout(timer);
@@ -3946,9 +4049,22 @@ var AgentDirectChannel = class {
3946
4049
  };
3947
4050
 
3948
4051
  // src/agentSession.ts
3949
- var AGENT_QUEUE_LIMIT = 10;
3950
4052
  var CANCEL_SAFETY_MS = 1e4;
3951
4053
  var RECONCILE_DELAY_MS = 1e3;
4054
+ var ENDED_POLLS_BEFORE_NEWEST = 3;
4055
+ var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
4056
+ "textDelta",
4057
+ "textChunk",
4058
+ "thinking",
4059
+ "toolCall",
4060
+ "toolResult",
4061
+ "stepFinish"
4062
+ ]);
4063
+ var COPILOT_INPUT_TYPES = /* @__PURE__ */ new Set([
4064
+ "message",
4065
+ "interrupt",
4066
+ "approval_response"
4067
+ ]);
3952
4068
  function providerUsageOf(payload) {
3953
4069
  if (!payload) return null;
3954
4070
  try {
@@ -3977,7 +4093,120 @@ function errorCode(error) {
3977
4093
  function delay(milliseconds) {
3978
4094
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
3979
4095
  }
4096
+ function messageInput(prompt, options) {
4097
+ return {
4098
+ type: "message",
4099
+ content: prompt,
4100
+ ...options.agentType ? { agentType: options.agentType } : {},
4101
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4102
+ ...options.mode ? { mode: options.mode } : {}
4103
+ };
4104
+ }
4105
+ function backgroundTasksOf(value) {
4106
+ if (!Array.isArray(value)) return [];
4107
+ return value.flatMap((entry) => {
4108
+ const task = asObject2(entry);
4109
+ if (typeof task?.taskId !== "string" || typeof task.kind !== "string") return [];
4110
+ return [
4111
+ {
4112
+ taskId: task.taskId,
4113
+ kind: task.kind,
4114
+ ...typeof task.description === "string" ? { description: task.description } : {},
4115
+ ...typeof task.childThreadId === "string" ? { childThreadId: task.childThreadId } : {}
4116
+ }
4117
+ ];
4118
+ });
4119
+ }
4120
+ function pieceIdentityOf(event, payload) {
4121
+ const turnId = asObject2(payload?.lifecycle)?.turnId;
4122
+ return {
4123
+ ...sequenceOf(event),
4124
+ ...typeof payload?.itemId === "string" ? { itemId: payload.itemId } : {},
4125
+ ...typeof turnId === "string" ? { turnId } : {}
4126
+ };
4127
+ }
4128
+ function itemDeltaOf(payload) {
4129
+ return typeof payload?.itemDelta === "string" ? { itemDelta: payload.itemDelta } : {};
4130
+ }
4131
+ function sequenceOf(event) {
4132
+ return typeof event.sequence === "number" ? { sequence: event.sequence } : {};
4133
+ }
4134
+ function toolEventOf(event, payload, phase) {
4135
+ return {
4136
+ tool: typeof payload?.name === "string" ? payload.name : "",
4137
+ phase,
4138
+ timestamp: event.timestamp,
4139
+ ...pieceIdentityOf(event, payload),
4140
+ ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4141
+ ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4142
+ ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4143
+ };
4144
+ }
4145
+ function epochOf(value) {
4146
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4147
+ if (typeof value !== "string") return void 0;
4148
+ const parsed = Date.parse(value);
4149
+ return Number.isNaN(parsed) ? void 0 : parsed;
4150
+ }
4151
+ function timelineIdentityOf(message) {
4152
+ return {
4153
+ ...typeof message.sequence === "number" ? { sequence: message.sequence } : {},
4154
+ ...typeof message.lastSequence === "number" ? { lastSequence: message.lastSequence } : {},
4155
+ ...typeof message.boxLog === "number" ? { boxLog: message.boxLog } : {},
4156
+ ...typeof message.itemId === "string" ? { itemId: message.itemId } : {},
4157
+ ...typeof message.reason === "string" ? { reason: message.reason } : {}
4158
+ };
4159
+ }
4160
+ function historyCursorOf(history) {
4161
+ const newest = [...history].reverse().find((item) => typeof item.sequence === "number");
4162
+ if (!newest) return void 0;
4163
+ let sequence = 0;
4164
+ for (const item of history) {
4165
+ if (item.boxLog === newest.boxLog && typeof item.sequence === "number") {
4166
+ sequence = Math.max(sequence, item.lastSequence ?? item.sequence);
4167
+ }
4168
+ }
4169
+ return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4170
+ }
4171
+ function isChatRow(message) {
4172
+ return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4173
+ }
4174
+ var REQUEST_ROW_KINDS = {
4175
+ APPROVAL: "approval",
4176
+ USER_INPUT_REQUEST: "userInputRequest"
4177
+ };
4178
+ function parseJson(text) {
4179
+ try {
4180
+ return JSON.parse(text);
4181
+ } catch {
4182
+ return void 0;
4183
+ }
4184
+ }
3980
4185
  function toAgentTimelineItem(message) {
4186
+ if (message.type === "REASONING") {
4187
+ return {
4188
+ id: message.id,
4189
+ kind: "reasoning",
4190
+ text: message.content,
4191
+ at: message.createdAt,
4192
+ ...timelineIdentityOf(message),
4193
+ ...parentToolIdOf(message.parentToolId)
4194
+ };
4195
+ }
4196
+ const requestKind = REQUEST_ROW_KINDS[message.type];
4197
+ if (requestKind) {
4198
+ const payload = asObject2(parseJson(message.content));
4199
+ if (payload) {
4200
+ return {
4201
+ id: message.id,
4202
+ kind: requestKind,
4203
+ payload,
4204
+ at: message.createdAt,
4205
+ ...timelineIdentityOf(message),
4206
+ ...parentToolIdOf(message.parentToolId)
4207
+ };
4208
+ }
4209
+ }
3981
4210
  if (message.type === "TOOL_USE") {
3982
4211
  try {
3983
4212
  const payload = JSON.parse(message.content);
@@ -3988,11 +4217,14 @@ function toAgentTimelineItem(message) {
3988
4217
  tool: {
3989
4218
  tool: typeof payload.name === "string" ? payload.name : "",
3990
4219
  ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
4220
+ ...parentToolIdOf(payload.parentToolId ?? message.parentToolId),
3991
4221
  ...payload.input !== void 0 ? { input: payload.input } : {},
3992
4222
  ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
3993
4223
  phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
3994
4224
  },
3995
- at: message.createdAt
4225
+ at: message.createdAt,
4226
+ ...timelineIdentityOf(message),
4227
+ ...asObject2(message.subagent) ? { subagent: message.subagent } : {}
3996
4228
  };
3997
4229
  }
3998
4230
  } catch {
@@ -4003,9 +4235,18 @@ function toAgentTimelineItem(message) {
4003
4235
  kind: message.sender === "USER" ? "user" : "agent",
4004
4236
  text: message.content,
4005
4237
  at: message.createdAt,
4006
- ...message.usage ? { usage: message.usage } : {}
4238
+ ...message.usage ? { usage: message.usage } : {},
4239
+ ...timelineIdentityOf(message),
4240
+ ...typeof message.clientMessageId === "string" ? { clientMessageId: message.clientMessageId } : {},
4241
+ ...parentToolIdOf(message.parentToolId)
4007
4242
  };
4008
4243
  }
4244
+ function liveAtOf(event) {
4245
+ return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
4246
+ }
4247
+ function parentToolIdOf(value) {
4248
+ return typeof value === "string" ? { parentToolId: value } : {};
4249
+ }
4009
4250
  function createAgentTaskSessionManager(options) {
4010
4251
  const sessions = /* @__PURE__ */ new Map();
4011
4252
  const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
@@ -4050,7 +4291,6 @@ var CoreAgentTaskSession = class {
4050
4291
  _status = "opening";
4051
4292
  _history = [];
4052
4293
  _content = "";
4053
- _queue = [];
4054
4294
  isNewSession;
4055
4295
  listeners = /* @__PURE__ */ new Map();
4056
4296
  connection = null;
@@ -4069,10 +4309,47 @@ var CoreAgentTaskSession = class {
4069
4309
  recoveryGeneration = 0;
4070
4310
  recoveredTerminalReason;
4071
4311
  recoveredTerminalUsage;
4312
+ // Polls that found no closing row although a terminal with usage was heard.
4313
+ endedPollsWithoutRow = 0;
4314
+ // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
4315
+ // stream a dropped session falls back to replays the turn from what the history has, so it
4316
+ // repeats frames the box socket already delivered.
4317
+ turnIds = /* @__PURE__ */ new Set();
4318
+ turnSequenceHigh = -1;
4072
4319
  cancelTimer = null;
4073
- queueSequence = 0;
4320
+ // Messages leave in the order they were sent: each one is handed over only after the one
4321
+ // before it was, not after it was answered.
4322
+ handOff = Promise.resolve();
4074
4323
  activeWaiter;
4324
+ // Every steer sits in exactly one of the two lists until it is settled or forgotten: `steers`
4325
+ // while the turn it was sent into runs (taken ones settle with that turn), `strayedSteers` once
4326
+ // it waits for a turn of its own (sent with no turn, not taken when its turn ended, or queued by
4327
+ // the provider). A non-empty `strayedSteers` keeps the session busy, which is what stops a new
4328
+ // message from opening a turn the steer's answer would settle. `pendingSteers` counts the ones
4329
+ // the box has not answered yet, wherever they sit.
4330
+ steers = [];
4331
+ strayedSteers = [];
4332
+ pendingSteers = 0;
4333
+ // The id the message that opened the current turn went out with, so a refusal naming it fails
4334
+ // that turn and one naming a steer does not.
4335
+ openingMessageId;
4336
+ // The opening message went to the box, which starts its turn with a `stepStart`. Until then a
4337
+ // turn frame naming a turn is another turn's tail: the one before, closed here from the history
4338
+ // (r5 S17, dev 2026-10-19), whose live end came after the next message went out.
4339
+ openingAwaitsStart = false;
4075
4340
  turnBaselineIds = /* @__PURE__ */ new Set();
4341
+ subagentsById = /* @__PURE__ */ new Map();
4342
+ subagentSequences = /* @__PURE__ */ new Map();
4343
+ queueItems = [];
4344
+ _backgroundTasks = [];
4345
+ /** The text of each message this session sent, by its `clientMessageId`. */
4346
+ sentTexts = /* @__PURE__ */ new Map();
4347
+ // Messages of this session `accepted` was already emitted for. The frame that names a message
4348
+ // emits it in its place in the stream, so a turn delivered in one tick gives the same events as
4349
+ // one spaced out; the admission the send awaits only covers a box or a Copilot that names none.
4350
+ acceptedIds = [];
4351
+ // Taken by the first channel of `session({ taskId })`; no later channel asks for a replay.
4352
+ openingCursor;
4076
4353
  get taskId() {
4077
4354
  return this._taskId;
4078
4355
  }
@@ -4092,22 +4369,18 @@ var CoreAgentTaskSession = class {
4092
4369
  return this._content;
4093
4370
  }
4094
4371
  get queue() {
4095
- return this._queue.map((item) => ({
4096
- id: item.id,
4097
- text: item.text,
4098
- createdAt: item.createdAt,
4099
- ...item.agentType ? { agentType: item.agentType } : {},
4100
- ...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
4101
- }));
4372
+ return [...this.queueItems];
4373
+ }
4374
+ get subagents() {
4375
+ return [...this.subagentsById.values()];
4102
4376
  }
4103
4377
  send(prompt, options = {}) {
4104
4378
  this.requireOpen();
4105
- if (!prompt.trim()) return;
4106
- if (this.isBusy()) {
4107
- this.enqueue(prompt, options);
4108
- return;
4109
- }
4110
- this.startDispatch(prompt, options);
4379
+ if (!prompt.trim()) return void 0;
4380
+ if (this.isBusy()) return this.steer(prompt, options);
4381
+ const clientMessageId = newClientMessageId();
4382
+ this.startDispatch(prompt, options, clientMessageId);
4383
+ return clientMessageId;
4111
4384
  }
4112
4385
  sendAndWait(prompt, options = {}) {
4113
4386
  this.requireOpen();
@@ -4116,14 +4389,14 @@ var CoreAgentTaskSession = class {
4116
4389
  if (waiter.settled) return waiter.promise;
4117
4390
  const sendOptions = {
4118
4391
  ...options.agentType ? { agentType: options.agentType } : {},
4119
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4392
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4393
+ ...options.mode ? { mode: options.mode } : {}
4120
4394
  };
4121
4395
  if (this.isBusy()) {
4122
- const queueId = this.enqueue(prompt, sendOptions, waiter);
4123
- if (queueId) waiter.queueId = queueId;
4396
+ this.steer(prompt, sendOptions, waiter);
4124
4397
  return waiter.promise;
4125
4398
  }
4126
- this.startDispatch(prompt, sendOptions, waiter);
4399
+ this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
4127
4400
  return waiter.promise;
4128
4401
  }
4129
4402
  async cancel() {
@@ -4155,11 +4428,23 @@ var CoreAgentTaskSession = class {
4155
4428
  this.emitError("Failed to answer Agent approval", error);
4156
4429
  });
4157
4430
  }
4431
+ respondUserInput(requestId, answers, attachmentsByQuestionId) {
4432
+ const input = {
4433
+ type: "runtime-request.respond",
4434
+ requestId,
4435
+ answers,
4436
+ ...attachmentsByQuestionId ? { attachmentsByQuestionId } : {}
4437
+ };
4438
+ void this.sendInput(input).catch((error) => {
4439
+ this.emitError("Failed to answer Agent input request", error);
4440
+ });
4441
+ }
4158
4442
  async loadHistory(options = {}) {
4159
4443
  if (!this._taskId) return [];
4160
4444
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4161
4445
  ...options.limit !== void 0 ? { size: options.limit } : {},
4162
- sort: "createdAt,desc"
4446
+ sort: "createdAt,desc",
4447
+ kinds: "all"
4163
4448
  });
4164
4449
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4165
4450
  const history = this.history;
@@ -4167,25 +4452,47 @@ var CoreAgentTaskSession = class {
4167
4452
  return history;
4168
4453
  }
4169
4454
  editQueueItem(id, text) {
4170
- if (!text.trim()) {
4171
- this.removeQueueItem(id);
4172
- return;
4173
- }
4174
- this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
4175
- this.emitQueue();
4455
+ this.requireOpen();
4456
+ if (this.sentTexts.has(id)) this.sentTexts.set(id, text);
4457
+ void this.sendInput({ type: "queued-run.edit", clientMessageId: id, text }).catch(
4458
+ (error) => {
4459
+ this.emitError("Failed to edit the queued Agent message", error);
4460
+ }
4461
+ );
4176
4462
  }
4177
4463
  removeQueueItem(id) {
4178
- const removed = this._queue.find((item) => item.id === id);
4179
- this._queue = this._queue.filter((item) => item.id !== id);
4180
- removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
4181
- this.emitQueue();
4464
+ this.requireOpen();
4465
+ void this.sendInput({ type: "queued-run.cancel", clientMessageId: id }).catch(
4466
+ (error) => {
4467
+ this.emitError("Failed to remove the queued Agent message", error);
4468
+ }
4469
+ );
4182
4470
  }
4183
4471
  clearQueue() {
4184
- if (!this._queue.length) return;
4185
- const removed = this._queue;
4186
- this._queue = [];
4187
- for (const item of removed) item.waiter?.reject(new Error("Agent prompt queue was cleared."));
4188
- this.emitQueue();
4472
+ for (const item of this.queueItems) this.removeQueueItem(item.id);
4473
+ }
4474
+ steerQueueItem(id) {
4475
+ this.requireOpen();
4476
+ void this.sendInput({ type: "queued-message.promote-to-steer", clientMessageId: id }).catch(
4477
+ (error) => {
4478
+ this.emitError("Failed to steer the queued Agent message", error);
4479
+ }
4480
+ );
4481
+ }
4482
+ resumeQueue() {
4483
+ this.requireOpen();
4484
+ void this.sendInput({ type: "queue.resume" }).catch((error) => {
4485
+ this.emitError("Failed to resume the Agent queue", error);
4486
+ });
4487
+ }
4488
+ get backgroundTasks() {
4489
+ return this._backgroundTasks;
4490
+ }
4491
+ stopSubagent(subagentId) {
4492
+ this.requireOpen();
4493
+ void this.sendInput({ type: "subagent.stop", subagentId }).catch((error) => {
4494
+ this.emitError("Failed to stop the Agent subagent", error);
4495
+ });
4189
4496
  }
4190
4497
  on(event, handler) {
4191
4498
  let listeners = this.listeners.get(event);
@@ -4210,8 +4517,7 @@ var CoreAgentTaskSession = class {
4210
4517
  const closedError = new Error("Agent task session is closed.");
4211
4518
  this.activeWaiter?.reject(closedError);
4212
4519
  this.activeWaiter = void 0;
4213
- for (const item of this._queue) item.waiter?.reject(closedError);
4214
- this._queue = [];
4520
+ this.rejectSteers(closedError);
4215
4521
  if (this._taskId) this.dependencies.onClose(this._taskId, this);
4216
4522
  for (const listeners of this.listeners.values()) listeners.clear();
4217
4523
  }
@@ -4221,9 +4527,10 @@ var CoreAgentTaskSession = class {
4221
4527
  if (this.isClosed()) return false;
4222
4528
  await this.loadHistory();
4223
4529
  if (this.isClosed()) return false;
4530
+ this.openingCursor = historyCursorOf(this._history);
4224
4531
  await this.ensureChannel();
4225
4532
  if (this.isClosed()) return false;
4226
- this.setStatus("idle");
4533
+ if (this._status === "opening") this.setStatus("idle");
4227
4534
  return true;
4228
4535
  } catch (error) {
4229
4536
  if (this.isClosed()) return false;
@@ -4232,40 +4539,43 @@ var CoreAgentTaskSession = class {
4232
4539
  return false;
4233
4540
  }
4234
4541
  }
4235
- startDispatch(prompt, options, waiter) {
4542
+ startDispatch(prompt, options, clientMessageId, waiter) {
4543
+ this.sentTexts.set(clientMessageId, prompt);
4236
4544
  this.dispatching = true;
4237
- const dispatch = this.dispatchSend(prompt, options, waiter).catch((error) => {
4545
+ let handedOver;
4546
+ this.handOff = new Promise((resolve) => {
4547
+ handedOver = resolve;
4548
+ });
4549
+ const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4238
4550
  waiter?.reject(error);
4239
4551
  this.emitError("Failed to send Agent prompt", error);
4240
- if (this._status === "streaming") this.setStatus("idle");
4241
- this.flushQueue();
4552
+ if (this._status === "streaming") {
4553
+ this.settleSteers((steered) => steered.reject(error));
4554
+ this.setStatus("idle");
4555
+ }
4242
4556
  return false;
4243
4557
  }).finally(() => {
4244
- this.dispatching = false;
4245
- if (this.dispatch === dispatch) this.dispatch = null;
4246
- if (this._status === "idle") this.flushQueue();
4558
+ handedOver();
4559
+ if (this.dispatch === dispatch) {
4560
+ this.dispatching = false;
4561
+ this.dispatch = null;
4562
+ }
4247
4563
  });
4248
4564
  this.dispatch = dispatch;
4249
4565
  }
4250
- async dispatchSend(prompt, options, waiter) {
4566
+ async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
4251
4567
  if (this.openingPromise && !await this.openingPromise) {
4252
4568
  throw new Error("Agent task session could not be opened.");
4253
4569
  }
4254
- if (this.isClosed() || waiter?.settled) return false;
4570
+ if (this.isClosed()) return false;
4255
4571
  await this.ensureTask();
4256
- const input = {
4257
- type: "message",
4258
- content: prompt,
4259
- ...options.agentType ? { agentType: options.agentType } : {},
4260
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4261
- };
4572
+ const input = messageInput(prompt, options);
4262
4573
  if (this.isClosed()) {
4263
- await this.sendInput(input).catch(() => void 0);
4574
+ await this.handOver(input, clientMessageId).catch(() => void 0);
4264
4575
  return false;
4265
4576
  }
4266
- if (waiter?.settled) return false;
4267
4577
  await this.ensureChannel();
4268
- if (this.isClosed() || waiter?.settled) return false;
4578
+ if (this.isClosed()) return false;
4269
4579
  await this.captureTurnBaseline();
4270
4580
  this._content = "";
4271
4581
  this.recoveryUsed = false;
@@ -4275,10 +4585,136 @@ var CoreAgentTaskSession = class {
4275
4585
  this.activeWaiter = waiter;
4276
4586
  this.setStatus("streaming");
4277
4587
  this.emit("turnStart", {});
4278
- if (!await this.sendInput(input)) return false;
4279
- this.emit("accepted", {});
4588
+ this.openingMessageId = clientMessageId;
4589
+ this.openingAwaitsStart = true;
4590
+ const { admitted, direct } = await this.handOver(input, this.openingMessageId);
4591
+ if (!direct) this.openingAwaitsStart = false;
4592
+ handedOver();
4593
+ if (!await admitted) return false;
4594
+ this.acceptOnce(clientMessageId);
4280
4595
  return true;
4281
4596
  }
4597
+ // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
4598
+ // that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
4599
+ // that turn already ended. Nothing waits in this session. On the direct channel it goes with an
4600
+ // id the box echoes on the frame that takes it; without the channel, over REST to the Copilot,
4601
+ // which holds it while the box boots.
4602
+ //
4603
+ // It keeps its `agentType` and `reasoningEffort` on the box, which leaves the running turn's
4604
+ // model alone by itself and needs them for a message that becomes a turn of its own. Only on
4605
+ // the Copilot path, with a turn running, they are dropped: the Copilot restarts the live
4606
+ // session for a message that asks for another model, which would end that turn.
4607
+ steer(prompt, options, waiter) {
4608
+ const steered = {
4609
+ clientMessageId: newClientMessageId(),
4610
+ ...waiter ? { waiter } : {},
4611
+ taken: false
4612
+ };
4613
+ if (this.dispatching || this._status === "streaming" || this._status === "cancelled") {
4614
+ this.steers.push(steered);
4615
+ } else {
4616
+ this.strayedSteers.push(steered);
4617
+ }
4618
+ this.sentTexts.set(steered.clientMessageId, prompt);
4619
+ const input = messageInput(prompt, options);
4620
+ this.pendingSteers += 1;
4621
+ const handed = this.handOff.then(async () => {
4622
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4623
+ await this.prepareSend();
4624
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4625
+ return this.handOver(input, steered.clientMessageId, true);
4626
+ });
4627
+ this.handOff = handed.then(
4628
+ () => void 0,
4629
+ () => void 0
4630
+ );
4631
+ void handed.then(({ admitted }) => admitted).then((admitted) => {
4632
+ if (!admitted) {
4633
+ this.forgetSteer(steered);
4634
+ waiter?.reject(
4635
+ steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
4636
+ );
4637
+ return;
4638
+ }
4639
+ if (!steered.queued) this.steerTaken(steered);
4640
+ this.acceptOnce(steered.clientMessageId);
4641
+ }).catch((error) => {
4642
+ this.forgetSteer(steered);
4643
+ waiter?.reject(error);
4644
+ this.emitError("Failed to send Agent prompt", error);
4645
+ }).finally(() => {
4646
+ this.pendingSteers -= 1;
4647
+ });
4648
+ return steered.clientMessageId;
4649
+ }
4650
+ // The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
4651
+ // of its own, when that one ended before the box got to the message.
4652
+ steerTaken(steered) {
4653
+ if (steered.taken) return;
4654
+ steered.taken = true;
4655
+ if (!this.strayedSteers.includes(steered)) return;
4656
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4657
+ this.openTurnFor(steered.waiter);
4658
+ }
4659
+ steerOpenedBy(lifecycle) {
4660
+ const id = lifecycle?.clientMessageId;
4661
+ if (typeof id !== "string") return;
4662
+ const steered = [...this.steers, ...this.strayedSteers].find(
4663
+ (pending) => pending.clientMessageId === id
4664
+ );
4665
+ if (steered) this.steerTaken(steered);
4666
+ }
4667
+ // Queued behind the running turn, the message is answered by the turn the box opens for it
4668
+ // later, not by this one.
4669
+ steerQueuedBy(lifecycle) {
4670
+ const id = lifecycle?.clientMessageId;
4671
+ if (typeof id !== "string") return;
4672
+ const steered = [...this.steers, ...this.strayedSteers].find(
4673
+ (pending) => pending.clientMessageId === id
4674
+ );
4675
+ if (!steered || steered.taken) return;
4676
+ steered.queued = true;
4677
+ if (!this.steers.includes(steered)) return;
4678
+ this.steers = this.steers.filter((pending) => pending !== steered);
4679
+ this.strayedSteers.push(steered);
4680
+ }
4681
+ forgetSteer(steered) {
4682
+ this.steers = this.steers.filter((pending) => pending !== steered);
4683
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4684
+ }
4685
+ // The turn ended: what the box took is answered by it, what it had not taken yet waits for the
4686
+ // turn the box opens for it.
4687
+ settleSteers(settle) {
4688
+ const steers = this.steers;
4689
+ this.steers = [];
4690
+ for (const steered of steers) {
4691
+ if (!steered.taken) this.strayedSteers.push(steered);
4692
+ else if (steered.waiter) settle(steered.waiter);
4693
+ }
4694
+ }
4695
+ openTurnFor(waiter, start = {}) {
4696
+ if (this.isClosed()) return;
4697
+ if (this._status !== "streaming" && this._status !== "cancelled") {
4698
+ this._content = "";
4699
+ this.recoveryUsed = false;
4700
+ this.recoveredTerminalReason = void 0;
4701
+ this.recoveredTerminalUsage = void 0;
4702
+ this.recoveryGeneration += 1;
4703
+ this.turnBaselineIds = new Set(this._history.map((item) => item.id));
4704
+ void this.captureTurnBaseline().catch(() => void 0);
4705
+ this.setStatus("streaming");
4706
+ this.emit("turnStart", start);
4707
+ }
4708
+ if (!waiter) return;
4709
+ if (!this.activeWaiter) this.activeWaiter = waiter;
4710
+ else this.steers.push({ clientMessageId: "", waiter, taken: true });
4711
+ }
4712
+ rejectSteers(error) {
4713
+ const steers = [...this.steers, ...this.strayedSteers];
4714
+ this.steers = [];
4715
+ this.strayedSteers = [];
4716
+ for (const steered of steers) steered.waiter?.reject(error);
4717
+ }
4282
4718
  async ensureTask() {
4283
4719
  if (this._taskId) return;
4284
4720
  if (!("create" in this.options)) throw new Error("Agent task session has no task.");
@@ -4310,6 +4746,8 @@ var CoreAgentTaskSession = class {
4310
4746
  const abort = new AbortController();
4311
4747
  this.connectionAbort = abort;
4312
4748
  const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
4749
+ const historyCursor = this.openingCursor;
4750
+ this.openingCursor = void 0;
4313
4751
  this.connectionPromise = source.open(
4314
4752
  this._taskId,
4315
4753
  {
@@ -4317,7 +4755,8 @@ var CoreAgentTaskSession = class {
4317
4755
  onDisconnect: (error) => this.handleDisconnect(error)
4318
4756
  },
4319
4757
  abort.signal,
4320
- this.options.transport
4758
+ this.options.transport,
4759
+ historyCursor
4321
4760
  ).then((connection) => {
4322
4761
  if (this.isClosed() || this._status === "error") {
4323
4762
  connection.close();
@@ -4349,10 +4788,8 @@ var CoreAgentTaskSession = class {
4349
4788
  try {
4350
4789
  await this.ensureChannel();
4351
4790
  while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
4352
- if (await this.reconcilePersistedTurn(this.recoveredTerminalReason ?? "reconciled")) {
4353
- return;
4354
- }
4355
- if (this.activeWaiter?.settled) return;
4791
+ const reason = this.recoveredTerminalReason ?? (this._status === "cancelled" ? "interrupted" : "reconciled");
4792
+ if (await this.reconcilePersistedTurn(reason)) return;
4356
4793
  await delay(RECONCILE_DELAY_MS);
4357
4794
  }
4358
4795
  } catch (error) {
@@ -4365,7 +4802,8 @@ var CoreAgentTaskSession = class {
4365
4802
  if (!this._taskId) return;
4366
4803
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4367
4804
  size: 100,
4368
- sort: "createdAt,desc"
4805
+ sort: "createdAt,desc",
4806
+ kinds: "all"
4369
4807
  });
4370
4808
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
4371
4809
  }
@@ -4373,14 +4811,29 @@ var CoreAgentTaskSession = class {
4373
4811
  if (!this._taskId) return false;
4374
4812
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4375
4813
  size: 100,
4376
- sort: "createdAt,desc"
4814
+ sort: "createdAt,desc",
4815
+ kinds: "all"
4377
4816
  });
4378
4817
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4379
4818
  this.emit("historyLoaded", { history: this.history });
4380
- const recovered = page.content.find(
4381
- (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4819
+ const rows = page.content.filter(isChatRow);
4820
+ const recovered = rows.find(
4821
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
4382
4822
  );
4383
- if (!recovered) return false;
4823
+ if (!recovered) {
4824
+ if (this.recoveredTerminalReason === void 0) return false;
4825
+ if (this.recoveredTerminalUsage !== void 0) {
4826
+ this.endedPollsWithoutRow += 1;
4827
+ if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
4828
+ }
4829
+ const newest = rows.find(
4830
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4831
+ );
4832
+ if (!newest) return false;
4833
+ this._content = newest.content;
4834
+ this.finishTurn(reason, this.recoveredTerminalUsage);
4835
+ return true;
4836
+ }
4384
4837
  if (recovered.type === "ERROR") {
4385
4838
  const error = new AgentTaskTurnError(recovered.content);
4386
4839
  this.emit("error", { error: error.message });
@@ -4391,36 +4844,139 @@ var CoreAgentTaskSession = class {
4391
4844
  this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
4392
4845
  return true;
4393
4846
  }
4847
+ closesThisTurn(message) {
4848
+ if (!message.usage) return false;
4849
+ const prompt = message.usage.requestMessageId;
4850
+ return prompt === void 0 || !this.turnBaselineIds.has(prompt);
4851
+ }
4394
4852
  /** True once the server took the input; false when the box refused it on the stream. */
4395
4853
  async sendInput(input) {
4854
+ return (await this.handOver(input)).admitted;
4855
+ }
4856
+ // Resolves once the input left this session; `admitted` then says whether the server took it.
4857
+ // Wrapped so that awaiting the hand-over does not also await the answer.
4858
+ async handOver(input, clientMessageId, steering = false) {
4396
4859
  if (!this._taskId) throw new Error("Agent task has not been created.");
4397
- const direct = this.dependencies.channel.send(this._taskId, input);
4398
- if (direct) return direct;
4399
- await this.dependencies.tasks.sendInput(this._taskId, input);
4400
- return true;
4860
+ const direct = this.dependencies.channel.send(this._taskId, input, clientMessageId);
4861
+ if (direct) return { admitted: direct, direct: true };
4862
+ if (input.type === "runtime-request.respond") {
4863
+ throw new Error(
4864
+ "The answer to the Agent input request was not sent: the box channel is not connected right now."
4865
+ );
4866
+ }
4867
+ if (!COPILOT_INPUT_TYPES.has(input.type)) {
4868
+ throw new Error(
4869
+ `The Agent ${input.type} was not sent: the box channel is not connected right now.`
4870
+ );
4871
+ }
4872
+ const turnRunning = this._status === "streaming" || this._status === "cancelled";
4873
+ const id = clientMessageId === void 0 ? {} : { clientMessageId };
4874
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
4875
+ type: "message",
4876
+ content: input.content,
4877
+ ...input.agentType ? { agentType: input.agentType } : {},
4878
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
4879
+ ...id
4880
+ };
4881
+ await this.dependencies.tasks.sendInput(this._taskId, rest);
4882
+ return { admitted: Promise.resolve(true), direct: false };
4883
+ }
4884
+ async prepareSend() {
4885
+ if (this.openingPromise && !await this.openingPromise) {
4886
+ throw new Error("Agent task session could not be opened.");
4887
+ }
4888
+ await this.ensureTask();
4889
+ if (!this.isClosed()) await this.ensureChannel();
4401
4890
  }
4402
4891
  handleEvent(event) {
4403
4892
  this.emit("raw", event);
4404
4893
  const payload = asObject2(event.payload);
4894
+ if (payload && isSubagentFrame(event)) {
4895
+ this.handleSubagentFrame(event, payload);
4896
+ return;
4897
+ }
4898
+ const lifecycle = asObject2(payload?.lifecycle);
4899
+ if (this.endsQueuedMessage(event, payload, lifecycle)) return;
4900
+ if (this.repeatsTheRunningTurn(event, lifecycle)) return;
4901
+ if (event.type === "stepStart" || event.type === "steer") {
4902
+ const id = lifecycle?.clientMessageId;
4903
+ if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
4904
+ this.openingAwaitsStart = false;
4905
+ this.forgetFinishedTurn(lifecycle);
4906
+ }
4907
+ } else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
4908
+ this.rememberFinishedTurn(lifecycle);
4909
+ }
4405
4910
  switch (event.type) {
4406
4911
  // A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
4407
4912
  // como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
4408
4913
  // texto e o que faz a resposta recuperada aparecer; sem isso ela chega e morre aqui.
4409
4914
  case "textDelta":
4410
4915
  case "textChunk":
4411
- this.consumeDelta(payload, "text");
4916
+ this.consumeDelta(event, payload, "text");
4412
4917
  break;
4413
4918
  case "thinking":
4414
- this.consumeDelta(payload, "thinking");
4919
+ this.consumeDelta(event, payload, "thinking");
4415
4920
  break;
4416
4921
  case "toolCall":
4417
- this.emitTool(payload, "call", event.timestamp);
4922
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(event, payload, "call");
4418
4923
  break;
4924
+ // A result can come after its turn ended: a subagent in the background settles later, and
4925
+ // the box sends its result under the turn that called it. It reaches the app as that tool's
4926
+ // result and touches no turn.
4419
4927
  case "toolResult":
4420
- this.emitTool(payload, "result", event.timestamp);
4928
+ this.emitTool(event, payload, "result");
4421
4929
  break;
4422
4930
  case "workspace":
4423
- this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
4931
+ this.emit("workspace", {
4932
+ payload: event.payload,
4933
+ timestamp: event.timestamp,
4934
+ ...sequenceOf(event)
4935
+ });
4936
+ break;
4937
+ case "stepStart":
4938
+ if (!this.isFinishedTurnFrame(lifecycle)) {
4939
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
4940
+ }
4941
+ if (typeof lifecycle?.turnId === "string" && !this.isFinishedTurnFrame(lifecycle) && this._status !== "streaming" && this._status !== "cancelled") {
4942
+ this.openTurnFor(void 0, {
4943
+ ...typeof payload?.text === "string" ? { text: payload.text } : {},
4944
+ ...typeof lifecycle.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {},
4945
+ ...pieceIdentityOf(event, payload)
4946
+ });
4947
+ }
4948
+ this.leaveQueue(lifecycle?.clientMessageId);
4949
+ this.steerOpenedBy(asObject2(payload?.lifecycle));
4950
+ this.acceptNamed(lifecycle?.clientMessageId);
4951
+ break;
4952
+ case "steer":
4953
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
4954
+ this.leaveQueue(lifecycle?.clientMessageId);
4955
+ this.steerOpenedBy(lifecycle);
4956
+ this.acceptNamed(lifecycle?.clientMessageId);
4957
+ this.emit("steered", {
4958
+ text: typeof payload?.text === "string" ? payload.text : "",
4959
+ messageId: typeof payload?.messageId === "string" ? payload.messageId : "",
4960
+ ...typeof payload?.turnId === "string" ? { turnId: payload.turnId } : {},
4961
+ ...sequenceOf(event),
4962
+ ...typeof lifecycle?.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {}
4963
+ });
4964
+ break;
4965
+ case "backgroundTasks":
4966
+ this._backgroundTasks = backgroundTasksOf(payload?.tasks);
4967
+ this.emit("backgroundTasks", { tasks: this._backgroundTasks });
4968
+ break;
4969
+ case "messageQueued":
4970
+ if (payload?.cancelled === true) {
4971
+ this.cancelQueued(payload, lifecycle);
4972
+ break;
4973
+ }
4974
+ this.applyQueued(event, payload, lifecycle);
4975
+ this.steerQueuedBy(asObject2(payload?.lifecycle));
4976
+ this.acceptNamed(lifecycle?.clientMessageId);
4977
+ break;
4978
+ case "subagentUpdate":
4979
+ this.applySubagent(event, payload);
4424
4980
  break;
4425
4981
  case "providerUsage": {
4426
4982
  const usage = providerUsageOf(payload);
@@ -4429,15 +4985,22 @@ var CoreAgentTaskSession = class {
4429
4985
  }
4430
4986
  case "stepFinish": {
4431
4987
  const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
4432
- const lifecycle = payload?.lifecycle;
4988
+ const lifecycle2 = payload?.lifecycle;
4433
4989
  const usage = agentTurnUsageOf(payload?.usage);
4434
- if (reason === "interrupted" || lifecycle?.interruptTerminal === true) {
4435
- this.rememberFinishedTurn(lifecycle);
4436
- this.finishTurn("interrupted", usage);
4990
+ const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
4991
+ if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
4992
+ if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
4993
+ const end = {
4994
+ ...sequenceOf(event),
4995
+ ...finished === void 0 ? {} : { turnId: finished }
4996
+ };
4997
+ if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
4998
+ this.rememberFinishedTurn(lifecycle2);
4999
+ this.finishTurn("interrupted", usage, end);
4437
5000
  break;
4438
5001
  }
4439
5002
  if (reason === "stop" || reason === "endTurn") {
4440
- this.rememberFinishedTurn(lifecycle);
5003
+ this.rememberFinishedTurn(lifecycle2);
4441
5004
  if (this.recoveryUsed) {
4442
5005
  this.recoveredTerminalReason = reason;
4443
5006
  this.recoveredTerminalUsage = usage;
@@ -4448,7 +5011,7 @@ var CoreAgentTaskSession = class {
4448
5011
  });
4449
5012
  }
4450
5013
  } else {
4451
- this.finishTurn(reason, usage);
5014
+ this.finishTurn(reason, usage, end);
4452
5015
  }
4453
5016
  }
4454
5017
  break;
@@ -4456,23 +5019,165 @@ var CoreAgentTaskSession = class {
4456
5019
  case "error": {
4457
5020
  const code = typeof payload?.code === "string" ? payload.code : void 0;
4458
5021
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
4459
- this.emit("error", { ...code ? { code } : {}, error: message });
5022
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5023
+ if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5024
+ if (typeof payload?.command === "string") break;
5025
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
5026
+ if (typeof refused === "string") {
5027
+ if (refused !== this.openingMessageId) {
5028
+ const steered = [...this.steers, ...this.strayedSteers].find(
5029
+ (pending) => pending.clientMessageId === refused
5030
+ );
5031
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
5032
+ break;
5033
+ }
5034
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
4460
5035
  if (this._status === "streaming" || this._status === "cancelled") {
4461
5036
  this.failTurn(new AgentTaskTurnError(message, code));
4462
5037
  }
4463
5038
  break;
4464
5039
  }
5040
+ case "approval":
5041
+ case "user_input_request":
5042
+ this.liveRequest(event, payload);
5043
+ break;
4465
5044
  default:
4466
5045
  break;
4467
5046
  }
4468
5047
  }
5048
+ // The box admits every message with a `messageQueued` of no position; only one with a position
5049
+ // is in T3's queue.
5050
+ applyQueued(event, payload, lifecycle) {
5051
+ const id = payload?.clientMessageId ?? lifecycle?.clientMessageId;
5052
+ const position = payload?.position;
5053
+ if (typeof id !== "string" || typeof position !== "number") return;
5054
+ const known = this.queueItems.find((item2) => item2.id === id);
5055
+ if (this.alreadyApplied(known?.sequence, event)) return;
5056
+ const item = {
5057
+ id,
5058
+ text: typeof payload?.text === "string" ? payload.text : known?.text ?? "",
5059
+ createdAt: known?.createdAt ?? event.timestamp,
5060
+ position,
5061
+ ...typeof payload?.queueHeld === "boolean" ? { queueHeld: payload.queueHeld } : {},
5062
+ ...sequenceOf(event),
5063
+ ...typeof lifecycle?.turnId === "string" ? { turnId: lifecycle.turnId } : {}
5064
+ };
5065
+ this.queueItems = known ? this.queueItems.map((current) => current === known ? item : current) : [...this.queueItems, item];
5066
+ this.emit("queueChange", { queue: this.queue });
5067
+ }
5068
+ // The box took the message out of T3's queue on a `queued-run.cancel`, with no terminal of its
5069
+ // own: it leaves the queue and only its own `sendAndWait` ends. The message that opened this
5070
+ // session's turn was that turn, still waiting behind another one, which ends with it.
5071
+ cancelQueued(payload, lifecycle) {
5072
+ const id = payload.clientMessageId ?? lifecycle?.clientMessageId;
5073
+ if (typeof id !== "string") return;
5074
+ this.leaveQueue(id);
5075
+ const cancelled = new AgentTaskTurnError("The queued Agent message was cancelled.");
5076
+ if (id === this.openingMessageId) {
5077
+ this.cancelOpening(cancelled);
5078
+ return;
5079
+ }
5080
+ const steered = [...this.steers, ...this.strayedSteers].find(
5081
+ (pending) => pending.clientMessageId === id
5082
+ );
5083
+ if (!steered) return;
5084
+ this.forgetSteer(steered);
5085
+ steered.waiter?.reject(cancelled);
5086
+ }
5087
+ // A frame naming one of this session's messages in flight is the box taking it.
5088
+ acceptNamed(id) {
5089
+ if (typeof id !== "string") return;
5090
+ if (id === this.openingMessageId) this.dispatching = false;
5091
+ const ours = id === this.openingMessageId || [...this.steers, ...this.strayedSteers].some((pending) => pending.clientMessageId === id);
5092
+ if (ours) this.acceptOnce(id);
5093
+ }
5094
+ acceptOnce(id) {
5095
+ if (this.acceptedIds.includes(id)) return;
5096
+ this.acceptedIds.push(id);
5097
+ if (this.acceptedIds.length > 32) this.acceptedIds.shift();
5098
+ this.emit("accepted", {});
5099
+ }
5100
+ // As in T3, cancelling a queued run only takes that run out: no turn ends with it. The message
5101
+ // this session opened its turn with never ran, so only its own `sendAndWait` is rejected. A
5102
+ // message of this session still queued behind it keeps the session waiting for the turn the
5103
+ // box opens for it; with none, nothing of this session runs and it goes back to idle.
5104
+ cancelOpening(cancelled) {
5105
+ this.openingMessageId = void 0;
5106
+ if (!this.openingAwaitsStart) return;
5107
+ this.openingAwaitsStart = false;
5108
+ this.activeWaiter?.reject(cancelled);
5109
+ this.activeWaiter = void 0;
5110
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
5111
+ if (this.steers.length === 0 && this.strayedSteers.length === 0) this.setStatus("idle");
5112
+ }
5113
+ // After a replay the box sends the queue and the subagents as they are, each a copy of the line
5114
+ // that said it last, with that line's sequence: state this session may already hold.
5115
+ alreadyApplied(applied, event) {
5116
+ return applied !== void 0 && typeof event.sequence === "number" && event.sequence <= applied;
5117
+ }
5118
+ leaveQueue(id) {
5119
+ const item = this.queueItems.find((current) => current.id === id);
5120
+ if (!item) return void 0;
5121
+ this.queueItems = this.queueItems.filter((current) => current !== item);
5122
+ this.emit("queueChange", { queue: this.queue });
5123
+ return item;
5124
+ }
5125
+ // A queued message that ends before running (taken out of the queue, or dropped by T3) closes
5126
+ // with a terminal of its own while another turn may run: it leaves the queue and ends its own
5127
+ // `sendAndWait`, and the running turn goes on. The opening message of this session's turn is
5128
+ // that turn, and ends it as before.
5129
+ endsQueuedMessage(event, payload, lifecycle) {
5130
+ if (event.type !== "error" && event.type !== "stepFinish" || !lifecycle) return false;
5131
+ const id = payload?.clientMessageId ?? lifecycle.clientMessageId;
5132
+ const turnId = lifecycle.turnId;
5133
+ const item = this.queueItems.find(
5134
+ (current) => current.id === id || turnId !== void 0 && current.turnId === turnId
5135
+ );
5136
+ if (!item) return false;
5137
+ this.leaveQueue(item.id);
5138
+ if (item.id === this.openingMessageId) return false;
5139
+ const message = typeof payload?.message === "string" ? payload.message : "The queued Agent message ended before it ran.";
5140
+ if (event.type === "error") {
5141
+ const code = typeof payload?.code === "string" ? payload.code : void 0;
5142
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5143
+ }
5144
+ const steered = [...this.steers, ...this.strayedSteers].find(
5145
+ (pending) => pending.clientMessageId === item.id
5146
+ );
5147
+ if (steered) {
5148
+ this.forgetSteer(steered);
5149
+ steered.waiter?.reject(new AgentTaskTurnError(message));
5150
+ }
5151
+ return true;
5152
+ }
5153
+ repeatsTheRunningTurn(event, lifecycle) {
5154
+ if (this._status !== "streaming" && this._status !== "cancelled") return false;
5155
+ const turnId = lifecycle?.turnId;
5156
+ if (typeof turnId !== "string") return false;
5157
+ if (typeof event.sequence === "number") {
5158
+ if (this.turnIds.has(turnId) && event.sequence <= this.turnSequenceHigh) return true;
5159
+ this.turnSequenceHigh = Math.max(this.turnSequenceHigh, event.sequence);
5160
+ }
5161
+ this.turnIds.add(turnId);
5162
+ return false;
5163
+ }
5164
+ isFinishedTurnFrame(lifecycle) {
5165
+ const turnId = lifecycle?.turnId;
5166
+ return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
5167
+ }
5168
+ forgetFinishedTurn(lifecycle) {
5169
+ const turnId = lifecycle?.turnId;
5170
+ if (typeof turnId !== "string") return;
5171
+ const index = this.finishedTurnIds.indexOf(turnId);
5172
+ if (index >= 0) this.finishedTurnIds.splice(index, 1);
5173
+ }
4469
5174
  rememberFinishedTurn(lifecycle) {
4470
5175
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4471
5176
  if (!turnId) return;
4472
5177
  this.finishedTurnIds.push(turnId);
4473
5178
  if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
4474
5179
  }
4475
- consumeDelta(payload, kind) {
5180
+ consumeDelta(event, payload, kind) {
4476
5181
  const lifecycle = asObject2(payload?.lifecycle);
4477
5182
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4478
5183
  if (turnId && this.finishedTurnIds.includes(turnId)) return;
@@ -4484,19 +5189,194 @@ var CoreAgentTaskSession = class {
4484
5189
  this.emit("turnStart", {});
4485
5190
  }
4486
5191
  if (kind === "text") this._content += text;
4487
- this.emit("delta", { delta: text, kind });
4488
- }
4489
- emitTool(payload, phase, timestamp) {
4490
- this.emit("tool", {
4491
- tool: typeof payload?.name === "string" ? payload.name : "",
4492
- phase,
4493
- timestamp,
4494
- ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4495
- ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4496
- ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
5192
+ this.liveText(event, payload, kind);
5193
+ this.emit("delta", {
5194
+ delta: text,
5195
+ kind,
5196
+ ...itemDeltaOf(payload),
5197
+ ...pieceIdentityOf(event, payload)
4497
5198
  });
4498
5199
  }
4499
- finishTurn(reason, usage) {
5200
+ emitTool(event, payload, phase) {
5201
+ const tool = toolEventOf(event, payload, phase);
5202
+ this.liveTool(tool, event);
5203
+ this.emit("tool", tool);
5204
+ }
5205
+ // The conversation as it happens: the box's frames grow `history` while a turn runs, one item
5206
+ // per piece of T3, the same pieces the Copilot records and the reload at the turn's end brings
5207
+ // back in the same order. A piece the loaded history already has keeps growing in place, and a
5208
+ // frame it already holds (a replay after a reconnect or an F5) changes nothing.
5209
+ livePiece(match, create, update) {
5210
+ const index = this._history.findIndex(match);
5211
+ const current = this._history[index];
5212
+ if (current === void 0) this._history.push(create());
5213
+ else this._history[index] = update(current);
5214
+ }
5215
+ // The question enters the conversation where the box took it: its turn's `stepStart`, or the
5216
+ // `steer` that took it into the running turn. Until then it is in `queue`.
5217
+ liveQuestion(event, boxText, clientMessageId) {
5218
+ const id = typeof clientMessageId === "string" ? clientMessageId : void 0;
5219
+ const text = (id !== void 0 ? this.sentTexts.get(id) : void 0) ?? boxText;
5220
+ if (typeof text !== "string" || !text) return;
5221
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5222
+ this.livePiece(
5223
+ (item) => item.kind === "user" && (id !== void 0 && item.clientMessageId === id || sequence !== void 0 && item.sequence === sequence && item.text === text),
5224
+ () => ({
5225
+ id: `live:user:${id ?? sequence ?? this._history.length}`,
5226
+ kind: "user",
5227
+ text,
5228
+ at: liveAtOf(event),
5229
+ ...sequence === void 0 ? {} : { sequence },
5230
+ ...id === void 0 ? {} : { clientMessageId: id }
5231
+ }),
5232
+ (item) => item
5233
+ );
5234
+ }
5235
+ liveText(event, payload, kind, parentToolId) {
5236
+ const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
5237
+ if (itemId === void 0) return;
5238
+ const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
5239
+ const itemKind = kind === "thinking" ? "reasoning" : "agent";
5240
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5241
+ this.livePiece(
5242
+ (item) => item.kind === itemKind && item.itemId === itemId,
5243
+ () => ({
5244
+ id: `live:${itemKind}:${itemId}`,
5245
+ kind: itemKind,
5246
+ text: piece,
5247
+ at: liveAtOf(event),
5248
+ itemId,
5249
+ ...sequence === void 0 ? {} : { sequence },
5250
+ ...parentToolIdOf(parentToolId)
5251
+ }),
5252
+ (item) => {
5253
+ const held = item.lastSequence ?? item.sequence;
5254
+ if (!("text" in item) || sequence !== void 0 && held !== void 0 && sequence <= held)
5255
+ return item;
5256
+ return {
5257
+ ...item,
5258
+ text: item.text + piece,
5259
+ ...sequence === void 0 ? {} : { lastSequence: sequence }
5260
+ };
5261
+ }
5262
+ );
5263
+ }
5264
+ liveTool(tool, event) {
5265
+ const toolId = tool.toolId;
5266
+ if (toolId === void 0) return;
5267
+ this.livePiece(
5268
+ (item) => item.kind === "tool" && item.tool.toolId === toolId && item.tool.phase === tool.phase,
5269
+ () => ({
5270
+ id: tool.phase === "result" ? `live:tool:${toolId}:result` : `live:tool:${toolId}`,
5271
+ kind: "tool",
5272
+ tool,
5273
+ at: liveAtOf(event),
5274
+ ...tool.sequence === void 0 ? {} : { sequence: tool.sequence },
5275
+ ...tool.itemId === void 0 ? {} : { itemId: tool.itemId }
5276
+ }),
5277
+ (item) => item.kind === "tool" ? { ...item, tool: { ...item.tool, ...tool, input: tool.input ?? item.tool.input } } : item
5278
+ );
5279
+ }
5280
+ // An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
5281
+ // it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
5282
+ // reaches the app as a `raw` event, as before.
5283
+ liveRequest(event, payload, parentToolId) {
5284
+ if (!payload) return;
5285
+ const kind = event.type === "approval" ? "approval" : "userInputRequest";
5286
+ const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
5287
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5288
+ if (itemId === void 0 && sequence === void 0) return;
5289
+ this.livePiece(
5290
+ (item) => item.kind === kind && (itemId !== void 0 ? item.itemId === itemId : item.sequence === sequence),
5291
+ () => ({
5292
+ id: `live:${kind}:${itemId ?? sequence}`,
5293
+ kind,
5294
+ payload,
5295
+ at: liveAtOf(event),
5296
+ ...sequence === void 0 ? {} : { sequence },
5297
+ ...itemId === void 0 ? {} : { itemId },
5298
+ ...parentToolIdOf(parentToolId)
5299
+ }),
5300
+ (item) => item
5301
+ );
5302
+ }
5303
+ // A child thread's frames are the subagent's conversation: they open no turn and settle no
5304
+ // message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
5305
+ // which knew no subagents, so an app that only bumps the version sees what it saw before.
5306
+ handleSubagentFrame(event, payload) {
5307
+ const parentToolId = payload.parentToolId;
5308
+ switch (event.type) {
5309
+ case "textDelta":
5310
+ case "textChunk":
5311
+ case "thinking": {
5312
+ const delta = typeof payload.text === "string" ? payload.text : "";
5313
+ const kind = event.type === "thinking" ? "thinking" : "text";
5314
+ const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
5315
+ if (kind === "text") this._content += delta;
5316
+ this.liveText(event, payload, kind, parentToolId);
5317
+ this.emit("delta", { delta, kind, parentToolId, ...identity });
5318
+ this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
5319
+ break;
5320
+ }
5321
+ case "toolCall":
5322
+ case "toolResult": {
5323
+ const tool = {
5324
+ ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
5325
+ parentToolId
5326
+ };
5327
+ this.liveTool(tool, event);
5328
+ this.emit("tool", tool);
5329
+ this.emit("subagentTool", tool);
5330
+ break;
5331
+ }
5332
+ case "approval":
5333
+ case "user_input_request":
5334
+ this.liveRequest(event, payload, parentToolId);
5335
+ break;
5336
+ default:
5337
+ break;
5338
+ }
5339
+ }
5340
+ applySubagent(event, payload) {
5341
+ const subagentId = payload?.subagentId;
5342
+ const toolId = payload?.toolId;
5343
+ if (typeof subagentId !== "string" || typeof toolId !== "string") return;
5344
+ if (this.alreadyApplied(this.subagentSequences.get(subagentId), event)) return;
5345
+ if (typeof event.sequence === "number") this.subagentSequences.set(subagentId, event.sequence);
5346
+ const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
5347
+ if (status === void 0) return;
5348
+ const startedAt = epochOf(payload?.startedAt);
5349
+ const endedAt = epochOf(payload?.endedAt);
5350
+ const subagent = {
5351
+ subagentId,
5352
+ toolId,
5353
+ status,
5354
+ ...typeof payload?.progress === "string" ? { progress: payload.progress } : {},
5355
+ ...startedAt !== void 0 ? { startedAt } : {},
5356
+ ...endedAt !== void 0 ? { endedAt } : {},
5357
+ ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
5358
+ };
5359
+ this.subagentsById.set(subagentId, subagent);
5360
+ const index = this._history.findIndex(
5361
+ (item) => item.kind === "tool" && item.tool.toolId === toolId
5362
+ );
5363
+ const spawn = this._history[index];
5364
+ if (spawn?.kind === "tool") {
5365
+ this._history[index] = {
5366
+ ...spawn,
5367
+ subagent: {
5368
+ ...spawn.subagent,
5369
+ toolId,
5370
+ subagentId,
5371
+ status,
5372
+ ...subagent.progress === void 0 ? {} : { progress: subagent.progress },
5373
+ ...subagent.childThreadId === void 0 ? {} : { childThreadId: subagent.childThreadId }
5374
+ }
5375
+ };
5376
+ }
5377
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5378
+ }
5379
+ finishTurn(reason, usage, end = {}) {
4500
5380
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4501
5381
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
4502
5382
  this.cancelTimer = null;
@@ -4514,13 +5394,14 @@ var CoreAgentTaskSession = class {
4514
5394
  task,
4515
5395
  content: this._content,
4516
5396
  reason,
4517
- ...usage ? { usage } : {}
5397
+ ...usage ? { usage } : {},
5398
+ ...end
4518
5399
  };
4519
5400
  this.emit("turnEnd", result);
4520
5401
  this.activeWaiter?.resolve(result);
4521
5402
  this.activeWaiter = void 0;
5403
+ this.settleSteers((waiter) => waiter.resolve(result));
4522
5404
  this.setStatus("idle");
4523
- this.flushQueue();
4524
5405
  }
4525
5406
  failTurn(error) {
4526
5407
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
@@ -4528,56 +5409,17 @@ var CoreAgentTaskSession = class {
4528
5409
  this.recoveryGeneration += 1;
4529
5410
  this.activeWaiter?.reject(error);
4530
5411
  this.activeWaiter = void 0;
5412
+ this.settleSteers((waiter) => waiter.reject(error));
4531
5413
  this.setStatus("idle");
4532
- this.flushQueue();
4533
5414
  }
4534
5415
  failLiveChannel(observed, waiterError) {
4535
5416
  this.recoveryGeneration += 1;
4536
5417
  this.emitError("Agent live channel failed", observed);
4537
5418
  this.activeWaiter?.reject(waiterError);
4538
5419
  this.activeWaiter = void 0;
4539
- for (const item of this._queue) item.waiter?.reject(waiterError);
4540
- this._queue = [];
4541
- this.emitQueue();
5420
+ this.rejectSteers(waiterError);
4542
5421
  this.setStatus("error");
4543
5422
  }
4544
- enqueue(text, options, waiter) {
4545
- if (this._queue.length >= AGENT_QUEUE_LIMIT) {
4546
- const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
4547
- waiter?.reject(error);
4548
- this.emit("error", { error: error.message });
4549
- return void 0;
4550
- }
4551
- const id = `q-${++this.queueSequence}`;
4552
- this._queue = [
4553
- ...this._queue,
4554
- { id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
4555
- ];
4556
- this.emitQueue();
4557
- return id;
4558
- }
4559
- flushQueue() {
4560
- if (this.isBusy()) return;
4561
- let next = this._queue[0];
4562
- while (next?.waiter?.settled) {
4563
- this._queue = this._queue.slice(1);
4564
- next = this._queue[0];
4565
- }
4566
- if (!next) {
4567
- this.emitQueue();
4568
- return;
4569
- }
4570
- this._queue = this._queue.slice(1);
4571
- this.emitQueue();
4572
- this.startDispatch(
4573
- next.text,
4574
- {
4575
- ...next.agentType ? { agentType: next.agentType } : {},
4576
- ...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
4577
- },
4578
- next.waiter
4579
- );
4580
- }
4581
5423
  createWaiter(options) {
4582
5424
  let resolvePromise;
4583
5425
  let rejectPromise;
@@ -4599,7 +5441,6 @@ var CoreAgentTaskSession = class {
4599
5441
  if (waiter.settled) return;
4600
5442
  waiter.settled = true;
4601
5443
  waiter.cleanup();
4602
- if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
4603
5444
  rejectPromise(error);
4604
5445
  },
4605
5446
  cleanup: () => {
@@ -4624,14 +5465,6 @@ var CoreAgentTaskSession = class {
4624
5465
  }
4625
5466
  return waiter;
4626
5467
  }
4627
- removeQueuedWaiter(id) {
4628
- const size = this._queue.length;
4629
- this._queue = this._queue.filter((item) => item.id !== id);
4630
- if (this._queue.length !== size) this.emitQueue();
4631
- }
4632
- emitQueue() {
4633
- this.emit("queueChange", { queue: this.queue });
4634
- }
4635
5468
  emitError(prefix, error) {
4636
5469
  const code = errorCode(error);
4637
5470
  this.emit("error", {
@@ -4641,6 +5474,12 @@ var CoreAgentTaskSession = class {
4641
5474
  }
4642
5475
  setStatus(status) {
4643
5476
  if (this._status === status) return;
5477
+ if (status !== "streaming" && status !== "cancelled") {
5478
+ this.openingAwaitsStart = false;
5479
+ this.endedPollsWithoutRow = 0;
5480
+ this.turnIds.clear();
5481
+ this.turnSequenceHigh = -1;
5482
+ }
4644
5483
  this._status = status;
4645
5484
  this.emit("statusChange", { status });
4646
5485
  }
@@ -4650,8 +5489,11 @@ var CoreAgentTaskSession = class {
4650
5489
  isClosed() {
4651
5490
  return this._status === "closed";
4652
5491
  }
5492
+ // A turn running or being opened takes a new message as a steer. So does a session waiting for
5493
+ // the turn the box opens for a steer it took late: a new message started as a turn of its own
5494
+ // then would be answered by the steer's result, and the steer by its.
4653
5495
  isBusy() {
4654
- return this.dispatching || this._status === "streaming" || this._status === "cancelled";
5496
+ return this.dispatching || this._status === "streaming" || this._status === "cancelled" || this.strayedSteers.length > 0;
4655
5497
  }
4656
5498
  emit(event, payload) {
4657
5499
  const listeners = this.listeners.get(event);