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

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
@@ -48,6 +48,9 @@ function isObject(value) {
48
48
  function isNullableString(value) {
49
49
  return value === null || typeof value === "string";
50
50
  }
51
+ function isNonEmptyString(value) {
52
+ return typeof value === "string" && value.length > 0;
53
+ }
51
54
  function isNullableBoolean(value) {
52
55
  return value === null || typeof value === "boolean";
53
56
  }
@@ -681,6 +684,83 @@ function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFacto
681
684
  if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
682
685
  return response;
683
686
  }
687
+ function expectEmailTemplate(value, context, errors = defaultSdkCoreErrorFactory) {
688
+ const template = expectObject(value, context, errors);
689
+ if (typeof template.id !== "string") invalidField(context, "id", errors);
690
+ if (!isNonEmptyString(template.type)) invalidField(context, "type", errors);
691
+ if (!isNullableString(template.senderIdentityId)) {
692
+ invalidField(context, "senderIdentityId", errors);
693
+ }
694
+ if (typeof template.subject !== "string") invalidField(context, "subject", errors);
695
+ if (typeof template.htmlBody !== "string") invalidField(context, "htmlBody", errors);
696
+ if (!isNullableString(template.textBody)) invalidField(context, "textBody", errors);
697
+ if (typeof template.platformDefault !== "boolean") {
698
+ invalidField(context, "platformDefault", errors);
699
+ }
700
+ if (typeof template.createdAt !== "string") invalidField(context, "createdAt", errors);
701
+ if (typeof template.updatedAt !== "string") invalidField(context, "updatedAt", errors);
702
+ return template;
703
+ }
704
+ function expectEmailTemplateTypeCatalog(value, context, errors = defaultSdkCoreErrorFactory) {
705
+ const catalog = expectObject(value, context, errors);
706
+ if (!isNonEmptyString(catalog.type)) invalidField(context, "type", errors);
707
+ expectObjectArray(catalog.variables, `${context} variables`, errors).forEach(
708
+ (variable, position) => {
709
+ const variableContext = `${context} variable ${position}`;
710
+ if (typeof variable.name !== "string") invalidField(variableContext, "name", errors);
711
+ if (typeof variable.required !== "boolean") {
712
+ invalidField(variableContext, "required", errors);
713
+ }
714
+ if (!isNullableString(variable.description)) {
715
+ invalidField(variableContext, "description", errors);
716
+ }
717
+ if (!isNullableString(variable.preview)) invalidField(variableContext, "preview", errors);
718
+ }
719
+ );
720
+ return catalog;
721
+ }
722
+ function expectEmailTemplatePreview(value, context, errors = defaultSdkCoreErrorFactory) {
723
+ const preview = expectObject(value, context, errors);
724
+ if (typeof preview.subject !== "string") invalidField(context, "subject", errors);
725
+ if (typeof preview.htmlBody !== "string") invalidField(context, "htmlBody", errors);
726
+ if (!isNullableString(preview.textBody)) invalidField(context, "textBody", errors);
727
+ return preview;
728
+ }
729
+ function expectEmailSender(value, context, errors = defaultSdkCoreErrorFactory) {
730
+ const sender = expectObject(value, context, errors);
731
+ if (typeof sender.id !== "string") invalidField(context, "id", errors);
732
+ if (typeof sender.email !== "string") invalidField(context, "email", errors);
733
+ if (typeof sender.displayName !== "string") invalidField(context, "displayName", errors);
734
+ if (!isNonEmptyString(sender.status)) invalidField(context, "status", errors);
735
+ if (typeof sender.sharedWithCurrentWorkspace !== "boolean") {
736
+ invalidField(context, "sharedWithCurrentWorkspace", errors);
737
+ }
738
+ if (typeof sender.ownerConfirmationPending !== "boolean") {
739
+ invalidField(context, "ownerConfirmationPending", errors);
740
+ }
741
+ if (typeof sender.createdAt !== "string") invalidField(context, "createdAt", errors);
742
+ if (typeof sender.updatedAt !== "string") invalidField(context, "updatedAt", errors);
743
+ return sender;
744
+ }
745
+ function expectEmailSettings(value, context, errors = defaultSdkCoreErrorFactory) {
746
+ const settings = expectObject(value, context, errors);
747
+ if (typeof settings.appId !== "string") invalidField(context, "appId", errors);
748
+ if (!isNullableString(settings.senderIdentityId)) {
749
+ invalidField(context, "senderIdentityId", errors);
750
+ }
751
+ if (!isNullableString(settings.displayName)) invalidField(context, "displayName", errors);
752
+ if (!isNullableString(settings.replyTo)) invalidField(context, "replyTo", errors);
753
+ if (typeof settings.ownTemplateSendsFromBrand !== "boolean") {
754
+ invalidField(context, "ownTemplateSendsFromBrand", errors);
755
+ }
756
+ const senderContext = `${context} effectiveSender`;
757
+ const sender = expectObject(settings.effectiveSender, senderContext, errors);
758
+ if (typeof sender.email !== "string") invalidField(senderContext, "email", errors);
759
+ if (!isNullableString(sender.displayName)) invalidField(senderContext, "displayName", errors);
760
+ if (!isNonEmptyString(sender.source)) invalidField(senderContext, "source", errors);
761
+ if (!isNullableString(sender.reason)) invalidField(senderContext, "reason", errors);
762
+ return settings;
763
+ }
684
764
  function expectAgentDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
685
765
  const agent = expectObject(value, context, errors);
686
766
  if (typeof agent.id !== "string") invalidField(context, "id", errors);
@@ -942,7 +1022,8 @@ function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFact
942
1022
  if (typeof channel.wsUrl !== "string" || !channel.wsUrl) invalidField(context, "wsUrl", errors);
943
1023
  return {
944
1024
  wsUrl: channel.wsUrl,
945
- lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0
1025
+ lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0,
1026
+ ...isInteger(channel.boxLog) ? { boxLog: channel.boxLog } : {}
946
1027
  };
947
1028
  }
948
1029
  function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
@@ -1054,6 +1135,14 @@ function expectCredentialUsage(value, context, errors = defaultSdkCoreErrorFacto
1054
1135
  }
1055
1136
  return usage;
1056
1137
  }
1138
+ function expectAgentReadyProvider(value, context, errors = defaultSdkCoreErrorFactory) {
1139
+ const entry = expectObject(value, context, errors);
1140
+ if (typeof entry.provider !== "string") invalidField(context, "provider", errors);
1141
+ if (!isNullableString(entry.providerName)) invalidField(context, "providerName", errors);
1142
+ expectObjectArray(entry.models, `${context} models`, errors, expectAgentModel);
1143
+ if (entry.usage !== null) expectCredentialUsage(entry.usage, `${context} usage`, errors);
1144
+ return entry;
1145
+ }
1057
1146
  var CREDENTIAL_USAGE_NOT_FOUND = "CREDENTIAL_USAGE_NOT_FOUND";
1058
1147
  async function readCredentialUsage(request, context, errors = defaultSdkCoreErrorFactory) {
1059
1148
  let value;
@@ -1342,6 +1431,17 @@ function createAgentCredentialsModule(transport, errors = defaultSdkCoreErrorFac
1342
1431
  expectAgentModel
1343
1432
  );
1344
1433
  },
1434
+ async providers(agentId, options) {
1435
+ return expectObjectArray(
1436
+ await transport.request("/api/v1/models/providers", {
1437
+ method: "GET",
1438
+ params: { agentId, ...scopeParams(options).params }
1439
+ }),
1440
+ "Ready provider response",
1441
+ errors,
1442
+ expectAgentReadyProvider
1443
+ );
1444
+ },
1345
1445
  async usage(provider, options) {
1346
1446
  return readCredentialUsage(
1347
1447
  transport.request(`/api/v1/credentials/${providerSegment(provider)}/usage`, {
@@ -1614,7 +1714,13 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1614
1714
  const page = expectPage(
1615
1715
  await transport.request(`${path(id)}/messages`, {
1616
1716
  method: "GET",
1617
- params: { page: options.page, size: options.size, sort: options.sort }
1717
+ params: {
1718
+ page: options.page,
1719
+ size: options.size,
1720
+ sort: options.sort,
1721
+ kinds: options.kinds,
1722
+ before: options.before
1723
+ }
1618
1724
  }),
1619
1725
  context,
1620
1726
  errors
@@ -2852,7 +2958,23 @@ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
2852
2958
  }
2853
2959
 
2854
2960
  // src/modules/messenger.ts
2855
- function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2961
+ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory, getAppId) {
2962
+ const templatePath = (type) => `/api/v1/email/templates/${encodePathSegment(type, "email template type", errors)}`;
2963
+ const senderPath = (senderId) => `/api/v1/email/identities/${encodePathSegment(senderId, "email sender id", errors)}`;
2964
+ const currentAppId = () => {
2965
+ const appId = getAppId?.();
2966
+ if (!appId) configurationError("An appId is required for app email calls", errors);
2967
+ return appId;
2968
+ };
2969
+ const settingsPath = () => `/api/v1/email/apps/${encodePathSegment(currentAppId(), "app id", errors)}/settings`;
2970
+ const preview = async (type, appId) => expectEmailTemplatePreview(
2971
+ await transport.request(`${templatePath(type)}/preview`, {
2972
+ method: "GET",
2973
+ params: { appId }
2974
+ }),
2975
+ "Email template preview response",
2976
+ errors
2977
+ );
2856
2978
  return {
2857
2979
  async notify(content) {
2858
2980
  return expectMessageAccepted(
@@ -2873,6 +2995,120 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2873
2995
  "Send email response",
2874
2996
  errors
2875
2997
  );
2998
+ },
2999
+ async listEmailTemplates() {
3000
+ return expectObjectArray(
3001
+ await transport.request("/api/v1/email/templates", {
3002
+ method: "GET",
3003
+ params: { appId: currentAppId() }
3004
+ }),
3005
+ "Email template list response",
3006
+ errors,
3007
+ expectEmailTemplate
3008
+ );
3009
+ },
3010
+ async getEmailTemplateType(type) {
3011
+ return expectEmailTemplateTypeCatalog(
3012
+ await transport.request(
3013
+ `/api/v1/email/template-types/${encodePathSegment(type, "email template type", errors)}`,
3014
+ { method: "GET" }
3015
+ ),
3016
+ "Email template type response",
3017
+ errors
3018
+ );
3019
+ },
3020
+ async getEmailTemplate(type) {
3021
+ return expectEmailTemplate(
3022
+ await transport.request(templatePath(type), {
3023
+ method: "GET",
3024
+ params: { appId: currentAppId() }
3025
+ }),
3026
+ "Email template response",
3027
+ errors
3028
+ );
3029
+ },
3030
+ async upsertEmailTemplate(type, input) {
3031
+ const appId = currentAppId();
3032
+ const template = expectEmailTemplate(
3033
+ await transport.request(templatePath(type), {
3034
+ method: "PUT",
3035
+ body: templateBody(appId, input)
3036
+ }),
3037
+ "Upsert email template response",
3038
+ errors
3039
+ );
3040
+ try {
3041
+ return { template, preview: await preview(type, appId) };
3042
+ } catch (previewError) {
3043
+ return { template, preview: null, previewError };
3044
+ }
3045
+ },
3046
+ async previewEmailTemplate(type) {
3047
+ return preview(type, currentAppId());
3048
+ },
3049
+ async deleteEmailTemplate(type) {
3050
+ expectEmpty(
3051
+ await transport.request(templatePath(type), {
3052
+ method: "DELETE",
3053
+ params: { appId: currentAppId() }
3054
+ }),
3055
+ "Delete email template response",
3056
+ errors
3057
+ );
3058
+ },
3059
+ async listEmailSenders() {
3060
+ return expectObjectArray(
3061
+ await transport.request("/api/v1/email/identities/workspace", { method: "GET" }),
3062
+ "Email sender list response",
3063
+ errors,
3064
+ expectEmailSender
3065
+ );
3066
+ },
3067
+ async registerEmailSender(input) {
3068
+ return expectEmailSender(
3069
+ await transport.request("/api/v1/email/identities", {
3070
+ method: "POST",
3071
+ body: { email: input.email, displayName: input.displayName }
3072
+ }),
3073
+ "Register email sender response",
3074
+ errors
3075
+ );
3076
+ },
3077
+ async resendEmailSenderVerification(senderId) {
3078
+ return expectEmailSender(
3079
+ await transport.request(`${senderPath(senderId)}/resend-verification`, {
3080
+ method: "POST"
3081
+ }),
3082
+ "Resend email sender verification response",
3083
+ errors
3084
+ );
3085
+ },
3086
+ async confirmEmailSender(senderId, code) {
3087
+ return expectEmailSender(
3088
+ await transport.request(`${senderPath(senderId)}/confirm`, {
3089
+ method: "POST",
3090
+ body: { code }
3091
+ }),
3092
+ "Confirm email sender response",
3093
+ errors
3094
+ );
3095
+ },
3096
+ async getEmailSettings() {
3097
+ return expectEmailSettings(
3098
+ await transport.request(settingsPath(), { method: "GET" }),
3099
+ "Email settings response",
3100
+ errors
3101
+ );
3102
+ },
3103
+ async updateEmailSettings(input) {
3104
+ return expectEmailSettings(
3105
+ await transport.request(settingsPath(), {
3106
+ method: "PUT",
3107
+ body: settingsBody(input)
3108
+ }),
3109
+ "Update email settings response",
3110
+ errors
3111
+ );
2876
3112
  }
2877
3113
  };
2878
3114
  }
@@ -2888,6 +3124,21 @@ function rawEmailPayload(input) {
2888
3124
  ...input.text === void 0 ? {} : { text: input.text }
2889
3125
  };
2890
3126
  }
3127
+ function templateBody(appId, input) {
3128
+ return {
3129
+ appId,
3130
+ subject: input.subject,
3131
+ htmlBody: input.htmlBody,
3132
+ ...input.textBody === void 0 ? {} : { textBody: input.textBody }
3133
+ };
3134
+ }
3135
+ function settingsBody(input) {
3136
+ return {
3137
+ ...input.senderIdentityId === void 0 ? {} : { senderIdentityId: input.senderIdentityId },
3138
+ ...input.displayName === void 0 ? {} : { displayName: input.displayName },
3139
+ ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo }
3140
+ };
3141
+ }
2891
3142
 
2892
3143
  // src/modules/publicFunctions.ts
2893
3144
  function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
@@ -3205,7 +3456,7 @@ function createSdkCore(options) {
3205
3456
  integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
3206
3457
  integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
3207
3458
  members,
3208
- messenger: createMessengerModule(messengerTransport, errors),
3459
+ messenger: createMessengerModule(messengerTransport, errors, options.getAppId),
3209
3460
  publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
3210
3461
  queries: createQueriesModule(options.transports.dataManager, errors),
3211
3462
  sql: createSqlModule(options.transports.dataManager, errors),
@@ -3246,7 +3497,7 @@ function newClientMessageId() {
3246
3497
  }
3247
3498
  function admissionFor(link, event) {
3248
3499
  const payload = asObject(event.payload);
3249
- if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
3500
+ if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0 || payload?.command !== void 0)) {
3250
3501
  return void 0;
3251
3502
  }
3252
3503
  const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
@@ -3292,6 +3543,14 @@ function boxAddress(wsUrl) {
3292
3543
  const url = new URL(wsUrl);
3293
3544
  return `${url.origin}${url.pathname}`;
3294
3545
  }
3546
+ function helloOf(event) {
3547
+ if (event.type !== "hello") return void 0;
3548
+ const payload = asObject(event.payload);
3549
+ const threadId = payload?.threadId;
3550
+ const lastSequence = payload?.lastSequence;
3551
+ if (typeof threadId !== "string" || typeof lastSequence !== "number") return void 0;
3552
+ return { threadId, lastSequence };
3553
+ }
3295
3554
  function boxRoute(wsUrl, route) {
3296
3555
  const url = new URL(wsUrl);
3297
3556
  url.protocol = url.protocol === "wss:" ? "https:" : "http:";
@@ -3385,8 +3644,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
3385
3644
  "steer",
3386
3645
  "textDelta",
3387
3646
  "thinking",
3388
- "toolCall",
3389
- "toolResult"
3647
+ "toolCall"
3390
3648
  ]);
3391
3649
  var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
3392
3650
  function turnAfter(event, inTurn) {
@@ -3399,6 +3657,12 @@ function turnAfter(event, inTurn) {
3399
3657
  }
3400
3658
  return inTurn;
3401
3659
  }
3660
+ function followsTurn(link, event) {
3661
+ if (event.type === "messageQueued") return false;
3662
+ if (event.type !== "stepFinish" && event.type !== "error") return true;
3663
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3664
+ return typeof turnId !== "string" || link.turnId === void 0 || turnId === link.turnId;
3665
+ }
3402
3666
  function lostTurnFrame(turnId) {
3403
3667
  return {
3404
3668
  type: "stepFinish",
@@ -3470,7 +3734,7 @@ var AgentDirectChannel = class {
3470
3734
  enabled() {
3471
3735
  return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
3472
3736
  }
3473
- async open(taskId, observer, signal, transport) {
3737
+ async open(taskId, observer, signal, transport, historyCursor) {
3474
3738
  if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
3475
3739
  const mode = this.modeFor(transport);
3476
3740
  const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
@@ -3480,7 +3744,7 @@ var AgentDirectChannel = class {
3480
3744
  return this.fallback.open(taskId, observer, signal, transport);
3481
3745
  }
3482
3746
  try {
3483
- return await this.openDirect(taskId, mode, answer, observer, signal);
3747
+ return await this.openDirect(taskId, mode, answer, observer, signal, historyCursor);
3484
3748
  } catch (error) {
3485
3749
  if (signal?.aborted) throw error;
3486
3750
  observer.onEvent(
@@ -3605,26 +3869,36 @@ var AgentDirectChannel = class {
3605
3869
  * only when the redial gives up, when the Copilot no longer offers the box, or when there is
3606
3870
  * no turn to resume: dialing an idle box again would wake it for nobody.
3607
3871
  *
3608
- * Opening never asks for an older replay. What an idle chat missed is history, which the
3609
- * session loads by REST; replaying from an older cursor would put old turns on screen as live
3610
- * text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
3872
+ * Opening asks for the replay from where the session's history ends, with the same request the
3873
+ * redial makes: what the history has, the replay does not repeat, and what the Copilot has not
3874
+ * recorded yet (the turn running now, or one it is still behind on) comes in the replay before
3875
+ * any live frame. When the Copilot says the box log is another one than the history's newest,
3876
+ * nothing of it is in the history and the replay starts at its beginning. A history with no
3877
+ * box sequence asks for nothing, and the open starts at the sequence the Copilot reported.
3611
3878
  */
3612
- async openDirect(taskId, mode, channel, observer, signal) {
3879
+ async openDirect(taskId, mode, channel, observer, signal, historyCursor) {
3613
3880
  const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
3614
3881
  let box = boxAddress(channel.wsUrl);
3615
- let cursor = channel.lastSequence;
3882
+ let thread;
3883
+ const otherLog = historyCursor?.boxLog !== void 0 && channel.boxLog !== void 0 && historyCursor.boxLog !== channel.boxLog;
3884
+ const historyFrom = historyCursor === void 0 ? void 0 : otherLog ? 0 : historyCursor.sequence;
3885
+ let cursor = historyFrom ?? channel.lastSequence;
3616
3886
  const abort = new AbortController();
3617
3887
  const onAbort = () => abort.abort(signal?.reason);
3618
3888
  signal?.addEventListener("abort", onAbort, { once: true });
3619
3889
  const onFrame = (event) => {
3890
+ const hello = helloOf(event);
3891
+ if (hello) thread = hello.threadId;
3620
3892
  if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
3621
3893
  if (isSubagentFrame(event)) {
3622
3894
  observer.onEvent(event);
3623
3895
  return;
3624
3896
  }
3625
- const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3626
- if (typeof turnId === "string") link.turnId = turnId;
3627
- link.inTurn = turnAfter(event, link.inTurn);
3897
+ if (followsTurn(link, event)) {
3898
+ const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
3899
+ if (typeof turnId === "string" && event.type !== "toolResult") link.turnId = turnId;
3900
+ link.inTurn = turnAfter(event, link.inTurn);
3901
+ }
3628
3902
  observer.onEvent(event);
3629
3903
  if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
3630
3904
  else if (event.type === "error") admissionFor(link, event)?.settle(false);
@@ -3645,13 +3919,21 @@ var AgentDirectChannel = class {
3645
3919
  onFrame,
3646
3920
  onLost,
3647
3921
  replayFrom: (next) => {
3648
- const nextBox = boxAddress(next.wsUrl);
3649
- const zeroed = next.lastSequence === 0 && cursor > 0;
3650
- if (nextBox === box && !zeroed) return cursor;
3651
- if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3652
- box = nextBox;
3653
- cursor = next.lastSequence;
3654
- return void 0;
3922
+ const decide = (hello) => {
3923
+ const nextBox = boxAddress(next.wsUrl);
3924
+ const zeroed = next.lastSequence === 0 && cursor > 0;
3925
+ const otherBox = hello !== void 0 && (hello.threadId !== thread || hello.lastSequence < cursor);
3926
+ if (nextBox === box && !zeroed && !otherBox) return cursor;
3927
+ if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
3928
+ box = nextBox;
3929
+ if (mode === "websocket") {
3930
+ cursor = 0;
3931
+ return 0;
3932
+ }
3933
+ cursor = next.lastSequence;
3934
+ return void 0;
3935
+ };
3936
+ return mode === "websocket" && thread !== void 0 ? decide : decide(void 0);
3655
3937
  }
3656
3938
  }).then((outcome) => {
3657
3939
  if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
@@ -3661,11 +3943,17 @@ var AgentDirectChannel = class {
3661
3943
  }
3662
3944
  });
3663
3945
  };
3946
+ const afterHello = (hello) => {
3947
+ if (hello !== void 0 && hello.lastSequence < cursor) cursor = 0;
3948
+ return cursor;
3949
+ };
3950
+ const replay = historyFrom === void 0 ? {} : mode === "websocket" ? { replayAfterHello: afterHello } : { replayFrom: historyFrom };
3664
3951
  try {
3665
3952
  link.wire = await this.connect(taskId, mode, channel, {
3666
3953
  signal: abort.signal,
3667
3954
  onFrame,
3668
- onLost
3955
+ onLost,
3956
+ ...replay
3669
3957
  });
3670
3958
  } catch (error) {
3671
3959
  signal?.removeEventListener("abort", onAbort);
@@ -3748,7 +4036,8 @@ var AgentDirectChannel = class {
3748
4036
  onFrame: handlers.onFrame,
3749
4037
  onLost: handlers.onLost,
3750
4038
  signal,
3751
- ...replayFrom === void 0 ? {} : { replayFrom }
4039
+ ...typeof replayFrom === "function" ? { replayAfterHello: replayFrom } : {},
4040
+ ...typeof replayFrom === "number" ? { replayFrom } : {}
3752
4041
  });
3753
4042
  return { kind: "wire", wire };
3754
4043
  } catch (error) {
@@ -3897,6 +4186,7 @@ var AgentDirectChannel = class {
3897
4186
  const Socket = this.webSocket();
3898
4187
  if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
3899
4188
  const { signal, replayFrom } = options;
4189
+ let replayAfterHello = options.replayAfterHello;
3900
4190
  return new Promise((resolve, reject) => {
3901
4191
  const socket = new Socket(url);
3902
4192
  let opened = false;
@@ -3979,7 +4269,13 @@ var AgentDirectChannel = class {
3979
4269
  handlers.onmessage = (message) => {
3980
4270
  touch();
3981
4271
  const event = parseEvent(message.data);
3982
- if (event) options.onFrame(asDelta(event));
4272
+ if (!event) return;
4273
+ if (replayAfterHello) {
4274
+ const fromSequence = replayAfterHello(helloOf(event));
4275
+ replayAfterHello = void 0;
4276
+ if (fromSequence !== void 0) send(JSON.stringify({ type: "replay", fromSequence }));
4277
+ }
4278
+ options.onFrame(asDelta(event));
3983
4279
  };
3984
4280
  handlers.onclose = (event) => {
3985
4281
  clearTimeout(timer);
@@ -4048,14 +4344,44 @@ function messageInput(prompt, options) {
4048
4344
  content: prompt,
4049
4345
  ...options.agentType ? { agentType: options.agentType } : {},
4050
4346
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4051
- mode: "steer"
4347
+ ...options.mode ? { mode: options.mode } : {}
4348
+ };
4349
+ }
4350
+ function backgroundTasksOf(value) {
4351
+ if (!Array.isArray(value)) return [];
4352
+ return value.flatMap((entry) => {
4353
+ const task = asObject2(entry);
4354
+ if (typeof task?.taskId !== "string" || typeof task.kind !== "string") return [];
4355
+ return [
4356
+ {
4357
+ taskId: task.taskId,
4358
+ kind: task.kind,
4359
+ ...typeof task.description === "string" ? { description: task.description } : {},
4360
+ ...typeof task.childThreadId === "string" ? { childThreadId: task.childThreadId } : {}
4361
+ }
4362
+ ];
4363
+ });
4364
+ }
4365
+ function pieceIdentityOf(event, payload) {
4366
+ const turnId = asObject2(payload?.lifecycle)?.turnId;
4367
+ return {
4368
+ ...sequenceOf(event),
4369
+ ...typeof payload?.itemId === "string" ? { itemId: payload.itemId } : {},
4370
+ ...typeof turnId === "string" ? { turnId } : {}
4052
4371
  };
4053
4372
  }
4054
- function toolEventOf(payload, phase, timestamp) {
4373
+ function itemDeltaOf(payload) {
4374
+ return typeof payload?.itemDelta === "string" ? { itemDelta: payload.itemDelta } : {};
4375
+ }
4376
+ function sequenceOf(event) {
4377
+ return typeof event.sequence === "number" ? { sequence: event.sequence } : {};
4378
+ }
4379
+ function toolEventOf(event, payload, phase) {
4055
4380
  return {
4056
4381
  tool: typeof payload?.name === "string" ? payload.name : "",
4057
4382
  phase,
4058
- timestamp,
4383
+ timestamp: event.timestamp,
4384
+ ...pieceIdentityOf(event, payload),
4059
4385
  ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
4060
4386
  ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
4061
4387
  ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
@@ -4067,7 +4393,68 @@ function epochOf(value) {
4067
4393
  const parsed = Date.parse(value);
4068
4394
  return Number.isNaN(parsed) ? void 0 : parsed;
4069
4395
  }
4396
+ function timelineIdentityOf(message) {
4397
+ return {
4398
+ ...typeof message.sequence === "number" ? { sequence: message.sequence } : {},
4399
+ ...typeof message.lastSequence === "number" ? { lastSequence: message.lastSequence } : {},
4400
+ ...typeof message.boxLog === "number" ? { boxLog: message.boxLog } : {},
4401
+ ...typeof message.itemId === "string" ? { itemId: message.itemId } : {},
4402
+ ...typeof message.reason === "string" ? { reason: message.reason } : {}
4403
+ };
4404
+ }
4405
+ function historyCursorOf(history) {
4406
+ const newest = [...history].reverse().find((item) => typeof item.sequence === "number");
4407
+ if (!newest) return void 0;
4408
+ let sequence = 0;
4409
+ for (const item of history) {
4410
+ if (item.boxLog === newest.boxLog && typeof item.sequence === "number") {
4411
+ sequence = Math.max(sequence, item.lastSequence ?? item.sequence);
4412
+ }
4413
+ }
4414
+ return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4415
+ }
4416
+ function hasOlderRows(page) {
4417
+ return page.page.totalPages > page.page.number + 1;
4418
+ }
4419
+ function isChatRow(message) {
4420
+ return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4421
+ }
4422
+ var REQUEST_ROW_KINDS = {
4423
+ APPROVAL: "approval",
4424
+ USER_INPUT_REQUEST: "userInputRequest"
4425
+ };
4426
+ function parseJson(text) {
4427
+ try {
4428
+ return JSON.parse(text);
4429
+ } catch {
4430
+ return void 0;
4431
+ }
4432
+ }
4070
4433
  function toAgentTimelineItem(message) {
4434
+ if (message.type === "REASONING") {
4435
+ return {
4436
+ id: message.id,
4437
+ kind: "reasoning",
4438
+ text: message.content,
4439
+ at: message.createdAt,
4440
+ ...timelineIdentityOf(message),
4441
+ ...parentToolIdOf(message.parentToolId)
4442
+ };
4443
+ }
4444
+ const requestKind = REQUEST_ROW_KINDS[message.type];
4445
+ if (requestKind) {
4446
+ const payload = asObject2(parseJson(message.content));
4447
+ if (payload) {
4448
+ return {
4449
+ id: message.id,
4450
+ kind: requestKind,
4451
+ payload,
4452
+ at: message.createdAt,
4453
+ ...timelineIdentityOf(message),
4454
+ ...parentToolIdOf(message.parentToolId)
4455
+ };
4456
+ }
4457
+ }
4071
4458
  if (message.type === "TOOL_USE") {
4072
4459
  try {
4073
4460
  const payload = JSON.parse(message.content);
@@ -4078,11 +4465,14 @@ function toAgentTimelineItem(message) {
4078
4465
  tool: {
4079
4466
  tool: typeof payload.name === "string" ? payload.name : "",
4080
4467
  ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
4468
+ ...parentToolIdOf(payload.parentToolId ?? message.parentToolId),
4081
4469
  ...payload.input !== void 0 ? { input: payload.input } : {},
4082
4470
  ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
4083
4471
  phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
4084
4472
  },
4085
- at: message.createdAt
4473
+ at: message.createdAt,
4474
+ ...timelineIdentityOf(message),
4475
+ ...asObject2(message.subagent) ? { subagent: message.subagent } : {}
4086
4476
  };
4087
4477
  }
4088
4478
  } catch {
@@ -4093,9 +4483,18 @@ function toAgentTimelineItem(message) {
4093
4483
  kind: message.sender === "USER" ? "user" : "agent",
4094
4484
  text: message.content,
4095
4485
  at: message.createdAt,
4096
- ...message.usage ? { usage: message.usage } : {}
4486
+ ...message.usage ? { usage: message.usage } : {},
4487
+ ...timelineIdentityOf(message),
4488
+ ...typeof message.clientMessageId === "string" ? { clientMessageId: message.clientMessageId } : {},
4489
+ ...parentToolIdOf(message.parentToolId)
4097
4490
  };
4098
4491
  }
4492
+ function liveAtOf(event) {
4493
+ return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
4494
+ }
4495
+ function parentToolIdOf(value) {
4496
+ return typeof value === "string" ? { parentToolId: value } : {};
4497
+ }
4099
4498
  function createAgentTaskSessionManager(options) {
4100
4499
  const sessions = /* @__PURE__ */ new Map();
4101
4500
  const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
@@ -4188,6 +4587,22 @@ var CoreAgentTaskSession = class {
4188
4587
  openingAwaitsStart = false;
4189
4588
  turnBaselineIds = /* @__PURE__ */ new Set();
4190
4589
  subagentsById = /* @__PURE__ */ new Map();
4590
+ subagentSequences = /* @__PURE__ */ new Map();
4591
+ queueItems = [];
4592
+ _backgroundTasks = [];
4593
+ /** The text of each message this session sent, by its `clientMessageId`. */
4594
+ sentTexts = /* @__PURE__ */ new Map();
4595
+ // Messages of this session `accepted` was already emitted for. The frame that names a message
4596
+ // emits it in its place in the stream, so a turn delivered in one tick gives the same events as
4597
+ // one spaced out; the admission the send awaits only covers a box or a Copilot that names none.
4598
+ acceptedIds = [];
4599
+ // Taken by the first channel of `session({ taskId })`; no later channel asks for a replay.
4600
+ openingCursor;
4601
+ historyLimit;
4602
+ _hasOlder = false;
4603
+ // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4604
+ historyGeneration = 0;
4605
+ olderRead = null;
4191
4606
  get taskId() {
4192
4607
  return this._taskId;
4193
4608
  }
@@ -4207,19 +4622,18 @@ var CoreAgentTaskSession = class {
4207
4622
  return this._content;
4208
4623
  }
4209
4624
  get queue() {
4210
- return [];
4625
+ return [...this.queueItems];
4211
4626
  }
4212
4627
  get subagents() {
4213
4628
  return [...this.subagentsById.values()];
4214
4629
  }
4215
4630
  send(prompt, options = {}) {
4216
4631
  this.requireOpen();
4217
- if (!prompt.trim()) return;
4218
- if (this.isBusy()) {
4219
- this.steer(prompt, options);
4220
- return;
4221
- }
4222
- this.startDispatch(prompt, options);
4632
+ if (!prompt.trim()) return void 0;
4633
+ if (this.isBusy()) return this.steer(prompt, options);
4634
+ const clientMessageId = newClientMessageId();
4635
+ this.startDispatch(prompt, options, clientMessageId);
4636
+ return clientMessageId;
4223
4637
  }
4224
4638
  sendAndWait(prompt, options = {}) {
4225
4639
  this.requireOpen();
@@ -4228,13 +4642,14 @@ var CoreAgentTaskSession = class {
4228
4642
  if (waiter.settled) return waiter.promise;
4229
4643
  const sendOptions = {
4230
4644
  ...options.agentType ? { agentType: options.agentType } : {},
4231
- ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
4645
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4646
+ ...options.mode ? { mode: options.mode } : {}
4232
4647
  };
4233
4648
  if (this.isBusy()) {
4234
4649
  this.steer(prompt, sendOptions, waiter);
4235
4650
  return waiter.promise;
4236
4651
  }
4237
- this.startDispatch(prompt, sendOptions, waiter);
4652
+ this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
4238
4653
  return waiter.promise;
4239
4654
  }
4240
4655
  async cancel() {
@@ -4281,18 +4696,91 @@ var CoreAgentTaskSession = class {
4281
4696
  if (!this._taskId) return [];
4282
4697
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4283
4698
  ...options.limit !== void 0 ? { size: options.limit } : {},
4284
- sort: "createdAt,desc"
4699
+ sort: "createdAt,desc",
4700
+ kinds: "all"
4285
4701
  });
4286
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
4702
+ this.historyLimit = options.limit;
4703
+ this.replaceHistory(page);
4287
4704
  const history = this.history;
4288
4705
  this.emit("historyLoaded", { history });
4289
4706
  return history;
4290
4707
  }
4291
- editQueueItem() {
4708
+ get hasOlder() {
4709
+ return this._hasOlder;
4710
+ }
4711
+ loadOlder() {
4712
+ if (this.olderRead?.generation !== this.historyGeneration) {
4713
+ const generation = this.historyGeneration;
4714
+ const promise = this.readOlder(generation).finally(() => {
4715
+ if (this.olderRead?.promise === promise) this.olderRead = null;
4716
+ });
4717
+ this.olderRead = { generation, promise };
4718
+ }
4719
+ return this.olderRead.promise;
4720
+ }
4721
+ async readOlder(generation) {
4722
+ const oldest = this._history.find((item) => !item.id.startsWith("live:"));
4723
+ if (!this._taskId || !this._hasOlder || !oldest) return [];
4724
+ let page;
4725
+ try {
4726
+ page = await this.dependencies.tasks.listMessages(this._taskId, {
4727
+ before: oldest.id,
4728
+ ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4729
+ sort: "createdAt,desc",
4730
+ kinds: "all"
4731
+ });
4732
+ } catch (error) {
4733
+ if (generation !== this.historyGeneration || this.isClosed()) return [];
4734
+ throw error;
4735
+ }
4736
+ if (generation !== this.historyGeneration || this.isClosed()) return [];
4737
+ const older = [...page.content].reverse().map(toAgentTimelineItem);
4738
+ this._hasOlder = hasOlderRows(page);
4739
+ this._history = [...older, ...this._history];
4740
+ this.emit("historyLoaded", { history: this.history });
4741
+ return older;
4742
+ }
4743
+ replaceHistory(page) {
4744
+ this.historyGeneration += 1;
4745
+ this._hasOlder = hasOlderRows(page);
4746
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
4292
4747
  }
4293
- removeQueueItem() {
4748
+ editQueueItem(id, text) {
4749
+ this.requireOpen();
4750
+ if (this.sentTexts.has(id)) this.sentTexts.set(id, text);
4751
+ void this.sendInput({ type: "queued-run.edit", clientMessageId: id, text }).catch(
4752
+ (error) => {
4753
+ this.emitError("Failed to edit the queued Agent message", error);
4754
+ }
4755
+ );
4756
+ }
4757
+ removeQueueItem(id) {
4758
+ this.requireOpen();
4759
+ void this.sendInput({ type: "queued-run.cancel", clientMessageId: id }).catch(
4760
+ (error) => {
4761
+ this.emitError("Failed to remove the queued Agent message", error);
4762
+ }
4763
+ );
4294
4764
  }
4295
4765
  clearQueue() {
4766
+ for (const item of this.queueItems) this.removeQueueItem(item.id);
4767
+ }
4768
+ steerQueueItem(id) {
4769
+ this.requireOpen();
4770
+ void this.sendInput({ type: "queued-message.promote-to-steer", clientMessageId: id }).catch(
4771
+ (error) => {
4772
+ this.emitError("Failed to steer the queued Agent message", error);
4773
+ }
4774
+ );
4775
+ }
4776
+ resumeQueue() {
4777
+ this.requireOpen();
4778
+ void this.sendInput({ type: "queue.resume" }).catch((error) => {
4779
+ this.emitError("Failed to resume the Agent queue", error);
4780
+ });
4781
+ }
4782
+ get backgroundTasks() {
4783
+ return this._backgroundTasks;
4296
4784
  }
4297
4785
  stopSubagent(subagentId) {
4298
4786
  this.requireOpen();
@@ -4333,9 +4821,10 @@ var CoreAgentTaskSession = class {
4333
4821
  if (this.isClosed()) return false;
4334
4822
  await this.loadHistory();
4335
4823
  if (this.isClosed()) return false;
4824
+ this.openingCursor = historyCursorOf(this._history);
4336
4825
  await this.ensureChannel();
4337
4826
  if (this.isClosed()) return false;
4338
- this.setStatus("idle");
4827
+ if (this._status === "opening") this.setStatus("idle");
4339
4828
  return true;
4340
4829
  } catch (error) {
4341
4830
  if (this.isClosed()) return false;
@@ -4344,13 +4833,14 @@ var CoreAgentTaskSession = class {
4344
4833
  return false;
4345
4834
  }
4346
4835
  }
4347
- startDispatch(prompt, options, waiter) {
4836
+ startDispatch(prompt, options, clientMessageId, waiter) {
4837
+ this.sentTexts.set(clientMessageId, prompt);
4348
4838
  this.dispatching = true;
4349
4839
  let handedOver;
4350
4840
  this.handOff = new Promise((resolve) => {
4351
4841
  handedOver = resolve;
4352
4842
  });
4353
- const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
4843
+ const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4354
4844
  waiter?.reject(error);
4355
4845
  this.emitError("Failed to send Agent prompt", error);
4356
4846
  if (this._status === "streaming") {
@@ -4360,25 +4850,26 @@ var CoreAgentTaskSession = class {
4360
4850
  return false;
4361
4851
  }).finally(() => {
4362
4852
  handedOver();
4363
- this.dispatching = false;
4364
- if (this.dispatch === dispatch) this.dispatch = null;
4853
+ if (this.dispatch === dispatch) {
4854
+ this.dispatching = false;
4855
+ this.dispatch = null;
4856
+ }
4365
4857
  });
4366
4858
  this.dispatch = dispatch;
4367
4859
  }
4368
- async dispatchSend(prompt, options, handedOver, waiter) {
4860
+ async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
4369
4861
  if (this.openingPromise && !await this.openingPromise) {
4370
4862
  throw new Error("Agent task session could not be opened.");
4371
4863
  }
4372
- if (this.isClosed() || waiter?.settled) return false;
4864
+ if (this.isClosed()) return false;
4373
4865
  await this.ensureTask();
4374
4866
  const input = messageInput(prompt, options);
4375
4867
  if (this.isClosed()) {
4376
- await this.sendInput(input).catch(() => void 0);
4868
+ await this.handOver(input, clientMessageId).catch(() => void 0);
4377
4869
  return false;
4378
4870
  }
4379
- if (waiter?.settled) return false;
4380
4871
  await this.ensureChannel();
4381
- if (this.isClosed() || waiter?.settled) return false;
4872
+ if (this.isClosed()) return false;
4382
4873
  await this.captureTurnBaseline();
4383
4874
  this._content = "";
4384
4875
  this.recoveryUsed = false;
@@ -4388,13 +4879,13 @@ var CoreAgentTaskSession = class {
4388
4879
  this.activeWaiter = waiter;
4389
4880
  this.setStatus("streaming");
4390
4881
  this.emit("turnStart", {});
4391
- this.openingMessageId = newClientMessageId();
4882
+ this.openingMessageId = clientMessageId;
4392
4883
  this.openingAwaitsStart = true;
4393
4884
  const { admitted, direct } = await this.handOver(input, this.openingMessageId);
4394
4885
  if (!direct) this.openingAwaitsStart = false;
4395
4886
  handedOver();
4396
4887
  if (!await admitted) return false;
4397
- this.emit("accepted", {});
4888
+ this.acceptOnce(clientMessageId);
4398
4889
  return true;
4399
4890
  }
4400
4891
  // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
@@ -4418,6 +4909,7 @@ var CoreAgentTaskSession = class {
4418
4909
  } else {
4419
4910
  this.strayedSteers.push(steered);
4420
4911
  }
4912
+ this.sentTexts.set(steered.clientMessageId, prompt);
4421
4913
  const input = messageInput(prompt, options);
4422
4914
  this.pendingSteers += 1;
4423
4915
  const handed = this.handOff.then(async () => {
@@ -4439,7 +4931,7 @@ var CoreAgentTaskSession = class {
4439
4931
  return;
4440
4932
  }
4441
4933
  if (!steered.queued) this.steerTaken(steered);
4442
- this.emit("accepted", {});
4934
+ this.acceptOnce(steered.clientMessageId);
4443
4935
  }).catch((error) => {
4444
4936
  this.forgetSteer(steered);
4445
4937
  waiter?.reject(error);
@@ -4447,6 +4939,7 @@ var CoreAgentTaskSession = class {
4447
4939
  }).finally(() => {
4448
4940
  this.pendingSteers -= 1;
4449
4941
  });
4942
+ return steered.clientMessageId;
4450
4943
  }
4451
4944
  // The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
4452
4945
  // of its own, when that one ended before the box got to the message.
@@ -4493,7 +4986,7 @@ var CoreAgentTaskSession = class {
4493
4986
  else if (steered.waiter) settle(steered.waiter);
4494
4987
  }
4495
4988
  }
4496
- openTurnFor(waiter) {
4989
+ openTurnFor(waiter, start = {}) {
4497
4990
  if (this.isClosed()) return;
4498
4991
  if (this._status !== "streaming" && this._status !== "cancelled") {
4499
4992
  this._content = "";
@@ -4504,7 +4997,7 @@ var CoreAgentTaskSession = class {
4504
4997
  this.turnBaselineIds = new Set(this._history.map((item) => item.id));
4505
4998
  void this.captureTurnBaseline().catch(() => void 0);
4506
4999
  this.setStatus("streaming");
4507
- this.emit("turnStart", {});
5000
+ this.emit("turnStart", start);
4508
5001
  }
4509
5002
  if (!waiter) return;
4510
5003
  if (!this.activeWaiter) this.activeWaiter = waiter;
@@ -4547,6 +5040,8 @@ var CoreAgentTaskSession = class {
4547
5040
  const abort = new AbortController();
4548
5041
  this.connectionAbort = abort;
4549
5042
  const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
5043
+ const historyCursor = this.openingCursor;
5044
+ this.openingCursor = void 0;
4550
5045
  this.connectionPromise = source.open(
4551
5046
  this._taskId,
4552
5047
  {
@@ -4554,7 +5049,8 @@ var CoreAgentTaskSession = class {
4554
5049
  onDisconnect: (error) => this.handleDisconnect(error)
4555
5050
  },
4556
5051
  abort.signal,
4557
- this.options.transport
5052
+ this.options.transport,
5053
+ historyCursor
4558
5054
  ).then((connection) => {
4559
5055
  if (this.isClosed() || this._status === "error") {
4560
5056
  connection.close();
@@ -4600,7 +5096,8 @@ var CoreAgentTaskSession = class {
4600
5096
  if (!this._taskId) return;
4601
5097
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4602
5098
  size: 100,
4603
- sort: "createdAt,desc"
5099
+ sort: "createdAt,desc",
5100
+ kinds: "all"
4604
5101
  });
4605
5102
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
4606
5103
  }
@@ -4608,11 +5105,13 @@ var CoreAgentTaskSession = class {
4608
5105
  if (!this._taskId) return false;
4609
5106
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4610
5107
  size: 100,
4611
- sort: "createdAt,desc"
5108
+ sort: "createdAt,desc",
5109
+ kinds: "all"
4612
5110
  });
4613
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
5111
+ this.replaceHistory(page);
4614
5112
  this.emit("historyLoaded", { history: this.history });
4615
- const recovered = page.content.find(
5113
+ const rows = page.content.filter(isChatRow);
5114
+ const recovered = rows.find(
4616
5115
  (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
4617
5116
  );
4618
5117
  if (!recovered) {
@@ -4621,7 +5120,7 @@ var CoreAgentTaskSession = class {
4621
5120
  this.endedPollsWithoutRow += 1;
4622
5121
  if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
4623
5122
  }
4624
- const newest = page.content.find(
5123
+ const newest = rows.find(
4625
5124
  (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
4626
5125
  );
4627
5126
  if (!newest) return false;
@@ -4665,11 +5164,13 @@ var CoreAgentTaskSession = class {
4665
5164
  );
4666
5165
  }
4667
5166
  const turnRunning = this._status === "streaming" || this._status === "cancelled";
4668
- const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content } : {
5167
+ const id = clientMessageId === void 0 ? {} : { clientMessageId };
5168
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
4669
5169
  type: "message",
4670
5170
  content: input.content,
4671
5171
  ...input.agentType ? { agentType: input.agentType } : {},
4672
- ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
5172
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
5173
+ ...id
4673
5174
  };
4674
5175
  await this.dependencies.tasks.sendInput(this._taskId, rest);
4675
5176
  return { admitted: Promise.resolve(true), direct: false };
@@ -4689,6 +5190,7 @@ var CoreAgentTaskSession = class {
4689
5190
  return;
4690
5191
  }
4691
5192
  const lifecycle = asObject2(payload?.lifecycle);
5193
+ if (this.endsQueuedMessage(event, payload, lifecycle)) return;
4692
5194
  if (this.repeatsTheRunningTurn(event, lifecycle)) return;
4693
5195
  if (event.type === "stepStart" || event.type === "steer") {
4694
5196
  const id = lifecycle?.clientMessageId;
@@ -4705,35 +5207,70 @@ var CoreAgentTaskSession = class {
4705
5207
  // texto e o que faz a resposta recuperada aparecer; sem isso ela chega e morre aqui.
4706
5208
  case "textDelta":
4707
5209
  case "textChunk":
4708
- this.consumeDelta(payload, "text");
5210
+ this.consumeDelta(event, payload, "text");
4709
5211
  break;
4710
5212
  case "thinking":
4711
- this.consumeDelta(payload, "thinking");
5213
+ this.consumeDelta(event, payload, "thinking");
4712
5214
  break;
4713
5215
  case "toolCall":
4714
- if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call", event.timestamp);
5216
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(event, payload, "call");
4715
5217
  break;
5218
+ // A result can come after its turn ended: a subagent in the background settles later, and
5219
+ // the box sends its result under the turn that called it. It reaches the app as that tool's
5220
+ // result and touches no turn.
4716
5221
  case "toolResult":
4717
- if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "result", event.timestamp);
5222
+ this.emitTool(event, payload, "result");
4718
5223
  break;
4719
5224
  case "workspace":
4720
- this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
5225
+ this.emit("workspace", {
5226
+ payload: event.payload,
5227
+ timestamp: event.timestamp,
5228
+ ...sequenceOf(event)
5229
+ });
4721
5230
  break;
4722
5231
  case "stepStart":
5232
+ if (!this.isFinishedTurnFrame(lifecycle)) {
5233
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
5234
+ }
5235
+ if (typeof lifecycle?.turnId === "string" && !this.isFinishedTurnFrame(lifecycle) && this._status !== "streaming" && this._status !== "cancelled") {
5236
+ this.openTurnFor(void 0, {
5237
+ ...typeof payload?.text === "string" ? { text: payload.text } : {},
5238
+ ...typeof lifecycle.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {},
5239
+ ...pieceIdentityOf(event, payload)
5240
+ });
5241
+ }
5242
+ this.leaveQueue(lifecycle?.clientMessageId);
4723
5243
  this.steerOpenedBy(asObject2(payload?.lifecycle));
5244
+ this.acceptNamed(lifecycle?.clientMessageId);
4724
5245
  break;
4725
5246
  case "steer":
5247
+ this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
5248
+ this.leaveQueue(lifecycle?.clientMessageId);
4726
5249
  this.steerOpenedBy(lifecycle);
5250
+ this.acceptNamed(lifecycle?.clientMessageId);
4727
5251
  this.emit("steered", {
4728
5252
  text: typeof payload?.text === "string" ? payload.text : "",
4729
- messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
5253
+ messageId: typeof payload?.messageId === "string" ? payload.messageId : "",
5254
+ ...typeof payload?.turnId === "string" ? { turnId: payload.turnId } : {},
5255
+ ...sequenceOf(event),
5256
+ ...typeof lifecycle?.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {}
4730
5257
  });
4731
5258
  break;
5259
+ case "backgroundTasks":
5260
+ this._backgroundTasks = backgroundTasksOf(payload?.tasks);
5261
+ this.emit("backgroundTasks", { tasks: this._backgroundTasks });
5262
+ break;
4732
5263
  case "messageQueued":
5264
+ if (payload?.cancelled === true) {
5265
+ this.cancelQueued(payload, lifecycle);
5266
+ break;
5267
+ }
5268
+ this.applyQueued(event, payload, lifecycle);
4733
5269
  this.steerQueuedBy(asObject2(payload?.lifecycle));
5270
+ this.acceptNamed(lifecycle?.clientMessageId);
4734
5271
  break;
4735
5272
  case "subagentUpdate":
4736
- this.applySubagent(payload);
5273
+ this.applySubagent(event, payload);
4737
5274
  break;
4738
5275
  case "providerUsage": {
4739
5276
  const usage = providerUsageOf(payload);
@@ -4746,9 +5283,14 @@ var CoreAgentTaskSession = class {
4746
5283
  const usage = agentTurnUsageOf(payload?.usage);
4747
5284
  const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
4748
5285
  if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
5286
+ if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
5287
+ const end = {
5288
+ ...sequenceOf(event),
5289
+ ...finished === void 0 ? {} : { turnId: finished }
5290
+ };
4749
5291
  if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
4750
5292
  this.rememberFinishedTurn(lifecycle2);
4751
- this.finishTurn("interrupted", usage);
5293
+ this.finishTurn("interrupted", usage, end);
4752
5294
  break;
4753
5295
  }
4754
5296
  if (reason === "stop" || reason === "endTurn") {
@@ -4763,7 +5305,7 @@ var CoreAgentTaskSession = class {
4763
5305
  });
4764
5306
  }
4765
5307
  } else {
4766
- this.finishTurn(reason, usage);
5308
+ this.finishTurn(reason, usage, end);
4767
5309
  }
4768
5310
  }
4769
5311
  break;
@@ -4771,8 +5313,9 @@ var CoreAgentTaskSession = class {
4771
5313
  case "error": {
4772
5314
  const code = typeof payload?.code === "string" ? payload.code : void 0;
4773
5315
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
4774
- this.emit("error", { ...code ? { code } : {}, error: message });
5316
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
4775
5317
  if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5318
+ if (typeof payload?.command === "string") break;
4776
5319
  const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
4777
5320
  if (typeof refused === "string") {
4778
5321
  if (refused !== this.openingMessageId) {
@@ -4788,10 +5331,119 @@ var CoreAgentTaskSession = class {
4788
5331
  }
4789
5332
  break;
4790
5333
  }
5334
+ case "approval":
5335
+ case "user_input_request":
5336
+ this.liveRequest(event, payload);
5337
+ break;
4791
5338
  default:
4792
5339
  break;
4793
5340
  }
4794
5341
  }
5342
+ // The box admits every message with a `messageQueued` of no position; only one with a position
5343
+ // is in T3's queue.
5344
+ applyQueued(event, payload, lifecycle) {
5345
+ const id = payload?.clientMessageId ?? lifecycle?.clientMessageId;
5346
+ const position = payload?.position;
5347
+ if (typeof id !== "string" || typeof position !== "number") return;
5348
+ const known = this.queueItems.find((item2) => item2.id === id);
5349
+ if (this.alreadyApplied(known?.sequence, event)) return;
5350
+ const item = {
5351
+ id,
5352
+ text: typeof payload?.text === "string" ? payload.text : known?.text ?? "",
5353
+ createdAt: known?.createdAt ?? event.timestamp,
5354
+ position,
5355
+ ...typeof payload?.queueHeld === "boolean" ? { queueHeld: payload.queueHeld } : {},
5356
+ ...sequenceOf(event),
5357
+ ...typeof lifecycle?.turnId === "string" ? { turnId: lifecycle.turnId } : {}
5358
+ };
5359
+ this.queueItems = known ? this.queueItems.map((current) => current === known ? item : current) : [...this.queueItems, item];
5360
+ this.emit("queueChange", { queue: this.queue });
5361
+ }
5362
+ // The box took the message out of T3's queue on a `queued-run.cancel`, with no terminal of its
5363
+ // own: it leaves the queue and only its own `sendAndWait` ends. The message that opened this
5364
+ // session's turn was that turn, still waiting behind another one, which ends with it.
5365
+ cancelQueued(payload, lifecycle) {
5366
+ const id = payload.clientMessageId ?? lifecycle?.clientMessageId;
5367
+ if (typeof id !== "string") return;
5368
+ this.leaveQueue(id);
5369
+ const cancelled = new AgentTaskTurnError("The queued Agent message was cancelled.");
5370
+ if (id === this.openingMessageId) {
5371
+ this.cancelOpening(cancelled);
5372
+ return;
5373
+ }
5374
+ const steered = [...this.steers, ...this.strayedSteers].find(
5375
+ (pending) => pending.clientMessageId === id
5376
+ );
5377
+ if (!steered) return;
5378
+ this.forgetSteer(steered);
5379
+ steered.waiter?.reject(cancelled);
5380
+ }
5381
+ // A frame naming one of this session's messages in flight is the box taking it.
5382
+ acceptNamed(id) {
5383
+ if (typeof id !== "string") return;
5384
+ if (id === this.openingMessageId) this.dispatching = false;
5385
+ const ours = id === this.openingMessageId || [...this.steers, ...this.strayedSteers].some((pending) => pending.clientMessageId === id);
5386
+ if (ours) this.acceptOnce(id);
5387
+ }
5388
+ acceptOnce(id) {
5389
+ if (this.acceptedIds.includes(id)) return;
5390
+ this.acceptedIds.push(id);
5391
+ if (this.acceptedIds.length > 32) this.acceptedIds.shift();
5392
+ this.emit("accepted", {});
5393
+ }
5394
+ // As in T3, cancelling a queued run only takes that run out: no turn ends with it. The message
5395
+ // this session opened its turn with never ran, so only its own `sendAndWait` is rejected. A
5396
+ // message of this session still queued behind it keeps the session waiting for the turn the
5397
+ // box opens for it; with none, nothing of this session runs and it goes back to idle.
5398
+ cancelOpening(cancelled) {
5399
+ this.openingMessageId = void 0;
5400
+ if (!this.openingAwaitsStart) return;
5401
+ this.openingAwaitsStart = false;
5402
+ this.activeWaiter?.reject(cancelled);
5403
+ this.activeWaiter = void 0;
5404
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
5405
+ if (this.steers.length === 0 && this.strayedSteers.length === 0) this.setStatus("idle");
5406
+ }
5407
+ // After a replay the box sends the queue and the subagents as they are, each a copy of the line
5408
+ // that said it last, with that line's sequence: state this session may already hold.
5409
+ alreadyApplied(applied, event) {
5410
+ return applied !== void 0 && typeof event.sequence === "number" && event.sequence <= applied;
5411
+ }
5412
+ leaveQueue(id) {
5413
+ const item = this.queueItems.find((current) => current.id === id);
5414
+ if (!item) return void 0;
5415
+ this.queueItems = this.queueItems.filter((current) => current !== item);
5416
+ this.emit("queueChange", { queue: this.queue });
5417
+ return item;
5418
+ }
5419
+ // A queued message that ends before running (taken out of the queue, or dropped by T3) closes
5420
+ // with a terminal of its own while another turn may run: it leaves the queue and ends its own
5421
+ // `sendAndWait`, and the running turn goes on. The opening message of this session's turn is
5422
+ // that turn, and ends it as before.
5423
+ endsQueuedMessage(event, payload, lifecycle) {
5424
+ if (event.type !== "error" && event.type !== "stepFinish" || !lifecycle) return false;
5425
+ const id = payload?.clientMessageId ?? lifecycle.clientMessageId;
5426
+ const turnId = lifecycle.turnId;
5427
+ const item = this.queueItems.find(
5428
+ (current) => current.id === id || turnId !== void 0 && current.turnId === turnId
5429
+ );
5430
+ if (!item) return false;
5431
+ this.leaveQueue(item.id);
5432
+ if (item.id === this.openingMessageId) return false;
5433
+ const message = typeof payload?.message === "string" ? payload.message : "The queued Agent message ended before it ran.";
5434
+ if (event.type === "error") {
5435
+ const code = typeof payload?.code === "string" ? payload.code : void 0;
5436
+ this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5437
+ }
5438
+ const steered = [...this.steers, ...this.strayedSteers].find(
5439
+ (pending) => pending.clientMessageId === item.id
5440
+ );
5441
+ if (steered) {
5442
+ this.forgetSteer(steered);
5443
+ steered.waiter?.reject(new AgentTaskTurnError(message));
5444
+ }
5445
+ return true;
5446
+ }
4795
5447
  repeatsTheRunningTurn(event, lifecycle) {
4796
5448
  if (this._status !== "streaming" && this._status !== "cancelled") return false;
4797
5449
  const turnId = lifecycle?.turnId;
@@ -4819,7 +5471,7 @@ var CoreAgentTaskSession = class {
4819
5471
  this.finishedTurnIds.push(turnId);
4820
5472
  if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
4821
5473
  }
4822
- consumeDelta(payload, kind) {
5474
+ consumeDelta(event, payload, kind) {
4823
5475
  const lifecycle = asObject2(payload?.lifecycle);
4824
5476
  const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
4825
5477
  if (turnId && this.finishedTurnIds.includes(turnId)) return;
@@ -4831,40 +5483,160 @@ var CoreAgentTaskSession = class {
4831
5483
  this.emit("turnStart", {});
4832
5484
  }
4833
5485
  if (kind === "text") this._content += text;
4834
- this.emit("delta", { delta: text, kind });
5486
+ this.liveText(event, payload, kind);
5487
+ this.emit("delta", {
5488
+ delta: text,
5489
+ kind,
5490
+ ...itemDeltaOf(payload),
5491
+ ...pieceIdentityOf(event, payload)
5492
+ });
5493
+ }
5494
+ emitTool(event, payload, phase) {
5495
+ const tool = toolEventOf(event, payload, phase);
5496
+ this.liveTool(tool, event);
5497
+ this.emit("tool", tool);
5498
+ }
5499
+ // The conversation as it happens: the box's frames grow `history` while a turn runs, one item
5500
+ // per piece of T3, the same pieces the Copilot records and the reload at the turn's end brings
5501
+ // back in the same order. A piece the loaded history already has keeps growing in place, and a
5502
+ // frame it already holds (a replay after a reconnect or an F5) changes nothing.
5503
+ livePiece(match, create, update) {
5504
+ const index = this._history.findIndex(match);
5505
+ const current = this._history[index];
5506
+ if (current === void 0) this._history.push(create());
5507
+ else this._history[index] = update(current);
5508
+ }
5509
+ // The question enters the conversation where the box took it: its turn's `stepStart`, or the
5510
+ // `steer` that took it into the running turn. Until then it is in `queue`.
5511
+ liveQuestion(event, boxText, clientMessageId) {
5512
+ const id = typeof clientMessageId === "string" ? clientMessageId : void 0;
5513
+ const text = (id !== void 0 ? this.sentTexts.get(id) : void 0) ?? boxText;
5514
+ if (typeof text !== "string" || !text) return;
5515
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5516
+ this.livePiece(
5517
+ (item) => item.kind === "user" && (id !== void 0 && item.clientMessageId === id || sequence !== void 0 && item.sequence === sequence && item.text === text),
5518
+ () => ({
5519
+ id: `live:user:${id ?? sequence ?? this._history.length}`,
5520
+ kind: "user",
5521
+ text,
5522
+ at: liveAtOf(event),
5523
+ ...sequence === void 0 ? {} : { sequence },
5524
+ ...id === void 0 ? {} : { clientMessageId: id }
5525
+ }),
5526
+ (item) => item
5527
+ );
5528
+ }
5529
+ liveText(event, payload, kind, parentToolId) {
5530
+ const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
5531
+ if (itemId === void 0) return;
5532
+ const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
5533
+ const itemKind = kind === "thinking" ? "reasoning" : "agent";
5534
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5535
+ this.livePiece(
5536
+ (item) => item.kind === itemKind && item.itemId === itemId,
5537
+ () => ({
5538
+ id: `live:${itemKind}:${itemId}`,
5539
+ kind: itemKind,
5540
+ text: piece,
5541
+ at: liveAtOf(event),
5542
+ itemId,
5543
+ ...sequence === void 0 ? {} : { sequence },
5544
+ ...parentToolIdOf(parentToolId)
5545
+ }),
5546
+ (item) => {
5547
+ const held = item.lastSequence ?? item.sequence;
5548
+ if (!("text" in item) || sequence !== void 0 && held !== void 0 && sequence <= held)
5549
+ return item;
5550
+ return {
5551
+ ...item,
5552
+ text: item.text + piece,
5553
+ ...sequence === void 0 ? {} : { lastSequence: sequence }
5554
+ };
5555
+ }
5556
+ );
5557
+ }
5558
+ liveTool(tool, event) {
5559
+ const toolId = tool.toolId;
5560
+ if (toolId === void 0) return;
5561
+ this.livePiece(
5562
+ (item) => item.kind === "tool" && item.tool.toolId === toolId && item.tool.phase === tool.phase,
5563
+ () => ({
5564
+ id: tool.phase === "result" ? `live:tool:${toolId}:result` : `live:tool:${toolId}`,
5565
+ kind: "tool",
5566
+ tool,
5567
+ at: liveAtOf(event),
5568
+ ...tool.sequence === void 0 ? {} : { sequence: tool.sequence },
5569
+ ...tool.itemId === void 0 ? {} : { itemId: tool.itemId }
5570
+ }),
5571
+ (item) => item.kind === "tool" ? { ...item, tool: { ...item.tool, ...tool, input: tool.input ?? item.tool.input } } : item
5572
+ );
4835
5573
  }
4836
- emitTool(payload, phase, timestamp) {
4837
- this.emit("tool", toolEventOf(payload, phase, timestamp));
5574
+ // An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
5575
+ // it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
5576
+ // reaches the app as a `raw` event, as before.
5577
+ liveRequest(event, payload, parentToolId) {
5578
+ if (!payload) return;
5579
+ const kind = event.type === "approval" ? "approval" : "userInputRequest";
5580
+ const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
5581
+ const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
5582
+ if (itemId === void 0 && sequence === void 0) return;
5583
+ this.livePiece(
5584
+ (item) => item.kind === kind && (itemId !== void 0 ? item.itemId === itemId : item.sequence === sequence),
5585
+ () => ({
5586
+ id: `live:${kind}:${itemId ?? sequence}`,
5587
+ kind,
5588
+ payload,
5589
+ at: liveAtOf(event),
5590
+ ...sequence === void 0 ? {} : { sequence },
5591
+ ...itemId === void 0 ? {} : { itemId },
5592
+ ...parentToolIdOf(parentToolId)
5593
+ }),
5594
+ (item) => item
5595
+ );
4838
5596
  }
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`.
5597
+ // A child thread's frames are the subagent's conversation: they open no turn and settle no
5598
+ // message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
5599
+ // which knew no subagents, so an app that only bumps the version sees what it saw before.
4841
5600
  handleSubagentFrame(event, payload) {
4842
5601
  const parentToolId = payload.parentToolId;
4843
5602
  switch (event.type) {
4844
5603
  case "textDelta":
4845
5604
  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
- });
5605
+ case "thinking": {
5606
+ const delta = typeof payload.text === "string" ? payload.text : "";
5607
+ const kind = event.type === "thinking" ? "thinking" : "text";
5608
+ const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
5609
+ if (kind === "text") this._content += delta;
5610
+ this.liveText(event, payload, kind, parentToolId);
5611
+ this.emit("delta", { delta, kind, parentToolId, ...identity });
5612
+ this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
4852
5613
  break;
5614
+ }
4853
5615
  case "toolCall":
4854
- case "toolResult":
4855
- this.emit("subagentTool", {
4856
- ...toolEventOf(payload, event.type === "toolCall" ? "call" : "result", event.timestamp),
5616
+ case "toolResult": {
5617
+ const tool = {
5618
+ ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
4857
5619
  parentToolId
4858
- });
5620
+ };
5621
+ this.liveTool(tool, event);
5622
+ this.emit("tool", tool);
5623
+ this.emit("subagentTool", tool);
5624
+ break;
5625
+ }
5626
+ case "approval":
5627
+ case "user_input_request":
5628
+ this.liveRequest(event, payload, parentToolId);
4859
5629
  break;
4860
5630
  default:
4861
5631
  break;
4862
5632
  }
4863
5633
  }
4864
- applySubagent(payload) {
5634
+ applySubagent(event, payload) {
4865
5635
  const subagentId = payload?.subagentId;
4866
5636
  const toolId = payload?.toolId;
4867
5637
  if (typeof subagentId !== "string" || typeof toolId !== "string") return;
5638
+ if (this.alreadyApplied(this.subagentSequences.get(subagentId), event)) return;
5639
+ if (typeof event.sequence === "number") this.subagentSequences.set(subagentId, event.sequence);
4868
5640
  const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
4869
5641
  if (status === void 0) return;
4870
5642
  const startedAt = epochOf(payload?.startedAt);
@@ -4879,9 +5651,26 @@ var CoreAgentTaskSession = class {
4879
5651
  ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
4880
5652
  };
4881
5653
  this.subagentsById.set(subagentId, subagent);
4882
- this.emit("subagent", subagent);
5654
+ const index = this._history.findIndex(
5655
+ (item) => item.kind === "tool" && item.tool.toolId === toolId
5656
+ );
5657
+ const spawn = this._history[index];
5658
+ if (spawn?.kind === "tool") {
5659
+ this._history[index] = {
5660
+ ...spawn,
5661
+ subagent: {
5662
+ ...spawn.subagent,
5663
+ toolId,
5664
+ subagentId,
5665
+ status,
5666
+ ...subagent.progress === void 0 ? {} : { progress: subagent.progress },
5667
+ ...subagent.childThreadId === void 0 ? {} : { childThreadId: subagent.childThreadId }
5668
+ }
5669
+ };
5670
+ }
5671
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
4883
5672
  }
4884
- finishTurn(reason, usage) {
5673
+ finishTurn(reason, usage, end = {}) {
4885
5674
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4886
5675
  if (this.cancelTimer) clearTimeout(this.cancelTimer);
4887
5676
  this.cancelTimer = null;
@@ -4899,7 +5688,8 @@ var CoreAgentTaskSession = class {
4899
5688
  task,
4900
5689
  content: this._content,
4901
5690
  reason,
4902
- ...usage ? { usage } : {}
5691
+ ...usage ? { usage } : {},
5692
+ ...end
4903
5693
  };
4904
5694
  this.emit("turnEnd", result);
4905
5695
  this.activeWaiter?.resolve(result);