@mitralab.io/sdk-core 0.3.4 → 0.3.6

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
@@ -407,7 +407,7 @@ function expectFunctionVersion(value, context, errors) {
407
407
  if (typeof version.id !== "string") invalidField(context, "id", errors);
408
408
  if (typeof version.functionId !== "string") invalidField(context, "functionId", errors);
409
409
  if (typeof version.status !== "string") invalidField(context, "status", errors);
410
- if (typeof version.code !== "string") invalidField(context, "code", errors);
410
+ if (!isNullableString(version.code)) invalidField(context, "code", errors);
411
411
  if (version.inputSchema !== null && !isObject(version.inputSchema)) {
412
412
  invalidField(context, "inputSchema", errors);
413
413
  }
@@ -3955,12 +3955,14 @@ var AgentDirectChannel = class {
3955
3955
  const otherLog = historyCursor?.boxLog !== void 0 && channel.boxLog !== void 0 && historyCursor.boxLog !== channel.boxLog;
3956
3956
  const historyFrom = historyCursor === void 0 ? void 0 : otherLog ? 0 : historyCursor.sequence;
3957
3957
  let cursor = historyFrom ?? channel.lastSequence;
3958
+ let boxLog = channel.boxLog;
3958
3959
  const abort = new AbortController();
3959
3960
  const onAbort = () => abort.abort(signal?.reason);
3960
3961
  signal?.addEventListener("abort", onAbort, { once: true });
3961
- const onFrame = (event) => {
3962
- const hello = helloOf(event);
3962
+ const onFrame = (frame) => {
3963
+ const hello = helloOf(frame);
3963
3964
  if (hello) thread = hello.threadId;
3965
+ const event = hello && boxLog !== void 0 ? { ...frame, payload: { ...asObject(frame.payload), boxLog } } : frame;
3964
3966
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3965
3967
  if (isSubagentFrame(event)) {
3966
3968
  observer.onEvent(event);
@@ -3991,6 +3993,7 @@ var AgentDirectChannel = class {
3991
3993
  onFrame,
3992
3994
  onLost,
3993
3995
  replayFrom: (next) => {
3996
+ boxLog = next.boxLog;
3994
3997
  const decide = (hello) => {
3995
3998
  const nextBox = boxAddress(next.wsUrl);
3996
3999
  const zeroed = next.lastSequence === 0 && cursor > 0;
@@ -4683,6 +4686,9 @@ var CoreAgentTaskSession = class {
4683
4686
  _hasOlder = false;
4684
4687
  // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4685
4688
  historyGeneration = 0;
4689
+ // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
4690
+ // names another log, or reports a log shorter than the history's, has sequences that start over.
4691
+ rowsInChannelLog = true;
4686
4692
  olderRead = null;
4687
4693
  get taskId() {
4688
4694
  return this._taskId;
@@ -4823,6 +4829,7 @@ var CoreAgentTaskSession = class {
4823
4829
  }
4824
4830
  replaceHistory(page) {
4825
4831
  this.historyGeneration += 1;
4832
+ this.rowsInChannelLog = true;
4826
4833
  this._hasOlder = hasOlderRows(page);
4827
4834
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4828
4835
  }
@@ -4952,6 +4959,9 @@ var CoreAgentTaskSession = class {
4952
4959
  if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4953
4960
  await this.captureTurnBaseline();
4954
4961
  if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4962
+ if (this._status === "streaming" || this._status === "cancelled") {
4963
+ return this.sendBehindRunningTurn(input, clientMessageId, handedOver, waiter);
4964
+ }
4955
4965
  this._content = "";
4956
4966
  this.recoveryUsed = false;
4957
4967
  this.recoveredTerminalReason = void 0;
@@ -4969,6 +4979,37 @@ var CoreAgentTaskSession = class {
4969
4979
  this.acceptOnce(clientMessageId);
4970
4980
  return true;
4971
4981
  }
4982
+ async sendBehindRunningTurn(input, clientMessageId, handedOver, waiter) {
4983
+ const steered = {
4984
+ clientMessageId,
4985
+ ...waiter ? { waiter } : {},
4986
+ taken: false
4987
+ };
4988
+ this.steers.push(steered);
4989
+ const fail = (error) => {
4990
+ this.forgetSteer(steered);
4991
+ waiter?.reject(error);
4992
+ return false;
4993
+ };
4994
+ let taken;
4995
+ try {
4996
+ const { admitted } = await this.handOver(input, clientMessageId, true);
4997
+ handedOver();
4998
+ taken = await admitted;
4999
+ } catch (error) {
5000
+ handedOver();
5001
+ this.emitError("Failed to send Agent prompt", error);
5002
+ return fail(error);
5003
+ }
5004
+ if (!taken) {
5005
+ return fail(
5006
+ steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
5007
+ );
5008
+ }
5009
+ if (!steered.queued) this.steerTaken(steered);
5010
+ this.acceptOnce(clientMessageId);
5011
+ return true;
5012
+ }
4972
5013
  // A prompt whose task exists is never dropped by close; the task outlives the session. Apps
4973
5014
  // close the creating session inside taskCreated and reopen by task id, so the input still goes
4974
5015
  // out over REST. Only a prompt that never reached `handOver` comes here: the Copilot does not
@@ -5064,6 +5105,23 @@ var CoreAgentTaskSession = class {
5064
5105
  this.steers = this.steers.filter((pending) => pending !== steered);
5065
5106
  this.strayedSteers.push(steered);
5066
5107
  }
5108
+ // Another message's turn started while ours waited for its own: one runs ahead of ours (a tab
5109
+ // that sent to the queue before its socket said a turn was running). Its frames are the running
5110
+ // turn's, not a finished one's, or its terminal is dropped and the turn never ends here. Ours
5111
+ // waits for the turn the box opens for it, as a queued steer does, so that turn answers it.
5112
+ openingQueuedBehind() {
5113
+ const id = this.openingMessageId;
5114
+ this.openingAwaitsStart = false;
5115
+ this.openingMessageId = void 0;
5116
+ if (id === void 0) return;
5117
+ this.strayedSteers.push({
5118
+ clientMessageId: id,
5119
+ ...this.activeWaiter ? { waiter: this.activeWaiter } : {},
5120
+ taken: false,
5121
+ queued: true
5122
+ });
5123
+ this.activeWaiter = void 0;
5124
+ }
5067
5125
  forgetSteer(steered) {
5068
5126
  this.steers = this.steers.filter((pending) => pending !== steered);
5069
5127
  this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
@@ -5291,6 +5349,8 @@ var CoreAgentTaskSession = class {
5291
5349
  if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
5292
5350
  this.openingAwaitsStart = false;
5293
5351
  this.forgetFinishedTurn(lifecycle);
5352
+ } else if (event.type === "stepStart" && this.openingAwaitsStart) {
5353
+ this.openingQueuedBehind();
5294
5354
  }
5295
5355
  } else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
5296
5356
  this.rememberFinishedTurn(lifecycle);
@@ -5350,6 +5410,15 @@ var CoreAgentTaskSession = class {
5350
5410
  ...typeof lifecycle?.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {}
5351
5411
  });
5352
5412
  break;
5413
+ case "hello": {
5414
+ const lastSequence = payload?.lastSequence;
5415
+ const history = historyCursorOf(this._history);
5416
+ const rowsLog = [...this._history].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5417
+ if (typeof payload?.boxLog === "number" && rowsLog !== void 0 && payload.boxLog !== rowsLog || typeof lastSequence === "number" && history !== void 0 && lastSequence < history.sequence) {
5418
+ this.rowsInChannelLog = false;
5419
+ }
5420
+ break;
5421
+ }
5353
5422
  case "backgroundTasks":
5354
5423
  this._backgroundTasks = backgroundTasksOf(payload?.tasks);
5355
5424
  this.emit("backgroundTasks", { tasks: this._backgroundTasks });
@@ -5617,6 +5686,7 @@ var CoreAgentTaskSession = class {
5617
5686
  const text = (id !== void 0 ? this.sentTexts.get(id) : void 0) ?? boxText;
5618
5687
  if (typeof text !== "string" || !text) return;
5619
5688
  const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5689
+ if ((id === void 0 || !this.sentTexts.has(id)) && this.beforeLoadedRows(sequence)) return;
5620
5690
  this.livePiece(
5621
5691
  (item) => item.kind === "user" && (id !== void 0 && item.clientMessageId === id || sequence !== void 0 && item.sequence === sequence && item.text === text),
5622
5692
  () => ({
@@ -5630,6 +5700,20 @@ var CoreAgentTaskSession = class {
5630
5700
  (item) => item
5631
5701
  );
5632
5702
  }
5703
+ // Every connection to the box brings the running turn's `stepStart` again, and a history loaded
5704
+ // while that turn ran can start after its question (mitra-core-sdk#140: 121 rows after it, a
5705
+ // page of 100). Before the oldest row the history holds, with older rows still on the server,
5706
+ // the question is one of those rows, and `loadOlder` brings it in its place.
5707
+ beforeLoadedRows(sequence) {
5708
+ if (sequence === void 0 || !this._hasOlder || !this.rowsInChannelLog) return false;
5709
+ const rows = this._history.filter(
5710
+ (item) => !item.id.startsWith("live:") && typeof item.sequence === "number"
5711
+ );
5712
+ const oldest = rows[0];
5713
+ const newest = rows[rows.length - 1];
5714
+ if (oldest?.sequence === void 0 || oldest.boxLog !== newest?.boxLog) return false;
5715
+ return sequence < oldest.sequence;
5716
+ }
5633
5717
  liveText(event, payload, kind, parentToolId) {
5634
5718
  const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
5635
5719
  if (itemId === void 0) return;
package/dist/index.d.cts CHANGED
@@ -363,7 +363,7 @@ interface FunctionVersion {
363
363
  id: string;
364
364
  functionId: string;
365
365
  status: string;
366
- code: string;
366
+ code: string | null;
367
367
  inputSchema: Record<string, unknown> | null;
368
368
  outputSchema: Record<string, unknown> | null;
369
369
  secrets: string[] | null;
package/dist/index.d.ts CHANGED
@@ -363,7 +363,7 @@ interface FunctionVersion {
363
363
  id: string;
364
364
  functionId: string;
365
365
  status: string;
366
- code: string;
366
+ code: string | null;
367
367
  inputSchema: Record<string, unknown> | null;
368
368
  outputSchema: Record<string, unknown> | null;
369
369
  secrets: string[] | null;
package/dist/index.js CHANGED
@@ -335,7 +335,7 @@ function expectFunctionVersion(value, context, errors) {
335
335
  if (typeof version.id !== "string") invalidField(context, "id", errors);
336
336
  if (typeof version.functionId !== "string") invalidField(context, "functionId", errors);
337
337
  if (typeof version.status !== "string") invalidField(context, "status", errors);
338
- if (typeof version.code !== "string") invalidField(context, "code", errors);
338
+ if (!isNullableString(version.code)) invalidField(context, "code", errors);
339
339
  if (version.inputSchema !== null && !isObject(version.inputSchema)) {
340
340
  invalidField(context, "inputSchema", errors);
341
341
  }
@@ -3883,12 +3883,14 @@ var AgentDirectChannel = class {
3883
3883
  const otherLog = historyCursor?.boxLog !== void 0 && channel.boxLog !== void 0 && historyCursor.boxLog !== channel.boxLog;
3884
3884
  const historyFrom = historyCursor === void 0 ? void 0 : otherLog ? 0 : historyCursor.sequence;
3885
3885
  let cursor = historyFrom ?? channel.lastSequence;
3886
+ let boxLog = channel.boxLog;
3886
3887
  const abort = new AbortController();
3887
3888
  const onAbort = () => abort.abort(signal?.reason);
3888
3889
  signal?.addEventListener("abort", onAbort, { once: true });
3889
- const onFrame = (event) => {
3890
- const hello = helloOf(event);
3890
+ const onFrame = (frame) => {
3891
+ const hello = helloOf(frame);
3891
3892
  if (hello) thread = hello.threadId;
3893
+ const event = hello && boxLog !== void 0 ? { ...frame, payload: { ...asObject(frame.payload), boxLog } } : frame;
3892
3894
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3893
3895
  if (isSubagentFrame(event)) {
3894
3896
  observer.onEvent(event);
@@ -3919,6 +3921,7 @@ var AgentDirectChannel = class {
3919
3921
  onFrame,
3920
3922
  onLost,
3921
3923
  replayFrom: (next) => {
3924
+ boxLog = next.boxLog;
3922
3925
  const decide = (hello) => {
3923
3926
  const nextBox = boxAddress(next.wsUrl);
3924
3927
  const zeroed = next.lastSequence === 0 && cursor > 0;
@@ -4611,6 +4614,9 @@ var CoreAgentTaskSession = class {
4611
4614
  _hasOlder = false;
4612
4615
  // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4613
4616
  historyGeneration = 0;
4617
+ // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
4618
+ // names another log, or reports a log shorter than the history's, has sequences that start over.
4619
+ rowsInChannelLog = true;
4614
4620
  olderRead = null;
4615
4621
  get taskId() {
4616
4622
  return this._taskId;
@@ -4751,6 +4757,7 @@ var CoreAgentTaskSession = class {
4751
4757
  }
4752
4758
  replaceHistory(page) {
4753
4759
  this.historyGeneration += 1;
4760
+ this.rowsInChannelLog = true;
4754
4761
  this._hasOlder = hasOlderRows(page);
4755
4762
  this._history = [...page.content].reverse().map(toAgentTimelineItem);
4756
4763
  }
@@ -4880,6 +4887,9 @@ var CoreAgentTaskSession = class {
4880
4887
  if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4881
4888
  await this.captureTurnBaseline();
4882
4889
  if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4890
+ if (this._status === "streaming" || this._status === "cancelled") {
4891
+ return this.sendBehindRunningTurn(input, clientMessageId, handedOver, waiter);
4892
+ }
4883
4893
  this._content = "";
4884
4894
  this.recoveryUsed = false;
4885
4895
  this.recoveredTerminalReason = void 0;
@@ -4897,6 +4907,37 @@ var CoreAgentTaskSession = class {
4897
4907
  this.acceptOnce(clientMessageId);
4898
4908
  return true;
4899
4909
  }
4910
+ async sendBehindRunningTurn(input, clientMessageId, handedOver, waiter) {
4911
+ const steered = {
4912
+ clientMessageId,
4913
+ ...waiter ? { waiter } : {},
4914
+ taken: false
4915
+ };
4916
+ this.steers.push(steered);
4917
+ const fail = (error) => {
4918
+ this.forgetSteer(steered);
4919
+ waiter?.reject(error);
4920
+ return false;
4921
+ };
4922
+ let taken;
4923
+ try {
4924
+ const { admitted } = await this.handOver(input, clientMessageId, true);
4925
+ handedOver();
4926
+ taken = await admitted;
4927
+ } catch (error) {
4928
+ handedOver();
4929
+ this.emitError("Failed to send Agent prompt", error);
4930
+ return fail(error);
4931
+ }
4932
+ if (!taken) {
4933
+ return fail(
4934
+ steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
4935
+ );
4936
+ }
4937
+ if (!steered.queued) this.steerTaken(steered);
4938
+ this.acceptOnce(clientMessageId);
4939
+ return true;
4940
+ }
4900
4941
  // A prompt whose task exists is never dropped by close; the task outlives the session. Apps
4901
4942
  // close the creating session inside taskCreated and reopen by task id, so the input still goes
4902
4943
  // out over REST. Only a prompt that never reached `handOver` comes here: the Copilot does not
@@ -4992,6 +5033,23 @@ var CoreAgentTaskSession = class {
4992
5033
  this.steers = this.steers.filter((pending) => pending !== steered);
4993
5034
  this.strayedSteers.push(steered);
4994
5035
  }
5036
+ // Another message's turn started while ours waited for its own: one runs ahead of ours (a tab
5037
+ // that sent to the queue before its socket said a turn was running). Its frames are the running
5038
+ // turn's, not a finished one's, or its terminal is dropped and the turn never ends here. Ours
5039
+ // waits for the turn the box opens for it, as a queued steer does, so that turn answers it.
5040
+ openingQueuedBehind() {
5041
+ const id = this.openingMessageId;
5042
+ this.openingAwaitsStart = false;
5043
+ this.openingMessageId = void 0;
5044
+ if (id === void 0) return;
5045
+ this.strayedSteers.push({
5046
+ clientMessageId: id,
5047
+ ...this.activeWaiter ? { waiter: this.activeWaiter } : {},
5048
+ taken: false,
5049
+ queued: true
5050
+ });
5051
+ this.activeWaiter = void 0;
5052
+ }
4995
5053
  forgetSteer(steered) {
4996
5054
  this.steers = this.steers.filter((pending) => pending !== steered);
4997
5055
  this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
@@ -5219,6 +5277,8 @@ var CoreAgentTaskSession = class {
5219
5277
  if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
5220
5278
  this.openingAwaitsStart = false;
5221
5279
  this.forgetFinishedTurn(lifecycle);
5280
+ } else if (event.type === "stepStart" && this.openingAwaitsStart) {
5281
+ this.openingQueuedBehind();
5222
5282
  }
5223
5283
  } else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
5224
5284
  this.rememberFinishedTurn(lifecycle);
@@ -5278,6 +5338,15 @@ var CoreAgentTaskSession = class {
5278
5338
  ...typeof lifecycle?.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {}
5279
5339
  });
5280
5340
  break;
5341
+ case "hello": {
5342
+ const lastSequence = payload?.lastSequence;
5343
+ const history = historyCursorOf(this._history);
5344
+ const rowsLog = [...this._history].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5345
+ if (typeof payload?.boxLog === "number" && rowsLog !== void 0 && payload.boxLog !== rowsLog || typeof lastSequence === "number" && history !== void 0 && lastSequence < history.sequence) {
5346
+ this.rowsInChannelLog = false;
5347
+ }
5348
+ break;
5349
+ }
5281
5350
  case "backgroundTasks":
5282
5351
  this._backgroundTasks = backgroundTasksOf(payload?.tasks);
5283
5352
  this.emit("backgroundTasks", { tasks: this._backgroundTasks });
@@ -5545,6 +5614,7 @@ var CoreAgentTaskSession = class {
5545
5614
  const text = (id !== void 0 ? this.sentTexts.get(id) : void 0) ?? boxText;
5546
5615
  if (typeof text !== "string" || !text) return;
5547
5616
  const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5617
+ if ((id === void 0 || !this.sentTexts.has(id)) && this.beforeLoadedRows(sequence)) return;
5548
5618
  this.livePiece(
5549
5619
  (item) => item.kind === "user" && (id !== void 0 && item.clientMessageId === id || sequence !== void 0 && item.sequence === sequence && item.text === text),
5550
5620
  () => ({
@@ -5558,6 +5628,20 @@ var CoreAgentTaskSession = class {
5558
5628
  (item) => item
5559
5629
  );
5560
5630
  }
5631
+ // Every connection to the box brings the running turn's `stepStart` again, and a history loaded
5632
+ // while that turn ran can start after its question (mitra-core-sdk#140: 121 rows after it, a
5633
+ // page of 100). Before the oldest row the history holds, with older rows still on the server,
5634
+ // the question is one of those rows, and `loadOlder` brings it in its place.
5635
+ beforeLoadedRows(sequence) {
5636
+ if (sequence === void 0 || !this._hasOlder || !this.rowsInChannelLog) return false;
5637
+ const rows = this._history.filter(
5638
+ (item) => !item.id.startsWith("live:") && typeof item.sequence === "number"
5639
+ );
5640
+ const oldest = rows[0];
5641
+ const newest = rows[rows.length - 1];
5642
+ if (oldest?.sequence === void 0 || oldest.boxLog !== newest?.boxLog) return false;
5643
+ return sequence < oldest.sequence;
5644
+ }
5561
5645
  liveText(event, payload, kind, parentToolId) {
5562
5646
  const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
5563
5647
  if (itemId === void 0) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,