@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.cjs CHANGED
@@ -508,6 +508,9 @@ function expectAppFields(app, context, errors) {
508
508
  if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
509
509
  if (!isNullableString(app.template)) invalidField(context, "template", errors);
510
510
  if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
511
+ for (const field of ["emailLoginEnabled", "passwordLoginEnabled"]) {
512
+ if (field in app && typeof app[field] !== "boolean") invalidField(context, field, errors);
513
+ }
511
514
  if (typeof app.externalAccessEnabled !== "boolean") {
512
515
  invalidField(context, "externalAccessEnabled", errors);
513
516
  }
@@ -1029,7 +1032,8 @@ var TURN_USAGE_COUNTS = [
1029
1032
  "cacheReadTokens",
1030
1033
  "cacheCreationTokens",
1031
1034
  "requestCount",
1032
- "durationMs"
1035
+ "durationMs",
1036
+ "contextTokens"
1033
1037
  ];
1034
1038
  var TURN_USAGE_COSTS = ["costUsd", "costUsdRaw"];
1035
1039
  var TURN_USAGE_STRINGS = [
@@ -1057,6 +1061,8 @@ function agentTurnUsageOf(value) {
1057
1061
  const item = value[field];
1058
1062
  if (isCount(item)) usage[field] = item;
1059
1063
  }
1064
+ const { contextWindow } = value;
1065
+ if (isInteger(contextWindow) && contextWindow > 0) usage.contextWindow = contextWindow;
1060
1066
  for (const field of TURN_USAGE_COSTS) {
1061
1067
  const item = value[field];
1062
1068
  if (isFiniteNumber(item)) usage[field] = item;
@@ -2929,9 +2935,31 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2929
2935
  "Notify user response",
2930
2936
  errors
2931
2937
  );
2938
+ },
2939
+ async sendEmail(input) {
2940
+ return expectMessageAccepted(
2941
+ await transport.request("/api/v1/messages/send", {
2942
+ method: "POST",
2943
+ body: { channel: "EMAIL", payload: rawEmailPayload(input) }
2944
+ }),
2945
+ "Send email response",
2946
+ errors
2947
+ );
2932
2948
  }
2933
2949
  };
2934
2950
  }
2951
+ function rawEmailPayload(input) {
2952
+ return {
2953
+ type: "RAW",
2954
+ to: input.to,
2955
+ ...input.cc === void 0 ? {} : { cc: input.cc },
2956
+ ...input.bcc === void 0 ? {} : { bcc: input.bcc },
2957
+ ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo },
2958
+ subject: input.subject,
2959
+ html: input.html,
2960
+ ...input.text === void 0 ? {} : { text: input.text }
2961
+ };
2962
+ }
2935
2963
 
2936
2964
  // src/modules/publicFunctions.ts
2937
2965
  function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
@@ -3283,6 +3311,29 @@ var ADMISSION_TIMEOUT_MS = 35e3;
3283
3311
  var SUPERSEDED_CLOSE_CODE = 4409;
3284
3312
  var SOCKET_OPEN = 1;
3285
3313
  var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
3314
+ var clientMessageSequence = 0;
3315
+ function newClientMessageId() {
3316
+ const random = globalThis.crypto?.randomUUID;
3317
+ return random ? random.call(globalThis.crypto) : `m-${Date.now()}-${++clientMessageSequence}`;
3318
+ }
3319
+ function admissionFor(link, event) {
3320
+ const payload = asObject(event.payload);
3321
+ if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
3322
+ return void 0;
3323
+ }
3324
+ const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
3325
+ if (typeof id === "string")
3326
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3327
+ return link.admissions[0];
3328
+ }
3329
+ function queuedAdmission(link, event) {
3330
+ const id = asObject(asObject(event.payload)?.lifecycle)?.clientMessageId;
3331
+ if (typeof id !== "string") return void 0;
3332
+ return link.admissions.find((pending) => pending.clientMessageId === id);
3333
+ }
3334
+ function isSubagentFrame(event) {
3335
+ return typeof asObject(event.payload)?.parentToolId === "string";
3336
+ }
3286
3337
  function asObject(value) {
3287
3338
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3288
3339
  }
@@ -3403,6 +3454,7 @@ function asDelta(event) {
3403
3454
  }
3404
3455
  var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3405
3456
  "stepStart",
3457
+ "steer",
3406
3458
  "textDelta",
3407
3459
  "thinking",
3408
3460
  "toolCall",
@@ -3411,7 +3463,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3411
3463
  var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3412
3464
  function turnAfter(event, inTurn) {
3413
3465
  if (TURN_FRAME_TYPES.has(event.type)) return true;
3414
- if (event.type === "error") return false;
3466
+ if (event.type === "error") return asObject(event.payload)?.lifecycle ? false : inTurn;
3415
3467
  if (event.type === "stepFinish") {
3416
3468
  const payload = asObject(event.payload);
3417
3469
  if (TURN_END_REASONS.has(payload?.reason)) return false;
@@ -3419,6 +3471,21 @@ function turnAfter(event, inTurn) {
3419
3471
  }
3420
3472
  return inTurn;
3421
3473
  }
3474
+ function lostTurnFrame(turnId) {
3475
+ return {
3476
+ type: "stepFinish",
3477
+ payload: {
3478
+ reason: "interrupted",
3479
+ lifecycle: {
3480
+ ...turnId === void 0 ? {} : { turnId },
3481
+ terminal: true,
3482
+ sessionIdle: true,
3483
+ interruptTerminal: true
3484
+ }
3485
+ },
3486
+ timestamp: Date.now()
3487
+ };
3488
+ }
3422
3489
  function channelEvent(type, payload) {
3423
3490
  return { type, payload, timestamp: Date.now() };
3424
3491
  }
@@ -3498,9 +3565,11 @@ var AgentDirectChannel = class {
3498
3565
  }
3499
3566
  }
3500
3567
  /**
3501
- * Hands a message or an interrupt to the box when the chat is on the direct channel and its
3502
- * wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
3503
- * mid-redial, or an approval, which stays on REST.
3568
+ * Hands a message, an interrupt, a subagent stop or an answer to a T3 input request to the box
3569
+ * 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
3570
+ * mid-redial, or an approval, which stays on REST. Mid-redial the Copilot is the durable path:
3571
+ * the box URL kept from the last channel carries a proxy ticket that lasts 60 seconds, and a
3572
+ * box that dropped the socket is often the one that went away.
3504
3573
  *
3505
3574
  * A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
3506
3575
  * the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
@@ -3513,12 +3582,12 @@ var AgentDirectChannel = class {
3513
3582
  * have admitted the turn, and a second copy would start it twice. The redial replays the box
3514
3583
  * log, where the `stepStart` of an admitted turn is.
3515
3584
  */
3516
- send(taskId, input) {
3585
+ send(taskId, input, clientMessageId) {
3517
3586
  if (input.type === "approval_response") return null;
3518
3587
  const link = this.links.get(taskId);
3519
3588
  if (!link?.wire) return null;
3520
3589
  if (input.type !== "message") return link.wire.interrupt(input);
3521
- link.admission?.fail(new Error("A newer message replaced the one waiting for the box."));
3590
+ const messageId = clientMessageId ?? newClientMessageId();
3522
3591
  let admission;
3523
3592
  const admitted = new Promise((resolve, reject) => {
3524
3593
  let timer;
@@ -3534,11 +3603,13 @@ var AgentDirectChannel = class {
3534
3603
  };
3535
3604
  const done = () => {
3536
3605
  clearTimeout(timer);
3537
- if (link.admission === admission) link.admission = null;
3606
+ link.admissions = link.admissions.filter((pending) => pending !== admission);
3538
3607
  };
3539
3608
  admission = {
3609
+ clientMessageId: messageId,
3540
3610
  settle: (value) => {
3541
3611
  done();
3612
+ if (value) link.inTurn = true;
3542
3613
  resolve(value);
3543
3614
  },
3544
3615
  fail: (error) => {
@@ -3550,12 +3621,11 @@ var AgentDirectChannel = class {
3550
3621
  };
3551
3622
  arm();
3552
3623
  });
3553
- link.admission = admission;
3554
- if (!link.wire.message(input, admission)) {
3624
+ link.admissions = [...link.admissions, admission];
3625
+ if (!link.wire.message({ ...input, clientMessageId: messageId }, admission)) {
3555
3626
  admission.settle(false);
3556
3627
  return null;
3557
3628
  }
3558
- link.inTurn = true;
3559
3629
  return admitted;
3560
3630
  }
3561
3631
  /** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
@@ -3612,7 +3682,7 @@ var AgentDirectChannel = class {
3612
3682
  * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3613
3683
  */
3614
3684
  async openDirect(taskId, mode, channel, observer, signal) {
3615
- const link = { wire: null, inTurn: false, admission: null };
3685
+ const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
3616
3686
  let box = boxAddress(channel.wsUrl);
3617
3687
  let cursor = channel.lastSequence;
3618
3688
  const abort = new AbortController();
@@ -3620,35 +3690,46 @@ var AgentDirectChannel = class {
3620
3690
  signal?.addEventListener("abort", onAbort, { once: true });
3621
3691
  const onFrame = (event) => {
3622
3692
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3693
+ if (isSubagentFrame(event)) {
3694
+ observer.onEvent(event);
3695
+ return;
3696
+ }
3697
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3698
+ if (typeof turnId === "string") link.turnId = turnId;
3623
3699
  link.inTurn = turnAfter(event, link.inTurn);
3624
3700
  observer.onEvent(event);
3625
- if (event.type === "stepStart") link.admission?.settle(true);
3626
- else if (event.type === "error") link.admission?.settle(false);
3701
+ if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
3702
+ else if (event.type === "error") admissionFor(link, event)?.settle(false);
3703
+ else if (event.type === "messageQueued" || event.type === "steer") {
3704
+ queuedAdmission(link, event)?.settle(true);
3705
+ }
3627
3706
  };
3628
3707
  const onLost = (error, code) => {
3629
3708
  link.wire = null;
3630
3709
  if (abort.signal.aborted) return;
3631
- if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
3632
- link.admission?.fail(error);
3710
+ if (!link.inTurn && link.admissions.length === 0 || code === SUPERSEDED_CLOSE_CODE) {
3711
+ for (const pending of link.admissions) pending.fail(error);
3633
3712
  observer.onDisconnect(error);
3634
3713
  return;
3635
3714
  }
3636
- link.admission?.hold();
3715
+ for (const pending of link.admissions) pending.hold();
3637
3716
  void this.redial(taskId, mode, error, abort.signal, observer, {
3638
3717
  onFrame,
3639
3718
  onLost,
3640
3719
  replayFrom: (next) => {
3641
3720
  const nextBox = boxAddress(next.wsUrl);
3642
- if (nextBox === box) return cursor;
3721
+ const zeroed = next.lastSequence === 0 && cursor > 0;
3722
+ if (nextBox === box && !zeroed) return cursor;
3723
+ if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3643
3724
  box = nextBox;
3644
3725
  cursor = next.lastSequence;
3645
3726
  return void 0;
3646
3727
  }
3647
3728
  }).then((outcome) => {
3648
- if (outcome instanceof Error) link.admission?.fail(outcome);
3729
+ if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
3649
3730
  else if (outcome) {
3650
3731
  link.wire = outcome;
3651
- link.admission?.rearm();
3732
+ for (const pending of link.admissions) pending.rearm();
3652
3733
  }
3653
3734
  });
3654
3735
  };
@@ -3669,9 +3750,8 @@ var AgentDirectChannel = class {
3669
3750
  abort.abort();
3670
3751
  link.wire?.close();
3671
3752
  link.wire = null;
3672
- link.admission?.fail(
3673
- new Error("The Agent session closed before the box confirmed the turn.")
3674
- );
3753
+ const closed = new Error("The Agent session closed before the box confirmed the turn.");
3754
+ for (const pending of link.admissions) pending.fail(closed);
3675
3755
  if (this.links.get(taskId) === link) this.links.delete(taskId);
3676
3756
  }
3677
3757
  };
@@ -3808,7 +3888,7 @@ var AgentDirectChannel = class {
3808
3888
  close,
3809
3889
  interrupt: (input) => post(input).then((response) => {
3810
3890
  if (!response.ok) {
3811
- throw new Error(`The Agent box refused the interrupt (${response.status}).`);
3891
+ throw new Error(`The Agent box refused the ${input.type} (${response.status}).`);
3812
3892
  }
3813
3893
  return true;
3814
3894
  }),
@@ -3990,9 +4070,22 @@ var AgentDirectChannel = class {
3990
4070
  };
3991
4071
 
3992
4072
  // src/agentSession.ts
3993
- var AGENT_QUEUE_LIMIT = 10;
3994
4073
  var CANCEL_SAFETY_MS = 1e4;
3995
4074
  var RECONCILE_DELAY_MS = 1e3;
4075
+ var ENDED_POLLS_BEFORE_NEWEST = 3;
4076
+ var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
4077
+ "textDelta",
4078
+ "textChunk",
4079
+ "thinking",
4080
+ "toolCall",
4081
+ "toolResult",
4082
+ "stepFinish"
4083
+ ]);
4084
+ var COPILOT_INPUT_TYPES = /* @__PURE__ */ new Set([
4085
+ "message",
4086
+ "interrupt",
4087
+ "approval_response"
4088
+ ]);
3996
4089
  function providerUsageOf(payload) {
3997
4090
  if (!payload) return null;
3998
4091
  try {
@@ -4021,6 +4114,31 @@ function errorCode(error) {
4021
4114
  function delay(milliseconds) {
4022
4115
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
4023
4116
  }
4117
+ function messageInput(prompt, options) {
4118
+ return {
4119
+ type: "message",
4120
+ content: prompt,
4121
+ ...options.agentType ? { agentType: options.agentType } : {},
4122
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4123
+ mode: "steer"
4124
+ };
4125
+ }
4126
+ function toolEventOf(payload, phase, timestamp) {
4127
+ return {
4128
+ tool: typeof payload?.name === "string" ? payload.name : "",
4129
+ phase,
4130
+ timestamp,
4131
+ ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4132
+ ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4133
+ ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4134
+ };
4135
+ }
4136
+ function epochOf(value) {
4137
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4138
+ if (typeof value !== "string") return void 0;
4139
+ const parsed = Date.parse(value);
4140
+ return Number.isNaN(parsed) ? void 0 : parsed;
4141
+ }
4024
4142
  function toAgentTimelineItem(message) {
4025
4143
  if (message.type === "TOOL_USE") {
4026
4144
  try {
@@ -4094,7 +4212,6 @@ var CoreAgentTaskSession = class {
4094
4212
  _status = "opening";
4095
4213
  _history = [];
4096
4214
  _content = "";
4097
- _queue = [];
4098
4215
  isNewSession;
4099
4216
  listeners = /* @__PURE__ */ new Map();
4100
4217
  connection = null;
@@ -4113,10 +4230,36 @@ var CoreAgentTaskSession = class {
4113
4230
  recoveryGeneration = 0;
4114
4231
  recoveredTerminalReason;
4115
4232
  recoveredTerminalUsage;
4233
+ // Polls that found no closing row although a terminal with usage was heard.
4234
+ endedPollsWithoutRow = 0;
4235
+ // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
4236
+ // stream a dropped session falls back to replays the turn from what the history has, so it
4237
+ // repeats frames the box socket already delivered.
4238
+ turnIds = /* @__PURE__ */ new Set();
4239
+ turnSequenceHigh = -1;
4116
4240
  cancelTimer = null;
4117
- queueSequence = 0;
4241
+ // Messages leave in the order they were sent: each one is handed over only after the one
4242
+ // before it was, not after it was answered.
4243
+ handOff = Promise.resolve();
4118
4244
  activeWaiter;
4245
+ // Every steer sits in exactly one of the two lists until it is settled or forgotten: `steers`
4246
+ // while the turn it was sent into runs (taken ones settle with that turn), `strayedSteers` once
4247
+ // it waits for a turn of its own (sent with no turn, not taken when its turn ended, or queued by
4248
+ // the provider). A non-empty `strayedSteers` keeps the session busy, which is what stops a new
4249
+ // message from opening a turn the steer's answer would settle. `pendingSteers` counts the ones
4250
+ // the box has not answered yet, wherever they sit.
4251
+ steers = [];
4252
+ strayedSteers = [];
4253
+ pendingSteers = 0;
4254
+ // The id the message that opened the current turn went out with, so a refusal naming it fails
4255
+ // that turn and one naming a steer does not.
4256
+ openingMessageId;
4257
+ // The opening message went to the box, which starts its turn with a `stepStart`. Until then a
4258
+ // turn frame naming a turn is another turn's tail: the one before, closed here from the history
4259
+ // (r5 S17, dev 2026-10-19), whose live end came after the next message went out.
4260
+ openingAwaitsStart = false;
4119
4261
  turnBaselineIds = /* @__PURE__ */ new Set();
4262
+ subagentsById = /* @__PURE__ */ new Map();
4120
4263
  get taskId() {
4121
4264
  return this._taskId;
4122
4265
  }
@@ -4136,19 +4279,16 @@ var CoreAgentTaskSession = class {
4136
4279
  return this._content;
4137
4280
  }
4138
4281
  get queue() {
4139
- return this._queue.map((item) => ({
4140
- id: item.id,
4141
- text: item.text,
4142
- createdAt: item.createdAt,
4143
- ...item.agentType ? { agentType: item.agentType } : {},
4144
- ...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
4145
- }));
4282
+ return [];
4283
+ }
4284
+ get subagents() {
4285
+ return [...this.subagentsById.values()];
4146
4286
  }
4147
4287
  send(prompt, options = {}) {
4148
4288
  this.requireOpen();
4149
4289
  if (!prompt.trim()) return;
4150
4290
  if (this.isBusy()) {
4151
- this.enqueue(prompt, options);
4291
+ this.steer(prompt, options);
4152
4292
  return;
4153
4293
  }
4154
4294
  this.startDispatch(prompt, options);
@@ -4163,8 +4303,7 @@ var CoreAgentTaskSession = class {
4163
4303
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4164
4304
  };
4165
4305
  if (this.isBusy()) {
4166
- const queueId = this.enqueue(prompt, sendOptions, waiter);
4167
- if (queueId) waiter.queueId = queueId;
4306
+ this.steer(prompt, sendOptions, waiter);
4168
4307
  return waiter.promise;
4169
4308
  }
4170
4309
  this.startDispatch(prompt, sendOptions, waiter);
@@ -4199,6 +4338,17 @@ var CoreAgentTaskSession = class {
4199
4338
  this.emitError("Failed to answer Agent approval", error);
4200
4339
  });
4201
4340
  }
4341
+ respondUserInput(requestId, answers, attachmentsByQuestionId) {
4342
+ const input = {
4343
+ type: "runtime-request.respond",
4344
+ requestId,
4345
+ answers,
4346
+ ...attachmentsByQuestionId ? { attachmentsByQuestionId } : {}
4347
+ };
4348
+ void this.sendInput(input).catch((error) => {
4349
+ this.emitError("Failed to answer Agent input request", error);
4350
+ });
4351
+ }
4202
4352
  async loadHistory(options = {}) {
4203
4353
  if (!this._taskId) return [];
4204
4354
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
@@ -4210,26 +4360,17 @@ var CoreAgentTaskSession = class {
4210
4360
  this.emit("historyLoaded", { history });
4211
4361
  return history;
4212
4362
  }
4213
- editQueueItem(id, text) {
4214
- if (!text.trim()) {
4215
- this.removeQueueItem(id);
4216
- return;
4217
- }
4218
- this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
4219
- this.emitQueue();
4363
+ editQueueItem() {
4220
4364
  }
4221
- removeQueueItem(id) {
4222
- const removed = this._queue.find((item) => item.id === id);
4223
- this._queue = this._queue.filter((item) => item.id !== id);
4224
- removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
4225
- this.emitQueue();
4365
+ removeQueueItem() {
4226
4366
  }
4227
4367
  clearQueue() {
4228
- if (!this._queue.length) return;
4229
- const removed = this._queue;
4230
- this._queue = [];
4231
- for (const item of removed) item.waiter?.reject(new Error("Agent prompt queue was cleared."));
4232
- this.emitQueue();
4368
+ }
4369
+ stopSubagent(subagentId) {
4370
+ this.requireOpen();
4371
+ void this.sendInput({ type: "subagent.stop", subagentId }).catch((error) => {
4372
+ this.emitError("Failed to stop the Agent subagent", error);
4373
+ });
4233
4374
  }
4234
4375
  on(event, handler) {
4235
4376
  let listeners = this.listeners.get(event);
@@ -4254,8 +4395,7 @@ var CoreAgentTaskSession = class {
4254
4395
  const closedError = new Error("Agent task session is closed.");
4255
4396
  this.activeWaiter?.reject(closedError);
4256
4397
  this.activeWaiter = void 0;
4257
- for (const item of this._queue) item.waiter?.reject(closedError);
4258
- this._queue = [];
4398
+ this.rejectSteers(closedError);
4259
4399
  if (this._taskId) this.dependencies.onClose(this._taskId, this);
4260
4400
  for (const listeners of this.listeners.values()) listeners.clear();
4261
4401
  }
@@ -4278,31 +4418,32 @@ var CoreAgentTaskSession = class {
4278
4418
  }
4279
4419
  startDispatch(prompt, options, waiter) {
4280
4420
  this.dispatching = true;
4281
- const dispatch = this.dispatchSend(prompt, options, waiter).catch((error) => {
4421
+ let handedOver;
4422
+ this.handOff = new Promise((resolve) => {
4423
+ handedOver = resolve;
4424
+ });
4425
+ const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
4282
4426
  waiter?.reject(error);
4283
4427
  this.emitError("Failed to send Agent prompt", error);
4284
- if (this._status === "streaming") this.setStatus("idle");
4285
- this.flushQueue();
4428
+ if (this._status === "streaming") {
4429
+ this.settleSteers((steered) => steered.reject(error));
4430
+ this.setStatus("idle");
4431
+ }
4286
4432
  return false;
4287
4433
  }).finally(() => {
4434
+ handedOver();
4288
4435
  this.dispatching = false;
4289
4436
  if (this.dispatch === dispatch) this.dispatch = null;
4290
- if (this._status === "idle") this.flushQueue();
4291
4437
  });
4292
4438
  this.dispatch = dispatch;
4293
4439
  }
4294
- async dispatchSend(prompt, options, waiter) {
4440
+ async dispatchSend(prompt, options, handedOver, waiter) {
4295
4441
  if (this.openingPromise && !await this.openingPromise) {
4296
4442
  throw new Error("Agent task session could not be opened.");
4297
4443
  }
4298
4444
  if (this.isClosed() || waiter?.settled) return false;
4299
4445
  await this.ensureTask();
4300
- const input = {
4301
- type: "message",
4302
- content: prompt,
4303
- ...options.agentType ? { agentType: options.agentType } : {},
4304
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4305
- };
4446
+ const input = messageInput(prompt, options);
4306
4447
  if (this.isClosed()) {
4307
4448
  await this.sendInput(input).catch(() => void 0);
4308
4449
  return false;
@@ -4319,10 +4460,134 @@ var CoreAgentTaskSession = class {
4319
4460
  this.activeWaiter = waiter;
4320
4461
  this.setStatus("streaming");
4321
4462
  this.emit("turnStart", {});
4322
- if (!await this.sendInput(input)) return false;
4463
+ this.openingMessageId = newClientMessageId();
4464
+ this.openingAwaitsStart = true;
4465
+ const { admitted, direct } = await this.handOver(input, this.openingMessageId);
4466
+ if (!direct) this.openingAwaitsStart = false;
4467
+ handedOver();
4468
+ if (!await admitted) return false;
4323
4469
  this.emit("accepted", {});
4324
4470
  return true;
4325
4471
  }
4472
+ // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
4473
+ // that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
4474
+ // that turn already ended. Nothing waits in this session. On the direct channel it goes with an
4475
+ // id the box echoes on the frame that takes it; without the channel, over REST to the Copilot,
4476
+ // which holds it while the box boots.
4477
+ //
4478
+ // It keeps its `agentType` and `reasoningEffort` on the box, which leaves the running turn's
4479
+ // model alone by itself and needs them for a message that becomes a turn of its own. Only on
4480
+ // the Copilot path, with a turn running, they are dropped: the Copilot restarts the live
4481
+ // session for a message that asks for another model, which would end that turn.
4482
+ steer(prompt, options, waiter) {
4483
+ const steered = {
4484
+ clientMessageId: newClientMessageId(),
4485
+ ...waiter ? { waiter } : {},
4486
+ taken: false
4487
+ };
4488
+ if (this.dispatching || this._status === "streaming" || this._status === "cancelled") {
4489
+ this.steers.push(steered);
4490
+ } else {
4491
+ this.strayedSteers.push(steered);
4492
+ }
4493
+ const input = messageInput(prompt, options);
4494
+ this.pendingSteers += 1;
4495
+ const handed = this.handOff.then(async () => {
4496
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4497
+ await this.prepareSend();
4498
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
4499
+ return this.handOver(input, steered.clientMessageId, true);
4500
+ });
4501
+ this.handOff = handed.then(
4502
+ () => void 0,
4503
+ () => void 0
4504
+ );
4505
+ void handed.then(({ admitted }) => admitted).then((admitted) => {
4506
+ if (!admitted) {
4507
+ this.forgetSteer(steered);
4508
+ waiter?.reject(
4509
+ steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
4510
+ );
4511
+ return;
4512
+ }
4513
+ if (!steered.queued) this.steerTaken(steered);
4514
+ this.emit("accepted", {});
4515
+ }).catch((error) => {
4516
+ this.forgetSteer(steered);
4517
+ waiter?.reject(error);
4518
+ this.emitError("Failed to send Agent prompt", error);
4519
+ }).finally(() => {
4520
+ this.pendingSteers -= 1;
4521
+ });
4522
+ }
4523
+ // The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
4524
+ // of its own, when that one ended before the box got to the message.
4525
+ steerTaken(steered) {
4526
+ if (steered.taken) return;
4527
+ steered.taken = true;
4528
+ if (!this.strayedSteers.includes(steered)) return;
4529
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4530
+ this.openTurnFor(steered.waiter);
4531
+ }
4532
+ steerOpenedBy(lifecycle) {
4533
+ const id = lifecycle?.clientMessageId;
4534
+ if (typeof id !== "string") return;
4535
+ const steered = [...this.steers, ...this.strayedSteers].find(
4536
+ (pending) => pending.clientMessageId === id
4537
+ );
4538
+ if (steered) this.steerTaken(steered);
4539
+ }
4540
+ // Queued behind the running turn, the message is answered by the turn the box opens for it
4541
+ // later, not by this one.
4542
+ steerQueuedBy(lifecycle) {
4543
+ const id = lifecycle?.clientMessageId;
4544
+ if (typeof id !== "string") return;
4545
+ const steered = [...this.steers, ...this.strayedSteers].find(
4546
+ (pending) => pending.clientMessageId === id
4547
+ );
4548
+ if (!steered || steered.taken) return;
4549
+ steered.queued = true;
4550
+ if (!this.steers.includes(steered)) return;
4551
+ this.steers = this.steers.filter((pending) => pending !== steered);
4552
+ this.strayedSteers.push(steered);
4553
+ }
4554
+ forgetSteer(steered) {
4555
+ this.steers = this.steers.filter((pending) => pending !== steered);
4556
+ this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
4557
+ }
4558
+ // The turn ended: what the box took is answered by it, what it had not taken yet waits for the
4559
+ // turn the box opens for it.
4560
+ settleSteers(settle) {
4561
+ const steers = this.steers;
4562
+ this.steers = [];
4563
+ for (const steered of steers) {
4564
+ if (!steered.taken) this.strayedSteers.push(steered);
4565
+ else if (steered.waiter) settle(steered.waiter);
4566
+ }
4567
+ }
4568
+ openTurnFor(waiter) {
4569
+ if (this.isClosed()) return;
4570
+ if (this._status !== "streaming" && this._status !== "cancelled") {
4571
+ this._content = "";
4572
+ this.recoveryUsed = false;
4573
+ this.recoveredTerminalReason = void 0;
4574
+ this.recoveredTerminalUsage = void 0;
4575
+ this.recoveryGeneration += 1;
4576
+ this.turnBaselineIds = new Set(this._history.map((item) => item.id));
4577
+ void this.captureTurnBaseline().catch(() => void 0);
4578
+ this.setStatus("streaming");
4579
+ this.emit("turnStart", {});
4580
+ }
4581
+ if (!waiter) return;
4582
+ if (!this.activeWaiter) this.activeWaiter = waiter;
4583
+ else this.steers.push({ clientMessageId: "", waiter, taken: true });
4584
+ }
4585
+ rejectSteers(error) {
4586
+ const steers = [...this.steers, ...this.strayedSteers];
4587
+ this.steers = [];
4588
+ this.strayedSteers = [];
4589
+ for (const steered of steers) steered.waiter?.reject(error);
4590
+ }
4326
4591
  async ensureTask() {
4327
4592
  if (this._taskId) return;
4328
4593
  if (!("create" in this.options)) throw new Error("Agent task session has no task.");
@@ -4393,10 +4658,8 @@ var CoreAgentTaskSession = class {
4393
4658
  try {
4394
4659
  await this.ensureChannel();
4395
4660
  while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
4396
- if (await this.reconcilePersistedTurn(this.recoveredTerminalReason ?? "reconciled")) {
4397
- return;
4398
- }
4399
- if (this.activeWaiter?.settled) return;
4661
+ const reason = this.recoveredTerminalReason ?? (this._status === "cancelled" ? "interrupted" : "reconciled");
4662
+ if (await this.reconcilePersistedTurn(reason)) return;
4400
4663
  await delay(RECONCILE_DELAY_MS);
4401
4664
  }
4402
4665
  } catch (error) {
@@ -4422,9 +4685,22 @@ var CoreAgentTaskSession = class {
4422
4685
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4423
4686
  this.emit("historyLoaded", { history: this.history });
4424
4687
  const recovered = page.content.find(
4425
- (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4688
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
4426
4689
  );
4427
- if (!recovered) return false;
4690
+ if (!recovered) {
4691
+ if (this.recoveredTerminalReason === void 0) return false;
4692
+ if (this.recoveredTerminalUsage !== void 0) {
4693
+ this.endedPollsWithoutRow += 1;
4694
+ if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
4695
+ }
4696
+ const newest = page.content.find(
4697
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4698
+ );
4699
+ if (!newest) return false;
4700
+ this._content = newest.content;
4701
+ this.finishTurn(reason, this.recoveredTerminalUsage);
4702
+ return true;
4703
+ }
4428
4704
  if (recovered.type === "ERROR") {
4429
4705
  const error = new AgentTaskTurnError(recovered.content);
4430
4706
  this.emit("error", { error: error.message });
@@ -4435,17 +4711,66 @@ var CoreAgentTaskSession = class {
4435
4711
  this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
4436
4712
  return true;
4437
4713
  }
4714
+ closesThisTurn(message) {
4715
+ if (!message.usage) return false;
4716
+ const prompt = message.usage.requestMessageId;
4717
+ return prompt === void 0 || !this.turnBaselineIds.has(prompt);
4718
+ }
4438
4719
  /** True once the server took the input; false when the box refused it on the stream. */
4439
4720
  async sendInput(input) {
4721
+ return (await this.handOver(input)).admitted;
4722
+ }
4723
+ // Resolves once the input left this session; `admitted` then says whether the server took it.
4724
+ // Wrapped so that awaiting the hand-over does not also await the answer.
4725
+ async handOver(input, clientMessageId, steering = false) {
4440
4726
  if (!this._taskId) throw new Error("Agent task has not been created.");
4441
- const direct = this.dependencies.channel.send(this._taskId, input);
4442
- if (direct) return direct;
4443
- await this.dependencies.tasks.sendInput(this._taskId, input);
4444
- return true;
4727
+ const direct = this.dependencies.channel.send(this._taskId, input, clientMessageId);
4728
+ if (direct) return { admitted: direct, direct: true };
4729
+ if (input.type === "runtime-request.respond") {
4730
+ throw new Error(
4731
+ "The answer to the Agent input request was not sent: the box channel is not connected right now."
4732
+ );
4733
+ }
4734
+ if (!COPILOT_INPUT_TYPES.has(input.type)) {
4735
+ throw new Error(
4736
+ `The Agent ${input.type} was not sent: the box channel is not connected right now.`
4737
+ );
4738
+ }
4739
+ const turnRunning = this._status === "streaming" || this._status === "cancelled";
4740
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content } : {
4741
+ type: "message",
4742
+ content: input.content,
4743
+ ...input.agentType ? { agentType: input.agentType } : {},
4744
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
4745
+ };
4746
+ await this.dependencies.tasks.sendInput(this._taskId, rest);
4747
+ return { admitted: Promise.resolve(true), direct: false };
4748
+ }
4749
+ async prepareSend() {
4750
+ if (this.openingPromise && !await this.openingPromise) {
4751
+ throw new Error("Agent task session could not be opened.");
4752
+ }
4753
+ await this.ensureTask();
4754
+ if (!this.isClosed()) await this.ensureChannel();
4445
4755
  }
4446
4756
  handleEvent(event) {
4447
4757
  this.emit("raw", event);
4448
4758
  const payload = asObject2(event.payload);
4759
+ if (payload && isSubagentFrame(event)) {
4760
+ this.handleSubagentFrame(event, payload);
4761
+ return;
4762
+ }
4763
+ const lifecycle = asObject2(payload?.lifecycle);
4764
+ if (this.repeatsTheRunningTurn(event, lifecycle)) return;
4765
+ if (event.type === "stepStart" || event.type === "steer") {
4766
+ const id = lifecycle?.clientMessageId;
4767
+ if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
4768
+ this.openingAwaitsStart = false;
4769
+ this.forgetFinishedTurn(lifecycle);
4770
+ }
4771
+ } else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
4772
+ this.rememberFinishedTurn(lifecycle);
4773
+ }
4449
4774
  switch (event.type) {
4450
4775
  // A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
4451
4776
  // como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
@@ -4458,14 +4783,30 @@ var CoreAgentTaskSession = class {
4458
4783
  this.consumeDelta(payload, "thinking");
4459
4784
  break;
4460
4785
  case "toolCall":
4461
- this.emitTool(payload, "call", event.timestamp);
4786
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call", event.timestamp);
4462
4787
  break;
4463
4788
  case "toolResult":
4464
- this.emitTool(payload, "result", event.timestamp);
4789
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "result", event.timestamp);
4465
4790
  break;
4466
4791
  case "workspace":
4467
4792
  this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
4468
4793
  break;
4794
+ case "stepStart":
4795
+ this.steerOpenedBy(asObject2(payload?.lifecycle));
4796
+ break;
4797
+ case "steer":
4798
+ this.steerOpenedBy(lifecycle);
4799
+ this.emit("steered", {
4800
+ text: typeof payload?.text === "string" ? payload.text : "",
4801
+ messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
4802
+ });
4803
+ break;
4804
+ case "messageQueued":
4805
+ this.steerQueuedBy(asObject2(payload?.lifecycle));
4806
+ break;
4807
+ case "subagentUpdate":
4808
+ this.applySubagent(payload);
4809
+ break;
4469
4810
  case "providerUsage": {
4470
4811
  const usage = providerUsageOf(payload);
4471
4812
  if (usage) this.emit("providerUsage", usage);
@@ -4473,15 +4814,17 @@ var CoreAgentTaskSession = class {
4473
4814
  }
4474
4815
  case "stepFinish": {
4475
4816
  const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
4476
- const lifecycle = payload?.lifecycle;
4817
+ const lifecycle2 = payload?.lifecycle;
4477
4818
  const usage = agentTurnUsageOf(payload?.usage);
4478
- if (reason === "interrupted" || lifecycle?.interruptTerminal === true) {
4479
- this.rememberFinishedTurn(lifecycle);
4819
+ const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
4820
+ if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
4821
+ if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
4822
+ this.rememberFinishedTurn(lifecycle2);
4480
4823
  this.finishTurn("interrupted", usage);
4481
4824
  break;
4482
4825
  }
4483
4826
  if (reason === "stop" || reason === "endTurn") {
4484
- this.rememberFinishedTurn(lifecycle);
4827
+ this.rememberFinishedTurn(lifecycle2);
4485
4828
  if (this.recoveryUsed) {
4486
4829
  this.recoveredTerminalReason = reason;
4487
4830
  this.recoveredTerminalUsage = usage;
@@ -4501,6 +4844,17 @@ var CoreAgentTaskSession = class {
4501
4844
  const code = typeof payload?.code === "string" ? payload.code : void 0;
4502
4845
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
4503
4846
  this.emit("error", { ...code ? { code } : {}, error: message });
4847
+ if (!payload?.lifecycle && payload?.requestId !== void 0) break;
4848
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
4849
+ if (typeof refused === "string") {
4850
+ if (refused !== this.openingMessageId) {
4851
+ const steered = [...this.steers, ...this.strayedSteers].find(
4852
+ (pending) => pending.clientMessageId === refused
4853
+ );
4854
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
4855
+ break;
4856
+ }
4857
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
4504
4858
  if (this._status === "streaming" || this._status === "cancelled") {
4505
4859
  this.failTurn(new AgentTaskTurnError(message, code));
4506
4860
  }
@@ -4510,6 +4864,27 @@ var CoreAgentTaskSession = class {
4510
4864
  break;
4511
4865
  }
4512
4866
  }
4867
+ repeatsTheRunningTurn(event, lifecycle) {
4868
+ if (this._status !== "streaming" && this._status !== "cancelled") return false;
4869
+ const turnId = lifecycle?.turnId;
4870
+ if (typeof turnId !== "string") return false;
4871
+ if (typeof event.sequence === "number") {
4872
+ if (this.turnIds.has(turnId) && event.sequence <= this.turnSequenceHigh) return true;
4873
+ this.turnSequenceHigh = Math.max(this.turnSequenceHigh, event.sequence);
4874
+ }
4875
+ this.turnIds.add(turnId);
4876
+ return false;
4877
+ }
4878
+ isFinishedTurnFrame(lifecycle) {
4879
+ const turnId = lifecycle?.turnId;
4880
+ return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
4881
+ }
4882
+ forgetFinishedTurn(lifecycle) {
4883
+ const turnId = lifecycle?.turnId;
4884
+ if (typeof turnId !== "string") return;
4885
+ const index = this.finishedTurnIds.indexOf(turnId);
4886
+ if (index >= 0) this.finishedTurnIds.splice(index, 1);
4887
+ }
4513
4888
  rememberFinishedTurn(lifecycle) {
4514
4889
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4515
4890
  if (!turnId) return;
@@ -4531,14 +4906,52 @@ var CoreAgentTaskSession = class {
4531
4906
  this.emit("delta", { delta: text, kind });
4532
4907
  }
4533
4908
  emitTool(payload, phase, timestamp) {
4534
- this.emit("tool", {
4535
- tool: typeof payload?.name === "string" ? payload.name : "",
4536
- phase,
4537
- timestamp,
4538
- ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4539
- ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4540
- ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
4541
- });
4909
+ this.emit("tool", toolEventOf(payload, phase, timestamp));
4910
+ }
4911
+ // A child thread's frames are the subagent's conversation: they open no turn, settle no message
4912
+ // and never reach the chat's `content`.
4913
+ handleSubagentFrame(event, payload) {
4914
+ const parentToolId = payload.parentToolId;
4915
+ switch (event.type) {
4916
+ case "textDelta":
4917
+ case "textChunk":
4918
+ case "thinking":
4919
+ this.emit("subagentDelta", {
4920
+ parentToolId,
4921
+ delta: typeof payload.text === "string" ? payload.text : "",
4922
+ kind: event.type === "thinking" ? "thinking" : "text"
4923
+ });
4924
+ break;
4925
+ case "toolCall":
4926
+ case "toolResult":
4927
+ this.emit("subagentTool", {
4928
+ ...toolEventOf(payload, event.type === "toolCall" ? "call" : "result", event.timestamp),
4929
+ parentToolId
4930
+ });
4931
+ break;
4932
+ default:
4933
+ break;
4934
+ }
4935
+ }
4936
+ applySubagent(payload) {
4937
+ const subagentId = payload?.subagentId;
4938
+ const toolId = payload?.toolId;
4939
+ if (typeof subagentId !== "string" || typeof toolId !== "string") return;
4940
+ const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
4941
+ if (status === void 0) return;
4942
+ const startedAt = epochOf(payload?.startedAt);
4943
+ const endedAt = epochOf(payload?.endedAt);
4944
+ const subagent = {
4945
+ subagentId,
4946
+ toolId,
4947
+ status,
4948
+ ...typeof payload?.progress === "string" ? { progress: payload.progress } : {},
4949
+ ...startedAt !== void 0 ? { startedAt } : {},
4950
+ ...endedAt !== void 0 ? { endedAt } : {},
4951
+ ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
4952
+ };
4953
+ this.subagentsById.set(subagentId, subagent);
4954
+ this.emit("subagent", subagent);
4542
4955
  }
4543
4956
  finishTurn(reason, usage) {
4544
4957
  if (this._status !== "streaming" && this._status !== "cancelled") return;
@@ -4563,8 +4976,8 @@ var CoreAgentTaskSession = class {
4563
4976
  this.emit("turnEnd", result);
4564
4977
  this.activeWaiter?.resolve(result);
4565
4978
  this.activeWaiter = void 0;
4979
+ this.settleSteers((waiter) => waiter.resolve(result));
4566
4980
  this.setStatus("idle");
4567
- this.flushQueue();
4568
4981
  }
4569
4982
  failTurn(error) {
4570
4983
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
@@ -4572,56 +4985,17 @@ var CoreAgentTaskSession = class {
4572
4985
  this.recoveryGeneration += 1;
4573
4986
  this.activeWaiter?.reject(error);
4574
4987
  this.activeWaiter = void 0;
4988
+ this.settleSteers((waiter) => waiter.reject(error));
4575
4989
  this.setStatus("idle");
4576
- this.flushQueue();
4577
4990
  }
4578
4991
  failLiveChannel(observed, waiterError) {
4579
4992
  this.recoveryGeneration += 1;
4580
4993
  this.emitError("Agent live channel failed", observed);
4581
4994
  this.activeWaiter?.reject(waiterError);
4582
4995
  this.activeWaiter = void 0;
4583
- for (const item of this._queue) item.waiter?.reject(waiterError);
4584
- this._queue = [];
4585
- this.emitQueue();
4996
+ this.rejectSteers(waiterError);
4586
4997
  this.setStatus("error");
4587
4998
  }
4588
- enqueue(text, options, waiter) {
4589
- if (this._queue.length >= AGENT_QUEUE_LIMIT) {
4590
- const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
4591
- waiter?.reject(error);
4592
- this.emit("error", { error: error.message });
4593
- return void 0;
4594
- }
4595
- const id = `q-${++this.queueSequence}`;
4596
- this._queue = [
4597
- ...this._queue,
4598
- { id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
4599
- ];
4600
- this.emitQueue();
4601
- return id;
4602
- }
4603
- flushQueue() {
4604
- if (this.isBusy()) return;
4605
- let next = this._queue[0];
4606
- while (next?.waiter?.settled) {
4607
- this._queue = this._queue.slice(1);
4608
- next = this._queue[0];
4609
- }
4610
- if (!next) {
4611
- this.emitQueue();
4612
- return;
4613
- }
4614
- this._queue = this._queue.slice(1);
4615
- this.emitQueue();
4616
- this.startDispatch(
4617
- next.text,
4618
- {
4619
- ...next.agentType ? { agentType: next.agentType } : {},
4620
- ...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
4621
- },
4622
- next.waiter
4623
- );
4624
- }
4625
4999
  createWaiter(options) {
4626
5000
  let resolvePromise;
4627
5001
  let rejectPromise;
@@ -4643,7 +5017,6 @@ var CoreAgentTaskSession = class {
4643
5017
  if (waiter.settled) return;
4644
5018
  waiter.settled = true;
4645
5019
  waiter.cleanup();
4646
- if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
4647
5020
  rejectPromise(error);
4648
5021
  },
4649
5022
  cleanup: () => {
@@ -4668,14 +5041,6 @@ var CoreAgentTaskSession = class {
4668
5041
  }
4669
5042
  return waiter;
4670
5043
  }
4671
- removeQueuedWaiter(id) {
4672
- const size = this._queue.length;
4673
- this._queue = this._queue.filter((item) => item.id !== id);
4674
- if (this._queue.length !== size) this.emitQueue();
4675
- }
4676
- emitQueue() {
4677
- this.emit("queueChange", { queue: this.queue });
4678
- }
4679
5044
  emitError(prefix, error) {
4680
5045
  const code = errorCode(error);
4681
5046
  this.emit("error", {
@@ -4685,6 +5050,12 @@ var CoreAgentTaskSession = class {
4685
5050
  }
4686
5051
  setStatus(status) {
4687
5052
  if (this._status === status) return;
5053
+ if (status !== "streaming" && status !== "cancelled") {
5054
+ this.openingAwaitsStart = false;
5055
+ this.endedPollsWithoutRow = 0;
5056
+ this.turnIds.clear();
5057
+ this.turnSequenceHigh = -1;
5058
+ }
4688
5059
  this._status = status;
4689
5060
  this.emit("statusChange", { status });
4690
5061
  }
@@ -4694,8 +5065,11 @@ var CoreAgentTaskSession = class {
4694
5065
  isClosed() {
4695
5066
  return this._status === "closed";
4696
5067
  }
5068
+ // A turn running or being opened takes a new message as a steer. So does a session waiting for
5069
+ // the turn the box opens for a steer it took late: a new message started as a turn of its own
5070
+ // then would be answered by the steer's result, and the steer by its.
4697
5071
  isBusy() {
4698
- return this.dispatching || this._status === "streaming" || this._status === "cancelled";
5072
+ return this.dispatching || this._status === "streaming" || this._status === "cancelled" || this.strayedSteers.length > 0;
4699
5073
  }
4700
5074
  emit(event, payload) {
4701
5075
  const listeners = this.listeners.get(event);