@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.js CHANGED
@@ -942,7 +942,8 @@ function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFact
942
942
  if (typeof channel.wsUrl !== "string" || !channel.wsUrl) invalidField(context, "wsUrl", errors);
943
943
  return {
944
944
  wsUrl: channel.wsUrl,
945
- lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0
945
+ lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0,
946
+ ...isInteger(channel.boxLog) ? { boxLog: channel.boxLog } : {}
946
947
  };
947
948
  }
948
949
  function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
@@ -1614,7 +1615,12 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1614
1615
  const page = expectPage(
1615
1616
  await transport.request(`${path(id)}/messages`, {
1616
1617
  method: "GET",
1617
- params: { page: options.page, size: options.size, sort: options.sort }
1618
+ params: {
1619
+ page: options.page,
1620
+ size: options.size,
1621
+ sort: options.sort,
1622
+ kinds: options.kinds
1623
+ }
1618
1624
  }),
1619
1625
  context,
1620
1626
  errors
@@ -3246,7 +3252,7 @@ function newClientMessageId() {
3246
3252
  }
3247
3253
  function admissionFor(link, event) {
3248
3254
  const payload = asObject(event.payload);
3249
- if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
3255
+ if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0 || payload?.command !== void 0)) {
3250
3256
  return void 0;
3251
3257
  }
3252
3258
  const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
@@ -3292,6 +3298,14 @@ function boxAddress(wsUrl) {
3292
3298
  const url = new URL(wsUrl);
3293
3299
  return `${url.origin}${url.pathname}`;
3294
3300
  }
3301
+ function helloOf(event) {
3302
+ if (event.type !== "hello") return void 0;
3303
+ const payload = asObject(event.payload);
3304
+ const threadId = payload?.threadId;
3305
+ const lastSequence = payload?.lastSequence;
3306
+ if (typeof threadId !== "string" || typeof lastSequence !== "number") return void 0;
3307
+ return { threadId, lastSequence };
3308
+ }
3295
3309
  function boxRoute(wsUrl, route) {
3296
3310
  const url = new URL(wsUrl);
3297
3311
  url.protocol = url.protocol === "wss:" ? "https:" : "http:";
@@ -3385,8 +3399,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3385
3399
  "steer",
3386
3400
  "textDelta",
3387
3401
  "thinking",
3388
- "toolCall",
3389
- "toolResult"
3402
+ "toolCall"
3390
3403
  ]);
3391
3404
  var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3392
3405
  function turnAfter(event, inTurn) {
@@ -3399,6 +3412,12 @@ function turnAfter(event, inTurn) {
3399
3412
  }
3400
3413
  return inTurn;
3401
3414
  }
3415
+ function followsTurn(link, event) {
3416
+ if (event.type === "messageQueued") return false;
3417
+ if (event.type !== "stepFinish" && event.type !== "error") return true;
3418
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3419
+ return typeof turnId !== "string" || link.turnId === void 0 || turnId === link.turnId;
3420
+ }
3402
3421
  function lostTurnFrame(turnId) {
3403
3422
  return {
3404
3423
  type: "stepFinish",
@@ -3470,7 +3489,7 @@ var AgentDirectChannel = class {
3470
3489
  enabled() {
3471
3490
  return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
3472
3491
  }
3473
- async open(taskId, observer, signal, transport) {
3492
+ async open(taskId, observer, signal, transport, historyCursor) {
3474
3493
  if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
3475
3494
  const mode = this.modeFor(transport);
3476
3495
  const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
@@ -3480,7 +3499,7 @@ var AgentDirectChannel = class {
3480
3499
  return this.fallback.open(taskId, observer, signal, transport);
3481
3500
  }
3482
3501
  try {
3483
- return await this.openDirect(taskId, mode, answer, observer, signal);
3502
+ return await this.openDirect(taskId, mode, answer, observer, signal, historyCursor);
3484
3503
  } catch (error) {
3485
3504
  if (signal?.aborted) throw error;
3486
3505
  observer.onEvent(
@@ -3605,26 +3624,36 @@ var AgentDirectChannel = class {
3605
3624
  * only when the redial gives up, when the Copilot no longer offers the box, or when there is
3606
3625
  * no turn to resume: dialing an idle box again would wake it for nobody.
3607
3626
  *
3608
- * Opening never asks for an older replay. What an idle chat missed is history, which the
3609
- * session loads by REST; replaying from an older cursor would put old turns on screen as live
3610
- * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3627
+ * Opening asks for the replay from where the session's history ends, with the same request the
3628
+ * redial makes: what the history has, the replay does not repeat, and what the Copilot has not
3629
+ * recorded yet (the turn running now, or one it is still behind on) comes in the replay before
3630
+ * any live frame. When the Copilot says the box log is another one than the history's newest,
3631
+ * nothing of it is in the history and the replay starts at its beginning. A history with no
3632
+ * box sequence asks for nothing, and the open starts at the sequence the Copilot reported.
3611
3633
  */
3612
- async openDirect(taskId, mode, channel, observer, signal) {
3634
+ async openDirect(taskId, mode, channel, observer, signal, historyCursor) {
3613
3635
  const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
3614
3636
  let box = boxAddress(channel.wsUrl);
3615
- let cursor = channel.lastSequence;
3637
+ let thread;
3638
+ const otherLog = historyCursor?.boxLog !== void 0 && channel.boxLog !== void 0 && historyCursor.boxLog !== channel.boxLog;
3639
+ const historyFrom = historyCursor === void 0 ? void 0 : otherLog ? 0 : historyCursor.sequence;
3640
+ let cursor = historyFrom ?? channel.lastSequence;
3616
3641
  const abort = new AbortController();
3617
3642
  const onAbort = () => abort.abort(signal?.reason);
3618
3643
  signal?.addEventListener("abort", onAbort, { once: true });
3619
3644
  const onFrame = (event) => {
3645
+ const hello = helloOf(event);
3646
+ if (hello) thread = hello.threadId;
3620
3647
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3621
3648
  if (isSubagentFrame(event)) {
3622
3649
  observer.onEvent(event);
3623
3650
  return;
3624
3651
  }
3625
- const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3626
- if (typeof turnId === "string") link.turnId = turnId;
3627
- link.inTurn = turnAfter(event, link.inTurn);
3652
+ if (followsTurn(link, event)) {
3653
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3654
+ if (typeof turnId === "string" && event.type !== "toolResult") link.turnId = turnId;
3655
+ link.inTurn = turnAfter(event, link.inTurn);
3656
+ }
3628
3657
  observer.onEvent(event);
3629
3658
  if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
3630
3659
  else if (event.type === "error") admissionFor(link, event)?.settle(false);
@@ -3645,13 +3674,21 @@ var AgentDirectChannel = class {
3645
3674
  onFrame,
3646
3675
  onLost,
3647
3676
  replayFrom: (next) => {
3648
- const nextBox = boxAddress(next.wsUrl);
3649
- const zeroed = next.lastSequence === 0 && cursor > 0;
3650
- if (nextBox === box && !zeroed) return cursor;
3651
- if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3652
- box = nextBox;
3653
- cursor = next.lastSequence;
3654
- return void 0;
3677
+ const decide = (hello) => {
3678
+ const nextBox = boxAddress(next.wsUrl);
3679
+ const zeroed = next.lastSequence === 0 && cursor > 0;
3680
+ const otherBox = hello !== void 0 && (hello.threadId !== thread || hello.lastSequence < cursor);
3681
+ if (nextBox === box && !zeroed && !otherBox) return cursor;
3682
+ if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3683
+ box = nextBox;
3684
+ if (mode === "websocket") {
3685
+ cursor = 0;
3686
+ return 0;
3687
+ }
3688
+ cursor = next.lastSequence;
3689
+ return void 0;
3690
+ };
3691
+ return mode === "websocket" && thread !== void 0 ? decide : decide(void 0);
3655
3692
  }
3656
3693
  }).then((outcome) => {
3657
3694
  if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
@@ -3661,11 +3698,17 @@ var AgentDirectChannel = class {
3661
3698
  }
3662
3699
  });
3663
3700
  };
3701
+ const afterHello = (hello) => {
3702
+ if (hello !== void 0 && hello.lastSequence < cursor) cursor = 0;
3703
+ return cursor;
3704
+ };
3705
+ const replay = historyFrom === void 0 ? {} : mode === "websocket" ? { replayAfterHello: afterHello } : { replayFrom: historyFrom };
3664
3706
  try {
3665
3707
  link.wire = await this.connect(taskId, mode, channel, {
3666
3708
  signal: abort.signal,
3667
3709
  onFrame,
3668
- onLost
3710
+ onLost,
3711
+ ...replay
3669
3712
  });
3670
3713
  } catch (error) {
3671
3714
  signal?.removeEventListener("abort", onAbort);
@@ -3748,7 +3791,8 @@ var AgentDirectChannel = class {
3748
3791
  onFrame: handlers.onFrame,
3749
3792
  onLost: handlers.onLost,
3750
3793
  signal,
3751
- ...replayFrom === void 0 ? {} : { replayFrom }
3794
+ ...typeof replayFrom === "function" ? { replayAfterHello: replayFrom } : {},
3795
+ ...typeof replayFrom === "number" ? { replayFrom } : {}
3752
3796
  });
3753
3797
  return { kind: "wire", wire };
3754
3798
  } catch (error) {
@@ -3897,6 +3941,7 @@ var AgentDirectChannel = class {
3897
3941
  const Socket = this.webSocket();
3898
3942
  if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
3899
3943
  const { signal, replayFrom } = options;
3944
+ let replayAfterHello = options.replayAfterHello;
3900
3945
  return new Promise((resolve, reject) => {
3901
3946
  const socket = new Socket(url);
3902
3947
  let opened = false;
@@ -3979,7 +4024,13 @@ var AgentDirectChannel = class {
3979
4024
  handlers.onmessage = (message) => {
3980
4025
  touch();
3981
4026
  const event = parseEvent(message.data);
3982
- if (event) options.onFrame(asDelta(event));
4027
+ if (!event) return;
4028
+ if (replayAfterHello) {
4029
+ const fromSequence = replayAfterHello(helloOf(event));
4030
+ replayAfterHello = void 0;
4031
+ if (fromSequence !== void 0) send(JSON.stringify({ type: "replay", fromSequence }));
4032
+ }
4033
+ options.onFrame(asDelta(event));
3983
4034
  };
3984
4035
  handlers.onclose = (event) => {
3985
4036
  clearTimeout(timer);
@@ -4048,14 +4099,44 @@ function messageInput(prompt, options) {
4048
4099
  content: prompt,
4049
4100
  ...options.agentType ? { agentType: options.agentType } : {},
4050
4101
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4051
- mode: "steer"
4102
+ ...options.mode ? { mode: options.mode } : {}
4052
4103
  };
4053
4104
  }
4054
- function toolEventOf(payload, phase, timestamp) {
4105
+ function backgroundTasksOf(value) {
4106
+ if (!Array.isArray(value)) return [];
4107
+ return value.flatMap((entry) => {
4108
+ const task = asObject2(entry);
4109
+ if (typeof task?.taskId !== "string" || typeof task.kind !== "string") return [];
4110
+ return [
4111
+ {
4112
+ taskId: task.taskId,
4113
+ kind: task.kind,
4114
+ ...typeof task.description === "string" ? { description: task.description } : {},
4115
+ ...typeof task.childThreadId === "string" ? { childThreadId: task.childThreadId } : {}
4116
+ }
4117
+ ];
4118
+ });
4119
+ }
4120
+ function pieceIdentityOf(event, payload) {
4121
+ const turnId = asObject2(payload?.lifecycle)?.turnId;
4122
+ return {
4123
+ ...sequenceOf(event),
4124
+ ...typeof payload?.itemId === "string" ? { itemId: payload.itemId } : {},
4125
+ ...typeof turnId === "string" ? { turnId } : {}
4126
+ };
4127
+ }
4128
+ function itemDeltaOf(payload) {
4129
+ return typeof payload?.itemDelta === "string" ? { itemDelta: payload.itemDelta } : {};
4130
+ }
4131
+ function sequenceOf(event) {
4132
+ return typeof event.sequence === "number" ? { sequence: event.sequence } : {};
4133
+ }
4134
+ function toolEventOf(event, payload, phase) {
4055
4135
  return {
4056
4136
  tool: typeof payload?.name === "string" ? payload.name : "",
4057
4137
  phase,
4058
- timestamp,
4138
+ timestamp: event.timestamp,
4139
+ ...pieceIdentityOf(event, payload),
4059
4140
  ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4060
4141
  ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4061
4142
  ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
@@ -4067,7 +4148,65 @@ function epochOf(value) {
4067
4148
  const parsed = Date.parse(value);
4068
4149
  return Number.isNaN(parsed) ? void 0 : parsed;
4069
4150
  }
4151
+ function timelineIdentityOf(message) {
4152
+ return {
4153
+ ...typeof message.sequence === "number" ? { sequence: message.sequence } : {},
4154
+ ...typeof message.lastSequence === "number" ? { lastSequence: message.lastSequence } : {},
4155
+ ...typeof message.boxLog === "number" ? { boxLog: message.boxLog } : {},
4156
+ ...typeof message.itemId === "string" ? { itemId: message.itemId } : {},
4157
+ ...typeof message.reason === "string" ? { reason: message.reason } : {}
4158
+ };
4159
+ }
4160
+ function historyCursorOf(history) {
4161
+ const newest = [...history].reverse().find((item) => typeof item.sequence === "number");
4162
+ if (!newest) return void 0;
4163
+ let sequence = 0;
4164
+ for (const item of history) {
4165
+ if (item.boxLog === newest.boxLog && typeof item.sequence === "number") {
4166
+ sequence = Math.max(sequence, item.lastSequence ?? item.sequence);
4167
+ }
4168
+ }
4169
+ return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4170
+ }
4171
+ function isChatRow(message) {
4172
+ return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4173
+ }
4174
+ var REQUEST_ROW_KINDS = {
4175
+ APPROVAL: "approval",
4176
+ USER_INPUT_REQUEST: "userInputRequest"
4177
+ };
4178
+ function parseJson(text) {
4179
+ try {
4180
+ return JSON.parse(text);
4181
+ } catch {
4182
+ return void 0;
4183
+ }
4184
+ }
4070
4185
  function toAgentTimelineItem(message) {
4186
+ if (message.type === "REASONING") {
4187
+ return {
4188
+ id: message.id,
4189
+ kind: "reasoning",
4190
+ text: message.content,
4191
+ at: message.createdAt,
4192
+ ...timelineIdentityOf(message),
4193
+ ...parentToolIdOf(message.parentToolId)
4194
+ };
4195
+ }
4196
+ const requestKind = REQUEST_ROW_KINDS[message.type];
4197
+ if (requestKind) {
4198
+ const payload = asObject2(parseJson(message.content));
4199
+ if (payload) {
4200
+ return {
4201
+ id: message.id,
4202
+ kind: requestKind,
4203
+ payload,
4204
+ at: message.createdAt,
4205
+ ...timelineIdentityOf(message),
4206
+ ...parentToolIdOf(message.parentToolId)
4207
+ };
4208
+ }
4209
+ }
4071
4210
  if (message.type === "TOOL_USE") {
4072
4211
  try {
4073
4212
  const payload = JSON.parse(message.content);
@@ -4078,11 +4217,14 @@ function toAgentTimelineItem(message) {
4078
4217
  tool: {
4079
4218
  tool: typeof payload.name === "string" ? payload.name : "",
4080
4219
  ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
4220
+ ...parentToolIdOf(payload.parentToolId ?? message.parentToolId),
4081
4221
  ...payload.input !== void 0 ? { input: payload.input } : {},
4082
4222
  ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
4083
4223
  phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
4084
4224
  },
4085
- at: message.createdAt
4225
+ at: message.createdAt,
4226
+ ...timelineIdentityOf(message),
4227
+ ...asObject2(message.subagent) ? { subagent: message.subagent } : {}
4086
4228
  };
4087
4229
  }
4088
4230
  } catch {
@@ -4093,9 +4235,18 @@ function toAgentTimelineItem(message) {
4093
4235
  kind: message.sender === "USER" ? "user" : "agent",
4094
4236
  text: message.content,
4095
4237
  at: message.createdAt,
4096
- ...message.usage ? { usage: message.usage } : {}
4238
+ ...message.usage ? { usage: message.usage } : {},
4239
+ ...timelineIdentityOf(message),
4240
+ ...typeof message.clientMessageId === "string" ? { clientMessageId: message.clientMessageId } : {},
4241
+ ...parentToolIdOf(message.parentToolId)
4097
4242
  };
4098
4243
  }
4244
+ function liveAtOf(event) {
4245
+ return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
4246
+ }
4247
+ function parentToolIdOf(value) {
4248
+ return typeof value === "string" ? { parentToolId: value } : {};
4249
+ }
4099
4250
  function createAgentTaskSessionManager(options) {
4100
4251
  const sessions = /* @__PURE__ */ new Map();
4101
4252
  const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
@@ -4188,6 +4339,17 @@ var CoreAgentTaskSession = class {
4188
4339
  openingAwaitsStart = false;
4189
4340
  turnBaselineIds = /* @__PURE__ */ new Set();
4190
4341
  subagentsById = /* @__PURE__ */ new Map();
4342
+ subagentSequences = /* @__PURE__ */ new Map();
4343
+ queueItems = [];
4344
+ _backgroundTasks = [];
4345
+ /** The text of each message this session sent, by its `clientMessageId`. */
4346
+ sentTexts = /* @__PURE__ */ new Map();
4347
+ // Messages of this session `accepted` was already emitted for. The frame that names a message
4348
+ // emits it in its place in the stream, so a turn delivered in one tick gives the same events as
4349
+ // one spaced out; the admission the send awaits only covers a box or a Copilot that names none.
4350
+ acceptedIds = [];
4351
+ // Taken by the first channel of `session({ taskId })`; no later channel asks for a replay.
4352
+ openingCursor;
4191
4353
  get taskId() {
4192
4354
  return this._taskId;
4193
4355
  }
@@ -4207,19 +4369,18 @@ var CoreAgentTaskSession = class {
4207
4369
  return this._content;
4208
4370
  }
4209
4371
  get queue() {
4210
- return [];
4372
+ return [...this.queueItems];
4211
4373
  }
4212
4374
  get subagents() {
4213
4375
  return [...this.subagentsById.values()];
4214
4376
  }
4215
4377
  send(prompt, options = {}) {
4216
4378
  this.requireOpen();
4217
- if (!prompt.trim()) return;
4218
- if (this.isBusy()) {
4219
- this.steer(prompt, options);
4220
- return;
4221
- }
4222
- this.startDispatch(prompt, options);
4379
+ if (!prompt.trim()) return void 0;
4380
+ if (this.isBusy()) return this.steer(prompt, options);
4381
+ const clientMessageId = newClientMessageId();
4382
+ this.startDispatch(prompt, options, clientMessageId);
4383
+ return clientMessageId;
4223
4384
  }
4224
4385
  sendAndWait(prompt, options = {}) {
4225
4386
  this.requireOpen();
@@ -4228,13 +4389,14 @@ var CoreAgentTaskSession = class {
4228
4389
  if (waiter.settled) return waiter.promise;
4229
4390
  const sendOptions = {
4230
4391
  ...options.agentType ? { agentType: options.agentType } : {},
4231
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4392
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4393
+ ...options.mode ? { mode: options.mode } : {}
4232
4394
  };
4233
4395
  if (this.isBusy()) {
4234
4396
  this.steer(prompt, sendOptions, waiter);
4235
4397
  return waiter.promise;
4236
4398
  }
4237
- this.startDispatch(prompt, sendOptions, waiter);
4399
+ this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
4238
4400
  return waiter.promise;
4239
4401
  }
4240
4402
  async cancel() {
@@ -4281,18 +4443,50 @@ var CoreAgentTaskSession = class {
4281
4443
  if (!this._taskId) return [];
4282
4444
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4283
4445
  ...options.limit !== void 0 ? { size: options.limit } : {},
4284
- sort: "createdAt,desc"
4446
+ sort: "createdAt,desc",
4447
+ kinds: "all"
4285
4448
  });
4286
4449
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4287
4450
  const history = this.history;
4288
4451
  this.emit("historyLoaded", { history });
4289
4452
  return history;
4290
4453
  }
4291
- editQueueItem() {
4454
+ editQueueItem(id, text) {
4455
+ this.requireOpen();
4456
+ if (this.sentTexts.has(id)) this.sentTexts.set(id, text);
4457
+ void this.sendInput({ type: "queued-run.edit", clientMessageId: id, text }).catch(
4458
+ (error) => {
4459
+ this.emitError("Failed to edit the queued Agent message", error);
4460
+ }
4461
+ );
4292
4462
  }
4293
- removeQueueItem() {
4463
+ removeQueueItem(id) {
4464
+ this.requireOpen();
4465
+ void this.sendInput({ type: "queued-run.cancel", clientMessageId: id }).catch(
4466
+ (error) => {
4467
+ this.emitError("Failed to remove the queued Agent message", error);
4468
+ }
4469
+ );
4294
4470
  }
4295
4471
  clearQueue() {
4472
+ for (const item of this.queueItems) this.removeQueueItem(item.id);
4473
+ }
4474
+ steerQueueItem(id) {
4475
+ this.requireOpen();
4476
+ void this.sendInput({ type: "queued-message.promote-to-steer", clientMessageId: id }).catch(
4477
+ (error) => {
4478
+ this.emitError("Failed to steer the queued Agent message", error);
4479
+ }
4480
+ );
4481
+ }
4482
+ resumeQueue() {
4483
+ this.requireOpen();
4484
+ void this.sendInput({ type: "queue.resume" }).catch((error) => {
4485
+ this.emitError("Failed to resume the Agent queue", error);
4486
+ });
4487
+ }
4488
+ get backgroundTasks() {
4489
+ return this._backgroundTasks;
4296
4490
  }
4297
4491
  stopSubagent(subagentId) {
4298
4492
  this.requireOpen();
@@ -4333,9 +4527,10 @@ var CoreAgentTaskSession = class {
4333
4527
  if (this.isClosed()) return false;
4334
4528
  await this.loadHistory();
4335
4529
  if (this.isClosed()) return false;
4530
+ this.openingCursor = historyCursorOf(this._history);
4336
4531
  await this.ensureChannel();
4337
4532
  if (this.isClosed()) return false;
4338
- this.setStatus("idle");
4533
+ if (this._status === "opening") this.setStatus("idle");
4339
4534
  return true;
4340
4535
  } catch (error) {
4341
4536
  if (this.isClosed()) return false;
@@ -4344,13 +4539,14 @@ var CoreAgentTaskSession = class {
4344
4539
  return false;
4345
4540
  }
4346
4541
  }
4347
- startDispatch(prompt, options, waiter) {
4542
+ startDispatch(prompt, options, clientMessageId, waiter) {
4543
+ this.sentTexts.set(clientMessageId, prompt);
4348
4544
  this.dispatching = true;
4349
4545
  let handedOver;
4350
4546
  this.handOff = new Promise((resolve) => {
4351
4547
  handedOver = resolve;
4352
4548
  });
4353
- const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
4549
+ const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4354
4550
  waiter?.reject(error);
4355
4551
  this.emitError("Failed to send Agent prompt", error);
4356
4552
  if (this._status === "streaming") {
@@ -4360,25 +4556,26 @@ var CoreAgentTaskSession = class {
4360
4556
  return false;
4361
4557
  }).finally(() => {
4362
4558
  handedOver();
4363
- this.dispatching = false;
4364
- if (this.dispatch === dispatch) this.dispatch = null;
4559
+ if (this.dispatch === dispatch) {
4560
+ this.dispatching = false;
4561
+ this.dispatch = null;
4562
+ }
4365
4563
  });
4366
4564
  this.dispatch = dispatch;
4367
4565
  }
4368
- async dispatchSend(prompt, options, handedOver, waiter) {
4566
+ async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
4369
4567
  if (this.openingPromise && !await this.openingPromise) {
4370
4568
  throw new Error("Agent task session could not be opened.");
4371
4569
  }
4372
- if (this.isClosed() || waiter?.settled) return false;
4570
+ if (this.isClosed()) return false;
4373
4571
  await this.ensureTask();
4374
4572
  const input = messageInput(prompt, options);
4375
4573
  if (this.isClosed()) {
4376
- await this.sendInput(input).catch(() => void 0);
4574
+ await this.handOver(input, clientMessageId).catch(() => void 0);
4377
4575
  return false;
4378
4576
  }
4379
- if (waiter?.settled) return false;
4380
4577
  await this.ensureChannel();
4381
- if (this.isClosed() || waiter?.settled) return false;
4578
+ if (this.isClosed()) return false;
4382
4579
  await this.captureTurnBaseline();
4383
4580
  this._content = "";
4384
4581
  this.recoveryUsed = false;
@@ -4388,13 +4585,13 @@ var CoreAgentTaskSession = class {
4388
4585
  this.activeWaiter = waiter;
4389
4586
  this.setStatus("streaming");
4390
4587
  this.emit("turnStart", {});
4391
- this.openingMessageId = newClientMessageId();
4588
+ this.openingMessageId = clientMessageId;
4392
4589
  this.openingAwaitsStart = true;
4393
4590
  const { admitted, direct } = await this.handOver(input, this.openingMessageId);
4394
4591
  if (!direct) this.openingAwaitsStart = false;
4395
4592
  handedOver();
4396
4593
  if (!await admitted) return false;
4397
- this.emit("accepted", {});
4594
+ this.acceptOnce(clientMessageId);
4398
4595
  return true;
4399
4596
  }
4400
4597
  // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
@@ -4418,6 +4615,7 @@ var CoreAgentTaskSession = class {
4418
4615
  } else {
4419
4616
  this.strayedSteers.push(steered);
4420
4617
  }
4618
+ this.sentTexts.set(steered.clientMessageId, prompt);
4421
4619
  const input = messageInput(prompt, options);
4422
4620
  this.pendingSteers += 1;
4423
4621
  const handed = this.handOff.then(async () => {
@@ -4439,7 +4637,7 @@ var CoreAgentTaskSession = class {
4439
4637
  return;
4440
4638
  }
4441
4639
  if (!steered.queued) this.steerTaken(steered);
4442
- this.emit("accepted", {});
4640
+ this.acceptOnce(steered.clientMessageId);
4443
4641
  }).catch((error) => {
4444
4642
  this.forgetSteer(steered);
4445
4643
  waiter?.reject(error);
@@ -4447,6 +4645,7 @@ var CoreAgentTaskSession = class {
4447
4645
  }).finally(() => {
4448
4646
  this.pendingSteers -= 1;
4449
4647
  });
4648
+ return steered.clientMessageId;
4450
4649
  }
4451
4650
  // The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
4452
4651
  // of its own, when that one ended before the box got to the message.
@@ -4493,7 +4692,7 @@ var CoreAgentTaskSession = class {
4493
4692
  else if (steered.waiter) settle(steered.waiter);
4494
4693
  }
4495
4694
  }
4496
- openTurnFor(waiter) {
4695
+ openTurnFor(waiter, start = {}) {
4497
4696
  if (this.isClosed()) return;
4498
4697
  if (this._status !== "streaming" && this._status !== "cancelled") {
4499
4698
  this._content = "";
@@ -4504,7 +4703,7 @@ var CoreAgentTaskSession = class {
4504
4703
  this.turnBaselineIds = new Set(this._history.map((item) => item.id));
4505
4704
  void this.captureTurnBaseline().catch(() => void 0);
4506
4705
  this.setStatus("streaming");
4507
- this.emit("turnStart", {});
4706
+ this.emit("turnStart", start);
4508
4707
  }
4509
4708
  if (!waiter) return;
4510
4709
  if (!this.activeWaiter) this.activeWaiter = waiter;
@@ -4547,6 +4746,8 @@ var CoreAgentTaskSession = class {
4547
4746
  const abort = new AbortController();
4548
4747
  this.connectionAbort = abort;
4549
4748
  const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
4749
+ const historyCursor = this.openingCursor;
4750
+ this.openingCursor = void 0;
4550
4751
  this.connectionPromise = source.open(
4551
4752
  this._taskId,
4552
4753
  {
@@ -4554,7 +4755,8 @@ var CoreAgentTaskSession = class {
4554
4755
  onDisconnect: (error) => this.handleDisconnect(error)
4555
4756
  },
4556
4757
  abort.signal,
4557
- this.options.transport
4758
+ this.options.transport,
4759
+ historyCursor
4558
4760
  ).then((connection) => {
4559
4761
  if (this.isClosed() || this._status === "error") {
4560
4762
  connection.close();
@@ -4600,7 +4802,8 @@ var CoreAgentTaskSession = class {
4600
4802
  if (!this._taskId) return;
4601
4803
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4602
4804
  size: 100,
4603
- sort: "createdAt,desc"
4805
+ sort: "createdAt,desc",
4806
+ kinds: "all"
4604
4807
  });
4605
4808
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
4606
4809
  }
@@ -4608,11 +4811,13 @@ var CoreAgentTaskSession = class {
4608
4811
  if (!this._taskId) return false;
4609
4812
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4610
4813
  size: 100,
4611
- sort: "createdAt,desc"
4814
+ sort: "createdAt,desc",
4815
+ kinds: "all"
4612
4816
  });
4613
4817
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4614
4818
  this.emit("historyLoaded", { history: this.history });
4615
- const recovered = page.content.find(
4819
+ const rows = page.content.filter(isChatRow);
4820
+ const recovered = rows.find(
4616
4821
  (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
4617
4822
  );
4618
4823
  if (!recovered) {
@@ -4621,7 +4826,7 @@ var CoreAgentTaskSession = class {
4621
4826
  this.endedPollsWithoutRow += 1;
4622
4827
  if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
4623
4828
  }
4624
- const newest = page.content.find(
4829
+ const newest = rows.find(
4625
4830
  (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4626
4831
  );
4627
4832
  if (!newest) return false;
@@ -4665,11 +4870,13 @@ var CoreAgentTaskSession = class {
4665
4870
  );
4666
4871
  }
4667
4872
  const turnRunning = this._status === "streaming" || this._status === "cancelled";
4668
- const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content } : {
4873
+ const id = clientMessageId === void 0 ? {} : { clientMessageId };
4874
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
4669
4875
  type: "message",
4670
4876
  content: input.content,
4671
4877
  ...input.agentType ? { agentType: input.agentType } : {},
4672
- ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
4878
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
4879
+ ...id
4673
4880
  };
4674
4881
  await this.dependencies.tasks.sendInput(this._taskId, rest);
4675
4882
  return { admitted: Promise.resolve(true), direct: false };
@@ -4689,6 +4896,7 @@ var CoreAgentTaskSession = class {
4689
4896
  return;
4690
4897
  }
4691
4898
  const lifecycle = asObject2(payload?.lifecycle);
4899
+ if (this.endsQueuedMessage(event, payload, lifecycle)) return;
4692
4900
  if (this.repeatsTheRunningTurn(event, lifecycle)) return;
4693
4901
  if (event.type === "stepStart" || event.type === "steer") {
4694
4902
  const id = lifecycle?.clientMessageId;
@@ -4705,35 +4913,70 @@ var CoreAgentTaskSession = class {
4705
4913
  // texto e o que faz a resposta recuperada aparecer; sem isso ela chega e morre aqui.
4706
4914
  case "textDelta":
4707
4915
  case "textChunk":
4708
- this.consumeDelta(payload, "text");
4916
+ this.consumeDelta(event, payload, "text");
4709
4917
  break;
4710
4918
  case "thinking":
4711
- this.consumeDelta(payload, "thinking");
4919
+ this.consumeDelta(event, payload, "thinking");
4712
4920
  break;
4713
4921
  case "toolCall":
4714
- if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call", event.timestamp);
4922
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(event, payload, "call");
4715
4923
  break;
4924
+ // A result can come after its turn ended: a subagent in the background settles later, and
4925
+ // the box sends its result under the turn that called it. It reaches the app as that tool's
4926
+ // result and touches no turn.
4716
4927
  case "toolResult":
4717
- if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "result", event.timestamp);
4928
+ this.emitTool(event, payload, "result");
4718
4929
  break;
4719
4930
  case "workspace":
4720
- this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
4931
+ this.emit("workspace", {
4932
+ payload: event.payload,
4933
+ timestamp: event.timestamp,
4934
+ ...sequenceOf(event)
4935
+ });
4721
4936
  break;
4722
4937
  case "stepStart":
4938
+ if (!this.isFinishedTurnFrame(lifecycle)) {
4939
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
4940
+ }
4941
+ if (typeof lifecycle?.turnId === "string" && !this.isFinishedTurnFrame(lifecycle) && this._status !== "streaming" && this._status !== "cancelled") {
4942
+ this.openTurnFor(void 0, {
4943
+ ...typeof payload?.text === "string" ? { text: payload.text } : {},
4944
+ ...typeof lifecycle.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {},
4945
+ ...pieceIdentityOf(event, payload)
4946
+ });
4947
+ }
4948
+ this.leaveQueue(lifecycle?.clientMessageId);
4723
4949
  this.steerOpenedBy(asObject2(payload?.lifecycle));
4950
+ this.acceptNamed(lifecycle?.clientMessageId);
4724
4951
  break;
4725
4952
  case "steer":
4953
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
4954
+ this.leaveQueue(lifecycle?.clientMessageId);
4726
4955
  this.steerOpenedBy(lifecycle);
4956
+ this.acceptNamed(lifecycle?.clientMessageId);
4727
4957
  this.emit("steered", {
4728
4958
  text: typeof payload?.text === "string" ? payload.text : "",
4729
- messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
4959
+ messageId: typeof payload?.messageId === "string" ? payload.messageId : "",
4960
+ ...typeof payload?.turnId === "string" ? { turnId: payload.turnId } : {},
4961
+ ...sequenceOf(event),
4962
+ ...typeof lifecycle?.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {}
4730
4963
  });
4731
4964
  break;
4965
+ case "backgroundTasks":
4966
+ this._backgroundTasks = backgroundTasksOf(payload?.tasks);
4967
+ this.emit("backgroundTasks", { tasks: this._backgroundTasks });
4968
+ break;
4732
4969
  case "messageQueued":
4970
+ if (payload?.cancelled === true) {
4971
+ this.cancelQueued(payload, lifecycle);
4972
+ break;
4973
+ }
4974
+ this.applyQueued(event, payload, lifecycle);
4733
4975
  this.steerQueuedBy(asObject2(payload?.lifecycle));
4976
+ this.acceptNamed(lifecycle?.clientMessageId);
4734
4977
  break;
4735
4978
  case "subagentUpdate":
4736
- this.applySubagent(payload);
4979
+ this.applySubagent(event, payload);
4737
4980
  break;
4738
4981
  case "providerUsage": {
4739
4982
  const usage = providerUsageOf(payload);
@@ -4746,9 +4989,14 @@ var CoreAgentTaskSession = class {
4746
4989
  const usage = agentTurnUsageOf(payload?.usage);
4747
4990
  const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
4748
4991
  if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
4992
+ if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
4993
+ const end = {
4994
+ ...sequenceOf(event),
4995
+ ...finished === void 0 ? {} : { turnId: finished }
4996
+ };
4749
4997
  if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
4750
4998
  this.rememberFinishedTurn(lifecycle2);
4751
- this.finishTurn("interrupted", usage);
4999
+ this.finishTurn("interrupted", usage, end);
4752
5000
  break;
4753
5001
  }
4754
5002
  if (reason === "stop" || reason === "endTurn") {
@@ -4763,7 +5011,7 @@ var CoreAgentTaskSession = class {
4763
5011
  });
4764
5012
  }
4765
5013
  } else {
4766
- this.finishTurn(reason, usage);
5014
+ this.finishTurn(reason, usage, end);
4767
5015
  }
4768
5016
  }
4769
5017
  break;
@@ -4771,8 +5019,9 @@ var CoreAgentTaskSession = class {
4771
5019
  case "error": {
4772
5020
  const code = typeof payload?.code === "string" ? payload.code : void 0;
4773
5021
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
4774
- this.emit("error", { ...code ? { code } : {}, error: message });
5022
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
4775
5023
  if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5024
+ if (typeof payload?.command === "string") break;
4776
5025
  const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
4777
5026
  if (typeof refused === "string") {
4778
5027
  if (refused !== this.openingMessageId) {
@@ -4788,10 +5037,119 @@ var CoreAgentTaskSession = class {
4788
5037
  }
4789
5038
  break;
4790
5039
  }
5040
+ case "approval":
5041
+ case "user_input_request":
5042
+ this.liveRequest(event, payload);
5043
+ break;
4791
5044
  default:
4792
5045
  break;
4793
5046
  }
4794
5047
  }
5048
+ // The box admits every message with a `messageQueued` of no position; only one with a position
5049
+ // is in T3's queue.
5050
+ applyQueued(event, payload, lifecycle) {
5051
+ const id = payload?.clientMessageId ?? lifecycle?.clientMessageId;
5052
+ const position = payload?.position;
5053
+ if (typeof id !== "string" || typeof position !== "number") return;
5054
+ const known = this.queueItems.find((item2) => item2.id === id);
5055
+ if (this.alreadyApplied(known?.sequence, event)) return;
5056
+ const item = {
5057
+ id,
5058
+ text: typeof payload?.text === "string" ? payload.text : known?.text ?? "",
5059
+ createdAt: known?.createdAt ?? event.timestamp,
5060
+ position,
5061
+ ...typeof payload?.queueHeld === "boolean" ? { queueHeld: payload.queueHeld } : {},
5062
+ ...sequenceOf(event),
5063
+ ...typeof lifecycle?.turnId === "string" ? { turnId: lifecycle.turnId } : {}
5064
+ };
5065
+ this.queueItems = known ? this.queueItems.map((current) => current === known ? item : current) : [...this.queueItems, item];
5066
+ this.emit("queueChange", { queue: this.queue });
5067
+ }
5068
+ // The box took the message out of T3's queue on a `queued-run.cancel`, with no terminal of its
5069
+ // own: it leaves the queue and only its own `sendAndWait` ends. The message that opened this
5070
+ // session's turn was that turn, still waiting behind another one, which ends with it.
5071
+ cancelQueued(payload, lifecycle) {
5072
+ const id = payload.clientMessageId ?? lifecycle?.clientMessageId;
5073
+ if (typeof id !== "string") return;
5074
+ this.leaveQueue(id);
5075
+ const cancelled = new AgentTaskTurnError("The queued Agent message was cancelled.");
5076
+ if (id === this.openingMessageId) {
5077
+ this.cancelOpening(cancelled);
5078
+ return;
5079
+ }
5080
+ const steered = [...this.steers, ...this.strayedSteers].find(
5081
+ (pending) => pending.clientMessageId === id
5082
+ );
5083
+ if (!steered) return;
5084
+ this.forgetSteer(steered);
5085
+ steered.waiter?.reject(cancelled);
5086
+ }
5087
+ // A frame naming one of this session's messages in flight is the box taking it.
5088
+ acceptNamed(id) {
5089
+ if (typeof id !== "string") return;
5090
+ if (id === this.openingMessageId) this.dispatching = false;
5091
+ const ours = id === this.openingMessageId || [...this.steers, ...this.strayedSteers].some((pending) => pending.clientMessageId === id);
5092
+ if (ours) this.acceptOnce(id);
5093
+ }
5094
+ acceptOnce(id) {
5095
+ if (this.acceptedIds.includes(id)) return;
5096
+ this.acceptedIds.push(id);
5097
+ if (this.acceptedIds.length > 32) this.acceptedIds.shift();
5098
+ this.emit("accepted", {});
5099
+ }
5100
+ // As in T3, cancelling a queued run only takes that run out: no turn ends with it. The message
5101
+ // this session opened its turn with never ran, so only its own `sendAndWait` is rejected. A
5102
+ // message of this session still queued behind it keeps the session waiting for the turn the
5103
+ // box opens for it; with none, nothing of this session runs and it goes back to idle.
5104
+ cancelOpening(cancelled) {
5105
+ this.openingMessageId = void 0;
5106
+ if (!this.openingAwaitsStart) return;
5107
+ this.openingAwaitsStart = false;
5108
+ this.activeWaiter?.reject(cancelled);
5109
+ this.activeWaiter = void 0;
5110
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
5111
+ if (this.steers.length === 0 && this.strayedSteers.length === 0) this.setStatus("idle");
5112
+ }
5113
+ // After a replay the box sends the queue and the subagents as they are, each a copy of the line
5114
+ // that said it last, with that line's sequence: state this session may already hold.
5115
+ alreadyApplied(applied, event) {
5116
+ return applied !== void 0 && typeof event.sequence === "number" && event.sequence <= applied;
5117
+ }
5118
+ leaveQueue(id) {
5119
+ const item = this.queueItems.find((current) => current.id === id);
5120
+ if (!item) return void 0;
5121
+ this.queueItems = this.queueItems.filter((current) => current !== item);
5122
+ this.emit("queueChange", { queue: this.queue });
5123
+ return item;
5124
+ }
5125
+ // A queued message that ends before running (taken out of the queue, or dropped by T3) closes
5126
+ // with a terminal of its own while another turn may run: it leaves the queue and ends its own
5127
+ // `sendAndWait`, and the running turn goes on. The opening message of this session's turn is
5128
+ // that turn, and ends it as before.
5129
+ endsQueuedMessage(event, payload, lifecycle) {
5130
+ if (event.type !== "error" && event.type !== "stepFinish" || !lifecycle) return false;
5131
+ const id = payload?.clientMessageId ?? lifecycle.clientMessageId;
5132
+ const turnId = lifecycle.turnId;
5133
+ const item = this.queueItems.find(
5134
+ (current) => current.id === id || turnId !== void 0 && current.turnId === turnId
5135
+ );
5136
+ if (!item) return false;
5137
+ this.leaveQueue(item.id);
5138
+ if (item.id === this.openingMessageId) return false;
5139
+ const message = typeof payload?.message === "string" ? payload.message : "The queued Agent message ended before it ran.";
5140
+ if (event.type === "error") {
5141
+ const code = typeof payload?.code === "string" ? payload.code : void 0;
5142
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5143
+ }
5144
+ const steered = [...this.steers, ...this.strayedSteers].find(
5145
+ (pending) => pending.clientMessageId === item.id
5146
+ );
5147
+ if (steered) {
5148
+ this.forgetSteer(steered);
5149
+ steered.waiter?.reject(new AgentTaskTurnError(message));
5150
+ }
5151
+ return true;
5152
+ }
4795
5153
  repeatsTheRunningTurn(event, lifecycle) {
4796
5154
  if (this._status !== "streaming" && this._status !== "cancelled") return false;
4797
5155
  const turnId = lifecycle?.turnId;
@@ -4819,7 +5177,7 @@ var CoreAgentTaskSession = class {
4819
5177
  this.finishedTurnIds.push(turnId);
4820
5178
  if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
4821
5179
  }
4822
- consumeDelta(payload, kind) {
5180
+ consumeDelta(event, payload, kind) {
4823
5181
  const lifecycle = asObject2(payload?.lifecycle);
4824
5182
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4825
5183
  if (turnId && this.finishedTurnIds.includes(turnId)) return;
@@ -4831,40 +5189,160 @@ var CoreAgentTaskSession = class {
4831
5189
  this.emit("turnStart", {});
4832
5190
  }
4833
5191
  if (kind === "text") this._content += text;
4834
- this.emit("delta", { delta: text, kind });
5192
+ this.liveText(event, payload, kind);
5193
+ this.emit("delta", {
5194
+ delta: text,
5195
+ kind,
5196
+ ...itemDeltaOf(payload),
5197
+ ...pieceIdentityOf(event, payload)
5198
+ });
5199
+ }
5200
+ emitTool(event, payload, phase) {
5201
+ const tool = toolEventOf(event, payload, phase);
5202
+ this.liveTool(tool, event);
5203
+ this.emit("tool", tool);
5204
+ }
5205
+ // The conversation as it happens: the box's frames grow `history` while a turn runs, one item
5206
+ // per piece of T3, the same pieces the Copilot records and the reload at the turn's end brings
5207
+ // back in the same order. A piece the loaded history already has keeps growing in place, and a
5208
+ // frame it already holds (a replay after a reconnect or an F5) changes nothing.
5209
+ livePiece(match, create, update) {
5210
+ const index = this._history.findIndex(match);
5211
+ const current = this._history[index];
5212
+ if (current === void 0) this._history.push(create());
5213
+ else this._history[index] = update(current);
5214
+ }
5215
+ // The question enters the conversation where the box took it: its turn's `stepStart`, or the
5216
+ // `steer` that took it into the running turn. Until then it is in `queue`.
5217
+ liveQuestion(event, boxText, clientMessageId) {
5218
+ const id = typeof clientMessageId === "string" ? clientMessageId : void 0;
5219
+ const text = (id !== void 0 ? this.sentTexts.get(id) : void 0) ?? boxText;
5220
+ if (typeof text !== "string" || !text) return;
5221
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5222
+ this.livePiece(
5223
+ (item) => item.kind === "user" && (id !== void 0 && item.clientMessageId === id || sequence !== void 0 && item.sequence === sequence && item.text === text),
5224
+ () => ({
5225
+ id: `live:user:${id ?? sequence ?? this._history.length}`,
5226
+ kind: "user",
5227
+ text,
5228
+ at: liveAtOf(event),
5229
+ ...sequence === void 0 ? {} : { sequence },
5230
+ ...id === void 0 ? {} : { clientMessageId: id }
5231
+ }),
5232
+ (item) => item
5233
+ );
5234
+ }
5235
+ liveText(event, payload, kind, parentToolId) {
5236
+ const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
5237
+ if (itemId === void 0) return;
5238
+ const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
5239
+ const itemKind = kind === "thinking" ? "reasoning" : "agent";
5240
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5241
+ this.livePiece(
5242
+ (item) => item.kind === itemKind && item.itemId === itemId,
5243
+ () => ({
5244
+ id: `live:${itemKind}:${itemId}`,
5245
+ kind: itemKind,
5246
+ text: piece,
5247
+ at: liveAtOf(event),
5248
+ itemId,
5249
+ ...sequence === void 0 ? {} : { sequence },
5250
+ ...parentToolIdOf(parentToolId)
5251
+ }),
5252
+ (item) => {
5253
+ const held = item.lastSequence ?? item.sequence;
5254
+ if (!("text" in item) || sequence !== void 0 && held !== void 0 && sequence <= held)
5255
+ return item;
5256
+ return {
5257
+ ...item,
5258
+ text: item.text + piece,
5259
+ ...sequence === void 0 ? {} : { lastSequence: sequence }
5260
+ };
5261
+ }
5262
+ );
5263
+ }
5264
+ liveTool(tool, event) {
5265
+ const toolId = tool.toolId;
5266
+ if (toolId === void 0) return;
5267
+ this.livePiece(
5268
+ (item) => item.kind === "tool" && item.tool.toolId === toolId && item.tool.phase === tool.phase,
5269
+ () => ({
5270
+ id: tool.phase === "result" ? `live:tool:${toolId}:result` : `live:tool:${toolId}`,
5271
+ kind: "tool",
5272
+ tool,
5273
+ at: liveAtOf(event),
5274
+ ...tool.sequence === void 0 ? {} : { sequence: tool.sequence },
5275
+ ...tool.itemId === void 0 ? {} : { itemId: tool.itemId }
5276
+ }),
5277
+ (item) => item.kind === "tool" ? { ...item, tool: { ...item.tool, ...tool, input: tool.input ?? item.tool.input } } : item
5278
+ );
4835
5279
  }
4836
- emitTool(payload, phase, timestamp) {
4837
- this.emit("tool", toolEventOf(payload, phase, timestamp));
5280
+ // An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
5281
+ // it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
5282
+ // reaches the app as a `raw` event, as before.
5283
+ liveRequest(event, payload, parentToolId) {
5284
+ if (!payload) return;
5285
+ const kind = event.type === "approval" ? "approval" : "userInputRequest";
5286
+ const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
5287
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5288
+ if (itemId === void 0 && sequence === void 0) return;
5289
+ this.livePiece(
5290
+ (item) => item.kind === kind && (itemId !== void 0 ? item.itemId === itemId : item.sequence === sequence),
5291
+ () => ({
5292
+ id: `live:${kind}:${itemId ?? sequence}`,
5293
+ kind,
5294
+ payload,
5295
+ at: liveAtOf(event),
5296
+ ...sequence === void 0 ? {} : { sequence },
5297
+ ...itemId === void 0 ? {} : { itemId },
5298
+ ...parentToolIdOf(parentToolId)
5299
+ }),
5300
+ (item) => item
5301
+ );
4838
5302
  }
4839
- // A child thread's frames are the subagent's conversation: they open no turn, settle no message
4840
- // and never reach the chat's `content`.
5303
+ // A child thread's frames are the subagent's conversation: they open no turn and settle no
5304
+ // message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
5305
+ // which knew no subagents, so an app that only bumps the version sees what it saw before.
4841
5306
  handleSubagentFrame(event, payload) {
4842
5307
  const parentToolId = payload.parentToolId;
4843
5308
  switch (event.type) {
4844
5309
  case "textDelta":
4845
5310
  case "textChunk":
4846
- case "thinking":
4847
- this.emit("subagentDelta", {
4848
- parentToolId,
4849
- delta: typeof payload.text === "string" ? payload.text : "",
4850
- kind: event.type === "thinking" ? "thinking" : "text"
4851
- });
5311
+ case "thinking": {
5312
+ const delta = typeof payload.text === "string" ? payload.text : "";
5313
+ const kind = event.type === "thinking" ? "thinking" : "text";
5314
+ const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
5315
+ if (kind === "text") this._content += delta;
5316
+ this.liveText(event, payload, kind, parentToolId);
5317
+ this.emit("delta", { delta, kind, parentToolId, ...identity });
5318
+ this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
4852
5319
  break;
5320
+ }
4853
5321
  case "toolCall":
4854
- case "toolResult":
4855
- this.emit("subagentTool", {
4856
- ...toolEventOf(payload, event.type === "toolCall" ? "call" : "result", event.timestamp),
5322
+ case "toolResult": {
5323
+ const tool = {
5324
+ ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
4857
5325
  parentToolId
4858
- });
5326
+ };
5327
+ this.liveTool(tool, event);
5328
+ this.emit("tool", tool);
5329
+ this.emit("subagentTool", tool);
5330
+ break;
5331
+ }
5332
+ case "approval":
5333
+ case "user_input_request":
5334
+ this.liveRequest(event, payload, parentToolId);
4859
5335
  break;
4860
5336
  default:
4861
5337
  break;
4862
5338
  }
4863
5339
  }
4864
- applySubagent(payload) {
5340
+ applySubagent(event, payload) {
4865
5341
  const subagentId = payload?.subagentId;
4866
5342
  const toolId = payload?.toolId;
4867
5343
  if (typeof subagentId !== "string" || typeof toolId !== "string") return;
5344
+ if (this.alreadyApplied(this.subagentSequences.get(subagentId), event)) return;
5345
+ if (typeof event.sequence === "number") this.subagentSequences.set(subagentId, event.sequence);
4868
5346
  const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
4869
5347
  if (status === void 0) return;
4870
5348
  const startedAt = epochOf(payload?.startedAt);
@@ -4879,9 +5357,26 @@ var CoreAgentTaskSession = class {
4879
5357
  ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
4880
5358
  };
4881
5359
  this.subagentsById.set(subagentId, subagent);
4882
- this.emit("subagent", subagent);
5360
+ const index = this._history.findIndex(
5361
+ (item) => item.kind === "tool" && item.tool.toolId === toolId
5362
+ );
5363
+ const spawn = this._history[index];
5364
+ if (spawn?.kind === "tool") {
5365
+ this._history[index] = {
5366
+ ...spawn,
5367
+ subagent: {
5368
+ ...spawn.subagent,
5369
+ toolId,
5370
+ subagentId,
5371
+ status,
5372
+ ...subagent.progress === void 0 ? {} : { progress: subagent.progress },
5373
+ ...subagent.childThreadId === void 0 ? {} : { childThreadId: subagent.childThreadId }
5374
+ }
5375
+ };
5376
+ }
5377
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
4883
5378
  }
4884
- finishTurn(reason, usage) {
5379
+ finishTurn(reason, usage, end = {}) {
4885
5380
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4886
5381
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
4887
5382
  this.cancelTimer = null;
@@ -4899,7 +5394,8 @@ var CoreAgentTaskSession = class {
4899
5394
  task,
4900
5395
  content: this._content,
4901
5396
  reason,
4902
- ...usage ? { usage } : {}
5397
+ ...usage ? { usage } : {},
5398
+ ...end
4903
5399
  };
4904
5400
  this.emit("turnEnd", result);
4905
5401
  this.activeWaiter?.resolve(result);