@mitralab.io/sdk-core 0.2.12 → 0.3.0-beta.2

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
@@ -436,6 +436,9 @@ function expectAppFields(app, context, errors) {
436
436
  if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
437
437
  if (!isNullableString(app.template)) invalidField(context, "template", errors);
438
438
  if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
439
+ for (const field of ["emailLoginEnabled", "passwordLoginEnabled"]) {
440
+ if (field in app && typeof app[field] !== "boolean") invalidField(context, field, errors);
441
+ }
439
442
  if (typeof app.externalAccessEnabled !== "boolean") {
440
443
  invalidField(context, "externalAccessEnabled", errors);
441
444
  }
@@ -957,7 +960,8 @@ var TURN_USAGE_COUNTS = [
957
960
  "cacheReadTokens",
958
961
  "cacheCreationTokens",
959
962
  "requestCount",
960
- "durationMs"
963
+ "durationMs",
964
+ "contextTokens"
961
965
  ];
962
966
  var TURN_USAGE_COSTS = ["costUsd", "costUsdRaw"];
963
967
  var TURN_USAGE_STRINGS = [
@@ -985,6 +989,8 @@ function agentTurnUsageOf(value) {
985
989
  const item = value[field];
986
990
  if (isCount(item)) usage[field] = item;
987
991
  }
992
+ const { contextWindow } = value;
993
+ if (isInteger(contextWindow) && contextWindow > 0) usage.contextWindow = contextWindow;
988
994
  for (const field of TURN_USAGE_COSTS) {
989
995
  const item = value[field];
990
996
  if (isFiniteNumber(item)) usage[field] = item;
@@ -2857,9 +2863,31 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2857
2863
  "Notify user response",
2858
2864
  errors
2859
2865
  );
2866
+ },
2867
+ async sendEmail(input) {
2868
+ return expectMessageAccepted(
2869
+ await transport.request("/api/v1/messages/send", {
2870
+ method: "POST",
2871
+ body: { channel: "EMAIL", payload: rawEmailPayload(input) }
2872
+ }),
2873
+ "Send email response",
2874
+ errors
2875
+ );
2860
2876
  }
2861
2877
  };
2862
2878
  }
2879
+ function rawEmailPayload(input) {
2880
+ return {
2881
+ type: "RAW",
2882
+ to: input.to,
2883
+ ...input.cc === void 0 ? {} : { cc: input.cc },
2884
+ ...input.bcc === void 0 ? {} : { bcc: input.bcc },
2885
+ ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo },
2886
+ subject: input.subject,
2887
+ html: input.html,
2888
+ ...input.text === void 0 ? {} : { text: input.text }
2889
+ };
2890
+ }
2863
2891
 
2864
2892
  // src/modules/publicFunctions.ts
2865
2893
  function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
@@ -3211,6 +3239,29 @@ var ADMISSION_TIMEOUT_MS = 35e3;
3211
3239
  var SUPERSEDED_CLOSE_CODE = 4409;
3212
3240
  var SOCKET_OPEN = 1;
3213
3241
  var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
3242
+ var clientMessageSequence = 0;
3243
+ function newClientMessageId() {
3244
+ const random = globalThis.crypto?.randomUUID;
3245
+ return random ? random.call(globalThis.crypto) : `m-${Date.now()}-${++clientMessageSequence}`;
3246
+ }
3247
+ function admissionFor(link, event) {
3248
+ const payload = asObject(event.payload);
3249
+ if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
3250
+ return void 0;
3251
+ }
3252
+ const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
3253
+ if (typeof id === "string")
3254
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3255
+ return link.admissions[0];
3256
+ }
3257
+ function queuedAdmission(link, event) {
3258
+ const id = asObject(asObject(event.payload)?.lifecycle)?.clientMessageId;
3259
+ if (typeof id !== "string") return void 0;
3260
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3261
+ }
3262
+ function isSubagentFrame(event) {
3263
+ return typeof asObject(event.payload)?.parentToolId === "string";
3264
+ }
3214
3265
  function asObject(value) {
3215
3266
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3216
3267
  }
@@ -3331,6 +3382,7 @@ function asDelta(event) {
3331
3382
  }
3332
3383
  var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3333
3384
  "stepStart",
3385
+ "steer",
3334
3386
  "textDelta",
3335
3387
  "thinking",
3336
3388
  "toolCall",
@@ -3339,7 +3391,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3339
3391
  var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3340
3392
  function turnAfter(event, inTurn) {
3341
3393
  if (TURN_FRAME_TYPES.has(event.type)) return true;
3342
- if (event.type === "error") return false;
3394
+ if (event.type === "error") return asObject(event.payload)?.lifecycle ? false : inTurn;
3343
3395
  if (event.type === "stepFinish") {
3344
3396
  const payload = asObject(event.payload);
3345
3397
  if (TURN_END_REASONS.has(payload?.reason)) return false;
@@ -3347,6 +3399,21 @@ function turnAfter(event, inTurn) {
3347
3399
  }
3348
3400
  return inTurn;
3349
3401
  }
3402
+ function lostTurnFrame(turnId) {
3403
+ return {
3404
+ type: "stepFinish",
3405
+ payload: {
3406
+ reason: "interrupted",
3407
+ lifecycle: {
3408
+ ...turnId === void 0 ? {} : { turnId },
3409
+ terminal: true,
3410
+ sessionIdle: true,
3411
+ interruptTerminal: true
3412
+ }
3413
+ },
3414
+ timestamp: Date.now()
3415
+ };
3416
+ }
3350
3417
  function channelEvent(type, payload) {
3351
3418
  return { type, payload, timestamp: Date.now() };
3352
3419
  }
@@ -3426,9 +3493,11 @@ var AgentDirectChannel = class {
3426
3493
  }
3427
3494
  }
3428
3495
  /**
3429
- * Hands a message or an interrupt to the box when the chat is on the direct channel and its
3430
- * wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3431
- * mid-redial, or an approval, which stays on REST.
3496
+ * Hands a message, an interrupt, a subagent stop or an answer to a T3 input request to the box
3497
+ * when the chat is on the direct channel and its wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3498
+ * mid-redial, or an approval, which stays on REST. Mid-redial the Copilot is the durable path:
3499
+ * the box URL kept from the last channel carries a proxy ticket that lasts 60 seconds, and a
3500
+ * box that dropped the socket is often the one that went away.
3432
3501
  *
3433
3502
  * A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
3434
3503
  * the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
@@ -3441,12 +3510,12 @@ var AgentDirectChannel = class {
3441
3510
  * have admitted the turn, and a second copy would start it twice. The redial replays the box
3442
3511
  * log, where the `stepStart` of an admitted turn is.
3443
3512
  */
3444
- send(taskId, input) {
3513
+ send(taskId, input, clientMessageId) {
3445
3514
  if (input.type === "approval_response") return null;
3446
3515
  const link = this.links.get(taskId);
3447
3516
  if (!link?.wire) return null;
3448
3517
  if (input.type !== "message") return link.wire.interrupt(input);
3449
- link.admission?.fail(new Error("A newer message replaced the one waiting for the box."));
3518
+ const messageId = clientMessageId ?? newClientMessageId();
3450
3519
  let admission;
3451
3520
  const admitted = new Promise((resolve, reject) => {
3452
3521
  let timer;
@@ -3462,11 +3531,13 @@ var AgentDirectChannel = class {
3462
3531
  };
3463
3532
  const done = () => {
3464
3533
  clearTimeout(timer);
3465
- if (link.admission === admission) link.admission = null;
3534
+ link.admissions = link.admissions.filter((pending) => pending !== admission);
3466
3535
  };
3467
3536
  admission = {
3537
+ clientMessageId: messageId,
3468
3538
  settle: (value) => {
3469
3539
  done();
3540
+ if (value) link.inTurn = true;
3470
3541
  resolve(value);
3471
3542
  },
3472
3543
  fail: (error) => {
@@ -3478,12 +3549,11 @@ var AgentDirectChannel = class {
3478
3549
  };
3479
3550
  arm();
3480
3551
  });
3481
- link.admission = admission;
3482
- if (!link.wire.message(input, admission)) {
3552
+ link.admissions = [...link.admissions, admission];
3553
+ if (!link.wire.message({ ...input, clientMessageId: messageId }, admission)) {
3483
3554
  admission.settle(false);
3484
3555
  return null;
3485
3556
  }
3486
- link.inTurn = true;
3487
3557
  return admitted;
3488
3558
  }
3489
3559
  /** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
@@ -3540,7 +3610,7 @@ var AgentDirectChannel = class {
3540
3610
  * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3541
3611
  */
3542
3612
  async openDirect(taskId, mode, channel, observer, signal) {
3543
- const link = { wire: null, inTurn: false, admission: null };
3613
+ const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
3544
3614
  let box = boxAddress(channel.wsUrl);
3545
3615
  let cursor = channel.lastSequence;
3546
3616
  const abort = new AbortController();
@@ -3548,35 +3618,46 @@ var AgentDirectChannel = class {
3548
3618
  signal?.addEventListener("abort", onAbort, { once: true });
3549
3619
  const onFrame = (event) => {
3550
3620
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3621
+ if (isSubagentFrame(event)) {
3622
+ observer.onEvent(event);
3623
+ return;
3624
+ }
3625
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3626
+ if (typeof turnId === "string") link.turnId = turnId;
3551
3627
  link.inTurn = turnAfter(event, link.inTurn);
3552
3628
  observer.onEvent(event);
3553
- if (event.type === "stepStart") link.admission?.settle(true);
3554
- else if (event.type === "error") link.admission?.settle(false);
3629
+ if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
3630
+ else if (event.type === "error") admissionFor(link, event)?.settle(false);
3631
+ else if (event.type === "messageQueued" || event.type === "steer") {
3632
+ queuedAdmission(link, event)?.settle(true);
3633
+ }
3555
3634
  };
3556
3635
  const onLost = (error, code) => {
3557
3636
  link.wire = null;
3558
3637
  if (abort.signal.aborted) return;
3559
- if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
3560
- link.admission?.fail(error);
3638
+ if (!link.inTurn && link.admissions.length === 0 || code === SUPERSEDED_CLOSE_CODE) {
3639
+ for (const pending of link.admissions) pending.fail(error);
3561
3640
  observer.onDisconnect(error);
3562
3641
  return;
3563
3642
  }
3564
- link.admission?.hold();
3643
+ for (const pending of link.admissions) pending.hold();
3565
3644
  void this.redial(taskId, mode, error, abort.signal, observer, {
3566
3645
  onFrame,
3567
3646
  onLost,
3568
3647
  replayFrom: (next) => {
3569
3648
  const nextBox = boxAddress(next.wsUrl);
3570
- if (nextBox === box) return cursor;
3649
+ const zeroed = next.lastSequence === 0 && cursor > 0;
3650
+ if (nextBox === box && !zeroed) return cursor;
3651
+ if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3571
3652
  box = nextBox;
3572
3653
  cursor = next.lastSequence;
3573
3654
  return void 0;
3574
3655
  }
3575
3656
  }).then((outcome) => {
3576
- if (outcome instanceof Error) link.admission?.fail(outcome);
3657
+ if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
3577
3658
  else if (outcome) {
3578
3659
  link.wire = outcome;
3579
- link.admission?.rearm();
3660
+ for (const pending of link.admissions) pending.rearm();
3580
3661
  }
3581
3662
  });
3582
3663
  };
@@ -3597,9 +3678,8 @@ var AgentDirectChannel = class {
3597
3678
  abort.abort();
3598
3679
  link.wire?.close();
3599
3680
  link.wire = null;
3600
- link.admission?.fail(
3601
- new Error("The Agent session closed before the box confirmed the turn.")
3602
- );
3681
+ const closed = new Error("The Agent session closed before the box confirmed the turn.");
3682
+ for (const pending of link.admissions) pending.fail(closed);
3603
3683
  if (this.links.get(taskId) === link) this.links.delete(taskId);
3604
3684
  }
3605
3685
  };
@@ -3736,7 +3816,7 @@ var AgentDirectChannel = class {
3736
3816
  close,
3737
3817
  interrupt: (input) => post(input).then((response) => {
3738
3818
  if (!response.ok) {
3739
- throw new Error(`The Agent box refused the interrupt (${response.status}).`);
3819
+ throw new Error(`The Agent box refused the ${input.type} (${response.status}).`);
3740
3820
  }
3741
3821
  return true;
3742
3822
  }),
@@ -3918,9 +3998,22 @@ var AgentDirectChannel = class {
3918
3998
  };
3919
3999
 
3920
4000
  // src/agentSession.ts
3921
- var AGENT_QUEUE_LIMIT = 10;
3922
4001
  var CANCEL_SAFETY_MS = 1e4;
3923
4002
  var RECONCILE_DELAY_MS = 1e3;
4003
+ var ENDED_POLLS_BEFORE_NEWEST = 3;
4004
+ var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
4005
+ "textDelta",
4006
+ "textChunk",
4007
+ "thinking",
4008
+ "toolCall",
4009
+ "toolResult",
4010
+ "stepFinish"
4011
+ ]);
4012
+ var COPILOT_INPUT_TYPES = /* @__PURE__ */ new Set([
4013
+ "message",
4014
+ "interrupt",
4015
+ "approval_response"
4016
+ ]);
3924
4017
  function providerUsageOf(payload) {
3925
4018
  if (!payload) return null;
3926
4019
  try {
@@ -3949,6 +4042,31 @@ function errorCode(error) {
3949
4042
  function delay(milliseconds) {
3950
4043
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
3951
4044
  }
4045
+ function messageInput(prompt, options) {
4046
+ return {
4047
+ type: "message",
4048
+ content: prompt,
4049
+ ...options.agentType ? { agentType: options.agentType } : {},
4050
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4051
+ mode: "steer"
4052
+ };
4053
+ }
4054
+ function toolEventOf(payload, phase, timestamp) {
4055
+ return {
4056
+ tool: typeof payload?.name === "string" ? payload.name : "",
4057
+ phase,
4058
+ timestamp,
4059
+ ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4060
+ ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4061
+ ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4062
+ };
4063
+ }
4064
+ function epochOf(value) {
4065
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4066
+ if (typeof value !== "string") return void 0;
4067
+ const parsed = Date.parse(value);
4068
+ return Number.isNaN(parsed) ? void 0 : parsed;
4069
+ }
3952
4070
  function toAgentTimelineItem(message) {
3953
4071
  if (message.type === "TOOL_USE") {
3954
4072
  try {
@@ -4022,7 +4140,6 @@ var CoreAgentTaskSession = class {
4022
4140
  _status = "opening";
4023
4141
  _history = [];
4024
4142
  _content = "";
4025
- _queue = [];
4026
4143
  isNewSession;
4027
4144
  listeners = /* @__PURE__ */ new Map();
4028
4145
  connection = null;
@@ -4041,10 +4158,36 @@ var CoreAgentTaskSession = class {
4041
4158
  recoveryGeneration = 0;
4042
4159
  recoveredTerminalReason;
4043
4160
  recoveredTerminalUsage;
4161
+ // Polls that found no closing row although a terminal with usage was heard.
4162
+ endedPollsWithoutRow = 0;
4163
+ // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
4164
+ // stream a dropped session falls back to replays the turn from what the history has, so it
4165
+ // repeats frames the box socket already delivered.
4166
+ turnIds = /* @__PURE__ */ new Set();
4167
+ turnSequenceHigh = -1;
4044
4168
  cancelTimer = null;
4045
- queueSequence = 0;
4169
+ // Messages leave in the order they were sent: each one is handed over only after the one
4170
+ // before it was, not after it was answered.
4171
+ handOff = Promise.resolve();
4046
4172
  activeWaiter;
4173
+ // Every steer sits in exactly one of the two lists until it is settled or forgotten: `steers`
4174
+ // while the turn it was sent into runs (taken ones settle with that turn), `strayedSteers` once
4175
+ // it waits for a turn of its own (sent with no turn, not taken when its turn ended, or queued by
4176
+ // the provider). A non-empty `strayedSteers` keeps the session busy, which is what stops a new
4177
+ // message from opening a turn the steer's answer would settle. `pendingSteers` counts the ones
4178
+ // the box has not answered yet, wherever they sit.
4179
+ steers = [];
4180
+ strayedSteers = [];
4181
+ pendingSteers = 0;
4182
+ // The id the message that opened the current turn went out with, so a refusal naming it fails
4183
+ // that turn and one naming a steer does not.
4184
+ openingMessageId;
4185
+ // The opening message went to the box, which starts its turn with a `stepStart`. Until then a
4186
+ // turn frame naming a turn is another turn's tail: the one before, closed here from the history
4187
+ // (r5 S17, dev 2026-10-19), whose live end came after the next message went out.
4188
+ openingAwaitsStart = false;
4047
4189
  turnBaselineIds = /* @__PURE__ */ new Set();
4190
+ subagentsById = /* @__PURE__ */ new Map();
4048
4191
  get taskId() {
4049
4192
  return this._taskId;
4050
4193
  }
@@ -4064,19 +4207,16 @@ var CoreAgentTaskSession = class {
4064
4207
  return this._content;
4065
4208
  }
4066
4209
  get queue() {
4067
- return this._queue.map((item) => ({
4068
- id: item.id,
4069
- text: item.text,
4070
- createdAt: item.createdAt,
4071
- ...item.agentType ? { agentType: item.agentType } : {},
4072
- ...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
4073
- }));
4210
+ return [];
4211
+ }
4212
+ get subagents() {
4213
+ return [...this.subagentsById.values()];
4074
4214
  }
4075
4215
  send(prompt, options = {}) {
4076
4216
  this.requireOpen();
4077
4217
  if (!prompt.trim()) return;
4078
4218
  if (this.isBusy()) {
4079
- this.enqueue(prompt, options);
4219
+ this.steer(prompt, options);
4080
4220
  return;
4081
4221
  }
4082
4222
  this.startDispatch(prompt, options);
@@ -4091,8 +4231,7 @@ var CoreAgentTaskSession = class {
4091
4231
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4092
4232
  };
4093
4233
  if (this.isBusy()) {
4094
- const queueId = this.enqueue(prompt, sendOptions, waiter);
4095
- if (queueId) waiter.queueId = queueId;
4234
+ this.steer(prompt, sendOptions, waiter);
4096
4235
  return waiter.promise;
4097
4236
  }
4098
4237
  this.startDispatch(prompt, sendOptions, waiter);
@@ -4127,6 +4266,17 @@ var CoreAgentTaskSession = class {
4127
4266
  this.emitError("Failed to answer Agent approval", error);
4128
4267
  });
4129
4268
  }
4269
+ respondUserInput(requestId, answers, attachmentsByQuestionId) {
4270
+ const input = {
4271
+ type: "runtime-request.respond",
4272
+ requestId,
4273
+ answers,
4274
+ ...attachmentsByQuestionId ? { attachmentsByQuestionId } : {}
4275
+ };
4276
+ void this.sendInput(input).catch((error) => {
4277
+ this.emitError("Failed to answer Agent input request", error);
4278
+ });
4279
+ }
4130
4280
  async loadHistory(options = {}) {
4131
4281
  if (!this._taskId) return [];
4132
4282
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
@@ -4138,26 +4288,17 @@ var CoreAgentTaskSession = class {
4138
4288
  this.emit("historyLoaded", { history });
4139
4289
  return history;
4140
4290
  }
4141
- editQueueItem(id, text) {
4142
- if (!text.trim()) {
4143
- this.removeQueueItem(id);
4144
- return;
4145
- }
4146
- this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
4147
- this.emitQueue();
4291
+ editQueueItem() {
4148
4292
  }
4149
- removeQueueItem(id) {
4150
- const removed = this._queue.find((item) => item.id === id);
4151
- this._queue = this._queue.filter((item) => item.id !== id);
4152
- removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
4153
- this.emitQueue();
4293
+ removeQueueItem() {
4154
4294
  }
4155
4295
  clearQueue() {
4156
- if (!this._queue.length) return;
4157
- const removed = this._queue;
4158
- this._queue = [];
4159
- for (const item of removed) item.waiter?.reject(new Error("Agent prompt queue was cleared."));
4160
- this.emitQueue();
4296
+ }
4297
+ stopSubagent(subagentId) {
4298
+ this.requireOpen();
4299
+ void this.sendInput({ type: "subagent.stop", subagentId }).catch((error) => {
4300
+ this.emitError("Failed to stop the Agent subagent", error);
4301
+ });
4161
4302
  }
4162
4303
  on(event, handler) {
4163
4304
  let listeners = this.listeners.get(event);
@@ -4182,8 +4323,7 @@ var CoreAgentTaskSession = class {
4182
4323
  const closedError = new Error("Agent task session is closed.");
4183
4324
  this.activeWaiter?.reject(closedError);
4184
4325
  this.activeWaiter = void 0;
4185
- for (const item of this._queue) item.waiter?.reject(closedError);
4186
- this._queue = [];
4326
+ this.rejectSteers(closedError);
4187
4327
  if (this._taskId) this.dependencies.onClose(this._taskId, this);
4188
4328
  for (const listeners of this.listeners.values()) listeners.clear();
4189
4329
  }
@@ -4206,31 +4346,32 @@ var CoreAgentTaskSession = class {
4206
4346
  }
4207
4347
  startDispatch(prompt, options, waiter) {
4208
4348
  this.dispatching = true;
4209
- const dispatch = this.dispatchSend(prompt, options, waiter).catch((error) => {
4349
+ let handedOver;
4350
+ this.handOff = new Promise((resolve) => {
4351
+ handedOver = resolve;
4352
+ });
4353
+ const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
4210
4354
  waiter?.reject(error);
4211
4355
  this.emitError("Failed to send Agent prompt", error);
4212
- if (this._status === "streaming") this.setStatus("idle");
4213
- this.flushQueue();
4356
+ if (this._status === "streaming") {
4357
+ this.settleSteers((steered) => steered.reject(error));
4358
+ this.setStatus("idle");
4359
+ }
4214
4360
  return false;
4215
4361
  }).finally(() => {
4362
+ handedOver();
4216
4363
  this.dispatching = false;
4217
4364
  if (this.dispatch === dispatch) this.dispatch = null;
4218
- if (this._status === "idle") this.flushQueue();
4219
4365
  });
4220
4366
  this.dispatch = dispatch;
4221
4367
  }
4222
- async dispatchSend(prompt, options, waiter) {
4368
+ async dispatchSend(prompt, options, handedOver, waiter) {
4223
4369
  if (this.openingPromise && !await this.openingPromise) {
4224
4370
  throw new Error("Agent task session could not be opened.");
4225
4371
  }
4226
4372
  if (this.isClosed() || waiter?.settled) return false;
4227
4373
  await this.ensureTask();
4228
- const input = {
4229
- type: "message",
4230
- content: prompt,
4231
- ...options.agentType ? { agentType: options.agentType } : {},
4232
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4233
- };
4374
+ const input = messageInput(prompt, options);
4234
4375
  if (this.isClosed()) {
4235
4376
  await this.sendInput(input).catch(() => void 0);
4236
4377
  return false;
@@ -4247,10 +4388,134 @@ var CoreAgentTaskSession = class {
4247
4388
  this.activeWaiter = waiter;
4248
4389
  this.setStatus("streaming");
4249
4390
  this.emit("turnStart", {});
4250
- if (!await this.sendInput(input)) return false;
4391
+ this.openingMessageId = newClientMessageId();
4392
+ this.openingAwaitsStart = true;
4393
+ const { admitted, direct } = await this.handOver(input, this.openingMessageId);
4394
+ if (!direct) this.openingAwaitsStart = false;
4395
+ handedOver();
4396
+ if (!await admitted) return false;
4251
4397
  this.emit("accepted", {});
4252
4398
  return true;
4253
4399
  }
4400
+ // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
4401
+ // that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
4402
+ // that turn already ended. Nothing waits in this session. On the direct channel it goes with an
4403
+ // id the box echoes on the frame that takes it; without the channel, over REST to the Copilot,
4404
+ // which holds it while the box boots.
4405
+ //
4406
+ // It keeps its `agentType` and `reasoningEffort` on the box, which leaves the running turn's
4407
+ // model alone by itself and needs them for a message that becomes a turn of its own. Only on
4408
+ // the Copilot path, with a turn running, they are dropped: the Copilot restarts the live
4409
+ // session for a message that asks for another model, which would end that turn.
4410
+ steer(prompt, options, waiter) {
4411
+ const steered = {
4412
+ clientMessageId: newClientMessageId(),
4413
+ ...waiter ? { waiter } : {},
4414
+ taken: false
4415
+ };
4416
+ if (this.dispatching || this._status === "streaming" || this._status === "cancelled") {
4417
+ this.steers.push(steered);
4418
+ } else {
4419
+ this.strayedSteers.push(steered);
4420
+ }
4421
+ const input = messageInput(prompt, options);
4422
+ this.pendingSteers += 1;
4423
+ const handed = this.handOff.then(async () => {
4424
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4425
+ await this.prepareSend();
4426
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4427
+ return this.handOver(input, steered.clientMessageId, true);
4428
+ });
4429
+ this.handOff = handed.then(
4430
+ () => void 0,
4431
+ () => void 0
4432
+ );
4433
+ void handed.then(({ admitted }) => admitted).then((admitted) => {
4434
+ if (!admitted) {
4435
+ this.forgetSteer(steered);
4436
+ waiter?.reject(
4437
+ steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
4438
+ );
4439
+ return;
4440
+ }
4441
+ if (!steered.queued) this.steerTaken(steered);
4442
+ this.emit("accepted", {});
4443
+ }).catch((error) => {
4444
+ this.forgetSteer(steered);
4445
+ waiter?.reject(error);
4446
+ this.emitError("Failed to send Agent prompt", error);
4447
+ }).finally(() => {
4448
+ this.pendingSteers -= 1;
4449
+ });
4450
+ }
4451
+ // The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
4452
+ // of its own, when that one ended before the box got to the message.
4453
+ steerTaken(steered) {
4454
+ if (steered.taken) return;
4455
+ steered.taken = true;
4456
+ if (!this.strayedSteers.includes(steered)) return;
4457
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4458
+ this.openTurnFor(steered.waiter);
4459
+ }
4460
+ steerOpenedBy(lifecycle) {
4461
+ const id = lifecycle?.clientMessageId;
4462
+ if (typeof id !== "string") return;
4463
+ const steered = [...this.steers, ...this.strayedSteers].find(
4464
+ (pending) => pending.clientMessageId === id
4465
+ );
4466
+ if (steered) this.steerTaken(steered);
4467
+ }
4468
+ // Queued behind the running turn, the message is answered by the turn the box opens for it
4469
+ // later, not by this one.
4470
+ steerQueuedBy(lifecycle) {
4471
+ const id = lifecycle?.clientMessageId;
4472
+ if (typeof id !== "string") return;
4473
+ const steered = [...this.steers, ...this.strayedSteers].find(
4474
+ (pending) => pending.clientMessageId === id
4475
+ );
4476
+ if (!steered || steered.taken) return;
4477
+ steered.queued = true;
4478
+ if (!this.steers.includes(steered)) return;
4479
+ this.steers = this.steers.filter((pending) => pending !== steered);
4480
+ this.strayedSteers.push(steered);
4481
+ }
4482
+ forgetSteer(steered) {
4483
+ this.steers = this.steers.filter((pending) => pending !== steered);
4484
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4485
+ }
4486
+ // The turn ended: what the box took is answered by it, what it had not taken yet waits for the
4487
+ // turn the box opens for it.
4488
+ settleSteers(settle) {
4489
+ const steers = this.steers;
4490
+ this.steers = [];
4491
+ for (const steered of steers) {
4492
+ if (!steered.taken) this.strayedSteers.push(steered);
4493
+ else if (steered.waiter) settle(steered.waiter);
4494
+ }
4495
+ }
4496
+ openTurnFor(waiter) {
4497
+ if (this.isClosed()) return;
4498
+ if (this._status !== "streaming" && this._status !== "cancelled") {
4499
+ this._content = "";
4500
+ this.recoveryUsed = false;
4501
+ this.recoveredTerminalReason = void 0;
4502
+ this.recoveredTerminalUsage = void 0;
4503
+ this.recoveryGeneration += 1;
4504
+ this.turnBaselineIds = new Set(this._history.map((item) => item.id));
4505
+ void this.captureTurnBaseline().catch(() => void 0);
4506
+ this.setStatus("streaming");
4507
+ this.emit("turnStart", {});
4508
+ }
4509
+ if (!waiter) return;
4510
+ if (!this.activeWaiter) this.activeWaiter = waiter;
4511
+ else this.steers.push({ clientMessageId: "", waiter, taken: true });
4512
+ }
4513
+ rejectSteers(error) {
4514
+ const steers = [...this.steers, ...this.strayedSteers];
4515
+ this.steers = [];
4516
+ this.strayedSteers = [];
4517
+ for (const steered of steers) steered.waiter?.reject(error);
4518
+ }
4254
4519
  async ensureTask() {
4255
4520
  if (this._taskId) return;
4256
4521
  if (!("create" in this.options)) throw new Error("Agent task session has no task.");
@@ -4321,10 +4586,8 @@ var CoreAgentTaskSession = class {
4321
4586
  try {
4322
4587
  await this.ensureChannel();
4323
4588
  while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
4324
- if (await this.reconcilePersistedTurn(this.recoveredTerminalReason ?? "reconciled")) {
4325
- return;
4326
- }
4327
- if (this.activeWaiter?.settled) return;
4589
+ const reason = this.recoveredTerminalReason ?? (this._status === "cancelled" ? "interrupted" : "reconciled");
4590
+ if (await this.reconcilePersistedTurn(reason)) return;
4328
4591
  await delay(RECONCILE_DELAY_MS);
4329
4592
  }
4330
4593
  } catch (error) {
@@ -4350,9 +4613,22 @@ var CoreAgentTaskSession = class {
4350
4613
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4351
4614
  this.emit("historyLoaded", { history: this.history });
4352
4615
  const recovered = page.content.find(
4353
- (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4616
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
4354
4617
  );
4355
- if (!recovered) return false;
4618
+ if (!recovered) {
4619
+ if (this.recoveredTerminalReason === void 0) return false;
4620
+ if (this.recoveredTerminalUsage !== void 0) {
4621
+ this.endedPollsWithoutRow += 1;
4622
+ if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
4623
+ }
4624
+ const newest = page.content.find(
4625
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4626
+ );
4627
+ if (!newest) return false;
4628
+ this._content = newest.content;
4629
+ this.finishTurn(reason, this.recoveredTerminalUsage);
4630
+ return true;
4631
+ }
4356
4632
  if (recovered.type === "ERROR") {
4357
4633
  const error = new AgentTaskTurnError(recovered.content);
4358
4634
  this.emit("error", { error: error.message });
@@ -4363,17 +4639,66 @@ var CoreAgentTaskSession = class {
4363
4639
  this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
4364
4640
  return true;
4365
4641
  }
4642
+ closesThisTurn(message) {
4643
+ if (!message.usage) return false;
4644
+ const prompt = message.usage.requestMessageId;
4645
+ return prompt === void 0 || !this.turnBaselineIds.has(prompt);
4646
+ }
4366
4647
  /** True once the server took the input; false when the box refused it on the stream. */
4367
4648
  async sendInput(input) {
4649
+ return (await this.handOver(input)).admitted;
4650
+ }
4651
+ // Resolves once the input left this session; `admitted` then says whether the server took it.
4652
+ // Wrapped so that awaiting the hand-over does not also await the answer.
4653
+ async handOver(input, clientMessageId, steering = false) {
4368
4654
  if (!this._taskId) throw new Error("Agent task has not been created.");
4369
- const direct = this.dependencies.channel.send(this._taskId, input);
4370
- if (direct) return direct;
4371
- await this.dependencies.tasks.sendInput(this._taskId, input);
4372
- return true;
4655
+ const direct = this.dependencies.channel.send(this._taskId, input, clientMessageId);
4656
+ if (direct) return { admitted: direct, direct: true };
4657
+ if (input.type === "runtime-request.respond") {
4658
+ throw new Error(
4659
+ "The answer to the Agent input request was not sent: the box channel is not connected right now."
4660
+ );
4661
+ }
4662
+ if (!COPILOT_INPUT_TYPES.has(input.type)) {
4663
+ throw new Error(
4664
+ `The Agent ${input.type} was not sent: the box channel is not connected right now.`
4665
+ );
4666
+ }
4667
+ const turnRunning = this._status === "streaming" || this._status === "cancelled";
4668
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content } : {
4669
+ type: "message",
4670
+ content: input.content,
4671
+ ...input.agentType ? { agentType: input.agentType } : {},
4672
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
4673
+ };
4674
+ await this.dependencies.tasks.sendInput(this._taskId, rest);
4675
+ return { admitted: Promise.resolve(true), direct: false };
4676
+ }
4677
+ async prepareSend() {
4678
+ if (this.openingPromise && !await this.openingPromise) {
4679
+ throw new Error("Agent task session could not be opened.");
4680
+ }
4681
+ await this.ensureTask();
4682
+ if (!this.isClosed()) await this.ensureChannel();
4373
4683
  }
4374
4684
  handleEvent(event) {
4375
4685
  this.emit("raw", event);
4376
4686
  const payload = asObject2(event.payload);
4687
+ if (payload && isSubagentFrame(event)) {
4688
+ this.handleSubagentFrame(event, payload);
4689
+ return;
4690
+ }
4691
+ const lifecycle = asObject2(payload?.lifecycle);
4692
+ if (this.repeatsTheRunningTurn(event, lifecycle)) return;
4693
+ if (event.type === "stepStart" || event.type === "steer") {
4694
+ const id = lifecycle?.clientMessageId;
4695
+ if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
4696
+ this.openingAwaitsStart = false;
4697
+ this.forgetFinishedTurn(lifecycle);
4698
+ }
4699
+ } else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
4700
+ this.rememberFinishedTurn(lifecycle);
4701
+ }
4377
4702
  switch (event.type) {
4378
4703
  // A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
4379
4704
  // como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
@@ -4386,14 +4711,30 @@ var CoreAgentTaskSession = class {
4386
4711
  this.consumeDelta(payload, "thinking");
4387
4712
  break;
4388
4713
  case "toolCall":
4389
- this.emitTool(payload, "call", event.timestamp);
4714
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call", event.timestamp);
4390
4715
  break;
4391
4716
  case "toolResult":
4392
- this.emitTool(payload, "result", event.timestamp);
4717
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "result", event.timestamp);
4393
4718
  break;
4394
4719
  case "workspace":
4395
4720
  this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
4396
4721
  break;
4722
+ case "stepStart":
4723
+ this.steerOpenedBy(asObject2(payload?.lifecycle));
4724
+ break;
4725
+ case "steer":
4726
+ this.steerOpenedBy(lifecycle);
4727
+ this.emit("steered", {
4728
+ text: typeof payload?.text === "string" ? payload.text : "",
4729
+ messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
4730
+ });
4731
+ break;
4732
+ case "messageQueued":
4733
+ this.steerQueuedBy(asObject2(payload?.lifecycle));
4734
+ break;
4735
+ case "subagentUpdate":
4736
+ this.applySubagent(payload);
4737
+ break;
4397
4738
  case "providerUsage": {
4398
4739
  const usage = providerUsageOf(payload);
4399
4740
  if (usage) this.emit("providerUsage", usage);
@@ -4401,15 +4742,17 @@ var CoreAgentTaskSession = class {
4401
4742
  }
4402
4743
  case "stepFinish": {
4403
4744
  const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
4404
- const lifecycle = payload?.lifecycle;
4745
+ const lifecycle2 = payload?.lifecycle;
4405
4746
  const usage = agentTurnUsageOf(payload?.usage);
4406
- if (reason === "interrupted" || lifecycle?.interruptTerminal === true) {
4407
- this.rememberFinishedTurn(lifecycle);
4747
+ const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
4748
+ if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
4749
+ if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
4750
+ this.rememberFinishedTurn(lifecycle2);
4408
4751
  this.finishTurn("interrupted", usage);
4409
4752
  break;
4410
4753
  }
4411
4754
  if (reason === "stop" || reason === "endTurn") {
4412
- this.rememberFinishedTurn(lifecycle);
4755
+ this.rememberFinishedTurn(lifecycle2);
4413
4756
  if (this.recoveryUsed) {
4414
4757
  this.recoveredTerminalReason = reason;
4415
4758
  this.recoveredTerminalUsage = usage;
@@ -4429,6 +4772,17 @@ var CoreAgentTaskSession = class {
4429
4772
  const code = typeof payload?.code === "string" ? payload.code : void 0;
4430
4773
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
4431
4774
  this.emit("error", { ...code ? { code } : {}, error: message });
4775
+ if (!payload?.lifecycle && payload?.requestId !== void 0) break;
4776
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
4777
+ if (typeof refused === "string") {
4778
+ if (refused !== this.openingMessageId) {
4779
+ const steered = [...this.steers, ...this.strayedSteers].find(
4780
+ (pending) => pending.clientMessageId === refused
4781
+ );
4782
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
4783
+ break;
4784
+ }
4785
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
4432
4786
  if (this._status === "streaming" || this._status === "cancelled") {
4433
4787
  this.failTurn(new AgentTaskTurnError(message, code));
4434
4788
  }
@@ -4438,6 +4792,27 @@ var CoreAgentTaskSession = class {
4438
4792
  break;
4439
4793
  }
4440
4794
  }
4795
+ repeatsTheRunningTurn(event, lifecycle) {
4796
+ if (this._status !== "streaming" && this._status !== "cancelled") return false;
4797
+ const turnId = lifecycle?.turnId;
4798
+ if (typeof turnId !== "string") return false;
4799
+ if (typeof event.sequence === "number") {
4800
+ if (this.turnIds.has(turnId) && event.sequence <= this.turnSequenceHigh) return true;
4801
+ this.turnSequenceHigh = Math.max(this.turnSequenceHigh, event.sequence);
4802
+ }
4803
+ this.turnIds.add(turnId);
4804
+ return false;
4805
+ }
4806
+ isFinishedTurnFrame(lifecycle) {
4807
+ const turnId = lifecycle?.turnId;
4808
+ return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
4809
+ }
4810
+ forgetFinishedTurn(lifecycle) {
4811
+ const turnId = lifecycle?.turnId;
4812
+ if (typeof turnId !== "string") return;
4813
+ const index = this.finishedTurnIds.indexOf(turnId);
4814
+ if (index >= 0) this.finishedTurnIds.splice(index, 1);
4815
+ }
4441
4816
  rememberFinishedTurn(lifecycle) {
4442
4817
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4443
4818
  if (!turnId) return;
@@ -4459,14 +4834,52 @@ var CoreAgentTaskSession = class {
4459
4834
  this.emit("delta", { delta: text, kind });
4460
4835
  }
4461
4836
  emitTool(payload, phase, timestamp) {
4462
- this.emit("tool", {
4463
- tool: typeof payload?.name === "string" ? payload.name : "",
4464
- phase,
4465
- timestamp,
4466
- ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4467
- ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4468
- ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4469
- });
4837
+ this.emit("tool", toolEventOf(payload, phase, timestamp));
4838
+ }
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`.
4841
+ handleSubagentFrame(event, payload) {
4842
+ const parentToolId = payload.parentToolId;
4843
+ switch (event.type) {
4844
+ case "textDelta":
4845
+ 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
+ });
4852
+ break;
4853
+ case "toolCall":
4854
+ case "toolResult":
4855
+ this.emit("subagentTool", {
4856
+ ...toolEventOf(payload, event.type === "toolCall" ? "call" : "result", event.timestamp),
4857
+ parentToolId
4858
+ });
4859
+ break;
4860
+ default:
4861
+ break;
4862
+ }
4863
+ }
4864
+ applySubagent(payload) {
4865
+ const subagentId = payload?.subagentId;
4866
+ const toolId = payload?.toolId;
4867
+ if (typeof subagentId !== "string" || typeof toolId !== "string") return;
4868
+ const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
4869
+ if (status === void 0) return;
4870
+ const startedAt = epochOf(payload?.startedAt);
4871
+ const endedAt = epochOf(payload?.endedAt);
4872
+ const subagent = {
4873
+ subagentId,
4874
+ toolId,
4875
+ status,
4876
+ ...typeof payload?.progress === "string" ? { progress: payload.progress } : {},
4877
+ ...startedAt !== void 0 ? { startedAt } : {},
4878
+ ...endedAt !== void 0 ? { endedAt } : {},
4879
+ ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
4880
+ };
4881
+ this.subagentsById.set(subagentId, subagent);
4882
+ this.emit("subagent", subagent);
4470
4883
  }
4471
4884
  finishTurn(reason, usage) {
4472
4885
  if (this._status !== "streaming" && this._status !== "cancelled") return;
@@ -4491,8 +4904,8 @@ var CoreAgentTaskSession = class {
4491
4904
  this.emit("turnEnd", result);
4492
4905
  this.activeWaiter?.resolve(result);
4493
4906
  this.activeWaiter = void 0;
4907
+ this.settleSteers((waiter) => waiter.resolve(result));
4494
4908
  this.setStatus("idle");
4495
- this.flushQueue();
4496
4909
  }
4497
4910
  failTurn(error) {
4498
4911
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
@@ -4500,56 +4913,17 @@ var CoreAgentTaskSession = class {
4500
4913
  this.recoveryGeneration += 1;
4501
4914
  this.activeWaiter?.reject(error);
4502
4915
  this.activeWaiter = void 0;
4916
+ this.settleSteers((waiter) => waiter.reject(error));
4503
4917
  this.setStatus("idle");
4504
- this.flushQueue();
4505
4918
  }
4506
4919
  failLiveChannel(observed, waiterError) {
4507
4920
  this.recoveryGeneration += 1;
4508
4921
  this.emitError("Agent live channel failed", observed);
4509
4922
  this.activeWaiter?.reject(waiterError);
4510
4923
  this.activeWaiter = void 0;
4511
- for (const item of this._queue) item.waiter?.reject(waiterError);
4512
- this._queue = [];
4513
- this.emitQueue();
4924
+ this.rejectSteers(waiterError);
4514
4925
  this.setStatus("error");
4515
4926
  }
4516
- enqueue(text, options, waiter) {
4517
- if (this._queue.length >= AGENT_QUEUE_LIMIT) {
4518
- const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
4519
- waiter?.reject(error);
4520
- this.emit("error", { error: error.message });
4521
- return void 0;
4522
- }
4523
- const id = `q-${++this.queueSequence}`;
4524
- this._queue = [
4525
- ...this._queue,
4526
- { id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
4527
- ];
4528
- this.emitQueue();
4529
- return id;
4530
- }
4531
- flushQueue() {
4532
- if (this.isBusy()) return;
4533
- let next = this._queue[0];
4534
- while (next?.waiter?.settled) {
4535
- this._queue = this._queue.slice(1);
4536
- next = this._queue[0];
4537
- }
4538
- if (!next) {
4539
- this.emitQueue();
4540
- return;
4541
- }
4542
- this._queue = this._queue.slice(1);
4543
- this.emitQueue();
4544
- this.startDispatch(
4545
- next.text,
4546
- {
4547
- ...next.agentType ? { agentType: next.agentType } : {},
4548
- ...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
4549
- },
4550
- next.waiter
4551
- );
4552
- }
4553
4927
  createWaiter(options) {
4554
4928
  let resolvePromise;
4555
4929
  let rejectPromise;
@@ -4571,7 +4945,6 @@ var CoreAgentTaskSession = class {
4571
4945
  if (waiter.settled) return;
4572
4946
  waiter.settled = true;
4573
4947
  waiter.cleanup();
4574
- if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
4575
4948
  rejectPromise(error);
4576
4949
  },
4577
4950
  cleanup: () => {
@@ -4596,14 +4969,6 @@ var CoreAgentTaskSession = class {
4596
4969
  }
4597
4970
  return waiter;
4598
4971
  }
4599
- removeQueuedWaiter(id) {
4600
- const size = this._queue.length;
4601
- this._queue = this._queue.filter((item) => item.id !== id);
4602
- if (this._queue.length !== size) this.emitQueue();
4603
- }
4604
- emitQueue() {
4605
- this.emit("queueChange", { queue: this.queue });
4606
- }
4607
4972
  emitError(prefix, error) {
4608
4973
  const code = errorCode(error);
4609
4974
  this.emit("error", {
@@ -4613,6 +4978,12 @@ var CoreAgentTaskSession = class {
4613
4978
  }
4614
4979
  setStatus(status) {
4615
4980
  if (this._status === status) return;
4981
+ if (status !== "streaming" && status !== "cancelled") {
4982
+ this.openingAwaitsStart = false;
4983
+ this.endedPollsWithoutRow = 0;
4984
+ this.turnIds.clear();
4985
+ this.turnSequenceHigh = -1;
4986
+ }
4616
4987
  this._status = status;
4617
4988
  this.emit("statusChange", { status });
4618
4989
  }
@@ -4622,8 +4993,11 @@ var CoreAgentTaskSession = class {
4622
4993
  isClosed() {
4623
4994
  return this._status === "closed";
4624
4995
  }
4996
+ // A turn running or being opened takes a new message as a steer. So does a session waiting for
4997
+ // the turn the box opens for a steer it took late: a new message started as a turn of its own
4998
+ // then would be answered by the steer's result, and the steer by its.
4625
4999
  isBusy() {
4626
- return this.dispatching || this._status === "streaming" || this._status === "cancelled";
5000
+ return this.dispatching || this._status === "streaming" || this._status === "cancelled" || this.strayedSteers.length > 0;
4627
5001
  }
4628
5002
  emit(event, payload) {
4629
5003
  const listeners = this.listeners.get(event);