@mitralab.io/sdk-core 0.3.0-beta.2 → 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
@@ -3318,7 +3324,7 @@ function newClientMessageId() {
3318
3324
  }
3319
3325
  function admissionFor(link, event) {
3320
3326
  const payload = asObject(event.payload);
3321
- if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
3327
+ if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0 || payload?.command !== void 0)) {
3322
3328
  return void 0;
3323
3329
  }
3324
3330
  const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
@@ -3364,6 +3370,14 @@ function boxAddress(wsUrl) {
3364
3370
  const url = new URL(wsUrl);
3365
3371
  return `${url.origin}${url.pathname}`;
3366
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
+ }
3367
3381
  function boxRoute(wsUrl, route) {
3368
3382
  const url = new URL(wsUrl);
3369
3383
  url.protocol = url.protocol === "wss:" ? "https:" : "http:";
@@ -3457,8 +3471,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3457
3471
  "steer",
3458
3472
  "textDelta",
3459
3473
  "thinking",
3460
- "toolCall",
3461
- "toolResult"
3474
+ "toolCall"
3462
3475
  ]);
3463
3476
  var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3464
3477
  function turnAfter(event, inTurn) {
@@ -3471,6 +3484,12 @@ function turnAfter(event, inTurn) {
3471
3484
  }
3472
3485
  return inTurn;
3473
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
+ }
3474
3493
  function lostTurnFrame(turnId) {
3475
3494
  return {
3476
3495
  type: "stepFinish",
@@ -3542,7 +3561,7 @@ var AgentDirectChannel = class {
3542
3561
  enabled() {
3543
3562
  return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
3544
3563
  }
3545
- async open(taskId, observer, signal, transport) {
3564
+ async open(taskId, observer, signal, transport, historyCursor) {
3546
3565
  if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
3547
3566
  const mode = this.modeFor(transport);
3548
3567
  const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
@@ -3552,7 +3571,7 @@ var AgentDirectChannel = class {
3552
3571
  return this.fallback.open(taskId, observer, signal, transport);
3553
3572
  }
3554
3573
  try {
3555
- return await this.openDirect(taskId, mode, answer, observer, signal);
3574
+ return await this.openDirect(taskId, mode, answer, observer, signal, historyCursor);
3556
3575
  } catch (error) {
3557
3576
  if (signal?.aborted) throw error;
3558
3577
  observer.onEvent(
@@ -3677,26 +3696,36 @@ var AgentDirectChannel = class {
3677
3696
  * only when the redial gives up, when the Copilot no longer offers the box, or when there is
3678
3697
  * no turn to resume: dialing an idle box again would wake it for nobody.
3679
3698
  *
3680
- * Opening never asks for an older replay. What an idle chat missed is history, which the
3681
- * session loads by REST; replaying from an older cursor would put old turns on screen as live
3682
- * 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.
3683
3705
  */
3684
- async openDirect(taskId, mode, channel, observer, signal) {
3706
+ async openDirect(taskId, mode, channel, observer, signal, historyCursor) {
3685
3707
  const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
3686
3708
  let box = boxAddress(channel.wsUrl);
3687
- 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;
3688
3713
  const abort = new AbortController();
3689
3714
  const onAbort = () => abort.abort(signal?.reason);
3690
3715
  signal?.addEventListener("abort", onAbort, { once: true });
3691
3716
  const onFrame = (event) => {
3717
+ const hello = helloOf(event);
3718
+ if (hello) thread = hello.threadId;
3692
3719
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3693
3720
  if (isSubagentFrame(event)) {
3694
3721
  observer.onEvent(event);
3695
3722
  return;
3696
3723
  }
3697
- const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3698
- if (typeof turnId === "string") link.turnId = turnId;
3699
- link.inTurn = turnAfter(event, link.inTurn);
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
+ }
3700
3729
  observer.onEvent(event);
3701
3730
  if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
3702
3731
  else if (event.type === "error") admissionFor(link, event)?.settle(false);
@@ -3717,13 +3746,21 @@ var AgentDirectChannel = class {
3717
3746
  onFrame,
3718
3747
  onLost,
3719
3748
  replayFrom: (next) => {
3720
- const nextBox = boxAddress(next.wsUrl);
3721
- const zeroed = next.lastSequence === 0 && cursor > 0;
3722
- if (nextBox === box && !zeroed) return cursor;
3723
- if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3724
- box = nextBox;
3725
- cursor = next.lastSequence;
3726
- 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);
3727
3764
  }
3728
3765
  }).then((outcome) => {
3729
3766
  if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
@@ -3733,11 +3770,17 @@ var AgentDirectChannel = class {
3733
3770
  }
3734
3771
  });
3735
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 };
3736
3778
  try {
3737
3779
  link.wire = await this.connect(taskId, mode, channel, {
3738
3780
  signal: abort.signal,
3739
3781
  onFrame,
3740
- onLost
3782
+ onLost,
3783
+ ...replay
3741
3784
  });
3742
3785
  } catch (error) {
3743
3786
  signal?.removeEventListener("abort", onAbort);
@@ -3820,7 +3863,8 @@ var AgentDirectChannel = class {
3820
3863
  onFrame: handlers.onFrame,
3821
3864
  onLost: handlers.onLost,
3822
3865
  signal,
3823
- ...replayFrom === void 0 ? {} : { replayFrom }
3866
+ ...typeof replayFrom === "function" ? { replayAfterHello: replayFrom } : {},
3867
+ ...typeof replayFrom === "number" ? { replayFrom } : {}
3824
3868
  });
3825
3869
  return { kind: "wire", wire };
3826
3870
  } catch (error) {
@@ -3969,6 +4013,7 @@ var AgentDirectChannel = class {
3969
4013
  const Socket = this.webSocket();
3970
4014
  if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
3971
4015
  const { signal, replayFrom } = options;
4016
+ let replayAfterHello = options.replayAfterHello;
3972
4017
  return new Promise((resolve, reject) => {
3973
4018
  const socket = new Socket(url);
3974
4019
  let opened = false;
@@ -4051,7 +4096,13 @@ var AgentDirectChannel = class {
4051
4096
  handlers.onmessage = (message) => {
4052
4097
  touch();
4053
4098
  const event = parseEvent(message.data);
4054
- 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));
4055
4106
  };
4056
4107
  handlers.onclose = (event) => {
4057
4108
  clearTimeout(timer);
@@ -4120,14 +4171,44 @@ function messageInput(prompt, options) {
4120
4171
  content: prompt,
4121
4172
  ...options.agentType ? { agentType: options.agentType } : {},
4122
4173
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4123
- mode: "steer"
4174
+ ...options.mode ? { mode: options.mode } : {}
4124
4175
  };
4125
4176
  }
4126
- function toolEventOf(payload, phase, timestamp) {
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) {
4127
4207
  return {
4128
4208
  tool: typeof payload?.name === "string" ? payload.name : "",
4129
4209
  phase,
4130
- timestamp,
4210
+ timestamp: event.timestamp,
4211
+ ...pieceIdentityOf(event, payload),
4131
4212
  ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4132
4213
  ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4133
4214
  ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
@@ -4139,7 +4220,65 @@ function epochOf(value) {
4139
4220
  const parsed = Date.parse(value);
4140
4221
  return Number.isNaN(parsed) ? void 0 : parsed;
4141
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
+ }
4142
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
+ }
4143
4282
  if (message.type === "TOOL_USE") {
4144
4283
  try {
4145
4284
  const payload = JSON.parse(message.content);
@@ -4150,11 +4289,14 @@ function toAgentTimelineItem(message) {
4150
4289
  tool: {
4151
4290
  tool: typeof payload.name === "string" ? payload.name : "",
4152
4291
  ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
4292
+ ...parentToolIdOf(payload.parentToolId ?? message.parentToolId),
4153
4293
  ...payload.input !== void 0 ? { input: payload.input } : {},
4154
4294
  ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
4155
4295
  phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
4156
4296
  },
4157
- at: message.createdAt
4297
+ at: message.createdAt,
4298
+ ...timelineIdentityOf(message),
4299
+ ...asObject2(message.subagent) ? { subagent: message.subagent } : {}
4158
4300
  };
4159
4301
  }
4160
4302
  } catch {
@@ -4165,9 +4307,18 @@ function toAgentTimelineItem(message) {
4165
4307
  kind: message.sender === "USER" ? "user" : "agent",
4166
4308
  text: message.content,
4167
4309
  at: message.createdAt,
4168
- ...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)
4169
4314
  };
4170
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
+ }
4171
4322
  function createAgentTaskSessionManager(options) {
4172
4323
  const sessions = /* @__PURE__ */ new Map();
4173
4324
  const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
@@ -4260,6 +4411,17 @@ var CoreAgentTaskSession = class {
4260
4411
  openingAwaitsStart = false;
4261
4412
  turnBaselineIds = /* @__PURE__ */ new Set();
4262
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;
4263
4425
  get taskId() {
4264
4426
  return this._taskId;
4265
4427
  }
@@ -4279,19 +4441,18 @@ var CoreAgentTaskSession = class {
4279
4441
  return this._content;
4280
4442
  }
4281
4443
  get queue() {
4282
- return [];
4444
+ return [...this.queueItems];
4283
4445
  }
4284
4446
  get subagents() {
4285
4447
  return [...this.subagentsById.values()];
4286
4448
  }
4287
4449
  send(prompt, options = {}) {
4288
4450
  this.requireOpen();
4289
- if (!prompt.trim()) return;
4290
- if (this.isBusy()) {
4291
- this.steer(prompt, options);
4292
- return;
4293
- }
4294
- 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;
4295
4456
  }
4296
4457
  sendAndWait(prompt, options = {}) {
4297
4458
  this.requireOpen();
@@ -4300,13 +4461,14 @@ var CoreAgentTaskSession = class {
4300
4461
  if (waiter.settled) return waiter.promise;
4301
4462
  const sendOptions = {
4302
4463
  ...options.agentType ? { agentType: options.agentType } : {},
4303
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4464
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4465
+ ...options.mode ? { mode: options.mode } : {}
4304
4466
  };
4305
4467
  if (this.isBusy()) {
4306
4468
  this.steer(prompt, sendOptions, waiter);
4307
4469
  return waiter.promise;
4308
4470
  }
4309
- this.startDispatch(prompt, sendOptions, waiter);
4471
+ this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
4310
4472
  return waiter.promise;
4311
4473
  }
4312
4474
  async cancel() {
@@ -4353,18 +4515,50 @@ var CoreAgentTaskSession = class {
4353
4515
  if (!this._taskId) return [];
4354
4516
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4355
4517
  ...options.limit !== void 0 ? { size: options.limit } : {},
4356
- sort: "createdAt,desc"
4518
+ sort: "createdAt,desc",
4519
+ kinds: "all"
4357
4520
  });
4358
4521
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4359
4522
  const history = this.history;
4360
4523
  this.emit("historyLoaded", { history });
4361
4524
  return history;
4362
4525
  }
4363
- editQueueItem() {
4526
+ editQueueItem(id, text) {
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
+ );
4364
4534
  }
4365
- removeQueueItem() {
4535
+ removeQueueItem(id) {
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
+ );
4366
4542
  }
4367
4543
  clearQueue() {
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;
4368
4562
  }
4369
4563
  stopSubagent(subagentId) {
4370
4564
  this.requireOpen();
@@ -4405,9 +4599,10 @@ var CoreAgentTaskSession = class {
4405
4599
  if (this.isClosed()) return false;
4406
4600
  await this.loadHistory();
4407
4601
  if (this.isClosed()) return false;
4602
+ this.openingCursor = historyCursorOf(this._history);
4408
4603
  await this.ensureChannel();
4409
4604
  if (this.isClosed()) return false;
4410
- this.setStatus("idle");
4605
+ if (this._status === "opening") this.setStatus("idle");
4411
4606
  return true;
4412
4607
  } catch (error) {
4413
4608
  if (this.isClosed()) return false;
@@ -4416,13 +4611,14 @@ var CoreAgentTaskSession = class {
4416
4611
  return false;
4417
4612
  }
4418
4613
  }
4419
- startDispatch(prompt, options, waiter) {
4614
+ startDispatch(prompt, options, clientMessageId, waiter) {
4615
+ this.sentTexts.set(clientMessageId, prompt);
4420
4616
  this.dispatching = true;
4421
4617
  let handedOver;
4422
4618
  this.handOff = new Promise((resolve) => {
4423
4619
  handedOver = resolve;
4424
4620
  });
4425
- const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
4621
+ const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4426
4622
  waiter?.reject(error);
4427
4623
  this.emitError("Failed to send Agent prompt", error);
4428
4624
  if (this._status === "streaming") {
@@ -4432,25 +4628,26 @@ var CoreAgentTaskSession = class {
4432
4628
  return false;
4433
4629
  }).finally(() => {
4434
4630
  handedOver();
4435
- this.dispatching = false;
4436
- if (this.dispatch === dispatch) this.dispatch = null;
4631
+ if (this.dispatch === dispatch) {
4632
+ this.dispatching = false;
4633
+ this.dispatch = null;
4634
+ }
4437
4635
  });
4438
4636
  this.dispatch = dispatch;
4439
4637
  }
4440
- async dispatchSend(prompt, options, handedOver, waiter) {
4638
+ async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
4441
4639
  if (this.openingPromise && !await this.openingPromise) {
4442
4640
  throw new Error("Agent task session could not be opened.");
4443
4641
  }
4444
- if (this.isClosed() || waiter?.settled) return false;
4642
+ if (this.isClosed()) return false;
4445
4643
  await this.ensureTask();
4446
4644
  const input = messageInput(prompt, options);
4447
4645
  if (this.isClosed()) {
4448
- await this.sendInput(input).catch(() => void 0);
4646
+ await this.handOver(input, clientMessageId).catch(() => void 0);
4449
4647
  return false;
4450
4648
  }
4451
- if (waiter?.settled) return false;
4452
4649
  await this.ensureChannel();
4453
- if (this.isClosed() || waiter?.settled) return false;
4650
+ if (this.isClosed()) return false;
4454
4651
  await this.captureTurnBaseline();
4455
4652
  this._content = "";
4456
4653
  this.recoveryUsed = false;
@@ -4460,13 +4657,13 @@ var CoreAgentTaskSession = class {
4460
4657
  this.activeWaiter = waiter;
4461
4658
  this.setStatus("streaming");
4462
4659
  this.emit("turnStart", {});
4463
- this.openingMessageId = newClientMessageId();
4660
+ this.openingMessageId = clientMessageId;
4464
4661
  this.openingAwaitsStart = true;
4465
4662
  const { admitted, direct } = await this.handOver(input, this.openingMessageId);
4466
4663
  if (!direct) this.openingAwaitsStart = false;
4467
4664
  handedOver();
4468
4665
  if (!await admitted) return false;
4469
- this.emit("accepted", {});
4666
+ this.acceptOnce(clientMessageId);
4470
4667
  return true;
4471
4668
  }
4472
4669
  // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
@@ -4490,6 +4687,7 @@ var CoreAgentTaskSession = class {
4490
4687
  } else {
4491
4688
  this.strayedSteers.push(steered);
4492
4689
  }
4690
+ this.sentTexts.set(steered.clientMessageId, prompt);
4493
4691
  const input = messageInput(prompt, options);
4494
4692
  this.pendingSteers += 1;
4495
4693
  const handed = this.handOff.then(async () => {
@@ -4511,7 +4709,7 @@ var CoreAgentTaskSession = class {
4511
4709
  return;
4512
4710
  }
4513
4711
  if (!steered.queued) this.steerTaken(steered);
4514
- this.emit("accepted", {});
4712
+ this.acceptOnce(steered.clientMessageId);
4515
4713
  }).catch((error) => {
4516
4714
  this.forgetSteer(steered);
4517
4715
  waiter?.reject(error);
@@ -4519,6 +4717,7 @@ var CoreAgentTaskSession = class {
4519
4717
  }).finally(() => {
4520
4718
  this.pendingSteers -= 1;
4521
4719
  });
4720
+ return steered.clientMessageId;
4522
4721
  }
4523
4722
  // The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
4524
4723
  // of its own, when that one ended before the box got to the message.
@@ -4565,7 +4764,7 @@ var CoreAgentTaskSession = class {
4565
4764
  else if (steered.waiter) settle(steered.waiter);
4566
4765
  }
4567
4766
  }
4568
- openTurnFor(waiter) {
4767
+ openTurnFor(waiter, start = {}) {
4569
4768
  if (this.isClosed()) return;
4570
4769
  if (this._status !== "streaming" && this._status !== "cancelled") {
4571
4770
  this._content = "";
@@ -4576,7 +4775,7 @@ var CoreAgentTaskSession = class {
4576
4775
  this.turnBaselineIds = new Set(this._history.map((item) => item.id));
4577
4776
  void this.captureTurnBaseline().catch(() => void 0);
4578
4777
  this.setStatus("streaming");
4579
- this.emit("turnStart", {});
4778
+ this.emit("turnStart", start);
4580
4779
  }
4581
4780
  if (!waiter) return;
4582
4781
  if (!this.activeWaiter) this.activeWaiter = waiter;
@@ -4619,6 +4818,8 @@ var CoreAgentTaskSession = class {
4619
4818
  const abort = new AbortController();
4620
4819
  this.connectionAbort = abort;
4621
4820
  const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
4821
+ const historyCursor = this.openingCursor;
4822
+ this.openingCursor = void 0;
4622
4823
  this.connectionPromise = source.open(
4623
4824
  this._taskId,
4624
4825
  {
@@ -4626,7 +4827,8 @@ var CoreAgentTaskSession = class {
4626
4827
  onDisconnect: (error) => this.handleDisconnect(error)
4627
4828
  },
4628
4829
  abort.signal,
4629
- this.options.transport
4830
+ this.options.transport,
4831
+ historyCursor
4630
4832
  ).then((connection) => {
4631
4833
  if (this.isClosed() || this._status === "error") {
4632
4834
  connection.close();
@@ -4672,7 +4874,8 @@ var CoreAgentTaskSession = class {
4672
4874
  if (!this._taskId) return;
4673
4875
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4674
4876
  size: 100,
4675
- sort: "createdAt,desc"
4877
+ sort: "createdAt,desc",
4878
+ kinds: "all"
4676
4879
  });
4677
4880
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
4678
4881
  }
@@ -4680,11 +4883,13 @@ var CoreAgentTaskSession = class {
4680
4883
  if (!this._taskId) return false;
4681
4884
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4682
4885
  size: 100,
4683
- sort: "createdAt,desc"
4886
+ sort: "createdAt,desc",
4887
+ kinds: "all"
4684
4888
  });
4685
4889
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4686
4890
  this.emit("historyLoaded", { history: this.history });
4687
- const recovered = page.content.find(
4891
+ const rows = page.content.filter(isChatRow);
4892
+ const recovered = rows.find(
4688
4893
  (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
4689
4894
  );
4690
4895
  if (!recovered) {
@@ -4693,7 +4898,7 @@ var CoreAgentTaskSession = class {
4693
4898
  this.endedPollsWithoutRow += 1;
4694
4899
  if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
4695
4900
  }
4696
- const newest = page.content.find(
4901
+ const newest = rows.find(
4697
4902
  (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4698
4903
  );
4699
4904
  if (!newest) return false;
@@ -4737,11 +4942,13 @@ var CoreAgentTaskSession = class {
4737
4942
  );
4738
4943
  }
4739
4944
  const turnRunning = this._status === "streaming" || this._status === "cancelled";
4740
- const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content } : {
4945
+ const id = clientMessageId === void 0 ? {} : { clientMessageId };
4946
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
4741
4947
  type: "message",
4742
4948
  content: input.content,
4743
4949
  ...input.agentType ? { agentType: input.agentType } : {},
4744
- ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
4950
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
4951
+ ...id
4745
4952
  };
4746
4953
  await this.dependencies.tasks.sendInput(this._taskId, rest);
4747
4954
  return { admitted: Promise.resolve(true), direct: false };
@@ -4761,6 +4968,7 @@ var CoreAgentTaskSession = class {
4761
4968
  return;
4762
4969
  }
4763
4970
  const lifecycle = asObject2(payload?.lifecycle);
4971
+ if (this.endsQueuedMessage(event, payload, lifecycle)) return;
4764
4972
  if (this.repeatsTheRunningTurn(event, lifecycle)) return;
4765
4973
  if (event.type === "stepStart" || event.type === "steer") {
4766
4974
  const id = lifecycle?.clientMessageId;
@@ -4777,35 +4985,70 @@ var CoreAgentTaskSession = class {
4777
4985
  // texto e o que faz a resposta recuperada aparecer; sem isso ela chega e morre aqui.
4778
4986
  case "textDelta":
4779
4987
  case "textChunk":
4780
- this.consumeDelta(payload, "text");
4988
+ this.consumeDelta(event, payload, "text");
4781
4989
  break;
4782
4990
  case "thinking":
4783
- this.consumeDelta(payload, "thinking");
4991
+ this.consumeDelta(event, payload, "thinking");
4784
4992
  break;
4785
4993
  case "toolCall":
4786
- if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call", event.timestamp);
4994
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(event, payload, "call");
4787
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.
4788
4999
  case "toolResult":
4789
- if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "result", event.timestamp);
5000
+ this.emitTool(event, payload, "result");
4790
5001
  break;
4791
5002
  case "workspace":
4792
- 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
+ });
4793
5008
  break;
4794
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);
4795
5021
  this.steerOpenedBy(asObject2(payload?.lifecycle));
5022
+ this.acceptNamed(lifecycle?.clientMessageId);
4796
5023
  break;
4797
5024
  case "steer":
5025
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
5026
+ this.leaveQueue(lifecycle?.clientMessageId);
4798
5027
  this.steerOpenedBy(lifecycle);
5028
+ this.acceptNamed(lifecycle?.clientMessageId);
4799
5029
  this.emit("steered", {
4800
5030
  text: typeof payload?.text === "string" ? payload.text : "",
4801
- messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
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 } : {}
4802
5035
  });
4803
5036
  break;
5037
+ case "backgroundTasks":
5038
+ this._backgroundTasks = backgroundTasksOf(payload?.tasks);
5039
+ this.emit("backgroundTasks", { tasks: this._backgroundTasks });
5040
+ break;
4804
5041
  case "messageQueued":
5042
+ if (payload?.cancelled === true) {
5043
+ this.cancelQueued(payload, lifecycle);
5044
+ break;
5045
+ }
5046
+ this.applyQueued(event, payload, lifecycle);
4805
5047
  this.steerQueuedBy(asObject2(payload?.lifecycle));
5048
+ this.acceptNamed(lifecycle?.clientMessageId);
4806
5049
  break;
4807
5050
  case "subagentUpdate":
4808
- this.applySubagent(payload);
5051
+ this.applySubagent(event, payload);
4809
5052
  break;
4810
5053
  case "providerUsage": {
4811
5054
  const usage = providerUsageOf(payload);
@@ -4818,9 +5061,14 @@ var CoreAgentTaskSession = class {
4818
5061
  const usage = agentTurnUsageOf(payload?.usage);
4819
5062
  const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
4820
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
+ };
4821
5069
  if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
4822
5070
  this.rememberFinishedTurn(lifecycle2);
4823
- this.finishTurn("interrupted", usage);
5071
+ this.finishTurn("interrupted", usage, end);
4824
5072
  break;
4825
5073
  }
4826
5074
  if (reason === "stop" || reason === "endTurn") {
@@ -4835,7 +5083,7 @@ var CoreAgentTaskSession = class {
4835
5083
  });
4836
5084
  }
4837
5085
  } else {
4838
- this.finishTurn(reason, usage);
5086
+ this.finishTurn(reason, usage, end);
4839
5087
  }
4840
5088
  }
4841
5089
  break;
@@ -4843,8 +5091,9 @@ var CoreAgentTaskSession = class {
4843
5091
  case "error": {
4844
5092
  const code = typeof payload?.code === "string" ? payload.code : void 0;
4845
5093
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
4846
- this.emit("error", { ...code ? { code } : {}, error: message });
5094
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
4847
5095
  if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5096
+ if (typeof payload?.command === "string") break;
4848
5097
  const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
4849
5098
  if (typeof refused === "string") {
4850
5099
  if (refused !== this.openingMessageId) {
@@ -4860,10 +5109,119 @@ var CoreAgentTaskSession = class {
4860
5109
  }
4861
5110
  break;
4862
5111
  }
5112
+ case "approval":
5113
+ case "user_input_request":
5114
+ this.liveRequest(event, payload);
5115
+ break;
4863
5116
  default:
4864
5117
  break;
4865
5118
  }
4866
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
+ }
4867
5225
  repeatsTheRunningTurn(event, lifecycle) {
4868
5226
  if (this._status !== "streaming" && this._status !== "cancelled") return false;
4869
5227
  const turnId = lifecycle?.turnId;
@@ -4891,7 +5249,7 @@ var CoreAgentTaskSession = class {
4891
5249
  this.finishedTurnIds.push(turnId);
4892
5250
  if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
4893
5251
  }
4894
- consumeDelta(payload, kind) {
5252
+ consumeDelta(event, payload, kind) {
4895
5253
  const lifecycle = asObject2(payload?.lifecycle);
4896
5254
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4897
5255
  if (turnId && this.finishedTurnIds.includes(turnId)) return;
@@ -4903,40 +5261,160 @@ var CoreAgentTaskSession = class {
4903
5261
  this.emit("turnStart", {});
4904
5262
  }
4905
5263
  if (kind === "text") this._content += text;
4906
- this.emit("delta", { delta: text, kind });
5264
+ this.liveText(event, payload, kind);
5265
+ this.emit("delta", {
5266
+ delta: text,
5267
+ kind,
5268
+ ...itemDeltaOf(payload),
5269
+ ...pieceIdentityOf(event, payload)
5270
+ });
5271
+ }
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
+ );
4907
5351
  }
4908
- emitTool(payload, phase, timestamp) {
4909
- this.emit("tool", toolEventOf(payload, phase, timestamp));
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
+ );
4910
5374
  }
4911
- // A child thread's frames are the subagent's conversation: they open no turn, settle no message
4912
- // and never reach the chat's `content`.
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.
4913
5378
  handleSubagentFrame(event, payload) {
4914
5379
  const parentToolId = payload.parentToolId;
4915
5380
  switch (event.type) {
4916
5381
  case "textDelta":
4917
5382
  case "textChunk":
4918
- case "thinking":
4919
- this.emit("subagentDelta", {
4920
- parentToolId,
4921
- delta: typeof payload.text === "string" ? payload.text : "",
4922
- kind: event.type === "thinking" ? "thinking" : "text"
4923
- });
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 });
4924
5391
  break;
5392
+ }
4925
5393
  case "toolCall":
4926
- case "toolResult":
4927
- this.emit("subagentTool", {
4928
- ...toolEventOf(payload, event.type === "toolCall" ? "call" : "result", event.timestamp),
5394
+ case "toolResult": {
5395
+ const tool = {
5396
+ ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
4929
5397
  parentToolId
4930
- });
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);
4931
5407
  break;
4932
5408
  default:
4933
5409
  break;
4934
5410
  }
4935
5411
  }
4936
- applySubagent(payload) {
5412
+ applySubagent(event, payload) {
4937
5413
  const subagentId = payload?.subagentId;
4938
5414
  const toolId = payload?.toolId;
4939
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);
4940
5418
  const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
4941
5419
  if (status === void 0) return;
4942
5420
  const startedAt = epochOf(payload?.startedAt);
@@ -4951,9 +5429,26 @@ var CoreAgentTaskSession = class {
4951
5429
  ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
4952
5430
  };
4953
5431
  this.subagentsById.set(subagentId, subagent);
4954
- this.emit("subagent", 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) });
4955
5450
  }
4956
- finishTurn(reason, usage) {
5451
+ finishTurn(reason, usage, end = {}) {
4957
5452
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4958
5453
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
4959
5454
  this.cancelTimer = null;
@@ -4971,7 +5466,8 @@ var CoreAgentTaskSession = class {
4971
5466
  task,
4972
5467
  content: this._content,
4973
5468
  reason,
4974
- ...usage ? { usage } : {}
5469
+ ...usage ? { usage } : {},
5470
+ ...end
4975
5471
  };
4976
5472
  this.emit("turnEnd", result);
4977
5473
  this.activeWaiter?.resolve(result);