@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.cjs CHANGED
@@ -1014,7 +1014,8 @@ function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFact
1014
1014
  if (typeof channel.wsUrl !== "string" || !channel.wsUrl) invalidField(context, "wsUrl", errors);
1015
1015
  return {
1016
1016
  wsUrl: channel.wsUrl,
1017
- lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0
1017
+ lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0,
1018
+ ...isInteger(channel.boxLog) ? { boxLog: channel.boxLog } : {}
1018
1019
  };
1019
1020
  }
1020
1021
  function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
@@ -1686,7 +1687,12 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1686
1687
  const page = expectPage(
1687
1688
  await transport.request(`${path(id)}/messages`, {
1688
1689
  method: "GET",
1689
- params: { page: options.page, size: options.size, sort: options.sort }
1690
+ params: {
1691
+ page: options.page,
1692
+ size: options.size,
1693
+ sort: options.sort,
1694
+ kinds: options.kinds
1695
+ }
1690
1696
  }),
1691
1697
  context,
1692
1698
  errors
@@ -3311,6 +3317,29 @@ var ADMISSION_TIMEOUT_MS = 35e3;
3311
3317
  var SUPERSEDED_CLOSE_CODE = 4409;
3312
3318
  var SOCKET_OPEN = 1;
3313
3319
  var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
3320
+ var clientMessageSequence = 0;
3321
+ function newClientMessageId() {
3322
+ const random = globalThis.crypto?.randomUUID;
3323
+ return random ? random.call(globalThis.crypto) : `m-${Date.now()}-${++clientMessageSequence}`;
3324
+ }
3325
+ function admissionFor(link, event) {
3326
+ const payload = asObject(event.payload);
3327
+ if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0 || payload?.command !== void 0)) {
3328
+ return void 0;
3329
+ }
3330
+ const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
3331
+ if (typeof id === "string")
3332
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3333
+ return link.admissions[0];
3334
+ }
3335
+ function queuedAdmission(link, event) {
3336
+ const id = asObject(asObject(event.payload)?.lifecycle)?.clientMessageId;
3337
+ if (typeof id !== "string") return void 0;
3338
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3339
+ }
3340
+ function isSubagentFrame(event) {
3341
+ return typeof asObject(event.payload)?.parentToolId === "string";
3342
+ }
3314
3343
  function asObject(value) {
3315
3344
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3316
3345
  }
@@ -3341,6 +3370,14 @@ function boxAddress(wsUrl) {
3341
3370
  const url = new URL(wsUrl);
3342
3371
  return `${url.origin}${url.pathname}`;
3343
3372
  }
3373
+ function helloOf(event) {
3374
+ if (event.type !== "hello") return void 0;
3375
+ const payload = asObject(event.payload);
3376
+ const threadId = payload?.threadId;
3377
+ const lastSequence = payload?.lastSequence;
3378
+ if (typeof threadId !== "string" || typeof lastSequence !== "number") return void 0;
3379
+ return { threadId, lastSequence };
3380
+ }
3344
3381
  function boxRoute(wsUrl, route) {
3345
3382
  const url = new URL(wsUrl);
3346
3383
  url.protocol = url.protocol === "wss:" ? "https:" : "http:";
@@ -3431,15 +3468,15 @@ function asDelta(event) {
3431
3468
  }
3432
3469
  var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3433
3470
  "stepStart",
3471
+ "steer",
3434
3472
  "textDelta",
3435
3473
  "thinking",
3436
- "toolCall",
3437
- "toolResult"
3474
+ "toolCall"
3438
3475
  ]);
3439
3476
  var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3440
3477
  function turnAfter(event, inTurn) {
3441
3478
  if (TURN_FRAME_TYPES.has(event.type)) return true;
3442
- if (event.type === "error") return false;
3479
+ if (event.type === "error") return asObject(event.payload)?.lifecycle ? false : inTurn;
3443
3480
  if (event.type === "stepFinish") {
3444
3481
  const payload = asObject(event.payload);
3445
3482
  if (TURN_END_REASONS.has(payload?.reason)) return false;
@@ -3447,6 +3484,27 @@ function turnAfter(event, inTurn) {
3447
3484
  }
3448
3485
  return inTurn;
3449
3486
  }
3487
+ function followsTurn(link, event) {
3488
+ if (event.type === "messageQueued") return false;
3489
+ if (event.type !== "stepFinish" && event.type !== "error") return true;
3490
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3491
+ return typeof turnId !== "string" || link.turnId === void 0 || turnId === link.turnId;
3492
+ }
3493
+ function lostTurnFrame(turnId) {
3494
+ return {
3495
+ type: "stepFinish",
3496
+ payload: {
3497
+ reason: "interrupted",
3498
+ lifecycle: {
3499
+ ...turnId === void 0 ? {} : { turnId },
3500
+ terminal: true,
3501
+ sessionIdle: true,
3502
+ interruptTerminal: true
3503
+ }
3504
+ },
3505
+ timestamp: Date.now()
3506
+ };
3507
+ }
3450
3508
  function channelEvent(type, payload) {
3451
3509
  return { type, payload, timestamp: Date.now() };
3452
3510
  }
@@ -3503,7 +3561,7 @@ var AgentDirectChannel = class {
3503
3561
  enabled() {
3504
3562
  return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
3505
3563
  }
3506
- async open(taskId, observer, signal, transport) {
3564
+ async open(taskId, observer, signal, transport, historyCursor) {
3507
3565
  if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
3508
3566
  const mode = this.modeFor(transport);
3509
3567
  const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
@@ -3513,7 +3571,7 @@ var AgentDirectChannel = class {
3513
3571
  return this.fallback.open(taskId, observer, signal, transport);
3514
3572
  }
3515
3573
  try {
3516
- return await this.openDirect(taskId, mode, answer, observer, signal);
3574
+ return await this.openDirect(taskId, mode, answer, observer, signal, historyCursor);
3517
3575
  } catch (error) {
3518
3576
  if (signal?.aborted) throw error;
3519
3577
  observer.onEvent(
@@ -3526,9 +3584,11 @@ var AgentDirectChannel = class {
3526
3584
  }
3527
3585
  }
3528
3586
  /**
3529
- * Hands a message or an interrupt to the box when the chat is on the direct channel and its
3530
- * wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3531
- * mid-redial, or an approval, which stays on REST.
3587
+ * Hands a message, an interrupt, a subagent stop or an answer to a T3 input request to the box
3588
+ * 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
3589
+ * mid-redial, or an approval, which stays on REST. Mid-redial the Copilot is the durable path:
3590
+ * the box URL kept from the last channel carries a proxy ticket that lasts 60 seconds, and a
3591
+ * box that dropped the socket is often the one that went away.
3532
3592
  *
3533
3593
  * A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
3534
3594
  * the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
@@ -3541,12 +3601,12 @@ var AgentDirectChannel = class {
3541
3601
  * have admitted the turn, and a second copy would start it twice. The redial replays the box
3542
3602
  * log, where the `stepStart` of an admitted turn is.
3543
3603
  */
3544
- send(taskId, input) {
3604
+ send(taskId, input, clientMessageId) {
3545
3605
  if (input.type === "approval_response") return null;
3546
3606
  const link = this.links.get(taskId);
3547
3607
  if (!link?.wire) return null;
3548
3608
  if (input.type !== "message") return link.wire.interrupt(input);
3549
- link.admission?.fail(new Error("A newer message replaced the one waiting for the box."));
3609
+ const messageId = clientMessageId ?? newClientMessageId();
3550
3610
  let admission;
3551
3611
  const admitted = new Promise((resolve, reject) => {
3552
3612
  let timer;
@@ -3562,11 +3622,13 @@ var AgentDirectChannel = class {
3562
3622
  };
3563
3623
  const done = () => {
3564
3624
  clearTimeout(timer);
3565
- if (link.admission === admission) link.admission = null;
3625
+ link.admissions = link.admissions.filter((pending) => pending !== admission);
3566
3626
  };
3567
3627
  admission = {
3628
+ clientMessageId: messageId,
3568
3629
  settle: (value) => {
3569
3630
  done();
3631
+ if (value) link.inTurn = true;
3570
3632
  resolve(value);
3571
3633
  },
3572
3634
  fail: (error) => {
@@ -3578,12 +3640,11 @@ var AgentDirectChannel = class {
3578
3640
  };
3579
3641
  arm();
3580
3642
  });
3581
- link.admission = admission;
3582
- if (!link.wire.message(input, admission)) {
3643
+ link.admissions = [...link.admissions, admission];
3644
+ if (!link.wire.message({ ...input, clientMessageId: messageId }, admission)) {
3583
3645
  admission.settle(false);
3584
3646
  return null;
3585
3647
  }
3586
- link.inTurn = true;
3587
3648
  return admitted;
3588
3649
  }
3589
3650
  /** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
@@ -3635,56 +3696,91 @@ var AgentDirectChannel = class {
3635
3696
  * only when the redial gives up, when the Copilot no longer offers the box, or when there is
3636
3697
  * no turn to resume: dialing an idle box again would wake it for nobody.
3637
3698
  *
3638
- * Opening never asks for an older replay. What an idle chat missed is history, which the
3639
- * session loads by REST; replaying from an older cursor would put old turns on screen as live
3640
- * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3699
+ * Opening asks for the replay from where the session's history ends, with the same request the
3700
+ * redial makes: what the history has, the replay does not repeat, and what the Copilot has not
3701
+ * recorded yet (the turn running now, or one it is still behind on) comes in the replay before
3702
+ * any live frame. When the Copilot says the box log is another one than the history's newest,
3703
+ * nothing of it is in the history and the replay starts at its beginning. A history with no
3704
+ * box sequence asks for nothing, and the open starts at the sequence the Copilot reported.
3641
3705
  */
3642
- async openDirect(taskId, mode, channel, observer, signal) {
3643
- const link = { wire: null, inTurn: false, admission: null };
3706
+ async openDirect(taskId, mode, channel, observer, signal, historyCursor) {
3707
+ const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
3644
3708
  let box = boxAddress(channel.wsUrl);
3645
- let cursor = channel.lastSequence;
3709
+ let thread;
3710
+ const otherLog = historyCursor?.boxLog !== void 0 && channel.boxLog !== void 0 && historyCursor.boxLog !== channel.boxLog;
3711
+ const historyFrom = historyCursor === void 0 ? void 0 : otherLog ? 0 : historyCursor.sequence;
3712
+ let cursor = historyFrom ?? channel.lastSequence;
3646
3713
  const abort = new AbortController();
3647
3714
  const onAbort = () => abort.abort(signal?.reason);
3648
3715
  signal?.addEventListener("abort", onAbort, { once: true });
3649
3716
  const onFrame = (event) => {
3717
+ const hello = helloOf(event);
3718
+ if (hello) thread = hello.threadId;
3650
3719
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3651
- link.inTurn = turnAfter(event, link.inTurn);
3720
+ if (isSubagentFrame(event)) {
3721
+ observer.onEvent(event);
3722
+ return;
3723
+ }
3724
+ if (followsTurn(link, event)) {
3725
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3726
+ if (typeof turnId === "string" && event.type !== "toolResult") link.turnId = turnId;
3727
+ link.inTurn = turnAfter(event, link.inTurn);
3728
+ }
3652
3729
  observer.onEvent(event);
3653
- if (event.type === "stepStart") link.admission?.settle(true);
3654
- else if (event.type === "error") link.admission?.settle(false);
3730
+ if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
3731
+ else if (event.type === "error") admissionFor(link, event)?.settle(false);
3732
+ else if (event.type === "messageQueued" || event.type === "steer") {
3733
+ queuedAdmission(link, event)?.settle(true);
3734
+ }
3655
3735
  };
3656
3736
  const onLost = (error, code) => {
3657
3737
  link.wire = null;
3658
3738
  if (abort.signal.aborted) return;
3659
- if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
3660
- link.admission?.fail(error);
3739
+ if (!link.inTurn && link.admissions.length === 0 || code === SUPERSEDED_CLOSE_CODE) {
3740
+ for (const pending of link.admissions) pending.fail(error);
3661
3741
  observer.onDisconnect(error);
3662
3742
  return;
3663
3743
  }
3664
- link.admission?.hold();
3744
+ for (const pending of link.admissions) pending.hold();
3665
3745
  void this.redial(taskId, mode, error, abort.signal, observer, {
3666
3746
  onFrame,
3667
3747
  onLost,
3668
3748
  replayFrom: (next) => {
3669
- const nextBox = boxAddress(next.wsUrl);
3670
- if (nextBox === box) return cursor;
3671
- box = nextBox;
3672
- cursor = next.lastSequence;
3673
- return void 0;
3749
+ const decide = (hello) => {
3750
+ const nextBox = boxAddress(next.wsUrl);
3751
+ const zeroed = next.lastSequence === 0 && cursor > 0;
3752
+ const otherBox = hello !== void 0 && (hello.threadId !== thread || hello.lastSequence < cursor);
3753
+ if (nextBox === box && !zeroed && !otherBox) return cursor;
3754
+ if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3755
+ box = nextBox;
3756
+ if (mode === "websocket") {
3757
+ cursor = 0;
3758
+ return 0;
3759
+ }
3760
+ cursor = next.lastSequence;
3761
+ return void 0;
3762
+ };
3763
+ return mode === "websocket" && thread !== void 0 ? decide : decide(void 0);
3674
3764
  }
3675
3765
  }).then((outcome) => {
3676
- if (outcome instanceof Error) link.admission?.fail(outcome);
3766
+ if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
3677
3767
  else if (outcome) {
3678
3768
  link.wire = outcome;
3679
- link.admission?.rearm();
3769
+ for (const pending of link.admissions) pending.rearm();
3680
3770
  }
3681
3771
  });
3682
3772
  };
3773
+ const afterHello = (hello) => {
3774
+ if (hello !== void 0 && hello.lastSequence < cursor) cursor = 0;
3775
+ return cursor;
3776
+ };
3777
+ const replay = historyFrom === void 0 ? {} : mode === "websocket" ? { replayAfterHello: afterHello } : { replayFrom: historyFrom };
3683
3778
  try {
3684
3779
  link.wire = await this.connect(taskId, mode, channel, {
3685
3780
  signal: abort.signal,
3686
3781
  onFrame,
3687
- onLost
3782
+ onLost,
3783
+ ...replay
3688
3784
  });
3689
3785
  } catch (error) {
3690
3786
  signal?.removeEventListener("abort", onAbort);
@@ -3697,9 +3793,8 @@ var AgentDirectChannel = class {
3697
3793
  abort.abort();
3698
3794
  link.wire?.close();
3699
3795
  link.wire = null;
3700
- link.admission?.fail(
3701
- new Error("The Agent session closed before the box confirmed the turn.")
3702
- );
3796
+ const closed = new Error("The Agent session closed before the box confirmed the turn.");
3797
+ for (const pending of link.admissions) pending.fail(closed);
3703
3798
  if (this.links.get(taskId) === link) this.links.delete(taskId);
3704
3799
  }
3705
3800
  };
@@ -3768,7 +3863,8 @@ var AgentDirectChannel = class {
3768
3863
  onFrame: handlers.onFrame,
3769
3864
  onLost: handlers.onLost,
3770
3865
  signal,
3771
- ...replayFrom === void 0 ? {} : { replayFrom }
3866
+ ...typeof replayFrom === "function" ? { replayAfterHello: replayFrom } : {},
3867
+ ...typeof replayFrom === "number" ? { replayFrom } : {}
3772
3868
  });
3773
3869
  return { kind: "wire", wire };
3774
3870
  } catch (error) {
@@ -3836,7 +3932,7 @@ var AgentDirectChannel = class {
3836
3932
  close,
3837
3933
  interrupt: (input) => post(input).then((response) => {
3838
3934
  if (!response.ok) {
3839
- throw new Error(`The Agent box refused the interrupt (${response.status}).`);
3935
+ throw new Error(`The Agent box refused the ${input.type} (${response.status}).`);
3840
3936
  }
3841
3937
  return true;
3842
3938
  }),
@@ -3917,6 +4013,7 @@ var AgentDirectChannel = class {
3917
4013
  const Socket = this.webSocket();
3918
4014
  if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
3919
4015
  const { signal, replayFrom } = options;
4016
+ let replayAfterHello = options.replayAfterHello;
3920
4017
  return new Promise((resolve, reject) => {
3921
4018
  const socket = new Socket(url);
3922
4019
  let opened = false;
@@ -3999,7 +4096,13 @@ var AgentDirectChannel = class {
3999
4096
  handlers.onmessage = (message) => {
4000
4097
  touch();
4001
4098
  const event = parseEvent(message.data);
4002
- if (event) options.onFrame(asDelta(event));
4099
+ if (!event) return;
4100
+ if (replayAfterHello) {
4101
+ const fromSequence = replayAfterHello(helloOf(event));
4102
+ replayAfterHello = void 0;
4103
+ if (fromSequence !== void 0) send(JSON.stringify({ type: "replay", fromSequence }));
4104
+ }
4105
+ options.onFrame(asDelta(event));
4003
4106
  };
4004
4107
  handlers.onclose = (event) => {
4005
4108
  clearTimeout(timer);
@@ -4018,9 +4121,22 @@ var AgentDirectChannel = class {
4018
4121
  };
4019
4122
 
4020
4123
  // src/agentSession.ts
4021
- var AGENT_QUEUE_LIMIT = 10;
4022
4124
  var CANCEL_SAFETY_MS = 1e4;
4023
4125
  var RECONCILE_DELAY_MS = 1e3;
4126
+ var ENDED_POLLS_BEFORE_NEWEST = 3;
4127
+ var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
4128
+ "textDelta",
4129
+ "textChunk",
4130
+ "thinking",
4131
+ "toolCall",
4132
+ "toolResult",
4133
+ "stepFinish"
4134
+ ]);
4135
+ var COPILOT_INPUT_TYPES = /* @__PURE__ */ new Set([
4136
+ "message",
4137
+ "interrupt",
4138
+ "approval_response"
4139
+ ]);
4024
4140
  function providerUsageOf(payload) {
4025
4141
  if (!payload) return null;
4026
4142
  try {
@@ -4049,7 +4165,120 @@ function errorCode(error) {
4049
4165
  function delay(milliseconds) {
4050
4166
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
4051
4167
  }
4168
+ function messageInput(prompt, options) {
4169
+ return {
4170
+ type: "message",
4171
+ content: prompt,
4172
+ ...options.agentType ? { agentType: options.agentType } : {},
4173
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4174
+ ...options.mode ? { mode: options.mode } : {}
4175
+ };
4176
+ }
4177
+ function backgroundTasksOf(value) {
4178
+ if (!Array.isArray(value)) return [];
4179
+ return value.flatMap((entry) => {
4180
+ const task = asObject2(entry);
4181
+ if (typeof task?.taskId !== "string" || typeof task.kind !== "string") return [];
4182
+ return [
4183
+ {
4184
+ taskId: task.taskId,
4185
+ kind: task.kind,
4186
+ ...typeof task.description === "string" ? { description: task.description } : {},
4187
+ ...typeof task.childThreadId === "string" ? { childThreadId: task.childThreadId } : {}
4188
+ }
4189
+ ];
4190
+ });
4191
+ }
4192
+ function pieceIdentityOf(event, payload) {
4193
+ const turnId = asObject2(payload?.lifecycle)?.turnId;
4194
+ return {
4195
+ ...sequenceOf(event),
4196
+ ...typeof payload?.itemId === "string" ? { itemId: payload.itemId } : {},
4197
+ ...typeof turnId === "string" ? { turnId } : {}
4198
+ };
4199
+ }
4200
+ function itemDeltaOf(payload) {
4201
+ return typeof payload?.itemDelta === "string" ? { itemDelta: payload.itemDelta } : {};
4202
+ }
4203
+ function sequenceOf(event) {
4204
+ return typeof event.sequence === "number" ? { sequence: event.sequence } : {};
4205
+ }
4206
+ function toolEventOf(event, payload, phase) {
4207
+ return {
4208
+ tool: typeof payload?.name === "string" ? payload.name : "",
4209
+ phase,
4210
+ timestamp: event.timestamp,
4211
+ ...pieceIdentityOf(event, payload),
4212
+ ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4213
+ ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4214
+ ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4215
+ };
4216
+ }
4217
+ function epochOf(value) {
4218
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4219
+ if (typeof value !== "string") return void 0;
4220
+ const parsed = Date.parse(value);
4221
+ return Number.isNaN(parsed) ? void 0 : parsed;
4222
+ }
4223
+ function timelineIdentityOf(message) {
4224
+ return {
4225
+ ...typeof message.sequence === "number" ? { sequence: message.sequence } : {},
4226
+ ...typeof message.lastSequence === "number" ? { lastSequence: message.lastSequence } : {},
4227
+ ...typeof message.boxLog === "number" ? { boxLog: message.boxLog } : {},
4228
+ ...typeof message.itemId === "string" ? { itemId: message.itemId } : {},
4229
+ ...typeof message.reason === "string" ? { reason: message.reason } : {}
4230
+ };
4231
+ }
4232
+ function historyCursorOf(history) {
4233
+ const newest = [...history].reverse().find((item) => typeof item.sequence === "number");
4234
+ if (!newest) return void 0;
4235
+ let sequence = 0;
4236
+ for (const item of history) {
4237
+ if (item.boxLog === newest.boxLog && typeof item.sequence === "number") {
4238
+ sequence = Math.max(sequence, item.lastSequence ?? item.sequence);
4239
+ }
4240
+ }
4241
+ return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4242
+ }
4243
+ function isChatRow(message) {
4244
+ return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4245
+ }
4246
+ var REQUEST_ROW_KINDS = {
4247
+ APPROVAL: "approval",
4248
+ USER_INPUT_REQUEST: "userInputRequest"
4249
+ };
4250
+ function parseJson(text) {
4251
+ try {
4252
+ return JSON.parse(text);
4253
+ } catch {
4254
+ return void 0;
4255
+ }
4256
+ }
4052
4257
  function toAgentTimelineItem(message) {
4258
+ if (message.type === "REASONING") {
4259
+ return {
4260
+ id: message.id,
4261
+ kind: "reasoning",
4262
+ text: message.content,
4263
+ at: message.createdAt,
4264
+ ...timelineIdentityOf(message),
4265
+ ...parentToolIdOf(message.parentToolId)
4266
+ };
4267
+ }
4268
+ const requestKind = REQUEST_ROW_KINDS[message.type];
4269
+ if (requestKind) {
4270
+ const payload = asObject2(parseJson(message.content));
4271
+ if (payload) {
4272
+ return {
4273
+ id: message.id,
4274
+ kind: requestKind,
4275
+ payload,
4276
+ at: message.createdAt,
4277
+ ...timelineIdentityOf(message),
4278
+ ...parentToolIdOf(message.parentToolId)
4279
+ };
4280
+ }
4281
+ }
4053
4282
  if (message.type === "TOOL_USE") {
4054
4283
  try {
4055
4284
  const payload = JSON.parse(message.content);
@@ -4060,11 +4289,14 @@ function toAgentTimelineItem(message) {
4060
4289
  tool: {
4061
4290
  tool: typeof payload.name === "string" ? payload.name : "",
4062
4291
  ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
4292
+ ...parentToolIdOf(payload.parentToolId ?? message.parentToolId),
4063
4293
  ...payload.input !== void 0 ? { input: payload.input } : {},
4064
4294
  ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
4065
4295
  phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
4066
4296
  },
4067
- at: message.createdAt
4297
+ at: message.createdAt,
4298
+ ...timelineIdentityOf(message),
4299
+ ...asObject2(message.subagent) ? { subagent: message.subagent } : {}
4068
4300
  };
4069
4301
  }
4070
4302
  } catch {
@@ -4075,9 +4307,18 @@ function toAgentTimelineItem(message) {
4075
4307
  kind: message.sender === "USER" ? "user" : "agent",
4076
4308
  text: message.content,
4077
4309
  at: message.createdAt,
4078
- ...message.usage ? { usage: message.usage } : {}
4310
+ ...message.usage ? { usage: message.usage } : {},
4311
+ ...timelineIdentityOf(message),
4312
+ ...typeof message.clientMessageId === "string" ? { clientMessageId: message.clientMessageId } : {},
4313
+ ...parentToolIdOf(message.parentToolId)
4079
4314
  };
4080
4315
  }
4316
+ function liveAtOf(event) {
4317
+ return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
4318
+ }
4319
+ function parentToolIdOf(value) {
4320
+ return typeof value === "string" ? { parentToolId: value } : {};
4321
+ }
4081
4322
  function createAgentTaskSessionManager(options) {
4082
4323
  const sessions = /* @__PURE__ */ new Map();
4083
4324
  const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
@@ -4122,7 +4363,6 @@ var CoreAgentTaskSession = class {
4122
4363
  _status = "opening";
4123
4364
  _history = [];
4124
4365
  _content = "";
4125
- _queue = [];
4126
4366
  isNewSession;
4127
4367
  listeners = /* @__PURE__ */ new Map();
4128
4368
  connection = null;
@@ -4141,10 +4381,47 @@ var CoreAgentTaskSession = class {
4141
4381
  recoveryGeneration = 0;
4142
4382
  recoveredTerminalReason;
4143
4383
  recoveredTerminalUsage;
4384
+ // Polls that found no closing row although a terminal with usage was heard.
4385
+ endedPollsWithoutRow = 0;
4386
+ // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
4387
+ // stream a dropped session falls back to replays the turn from what the history has, so it
4388
+ // repeats frames the box socket already delivered.
4389
+ turnIds = /* @__PURE__ */ new Set();
4390
+ turnSequenceHigh = -1;
4144
4391
  cancelTimer = null;
4145
- queueSequence = 0;
4392
+ // Messages leave in the order they were sent: each one is handed over only after the one
4393
+ // before it was, not after it was answered.
4394
+ handOff = Promise.resolve();
4146
4395
  activeWaiter;
4396
+ // Every steer sits in exactly one of the two lists until it is settled or forgotten: `steers`
4397
+ // while the turn it was sent into runs (taken ones settle with that turn), `strayedSteers` once
4398
+ // it waits for a turn of its own (sent with no turn, not taken when its turn ended, or queued by
4399
+ // the provider). A non-empty `strayedSteers` keeps the session busy, which is what stops a new
4400
+ // message from opening a turn the steer's answer would settle. `pendingSteers` counts the ones
4401
+ // the box has not answered yet, wherever they sit.
4402
+ steers = [];
4403
+ strayedSteers = [];
4404
+ pendingSteers = 0;
4405
+ // The id the message that opened the current turn went out with, so a refusal naming it fails
4406
+ // that turn and one naming a steer does not.
4407
+ openingMessageId;
4408
+ // The opening message went to the box, which starts its turn with a `stepStart`. Until then a
4409
+ // turn frame naming a turn is another turn's tail: the one before, closed here from the history
4410
+ // (r5 S17, dev 2026-10-19), whose live end came after the next message went out.
4411
+ openingAwaitsStart = false;
4147
4412
  turnBaselineIds = /* @__PURE__ */ new Set();
4413
+ subagentsById = /* @__PURE__ */ new Map();
4414
+ subagentSequences = /* @__PURE__ */ new Map();
4415
+ queueItems = [];
4416
+ _backgroundTasks = [];
4417
+ /** The text of each message this session sent, by its `clientMessageId`. */
4418
+ sentTexts = /* @__PURE__ */ new Map();
4419
+ // Messages of this session `accepted` was already emitted for. The frame that names a message
4420
+ // emits it in its place in the stream, so a turn delivered in one tick gives the same events as
4421
+ // one spaced out; the admission the send awaits only covers a box or a Copilot that names none.
4422
+ acceptedIds = [];
4423
+ // Taken by the first channel of `session({ taskId })`; no later channel asks for a replay.
4424
+ openingCursor;
4148
4425
  get taskId() {
4149
4426
  return this._taskId;
4150
4427
  }
@@ -4164,22 +4441,18 @@ var CoreAgentTaskSession = class {
4164
4441
  return this._content;
4165
4442
  }
4166
4443
  get queue() {
4167
- return this._queue.map((item) => ({
4168
- id: item.id,
4169
- text: item.text,
4170
- createdAt: item.createdAt,
4171
- ...item.agentType ? { agentType: item.agentType } : {},
4172
- ...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
4173
- }));
4444
+ return [...this.queueItems];
4445
+ }
4446
+ get subagents() {
4447
+ return [...this.subagentsById.values()];
4174
4448
  }
4175
4449
  send(prompt, options = {}) {
4176
4450
  this.requireOpen();
4177
- if (!prompt.trim()) return;
4178
- if (this.isBusy()) {
4179
- this.enqueue(prompt, options);
4180
- return;
4181
- }
4182
- this.startDispatch(prompt, options);
4451
+ if (!prompt.trim()) return void 0;
4452
+ if (this.isBusy()) return this.steer(prompt, options);
4453
+ const clientMessageId = newClientMessageId();
4454
+ this.startDispatch(prompt, options, clientMessageId);
4455
+ return clientMessageId;
4183
4456
  }
4184
4457
  sendAndWait(prompt, options = {}) {
4185
4458
  this.requireOpen();
@@ -4188,14 +4461,14 @@ var CoreAgentTaskSession = class {
4188
4461
  if (waiter.settled) return waiter.promise;
4189
4462
  const sendOptions = {
4190
4463
  ...options.agentType ? { agentType: options.agentType } : {},
4191
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4464
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4465
+ ...options.mode ? { mode: options.mode } : {}
4192
4466
  };
4193
4467
  if (this.isBusy()) {
4194
- const queueId = this.enqueue(prompt, sendOptions, waiter);
4195
- if (queueId) waiter.queueId = queueId;
4468
+ this.steer(prompt, sendOptions, waiter);
4196
4469
  return waiter.promise;
4197
4470
  }
4198
- this.startDispatch(prompt, sendOptions, waiter);
4471
+ this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
4199
4472
  return waiter.promise;
4200
4473
  }
4201
4474
  async cancel() {
@@ -4227,11 +4500,23 @@ var CoreAgentTaskSession = class {
4227
4500
  this.emitError("Failed to answer Agent approval", error);
4228
4501
  });
4229
4502
  }
4503
+ respondUserInput(requestId, answers, attachmentsByQuestionId) {
4504
+ const input = {
4505
+ type: "runtime-request.respond",
4506
+ requestId,
4507
+ answers,
4508
+ ...attachmentsByQuestionId ? { attachmentsByQuestionId } : {}
4509
+ };
4510
+ void this.sendInput(input).catch((error) => {
4511
+ this.emitError("Failed to answer Agent input request", error);
4512
+ });
4513
+ }
4230
4514
  async loadHistory(options = {}) {
4231
4515
  if (!this._taskId) return [];
4232
4516
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4233
4517
  ...options.limit !== void 0 ? { size: options.limit } : {},
4234
- sort: "createdAt,desc"
4518
+ sort: "createdAt,desc",
4519
+ kinds: "all"
4235
4520
  });
4236
4521
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4237
4522
  const history = this.history;
@@ -4239,25 +4524,47 @@ var CoreAgentTaskSession = class {
4239
4524
  return history;
4240
4525
  }
4241
4526
  editQueueItem(id, text) {
4242
- if (!text.trim()) {
4243
- this.removeQueueItem(id);
4244
- return;
4245
- }
4246
- this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
4247
- this.emitQueue();
4527
+ this.requireOpen();
4528
+ if (this.sentTexts.has(id)) this.sentTexts.set(id, text);
4529
+ void this.sendInput({ type: "queued-run.edit", clientMessageId: id, text }).catch(
4530
+ (error) => {
4531
+ this.emitError("Failed to edit the queued Agent message", error);
4532
+ }
4533
+ );
4248
4534
  }
4249
4535
  removeQueueItem(id) {
4250
- const removed = this._queue.find((item) => item.id === id);
4251
- this._queue = this._queue.filter((item) => item.id !== id);
4252
- removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
4253
- this.emitQueue();
4536
+ this.requireOpen();
4537
+ void this.sendInput({ type: "queued-run.cancel", clientMessageId: id }).catch(
4538
+ (error) => {
4539
+ this.emitError("Failed to remove the queued Agent message", error);
4540
+ }
4541
+ );
4254
4542
  }
4255
4543
  clearQueue() {
4256
- if (!this._queue.length) return;
4257
- const removed = this._queue;
4258
- this._queue = [];
4259
- for (const item of removed) item.waiter?.reject(new Error("Agent prompt queue was cleared."));
4260
- this.emitQueue();
4544
+ for (const item of this.queueItems) this.removeQueueItem(item.id);
4545
+ }
4546
+ steerQueueItem(id) {
4547
+ this.requireOpen();
4548
+ void this.sendInput({ type: "queued-message.promote-to-steer", clientMessageId: id }).catch(
4549
+ (error) => {
4550
+ this.emitError("Failed to steer the queued Agent message", error);
4551
+ }
4552
+ );
4553
+ }
4554
+ resumeQueue() {
4555
+ this.requireOpen();
4556
+ void this.sendInput({ type: "queue.resume" }).catch((error) => {
4557
+ this.emitError("Failed to resume the Agent queue", error);
4558
+ });
4559
+ }
4560
+ get backgroundTasks() {
4561
+ return this._backgroundTasks;
4562
+ }
4563
+ stopSubagent(subagentId) {
4564
+ this.requireOpen();
4565
+ void this.sendInput({ type: "subagent.stop", subagentId }).catch((error) => {
4566
+ this.emitError("Failed to stop the Agent subagent", error);
4567
+ });
4261
4568
  }
4262
4569
  on(event, handler) {
4263
4570
  let listeners = this.listeners.get(event);
@@ -4282,8 +4589,7 @@ var CoreAgentTaskSession = class {
4282
4589
  const closedError = new Error("Agent task session is closed.");
4283
4590
  this.activeWaiter?.reject(closedError);
4284
4591
  this.activeWaiter = void 0;
4285
- for (const item of this._queue) item.waiter?.reject(closedError);
4286
- this._queue = [];
4592
+ this.rejectSteers(closedError);
4287
4593
  if (this._taskId) this.dependencies.onClose(this._taskId, this);
4288
4594
  for (const listeners of this.listeners.values()) listeners.clear();
4289
4595
  }
@@ -4293,9 +4599,10 @@ var CoreAgentTaskSession = class {
4293
4599
  if (this.isClosed()) return false;
4294
4600
  await this.loadHistory();
4295
4601
  if (this.isClosed()) return false;
4602
+ this.openingCursor = historyCursorOf(this._history);
4296
4603
  await this.ensureChannel();
4297
4604
  if (this.isClosed()) return false;
4298
- this.setStatus("idle");
4605
+ if (this._status === "opening") this.setStatus("idle");
4299
4606
  return true;
4300
4607
  } catch (error) {
4301
4608
  if (this.isClosed()) return false;
@@ -4304,40 +4611,43 @@ var CoreAgentTaskSession = class {
4304
4611
  return false;
4305
4612
  }
4306
4613
  }
4307
- startDispatch(prompt, options, waiter) {
4614
+ startDispatch(prompt, options, clientMessageId, waiter) {
4615
+ this.sentTexts.set(clientMessageId, prompt);
4308
4616
  this.dispatching = true;
4309
- const dispatch = this.dispatchSend(prompt, options, waiter).catch((error) => {
4617
+ let handedOver;
4618
+ this.handOff = new Promise((resolve) => {
4619
+ handedOver = resolve;
4620
+ });
4621
+ const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4310
4622
  waiter?.reject(error);
4311
4623
  this.emitError("Failed to send Agent prompt", error);
4312
- if (this._status === "streaming") this.setStatus("idle");
4313
- this.flushQueue();
4624
+ if (this._status === "streaming") {
4625
+ this.settleSteers((steered) => steered.reject(error));
4626
+ this.setStatus("idle");
4627
+ }
4314
4628
  return false;
4315
4629
  }).finally(() => {
4316
- this.dispatching = false;
4317
- if (this.dispatch === dispatch) this.dispatch = null;
4318
- if (this._status === "idle") this.flushQueue();
4630
+ handedOver();
4631
+ if (this.dispatch === dispatch) {
4632
+ this.dispatching = false;
4633
+ this.dispatch = null;
4634
+ }
4319
4635
  });
4320
4636
  this.dispatch = dispatch;
4321
4637
  }
4322
- async dispatchSend(prompt, options, waiter) {
4638
+ async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
4323
4639
  if (this.openingPromise && !await this.openingPromise) {
4324
4640
  throw new Error("Agent task session could not be opened.");
4325
4641
  }
4326
- if (this.isClosed() || waiter?.settled) return false;
4642
+ if (this.isClosed()) return false;
4327
4643
  await this.ensureTask();
4328
- const input = {
4329
- type: "message",
4330
- content: prompt,
4331
- ...options.agentType ? { agentType: options.agentType } : {},
4332
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4333
- };
4644
+ const input = messageInput(prompt, options);
4334
4645
  if (this.isClosed()) {
4335
- await this.sendInput(input).catch(() => void 0);
4646
+ await this.handOver(input, clientMessageId).catch(() => void 0);
4336
4647
  return false;
4337
4648
  }
4338
- if (waiter?.settled) return false;
4339
4649
  await this.ensureChannel();
4340
- if (this.isClosed() || waiter?.settled) return false;
4650
+ if (this.isClosed()) return false;
4341
4651
  await this.captureTurnBaseline();
4342
4652
  this._content = "";
4343
4653
  this.recoveryUsed = false;
@@ -4347,10 +4657,136 @@ var CoreAgentTaskSession = class {
4347
4657
  this.activeWaiter = waiter;
4348
4658
  this.setStatus("streaming");
4349
4659
  this.emit("turnStart", {});
4350
- if (!await this.sendInput(input)) return false;
4351
- this.emit("accepted", {});
4660
+ this.openingMessageId = clientMessageId;
4661
+ this.openingAwaitsStart = true;
4662
+ const { admitted, direct } = await this.handOver(input, this.openingMessageId);
4663
+ if (!direct) this.openingAwaitsStart = false;
4664
+ handedOver();
4665
+ if (!await admitted) return false;
4666
+ this.acceptOnce(clientMessageId);
4352
4667
  return true;
4353
4668
  }
4669
+ // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
4670
+ // that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
4671
+ // that turn already ended. Nothing waits in this session. On the direct channel it goes with an
4672
+ // id the box echoes on the frame that takes it; without the channel, over REST to the Copilot,
4673
+ // which holds it while the box boots.
4674
+ //
4675
+ // It keeps its `agentType` and `reasoningEffort` on the box, which leaves the running turn's
4676
+ // model alone by itself and needs them for a message that becomes a turn of its own. Only on
4677
+ // the Copilot path, with a turn running, they are dropped: the Copilot restarts the live
4678
+ // session for a message that asks for another model, which would end that turn.
4679
+ steer(prompt, options, waiter) {
4680
+ const steered = {
4681
+ clientMessageId: newClientMessageId(),
4682
+ ...waiter ? { waiter } : {},
4683
+ taken: false
4684
+ };
4685
+ if (this.dispatching || this._status === "streaming" || this._status === "cancelled") {
4686
+ this.steers.push(steered);
4687
+ } else {
4688
+ this.strayedSteers.push(steered);
4689
+ }
4690
+ this.sentTexts.set(steered.clientMessageId, prompt);
4691
+ const input = messageInput(prompt, options);
4692
+ this.pendingSteers += 1;
4693
+ const handed = this.handOff.then(async () => {
4694
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4695
+ await this.prepareSend();
4696
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4697
+ return this.handOver(input, steered.clientMessageId, true);
4698
+ });
4699
+ this.handOff = handed.then(
4700
+ () => void 0,
4701
+ () => void 0
4702
+ );
4703
+ void handed.then(({ admitted }) => admitted).then((admitted) => {
4704
+ if (!admitted) {
4705
+ this.forgetSteer(steered);
4706
+ waiter?.reject(
4707
+ steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
4708
+ );
4709
+ return;
4710
+ }
4711
+ if (!steered.queued) this.steerTaken(steered);
4712
+ this.acceptOnce(steered.clientMessageId);
4713
+ }).catch((error) => {
4714
+ this.forgetSteer(steered);
4715
+ waiter?.reject(error);
4716
+ this.emitError("Failed to send Agent prompt", error);
4717
+ }).finally(() => {
4718
+ this.pendingSteers -= 1;
4719
+ });
4720
+ return steered.clientMessageId;
4721
+ }
4722
+ // The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
4723
+ // of its own, when that one ended before the box got to the message.
4724
+ steerTaken(steered) {
4725
+ if (steered.taken) return;
4726
+ steered.taken = true;
4727
+ if (!this.strayedSteers.includes(steered)) return;
4728
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4729
+ this.openTurnFor(steered.waiter);
4730
+ }
4731
+ steerOpenedBy(lifecycle) {
4732
+ const id = lifecycle?.clientMessageId;
4733
+ if (typeof id !== "string") return;
4734
+ const steered = [...this.steers, ...this.strayedSteers].find(
4735
+ (pending) => pending.clientMessageId === id
4736
+ );
4737
+ if (steered) this.steerTaken(steered);
4738
+ }
4739
+ // Queued behind the running turn, the message is answered by the turn the box opens for it
4740
+ // later, not by this one.
4741
+ steerQueuedBy(lifecycle) {
4742
+ const id = lifecycle?.clientMessageId;
4743
+ if (typeof id !== "string") return;
4744
+ const steered = [...this.steers, ...this.strayedSteers].find(
4745
+ (pending) => pending.clientMessageId === id
4746
+ );
4747
+ if (!steered || steered.taken) return;
4748
+ steered.queued = true;
4749
+ if (!this.steers.includes(steered)) return;
4750
+ this.steers = this.steers.filter((pending) => pending !== steered);
4751
+ this.strayedSteers.push(steered);
4752
+ }
4753
+ forgetSteer(steered) {
4754
+ this.steers = this.steers.filter((pending) => pending !== steered);
4755
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4756
+ }
4757
+ // The turn ended: what the box took is answered by it, what it had not taken yet waits for the
4758
+ // turn the box opens for it.
4759
+ settleSteers(settle) {
4760
+ const steers = this.steers;
4761
+ this.steers = [];
4762
+ for (const steered of steers) {
4763
+ if (!steered.taken) this.strayedSteers.push(steered);
4764
+ else if (steered.waiter) settle(steered.waiter);
4765
+ }
4766
+ }
4767
+ openTurnFor(waiter, start = {}) {
4768
+ if (this.isClosed()) return;
4769
+ if (this._status !== "streaming" && this._status !== "cancelled") {
4770
+ this._content = "";
4771
+ this.recoveryUsed = false;
4772
+ this.recoveredTerminalReason = void 0;
4773
+ this.recoveredTerminalUsage = void 0;
4774
+ this.recoveryGeneration += 1;
4775
+ this.turnBaselineIds = new Set(this._history.map((item) => item.id));
4776
+ void this.captureTurnBaseline().catch(() => void 0);
4777
+ this.setStatus("streaming");
4778
+ this.emit("turnStart", start);
4779
+ }
4780
+ if (!waiter) return;
4781
+ if (!this.activeWaiter) this.activeWaiter = waiter;
4782
+ else this.steers.push({ clientMessageId: "", waiter, taken: true });
4783
+ }
4784
+ rejectSteers(error) {
4785
+ const steers = [...this.steers, ...this.strayedSteers];
4786
+ this.steers = [];
4787
+ this.strayedSteers = [];
4788
+ for (const steered of steers) steered.waiter?.reject(error);
4789
+ }
4354
4790
  async ensureTask() {
4355
4791
  if (this._taskId) return;
4356
4792
  if (!("create" in this.options)) throw new Error("Agent task session has no task.");
@@ -4382,6 +4818,8 @@ var CoreAgentTaskSession = class {
4382
4818
  const abort = new AbortController();
4383
4819
  this.connectionAbort = abort;
4384
4820
  const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
4821
+ const historyCursor = this.openingCursor;
4822
+ this.openingCursor = void 0;
4385
4823
  this.connectionPromise = source.open(
4386
4824
  this._taskId,
4387
4825
  {
@@ -4389,7 +4827,8 @@ var CoreAgentTaskSession = class {
4389
4827
  onDisconnect: (error) => this.handleDisconnect(error)
4390
4828
  },
4391
4829
  abort.signal,
4392
- this.options.transport
4830
+ this.options.transport,
4831
+ historyCursor
4393
4832
  ).then((connection) => {
4394
4833
  if (this.isClosed() || this._status === "error") {
4395
4834
  connection.close();
@@ -4421,10 +4860,8 @@ var CoreAgentTaskSession = class {
4421
4860
  try {
4422
4861
  await this.ensureChannel();
4423
4862
  while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
4424
- if (await this.reconcilePersistedTurn(this.recoveredTerminalReason ?? "reconciled")) {
4425
- return;
4426
- }
4427
- if (this.activeWaiter?.settled) return;
4863
+ const reason = this.recoveredTerminalReason ?? (this._status === "cancelled" ? "interrupted" : "reconciled");
4864
+ if (await this.reconcilePersistedTurn(reason)) return;
4428
4865
  await delay(RECONCILE_DELAY_MS);
4429
4866
  }
4430
4867
  } catch (error) {
@@ -4437,7 +4874,8 @@ var CoreAgentTaskSession = class {
4437
4874
  if (!this._taskId) return;
4438
4875
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4439
4876
  size: 100,
4440
- sort: "createdAt,desc"
4877
+ sort: "createdAt,desc",
4878
+ kinds: "all"
4441
4879
  });
4442
4880
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
4443
4881
  }
@@ -4445,14 +4883,29 @@ var CoreAgentTaskSession = class {
4445
4883
  if (!this._taskId) return false;
4446
4884
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4447
4885
  size: 100,
4448
- sort: "createdAt,desc"
4886
+ sort: "createdAt,desc",
4887
+ kinds: "all"
4449
4888
  });
4450
4889
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4451
4890
  this.emit("historyLoaded", { history: this.history });
4452
- const recovered = page.content.find(
4453
- (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4891
+ const rows = page.content.filter(isChatRow);
4892
+ const recovered = rows.find(
4893
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
4454
4894
  );
4455
- if (!recovered) return false;
4895
+ if (!recovered) {
4896
+ if (this.recoveredTerminalReason === void 0) return false;
4897
+ if (this.recoveredTerminalUsage !== void 0) {
4898
+ this.endedPollsWithoutRow += 1;
4899
+ if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
4900
+ }
4901
+ const newest = rows.find(
4902
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4903
+ );
4904
+ if (!newest) return false;
4905
+ this._content = newest.content;
4906
+ this.finishTurn(reason, this.recoveredTerminalUsage);
4907
+ return true;
4908
+ }
4456
4909
  if (recovered.type === "ERROR") {
4457
4910
  const error = new AgentTaskTurnError(recovered.content);
4458
4911
  this.emit("error", { error: error.message });
@@ -4463,36 +4916,139 @@ var CoreAgentTaskSession = class {
4463
4916
  this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
4464
4917
  return true;
4465
4918
  }
4919
+ closesThisTurn(message) {
4920
+ if (!message.usage) return false;
4921
+ const prompt = message.usage.requestMessageId;
4922
+ return prompt === void 0 || !this.turnBaselineIds.has(prompt);
4923
+ }
4466
4924
  /** True once the server took the input; false when the box refused it on the stream. */
4467
4925
  async sendInput(input) {
4926
+ return (await this.handOver(input)).admitted;
4927
+ }
4928
+ // Resolves once the input left this session; `admitted` then says whether the server took it.
4929
+ // Wrapped so that awaiting the hand-over does not also await the answer.
4930
+ async handOver(input, clientMessageId, steering = false) {
4468
4931
  if (!this._taskId) throw new Error("Agent task has not been created.");
4469
- const direct = this.dependencies.channel.send(this._taskId, input);
4470
- if (direct) return direct;
4471
- await this.dependencies.tasks.sendInput(this._taskId, input);
4472
- return true;
4932
+ const direct = this.dependencies.channel.send(this._taskId, input, clientMessageId);
4933
+ if (direct) return { admitted: direct, direct: true };
4934
+ if (input.type === "runtime-request.respond") {
4935
+ throw new Error(
4936
+ "The answer to the Agent input request was not sent: the box channel is not connected right now."
4937
+ );
4938
+ }
4939
+ if (!COPILOT_INPUT_TYPES.has(input.type)) {
4940
+ throw new Error(
4941
+ `The Agent ${input.type} was not sent: the box channel is not connected right now.`
4942
+ );
4943
+ }
4944
+ const turnRunning = this._status === "streaming" || this._status === "cancelled";
4945
+ const id = clientMessageId === void 0 ? {} : { clientMessageId };
4946
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
4947
+ type: "message",
4948
+ content: input.content,
4949
+ ...input.agentType ? { agentType: input.agentType } : {},
4950
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
4951
+ ...id
4952
+ };
4953
+ await this.dependencies.tasks.sendInput(this._taskId, rest);
4954
+ return { admitted: Promise.resolve(true), direct: false };
4955
+ }
4956
+ async prepareSend() {
4957
+ if (this.openingPromise && !await this.openingPromise) {
4958
+ throw new Error("Agent task session could not be opened.");
4959
+ }
4960
+ await this.ensureTask();
4961
+ if (!this.isClosed()) await this.ensureChannel();
4473
4962
  }
4474
4963
  handleEvent(event) {
4475
4964
  this.emit("raw", event);
4476
4965
  const payload = asObject2(event.payload);
4966
+ if (payload && isSubagentFrame(event)) {
4967
+ this.handleSubagentFrame(event, payload);
4968
+ return;
4969
+ }
4970
+ const lifecycle = asObject2(payload?.lifecycle);
4971
+ if (this.endsQueuedMessage(event, payload, lifecycle)) return;
4972
+ if (this.repeatsTheRunningTurn(event, lifecycle)) return;
4973
+ if (event.type === "stepStart" || event.type === "steer") {
4974
+ const id = lifecycle?.clientMessageId;
4975
+ if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
4976
+ this.openingAwaitsStart = false;
4977
+ this.forgetFinishedTurn(lifecycle);
4978
+ }
4979
+ } else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
4980
+ this.rememberFinishedTurn(lifecycle);
4981
+ }
4477
4982
  switch (event.type) {
4478
4983
  // A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
4479
4984
  // como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
4480
4985
  // texto e o que faz a resposta recuperada aparecer; sem isso ela chega e morre aqui.
4481
4986
  case "textDelta":
4482
4987
  case "textChunk":
4483
- this.consumeDelta(payload, "text");
4988
+ this.consumeDelta(event, payload, "text");
4484
4989
  break;
4485
4990
  case "thinking":
4486
- this.consumeDelta(payload, "thinking");
4991
+ this.consumeDelta(event, payload, "thinking");
4487
4992
  break;
4488
4993
  case "toolCall":
4489
- this.emitTool(payload, "call", event.timestamp);
4994
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(event, payload, "call");
4490
4995
  break;
4996
+ // A result can come after its turn ended: a subagent in the background settles later, and
4997
+ // the box sends its result under the turn that called it. It reaches the app as that tool's
4998
+ // result and touches no turn.
4491
4999
  case "toolResult":
4492
- this.emitTool(payload, "result", event.timestamp);
5000
+ this.emitTool(event, payload, "result");
4493
5001
  break;
4494
5002
  case "workspace":
4495
- this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
5003
+ this.emit("workspace", {
5004
+ payload: event.payload,
5005
+ timestamp: event.timestamp,
5006
+ ...sequenceOf(event)
5007
+ });
5008
+ break;
5009
+ case "stepStart":
5010
+ if (!this.isFinishedTurnFrame(lifecycle)) {
5011
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
5012
+ }
5013
+ if (typeof lifecycle?.turnId === "string" && !this.isFinishedTurnFrame(lifecycle) && this._status !== "streaming" && this._status !== "cancelled") {
5014
+ this.openTurnFor(void 0, {
5015
+ ...typeof payload?.text === "string" ? { text: payload.text } : {},
5016
+ ...typeof lifecycle.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {},
5017
+ ...pieceIdentityOf(event, payload)
5018
+ });
5019
+ }
5020
+ this.leaveQueue(lifecycle?.clientMessageId);
5021
+ this.steerOpenedBy(asObject2(payload?.lifecycle));
5022
+ this.acceptNamed(lifecycle?.clientMessageId);
5023
+ break;
5024
+ case "steer":
5025
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
5026
+ this.leaveQueue(lifecycle?.clientMessageId);
5027
+ this.steerOpenedBy(lifecycle);
5028
+ this.acceptNamed(lifecycle?.clientMessageId);
5029
+ this.emit("steered", {
5030
+ text: typeof payload?.text === "string" ? payload.text : "",
5031
+ messageId: typeof payload?.messageId === "string" ? payload.messageId : "",
5032
+ ...typeof payload?.turnId === "string" ? { turnId: payload.turnId } : {},
5033
+ ...sequenceOf(event),
5034
+ ...typeof lifecycle?.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {}
5035
+ });
5036
+ break;
5037
+ case "backgroundTasks":
5038
+ this._backgroundTasks = backgroundTasksOf(payload?.tasks);
5039
+ this.emit("backgroundTasks", { tasks: this._backgroundTasks });
5040
+ break;
5041
+ case "messageQueued":
5042
+ if (payload?.cancelled === true) {
5043
+ this.cancelQueued(payload, lifecycle);
5044
+ break;
5045
+ }
5046
+ this.applyQueued(event, payload, lifecycle);
5047
+ this.steerQueuedBy(asObject2(payload?.lifecycle));
5048
+ this.acceptNamed(lifecycle?.clientMessageId);
5049
+ break;
5050
+ case "subagentUpdate":
5051
+ this.applySubagent(event, payload);
4496
5052
  break;
4497
5053
  case "providerUsage": {
4498
5054
  const usage = providerUsageOf(payload);
@@ -4501,15 +5057,22 @@ var CoreAgentTaskSession = class {
4501
5057
  }
4502
5058
  case "stepFinish": {
4503
5059
  const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
4504
- const lifecycle = payload?.lifecycle;
5060
+ const lifecycle2 = payload?.lifecycle;
4505
5061
  const usage = agentTurnUsageOf(payload?.usage);
4506
- if (reason === "interrupted" || lifecycle?.interruptTerminal === true) {
4507
- this.rememberFinishedTurn(lifecycle);
4508
- this.finishTurn("interrupted", usage);
5062
+ const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
5063
+ if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
5064
+ if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
5065
+ const end = {
5066
+ ...sequenceOf(event),
5067
+ ...finished === void 0 ? {} : { turnId: finished }
5068
+ };
5069
+ if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
5070
+ this.rememberFinishedTurn(lifecycle2);
5071
+ this.finishTurn("interrupted", usage, end);
4509
5072
  break;
4510
5073
  }
4511
5074
  if (reason === "stop" || reason === "endTurn") {
4512
- this.rememberFinishedTurn(lifecycle);
5075
+ this.rememberFinishedTurn(lifecycle2);
4513
5076
  if (this.recoveryUsed) {
4514
5077
  this.recoveredTerminalReason = reason;
4515
5078
  this.recoveredTerminalUsage = usage;
@@ -4520,7 +5083,7 @@ var CoreAgentTaskSession = class {
4520
5083
  });
4521
5084
  }
4522
5085
  } else {
4523
- this.finishTurn(reason, usage);
5086
+ this.finishTurn(reason, usage, end);
4524
5087
  }
4525
5088
  }
4526
5089
  break;
@@ -4528,23 +5091,165 @@ var CoreAgentTaskSession = class {
4528
5091
  case "error": {
4529
5092
  const code = typeof payload?.code === "string" ? payload.code : void 0;
4530
5093
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
4531
- this.emit("error", { ...code ? { code } : {}, error: message });
5094
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5095
+ if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5096
+ if (typeof payload?.command === "string") break;
5097
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
5098
+ if (typeof refused === "string") {
5099
+ if (refused !== this.openingMessageId) {
5100
+ const steered = [...this.steers, ...this.strayedSteers].find(
5101
+ (pending) => pending.clientMessageId === refused
5102
+ );
5103
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
5104
+ break;
5105
+ }
5106
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
4532
5107
  if (this._status === "streaming" || this._status === "cancelled") {
4533
5108
  this.failTurn(new AgentTaskTurnError(message, code));
4534
5109
  }
4535
5110
  break;
4536
5111
  }
5112
+ case "approval":
5113
+ case "user_input_request":
5114
+ this.liveRequest(event, payload);
5115
+ break;
4537
5116
  default:
4538
5117
  break;
4539
5118
  }
4540
5119
  }
5120
+ // The box admits every message with a `messageQueued` of no position; only one with a position
5121
+ // is in T3's queue.
5122
+ applyQueued(event, payload, lifecycle) {
5123
+ const id = payload?.clientMessageId ?? lifecycle?.clientMessageId;
5124
+ const position = payload?.position;
5125
+ if (typeof id !== "string" || typeof position !== "number") return;
5126
+ const known = this.queueItems.find((item2) => item2.id === id);
5127
+ if (this.alreadyApplied(known?.sequence, event)) return;
5128
+ const item = {
5129
+ id,
5130
+ text: typeof payload?.text === "string" ? payload.text : known?.text ?? "",
5131
+ createdAt: known?.createdAt ?? event.timestamp,
5132
+ position,
5133
+ ...typeof payload?.queueHeld === "boolean" ? { queueHeld: payload.queueHeld } : {},
5134
+ ...sequenceOf(event),
5135
+ ...typeof lifecycle?.turnId === "string" ? { turnId: lifecycle.turnId } : {}
5136
+ };
5137
+ this.queueItems = known ? this.queueItems.map((current) => current === known ? item : current) : [...this.queueItems, item];
5138
+ this.emit("queueChange", { queue: this.queue });
5139
+ }
5140
+ // The box took the message out of T3's queue on a `queued-run.cancel`, with no terminal of its
5141
+ // own: it leaves the queue and only its own `sendAndWait` ends. The message that opened this
5142
+ // session's turn was that turn, still waiting behind another one, which ends with it.
5143
+ cancelQueued(payload, lifecycle) {
5144
+ const id = payload.clientMessageId ?? lifecycle?.clientMessageId;
5145
+ if (typeof id !== "string") return;
5146
+ this.leaveQueue(id);
5147
+ const cancelled = new AgentTaskTurnError("The queued Agent message was cancelled.");
5148
+ if (id === this.openingMessageId) {
5149
+ this.cancelOpening(cancelled);
5150
+ return;
5151
+ }
5152
+ const steered = [...this.steers, ...this.strayedSteers].find(
5153
+ (pending) => pending.clientMessageId === id
5154
+ );
5155
+ if (!steered) return;
5156
+ this.forgetSteer(steered);
5157
+ steered.waiter?.reject(cancelled);
5158
+ }
5159
+ // A frame naming one of this session's messages in flight is the box taking it.
5160
+ acceptNamed(id) {
5161
+ if (typeof id !== "string") return;
5162
+ if (id === this.openingMessageId) this.dispatching = false;
5163
+ const ours = id === this.openingMessageId || [...this.steers, ...this.strayedSteers].some((pending) => pending.clientMessageId === id);
5164
+ if (ours) this.acceptOnce(id);
5165
+ }
5166
+ acceptOnce(id) {
5167
+ if (this.acceptedIds.includes(id)) return;
5168
+ this.acceptedIds.push(id);
5169
+ if (this.acceptedIds.length > 32) this.acceptedIds.shift();
5170
+ this.emit("accepted", {});
5171
+ }
5172
+ // As in T3, cancelling a queued run only takes that run out: no turn ends with it. The message
5173
+ // this session opened its turn with never ran, so only its own `sendAndWait` is rejected. A
5174
+ // message of this session still queued behind it keeps the session waiting for the turn the
5175
+ // box opens for it; with none, nothing of this session runs and it goes back to idle.
5176
+ cancelOpening(cancelled) {
5177
+ this.openingMessageId = void 0;
5178
+ if (!this.openingAwaitsStart) return;
5179
+ this.openingAwaitsStart = false;
5180
+ this.activeWaiter?.reject(cancelled);
5181
+ this.activeWaiter = void 0;
5182
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
5183
+ if (this.steers.length === 0 && this.strayedSteers.length === 0) this.setStatus("idle");
5184
+ }
5185
+ // After a replay the box sends the queue and the subagents as they are, each a copy of the line
5186
+ // that said it last, with that line's sequence: state this session may already hold.
5187
+ alreadyApplied(applied, event) {
5188
+ return applied !== void 0 && typeof event.sequence === "number" && event.sequence <= applied;
5189
+ }
5190
+ leaveQueue(id) {
5191
+ const item = this.queueItems.find((current) => current.id === id);
5192
+ if (!item) return void 0;
5193
+ this.queueItems = this.queueItems.filter((current) => current !== item);
5194
+ this.emit("queueChange", { queue: this.queue });
5195
+ return item;
5196
+ }
5197
+ // A queued message that ends before running (taken out of the queue, or dropped by T3) closes
5198
+ // with a terminal of its own while another turn may run: it leaves the queue and ends its own
5199
+ // `sendAndWait`, and the running turn goes on. The opening message of this session's turn is
5200
+ // that turn, and ends it as before.
5201
+ endsQueuedMessage(event, payload, lifecycle) {
5202
+ if (event.type !== "error" && event.type !== "stepFinish" || !lifecycle) return false;
5203
+ const id = payload?.clientMessageId ?? lifecycle.clientMessageId;
5204
+ const turnId = lifecycle.turnId;
5205
+ const item = this.queueItems.find(
5206
+ (current) => current.id === id || turnId !== void 0 && current.turnId === turnId
5207
+ );
5208
+ if (!item) return false;
5209
+ this.leaveQueue(item.id);
5210
+ if (item.id === this.openingMessageId) return false;
5211
+ const message = typeof payload?.message === "string" ? payload.message : "The queued Agent message ended before it ran.";
5212
+ if (event.type === "error") {
5213
+ const code = typeof payload?.code === "string" ? payload.code : void 0;
5214
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5215
+ }
5216
+ const steered = [...this.steers, ...this.strayedSteers].find(
5217
+ (pending) => pending.clientMessageId === item.id
5218
+ );
5219
+ if (steered) {
5220
+ this.forgetSteer(steered);
5221
+ steered.waiter?.reject(new AgentTaskTurnError(message));
5222
+ }
5223
+ return true;
5224
+ }
5225
+ repeatsTheRunningTurn(event, lifecycle) {
5226
+ if (this._status !== "streaming" && this._status !== "cancelled") return false;
5227
+ const turnId = lifecycle?.turnId;
5228
+ if (typeof turnId !== "string") return false;
5229
+ if (typeof event.sequence === "number") {
5230
+ if (this.turnIds.has(turnId) && event.sequence <= this.turnSequenceHigh) return true;
5231
+ this.turnSequenceHigh = Math.max(this.turnSequenceHigh, event.sequence);
5232
+ }
5233
+ this.turnIds.add(turnId);
5234
+ return false;
5235
+ }
5236
+ isFinishedTurnFrame(lifecycle) {
5237
+ const turnId = lifecycle?.turnId;
5238
+ return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
5239
+ }
5240
+ forgetFinishedTurn(lifecycle) {
5241
+ const turnId = lifecycle?.turnId;
5242
+ if (typeof turnId !== "string") return;
5243
+ const index = this.finishedTurnIds.indexOf(turnId);
5244
+ if (index >= 0) this.finishedTurnIds.splice(index, 1);
5245
+ }
4541
5246
  rememberFinishedTurn(lifecycle) {
4542
5247
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4543
5248
  if (!turnId) return;
4544
5249
  this.finishedTurnIds.push(turnId);
4545
5250
  if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
4546
5251
  }
4547
- consumeDelta(payload, kind) {
5252
+ consumeDelta(event, payload, kind) {
4548
5253
  const lifecycle = asObject2(payload?.lifecycle);
4549
5254
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4550
5255
  if (turnId && this.finishedTurnIds.includes(turnId)) return;
@@ -4556,19 +5261,194 @@ var CoreAgentTaskSession = class {
4556
5261
  this.emit("turnStart", {});
4557
5262
  }
4558
5263
  if (kind === "text") this._content += text;
4559
- this.emit("delta", { delta: text, kind });
4560
- }
4561
- emitTool(payload, phase, timestamp) {
4562
- this.emit("tool", {
4563
- tool: typeof payload?.name === "string" ? payload.name : "",
4564
- phase,
4565
- timestamp,
4566
- ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4567
- ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4568
- ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
5264
+ this.liveText(event, payload, kind);
5265
+ this.emit("delta", {
5266
+ delta: text,
5267
+ kind,
5268
+ ...itemDeltaOf(payload),
5269
+ ...pieceIdentityOf(event, payload)
4569
5270
  });
4570
5271
  }
4571
- finishTurn(reason, usage) {
5272
+ emitTool(event, payload, phase) {
5273
+ const tool = toolEventOf(event, payload, phase);
5274
+ this.liveTool(tool, event);
5275
+ this.emit("tool", tool);
5276
+ }
5277
+ // The conversation as it happens: the box's frames grow `history` while a turn runs, one item
5278
+ // per piece of T3, the same pieces the Copilot records and the reload at the turn's end brings
5279
+ // back in the same order. A piece the loaded history already has keeps growing in place, and a
5280
+ // frame it already holds (a replay after a reconnect or an F5) changes nothing.
5281
+ livePiece(match, create, update) {
5282
+ const index = this._history.findIndex(match);
5283
+ const current = this._history[index];
5284
+ if (current === void 0) this._history.push(create());
5285
+ else this._history[index] = update(current);
5286
+ }
5287
+ // The question enters the conversation where the box took it: its turn's `stepStart`, or the
5288
+ // `steer` that took it into the running turn. Until then it is in `queue`.
5289
+ liveQuestion(event, boxText, clientMessageId) {
5290
+ const id = typeof clientMessageId === "string" ? clientMessageId : void 0;
5291
+ const text = (id !== void 0 ? this.sentTexts.get(id) : void 0) ?? boxText;
5292
+ if (typeof text !== "string" || !text) return;
5293
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5294
+ this.livePiece(
5295
+ (item) => item.kind === "user" && (id !== void 0 && item.clientMessageId === id || sequence !== void 0 && item.sequence === sequence && item.text === text),
5296
+ () => ({
5297
+ id: `live:user:${id ?? sequence ?? this._history.length}`,
5298
+ kind: "user",
5299
+ text,
5300
+ at: liveAtOf(event),
5301
+ ...sequence === void 0 ? {} : { sequence },
5302
+ ...id === void 0 ? {} : { clientMessageId: id }
5303
+ }),
5304
+ (item) => item
5305
+ );
5306
+ }
5307
+ liveText(event, payload, kind, parentToolId) {
5308
+ const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
5309
+ if (itemId === void 0) return;
5310
+ const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
5311
+ const itemKind = kind === "thinking" ? "reasoning" : "agent";
5312
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5313
+ this.livePiece(
5314
+ (item) => item.kind === itemKind && item.itemId === itemId,
5315
+ () => ({
5316
+ id: `live:${itemKind}:${itemId}`,
5317
+ kind: itemKind,
5318
+ text: piece,
5319
+ at: liveAtOf(event),
5320
+ itemId,
5321
+ ...sequence === void 0 ? {} : { sequence },
5322
+ ...parentToolIdOf(parentToolId)
5323
+ }),
5324
+ (item) => {
5325
+ const held = item.lastSequence ?? item.sequence;
5326
+ if (!("text" in item) || sequence !== void 0 && held !== void 0 && sequence <= held)
5327
+ return item;
5328
+ return {
5329
+ ...item,
5330
+ text: item.text + piece,
5331
+ ...sequence === void 0 ? {} : { lastSequence: sequence }
5332
+ };
5333
+ }
5334
+ );
5335
+ }
5336
+ liveTool(tool, event) {
5337
+ const toolId = tool.toolId;
5338
+ if (toolId === void 0) return;
5339
+ this.livePiece(
5340
+ (item) => item.kind === "tool" && item.tool.toolId === toolId && item.tool.phase === tool.phase,
5341
+ () => ({
5342
+ id: tool.phase === "result" ? `live:tool:${toolId}:result` : `live:tool:${toolId}`,
5343
+ kind: "tool",
5344
+ tool,
5345
+ at: liveAtOf(event),
5346
+ ...tool.sequence === void 0 ? {} : { sequence: tool.sequence },
5347
+ ...tool.itemId === void 0 ? {} : { itemId: tool.itemId }
5348
+ }),
5349
+ (item) => item.kind === "tool" ? { ...item, tool: { ...item.tool, ...tool, input: tool.input ?? item.tool.input } } : item
5350
+ );
5351
+ }
5352
+ // An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
5353
+ // it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
5354
+ // reaches the app as a `raw` event, as before.
5355
+ liveRequest(event, payload, parentToolId) {
5356
+ if (!payload) return;
5357
+ const kind = event.type === "approval" ? "approval" : "userInputRequest";
5358
+ const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
5359
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5360
+ if (itemId === void 0 && sequence === void 0) return;
5361
+ this.livePiece(
5362
+ (item) => item.kind === kind && (itemId !== void 0 ? item.itemId === itemId : item.sequence === sequence),
5363
+ () => ({
5364
+ id: `live:${kind}:${itemId ?? sequence}`,
5365
+ kind,
5366
+ payload,
5367
+ at: liveAtOf(event),
5368
+ ...sequence === void 0 ? {} : { sequence },
5369
+ ...itemId === void 0 ? {} : { itemId },
5370
+ ...parentToolIdOf(parentToolId)
5371
+ }),
5372
+ (item) => item
5373
+ );
5374
+ }
5375
+ // A child thread's frames are the subagent's conversation: they open no turn and settle no
5376
+ // message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
5377
+ // which knew no subagents, so an app that only bumps the version sees what it saw before.
5378
+ handleSubagentFrame(event, payload) {
5379
+ const parentToolId = payload.parentToolId;
5380
+ switch (event.type) {
5381
+ case "textDelta":
5382
+ case "textChunk":
5383
+ case "thinking": {
5384
+ const delta = typeof payload.text === "string" ? payload.text : "";
5385
+ const kind = event.type === "thinking" ? "thinking" : "text";
5386
+ const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
5387
+ if (kind === "text") this._content += delta;
5388
+ this.liveText(event, payload, kind, parentToolId);
5389
+ this.emit("delta", { delta, kind, parentToolId, ...identity });
5390
+ this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
5391
+ break;
5392
+ }
5393
+ case "toolCall":
5394
+ case "toolResult": {
5395
+ const tool = {
5396
+ ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
5397
+ parentToolId
5398
+ };
5399
+ this.liveTool(tool, event);
5400
+ this.emit("tool", tool);
5401
+ this.emit("subagentTool", tool);
5402
+ break;
5403
+ }
5404
+ case "approval":
5405
+ case "user_input_request":
5406
+ this.liveRequest(event, payload, parentToolId);
5407
+ break;
5408
+ default:
5409
+ break;
5410
+ }
5411
+ }
5412
+ applySubagent(event, payload) {
5413
+ const subagentId = payload?.subagentId;
5414
+ const toolId = payload?.toolId;
5415
+ if (typeof subagentId !== "string" || typeof toolId !== "string") return;
5416
+ if (this.alreadyApplied(this.subagentSequences.get(subagentId), event)) return;
5417
+ if (typeof event.sequence === "number") this.subagentSequences.set(subagentId, event.sequence);
5418
+ const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
5419
+ if (status === void 0) return;
5420
+ const startedAt = epochOf(payload?.startedAt);
5421
+ const endedAt = epochOf(payload?.endedAt);
5422
+ const subagent = {
5423
+ subagentId,
5424
+ toolId,
5425
+ status,
5426
+ ...typeof payload?.progress === "string" ? { progress: payload.progress } : {},
5427
+ ...startedAt !== void 0 ? { startedAt } : {},
5428
+ ...endedAt !== void 0 ? { endedAt } : {},
5429
+ ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
5430
+ };
5431
+ this.subagentsById.set(subagentId, subagent);
5432
+ const index = this._history.findIndex(
5433
+ (item) => item.kind === "tool" && item.tool.toolId === toolId
5434
+ );
5435
+ const spawn = this._history[index];
5436
+ if (spawn?.kind === "tool") {
5437
+ this._history[index] = {
5438
+ ...spawn,
5439
+ subagent: {
5440
+ ...spawn.subagent,
5441
+ toolId,
5442
+ subagentId,
5443
+ status,
5444
+ ...subagent.progress === void 0 ? {} : { progress: subagent.progress },
5445
+ ...subagent.childThreadId === void 0 ? {} : { childThreadId: subagent.childThreadId }
5446
+ }
5447
+ };
5448
+ }
5449
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5450
+ }
5451
+ finishTurn(reason, usage, end = {}) {
4572
5452
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4573
5453
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
4574
5454
  this.cancelTimer = null;
@@ -4586,13 +5466,14 @@ var CoreAgentTaskSession = class {
4586
5466
  task,
4587
5467
  content: this._content,
4588
5468
  reason,
4589
- ...usage ? { usage } : {}
5469
+ ...usage ? { usage } : {},
5470
+ ...end
4590
5471
  };
4591
5472
  this.emit("turnEnd", result);
4592
5473
  this.activeWaiter?.resolve(result);
4593
5474
  this.activeWaiter = void 0;
5475
+ this.settleSteers((waiter) => waiter.resolve(result));
4594
5476
  this.setStatus("idle");
4595
- this.flushQueue();
4596
5477
  }
4597
5478
  failTurn(error) {
4598
5479
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
@@ -4600,56 +5481,17 @@ var CoreAgentTaskSession = class {
4600
5481
  this.recoveryGeneration += 1;
4601
5482
  this.activeWaiter?.reject(error);
4602
5483
  this.activeWaiter = void 0;
5484
+ this.settleSteers((waiter) => waiter.reject(error));
4603
5485
  this.setStatus("idle");
4604
- this.flushQueue();
4605
5486
  }
4606
5487
  failLiveChannel(observed, waiterError) {
4607
5488
  this.recoveryGeneration += 1;
4608
5489
  this.emitError("Agent live channel failed", observed);
4609
5490
  this.activeWaiter?.reject(waiterError);
4610
5491
  this.activeWaiter = void 0;
4611
- for (const item of this._queue) item.waiter?.reject(waiterError);
4612
- this._queue = [];
4613
- this.emitQueue();
5492
+ this.rejectSteers(waiterError);
4614
5493
  this.setStatus("error");
4615
5494
  }
4616
- enqueue(text, options, waiter) {
4617
- if (this._queue.length >= AGENT_QUEUE_LIMIT) {
4618
- const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
4619
- waiter?.reject(error);
4620
- this.emit("error", { error: error.message });
4621
- return void 0;
4622
- }
4623
- const id = `q-${++this.queueSequence}`;
4624
- this._queue = [
4625
- ...this._queue,
4626
- { id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
4627
- ];
4628
- this.emitQueue();
4629
- return id;
4630
- }
4631
- flushQueue() {
4632
- if (this.isBusy()) return;
4633
- let next = this._queue[0];
4634
- while (next?.waiter?.settled) {
4635
- this._queue = this._queue.slice(1);
4636
- next = this._queue[0];
4637
- }
4638
- if (!next) {
4639
- this.emitQueue();
4640
- return;
4641
- }
4642
- this._queue = this._queue.slice(1);
4643
- this.emitQueue();
4644
- this.startDispatch(
4645
- next.text,
4646
- {
4647
- ...next.agentType ? { agentType: next.agentType } : {},
4648
- ...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
4649
- },
4650
- next.waiter
4651
- );
4652
- }
4653
5495
  createWaiter(options) {
4654
5496
  let resolvePromise;
4655
5497
  let rejectPromise;
@@ -4671,7 +5513,6 @@ var CoreAgentTaskSession = class {
4671
5513
  if (waiter.settled) return;
4672
5514
  waiter.settled = true;
4673
5515
  waiter.cleanup();
4674
- if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
4675
5516
  rejectPromise(error);
4676
5517
  },
4677
5518
  cleanup: () => {
@@ -4696,14 +5537,6 @@ var CoreAgentTaskSession = class {
4696
5537
  }
4697
5538
  return waiter;
4698
5539
  }
4699
- removeQueuedWaiter(id) {
4700
- const size = this._queue.length;
4701
- this._queue = this._queue.filter((item) => item.id !== id);
4702
- if (this._queue.length !== size) this.emitQueue();
4703
- }
4704
- emitQueue() {
4705
- this.emit("queueChange", { queue: this.queue });
4706
- }
4707
5540
  emitError(prefix, error) {
4708
5541
  const code = errorCode(error);
4709
5542
  this.emit("error", {
@@ -4713,6 +5546,12 @@ var CoreAgentTaskSession = class {
4713
5546
  }
4714
5547
  setStatus(status) {
4715
5548
  if (this._status === status) return;
5549
+ if (status !== "streaming" && status !== "cancelled") {
5550
+ this.openingAwaitsStart = false;
5551
+ this.endedPollsWithoutRow = 0;
5552
+ this.turnIds.clear();
5553
+ this.turnSequenceHigh = -1;
5554
+ }
4716
5555
  this._status = status;
4717
5556
  this.emit("statusChange", { status });
4718
5557
  }
@@ -4722,8 +5561,11 @@ var CoreAgentTaskSession = class {
4722
5561
  isClosed() {
4723
5562
  return this._status === "closed";
4724
5563
  }
5564
+ // A turn running or being opened takes a new message as a steer. So does a session waiting for
5565
+ // the turn the box opens for a steer it took late: a new message started as a turn of its own
5566
+ // then would be answered by the steer's result, and the steer by its.
4725
5567
  isBusy() {
4726
- return this.dispatching || this._status === "streaming" || this._status === "cancelled";
5568
+ return this.dispatching || this._status === "streaming" || this._status === "cancelled" || this.strayedSteers.length > 0;
4727
5569
  }
4728
5570
  emit(event, payload) {
4729
5571
  const listeners = this.listeners.get(event);