@mitralab.io/sdk-core 0.3.7 → 0.3.9

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,9 +48,6 @@ 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
- }
54
51
  function isNullableBoolean(value) {
55
52
  return value === null || typeof value === "boolean";
56
53
  }
@@ -439,9 +436,6 @@ function expectAppFields(app, context, errors) {
439
436
  if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
440
437
  if (!isNullableString(app.template)) invalidField(context, "template", errors);
441
438
  if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
442
- for (const field of ["emailLoginEnabled", "passwordLoginEnabled"]) {
443
- if (field in app && typeof app[field] !== "boolean") invalidField(context, field, errors);
444
- }
445
439
  if (typeof app.externalAccessEnabled !== "boolean") {
446
440
  invalidField(context, "externalAccessEnabled", errors);
447
441
  }
@@ -684,83 +678,6 @@ function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFacto
684
678
  if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
685
679
  return response;
686
680
  }
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
- }
764
681
  function expectAgentDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
765
682
  const agent = expectObject(value, context, errors);
766
683
  if (typeof agent.id !== "string") invalidField(context, "id", errors);
@@ -1109,6 +1026,78 @@ function expectAgentModel(value, context, errors = defaultSdkCoreErrorFactory) {
1109
1026
  }
1110
1027
  return model;
1111
1028
  }
1029
+ function expectAiProviders(value, context, errors = defaultSdkCoreErrorFactory) {
1030
+ const providers = expectObject(value, context, errors);
1031
+ if (typeof providers.activeEngine !== "string") {
1032
+ invalidField(context, "activeEngine", errors);
1033
+ }
1034
+ if (typeof providers.includedAiAvailable !== "boolean") {
1035
+ invalidField(context, "includedAiAvailable", errors);
1036
+ }
1037
+ if (!isNullableString(providers.activeCustomProviderId)) {
1038
+ invalidField(context, "activeCustomProviderId", errors);
1039
+ }
1040
+ expectObjectArray(
1041
+ providers.customProviders,
1042
+ `${context} customProviders`,
1043
+ errors,
1044
+ expectAgentConnectionCustomProvider
1045
+ );
1046
+ if (providers.includedAiQuota !== null) {
1047
+ expectIncludedAiQuota(providers.includedAiQuota, `${context} includedAiQuota`, errors);
1048
+ }
1049
+ const opencode = expectObject(providers.opencode, `${context} opencode`, errors);
1050
+ if (typeof opencode.connected !== "boolean") invalidField(context, "opencode.connected", errors);
1051
+ for (const field of ["presetId", "presetName", "providerId", "baseUrl"]) {
1052
+ if (!isNullableString(opencode[field])) invalidField(context, `opencode.${field}`, errors);
1053
+ }
1054
+ if (!isNullableString(opencode.authMethod)) {
1055
+ invalidField(context, "opencode.authMethod", errors);
1056
+ }
1057
+ if (opencode.models !== null && !isStringArray(opencode.models)) {
1058
+ invalidField(context, "opencode.models", errors);
1059
+ }
1060
+ if (hasOwn(providers, "managedAiProfile") && providers.managedAiProfile !== null) {
1061
+ const profile = expectObject(
1062
+ providers.managedAiProfile,
1063
+ `${context} managedAiProfile`,
1064
+ errors
1065
+ );
1066
+ for (const field of [
1067
+ "profile",
1068
+ "agentType",
1069
+ "selectionMode",
1070
+ "model",
1071
+ "requiredScope"
1072
+ ]) {
1073
+ if (typeof profile[field] !== "string") {
1074
+ invalidField(context, `managedAiProfile.${field}`, errors);
1075
+ }
1076
+ }
1077
+ }
1078
+ return providers;
1079
+ }
1080
+ function expectIncludedAiQuota(value, context, errors) {
1081
+ const quota = expectObject(value, context, errors);
1082
+ if (typeof quota.planCode !== "string") invalidField(context, "planCode", errors);
1083
+ if (hasOwn(quota, "blockingWindow") && typeof quota.blockingWindow !== "string") {
1084
+ invalidField(context, "blockingWindow", errors);
1085
+ }
1086
+ if (hasOwn(quota, "remainingTokens") && !isInteger(quota.remainingTokens)) {
1087
+ invalidField(context, "remainingTokens", errors);
1088
+ }
1089
+ const windows = expectObject(quota.windows, `${context} windows`, errors);
1090
+ for (const kind of ["day", "month"]) {
1091
+ if (!hasOwn(windows, kind)) continue;
1092
+ const window = expectObject(windows[kind], `${context} windows.${kind}`, errors);
1093
+ for (const field of ["limit", "left", "leftCenticredits"]) {
1094
+ if (!isInteger(window[field])) invalidField(context, `windows.${kind}.${field}`, errors);
1095
+ }
1096
+ if (typeof window.resetsAt !== "string") {
1097
+ invalidField(context, `windows.${kind}.resetsAt`, errors);
1098
+ }
1099
+ }
1100
+ }
1112
1101
  function expectCredentialStatus(value, context, errors = defaultSdkCoreErrorFactory) {
1113
1102
  const status = expectObject(value, context, errors);
1114
1103
  if (typeof status.provider !== "string") invalidField(context, "provider", errors);
@@ -1743,6 +1732,19 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1743
1732
  };
1744
1733
  }
1745
1734
 
1735
+ // src/modules/aiProviders.ts
1736
+ function createAiProvidersModule(transport, errors = defaultSdkCoreErrorFactory) {
1737
+ return {
1738
+ async get() {
1739
+ return expectAiProviders(
1740
+ await transport.request("/api/v1/ai-providers", { method: "GET" }),
1741
+ "AI providers response",
1742
+ errors
1743
+ );
1744
+ }
1745
+ };
1746
+ }
1747
+
1746
1748
  // src/modules/apps.ts
1747
1749
  function createAppsModule(transport, errors = defaultSdkCoreErrorFactory) {
1748
1750
  const appPath = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}`;
@@ -2959,23 +2961,7 @@ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
2959
2961
  }
2960
2962
 
2961
2963
  // src/modules/messenger.ts
2962
- function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory, getAppId) {
2963
- const templatePath = (type) => `/api/v1/email/templates/${encodePathSegment(type, "email template type", errors)}`;
2964
- const senderPath = (senderId) => `/api/v1/email/identities/${encodePathSegment(senderId, "email sender id", errors)}`;
2965
- const currentAppId = () => {
2966
- const appId = getAppId?.();
2967
- if (!appId) configurationError("An appId is required for app email calls", errors);
2968
- return appId;
2969
- };
2970
- const settingsPath = () => `/api/v1/email/apps/${encodePathSegment(currentAppId(), "app id", errors)}/settings`;
2971
- const preview = async (type, appId) => expectEmailTemplatePreview(
2972
- await transport.request(`${templatePath(type)}/preview`, {
2973
- method: "GET",
2974
- params: { appId }
2975
- }),
2976
- "Email template preview response",
2977
- errors
2978
- );
2964
+ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2979
2965
  return {
2980
2966
  async notify(content) {
2981
2967
  return expectMessageAccepted(
@@ -2996,120 +2982,6 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory, g
2996
2982
  "Send email response",
2997
2983
  errors
2998
2984
  );
2999
- },
3000
- async listEmailTemplates() {
3001
- return expectObjectArray(
3002
- await transport.request("/api/v1/email/templates", {
3003
- method: "GET",
3004
- params: { appId: currentAppId() }
3005
- }),
3006
- "Email template list response",
3007
- errors,
3008
- expectEmailTemplate
3009
- );
3010
- },
3011
- async getEmailTemplateType(type) {
3012
- return expectEmailTemplateTypeCatalog(
3013
- await transport.request(
3014
- `/api/v1/email/template-types/${encodePathSegment(type, "email template type", errors)}`,
3015
- { method: "GET" }
3016
- ),
3017
- "Email template type response",
3018
- errors
3019
- );
3020
- },
3021
- async getEmailTemplate(type) {
3022
- return expectEmailTemplate(
3023
- await transport.request(templatePath(type), {
3024
- method: "GET",
3025
- params: { appId: currentAppId() }
3026
- }),
3027
- "Email template response",
3028
- errors
3029
- );
3030
- },
3031
- async upsertEmailTemplate(type, input) {
3032
- const appId = currentAppId();
3033
- const template = expectEmailTemplate(
3034
- await transport.request(templatePath(type), {
3035
- method: "PUT",
3036
- body: templateBody(appId, input)
3037
- }),
3038
- "Upsert email template response",
3039
- errors
3040
- );
3041
- try {
3042
- return { template, preview: await preview(type, appId) };
3043
- } catch (previewError) {
3044
- return { template, preview: null, previewError };
3045
- }
3046
- },
3047
- async previewEmailTemplate(type) {
3048
- return preview(type, currentAppId());
3049
- },
3050
- async deleteEmailTemplate(type) {
3051
- expectEmpty(
3052
- await transport.request(templatePath(type), {
3053
- method: "DELETE",
3054
- params: { appId: currentAppId() }
3055
- }),
3056
- "Delete email template response",
3057
- errors
3058
- );
3059
- },
3060
- async listEmailSenders() {
3061
- return expectObjectArray(
3062
- await transport.request("/api/v1/email/identities/workspace", { method: "GET" }),
3063
- "Email sender list response",
3064
- errors,
3065
- expectEmailSender
3066
- );
3067
- },
3068
- async registerEmailSender(input) {
3069
- return expectEmailSender(
3070
- await transport.request("/api/v1/email/identities", {
3071
- method: "POST",
3072
- body: { email: input.email, displayName: input.displayName }
3073
- }),
3074
- "Register email sender response",
3075
- errors
3076
- );
3077
- },
3078
- async resendEmailSenderVerification(senderId) {
3079
- return expectEmailSender(
3080
- await transport.request(`${senderPath(senderId)}/resend-verification`, {
3081
- method: "POST"
3082
- }),
3083
- "Resend email sender verification response",
3084
- errors
3085
- );
3086
- },
3087
- async confirmEmailSender(senderId, code) {
3088
- return expectEmailSender(
3089
- await transport.request(`${senderPath(senderId)}/confirm`, {
3090
- method: "POST",
3091
- body: { code }
3092
- }),
3093
- "Confirm email sender response",
3094
- errors
3095
- );
3096
- },
3097
- async getEmailSettings() {
3098
- return expectEmailSettings(
3099
- await transport.request(settingsPath(), { method: "GET" }),
3100
- "Email settings response",
3101
- errors
3102
- );
3103
- },
3104
- async updateEmailSettings(input) {
3105
- return expectEmailSettings(
3106
- await transport.request(settingsPath(), {
3107
- method: "PUT",
3108
- body: settingsBody(input)
3109
- }),
3110
- "Update email settings response",
3111
- errors
3112
- );
3113
2985
  }
3114
2986
  };
3115
2987
  }
@@ -3125,21 +2997,6 @@ function rawEmailPayload(input) {
3125
2997
  ...input.text === void 0 ? {} : { text: input.text }
3126
2998
  };
3127
2999
  }
3128
- function templateBody(appId, input) {
3129
- return {
3130
- appId,
3131
- subject: input.subject,
3132
- htmlBody: input.htmlBody,
3133
- ...input.textBody === void 0 ? {} : { textBody: input.textBody }
3134
- };
3135
- }
3136
- function settingsBody(input) {
3137
- return {
3138
- ...input.senderIdentityId === void 0 ? {} : { senderIdentityId: input.senderIdentityId },
3139
- ...input.displayName === void 0 ? {} : { displayName: input.displayName },
3140
- ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo }
3141
- };
3142
- }
3143
3000
 
3144
3001
  // src/modules/publicFunctions.ts
3145
3002
  function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
@@ -3432,6 +3289,7 @@ function createSdkCore(options) {
3432
3289
  agentCredentials: createAgentCredentialsModule(copilot, errors),
3433
3290
  agents,
3434
3291
  agentTasks: createAgentTasksModule(copilot, errors),
3292
+ aiProviders: createAiProvidersModule(copilot, errors),
3435
3293
  apps,
3436
3294
  auth: createAuthModule(options.transports.auth, errors),
3437
3295
  context: createContextModule(
@@ -3457,7 +3315,7 @@ function createSdkCore(options) {
3457
3315
  integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
3458
3316
  integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
3459
3317
  members,
3460
- messenger: createMessengerModule(messengerTransport, errors, options.getAppId),
3318
+ messenger: createMessengerModule(messengerTransport, errors),
3461
3319
  publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
3462
3320
  queries: createQueriesModule(options.transports.dataManager, errors),
3463
3321
  sql: createSqlModule(options.transports.dataManager, errors),
@@ -4341,6 +4199,14 @@ function errorCode(error) {
4341
4199
  const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
4342
4200
  return typeof code === "string" ? code : void 0;
4343
4201
  }
4202
+ function refusalSentence(error) {
4203
+ if (!error || typeof error !== "object" || errorCode(error) === void 0) return void 0;
4204
+ const candidate = error;
4205
+ const refused = error instanceof AgentTaskTurnError || typeof candidate.status === "number" && candidate.status >= 400;
4206
+ if (!refused) return void 0;
4207
+ const sentence = asObject2(candidate.details)?.message ?? asObject2(candidate.body)?.message ?? errorMessage2(error);
4208
+ return typeof sentence === "string" && sentence.trim() ? sentence : void 0;
4209
+ }
4344
4210
  function delay(milliseconds) {
4345
4211
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
4346
4212
  }
@@ -4420,6 +4286,46 @@ function historyCursorOf(history) {
4420
4286
  }
4421
4287
  return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4422
4288
  }
4289
+ var SUBAGENT_END_STATUSES = /* @__PURE__ */ new Set([
4290
+ "completed",
4291
+ "failed",
4292
+ "cancelled",
4293
+ "interrupted"
4294
+ ]);
4295
+ function samePiece(held, row) {
4296
+ if (held.id === row.id) return true;
4297
+ if (!held.id.startsWith("live:")) return false;
4298
+ if (held.kind === "user" && row.kind === "user" && held.clientMessageId !== void 0) {
4299
+ return held.clientMessageId === row.clientMessageId;
4300
+ }
4301
+ if (row.itemId === void 0) return false;
4302
+ if (held.kind !== row.kind || held.itemId !== row.itemId) return false;
4303
+ return held.kind !== "tool" || row.kind === "tool" && held.tool.phase === row.tool.phase;
4304
+ }
4305
+ function heldIsNewer(held, row) {
4306
+ const heldLast = held.lastSequence ?? held.sequence;
4307
+ const rowLast = row.lastSequence ?? row.sequence;
4308
+ if (heldLast === void 0 || rowLast === void 0) return false;
4309
+ if (held.boxLog !== void 0 && held.boxLog !== row.boxLog) return false;
4310
+ return heldLast > rowLast;
4311
+ }
4312
+ function heldHasRow(held, row) {
4313
+ if (held.kind !== "agent" && held.kind !== "reasoning") return true;
4314
+ return held.sequence !== void 0 && row.sequence !== void 0 && held.sequence <= row.sequence;
4315
+ }
4316
+ function oldestRowOf(history) {
4317
+ return history.find((item) => !item.id.startsWith("live:"));
4318
+ }
4319
+ function rowOrHeld(held, row, liveComparable) {
4320
+ if (!liveComparable || !heldIsNewer(held, row) || !heldHasRow(held, row)) return row;
4321
+ return {
4322
+ ...held,
4323
+ id: row.id,
4324
+ ...row.sequence === void 0 ? {} : { sequence: row.sequence },
4325
+ ...held.lastSequence === void 0 && held.sequence === void 0 ? {} : { lastSequence: held.lastSequence ?? held.sequence },
4326
+ ...row.boxLog === void 0 ? {} : { boxLog: row.boxLog }
4327
+ };
4328
+ }
4423
4329
  function hasOlderRows(page) {
4424
4330
  return page.page.totalPages > page.page.number + 1;
4425
4331
  }
@@ -4631,6 +4537,9 @@ var CoreAgentTaskSession = class {
4631
4537
  // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
4632
4538
  // names another log, or reports a log shorter than the history's, has sequences that start over.
4633
4539
  rowsInChannelLog = true;
4540
+ // The log the hello of the channel named. A reread compares its rows with it every time: the
4541
+ // flag above starts over at each reread, and a page from the old log may come again.
4542
+ channelLog;
4634
4543
  olderRead = null;
4635
4544
  get taskId() {
4636
4545
  return this._taskId;
@@ -4730,7 +4639,7 @@ var CoreAgentTaskSession = class {
4730
4639
  include: "plan"
4731
4640
  });
4732
4641
  this.historyLimit = options.limit;
4733
- this.replaceHistory(page);
4642
+ await this.rereadHistory(page);
4734
4643
  const history = this.history;
4735
4644
  this.emit("historyLoaded", { history });
4736
4645
  return history;
@@ -4749,7 +4658,7 @@ var CoreAgentTaskSession = class {
4749
4658
  return this.olderRead.promise;
4750
4659
  }
4751
4660
  async readOlder(generation) {
4752
- const oldest = this._history.find((item) => !item.id.startsWith("live:"));
4661
+ const oldest = oldestRowOf(this._history);
4753
4662
  if (!this._taskId || !this._hasOlder || !oldest) return [];
4754
4663
  let page;
4755
4664
  try {
@@ -4765,17 +4674,110 @@ var CoreAgentTaskSession = class {
4765
4674
  throw error;
4766
4675
  }
4767
4676
  if (generation !== this.historyGeneration || this.isClosed()) return [];
4768
- const older = [...page.content].reverse().map(toAgentTimelineItem);
4677
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4678
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4679
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4680
+ const taken = /* @__PURE__ */ new Set();
4681
+ const older = rows.map((row) => {
4682
+ const held = this._history.find(
4683
+ (item) => !taken.has(item) && item.id.startsWith("live:") && samePiece(item, row)
4684
+ );
4685
+ if (held === void 0) return row;
4686
+ taken.add(held);
4687
+ return rowOrHeld(held, row, liveComparable);
4688
+ });
4769
4689
  this._hasOlder = hasOlderRows(page);
4770
- this._history = [...older, ...this._history];
4690
+ this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
4771
4691
  this.emit("historyLoaded", { history: this.history });
4772
4692
  return older;
4773
4693
  }
4694
+ // A page that starts at a piece held live, with live pieces before it that no row of the page
4695
+ // takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
4696
+ // they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
4697
+ // The rows before the page are read as `loadOlder` reads them, until the page reaches a row the
4698
+ // history holds or the gap's pieces all have their rows. A read of a history since replaced
4699
+ // lands nowhere (#145).
4700
+ async rereadHistory(page) {
4701
+ const generation = this.historyGeneration;
4702
+ let current = page;
4703
+ let extended = false;
4704
+ while (this._taskId && hasOlderRows(current) && this.skipsRows(current, extended)) {
4705
+ const oldest = current.content[current.content.length - 1];
4706
+ if (!oldest) break;
4707
+ let older;
4708
+ try {
4709
+ older = await this.dependencies.tasks.listMessages(this._taskId, {
4710
+ before: oldest.id,
4711
+ ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4712
+ sort: "createdAt,desc",
4713
+ kinds: "all",
4714
+ include: "plan"
4715
+ });
4716
+ } catch (error) {
4717
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4718
+ throw error;
4719
+ }
4720
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4721
+ current = { content: [...current.content, ...older.content], page: older.page };
4722
+ extended = true;
4723
+ }
4724
+ this.replaceHistory(current);
4725
+ }
4726
+ // Newest first, as the Copilot answers. Once rows before the page were read, a row the history
4727
+ // does not hold at all (one the session never heard) is still inside the gap.
4728
+ skipsRows(page, extended) {
4729
+ const rows = page.content.map(toAgentTimelineItem);
4730
+ const first = rows[rows.length - 1];
4731
+ if (!first) return false;
4732
+ const anchor = this._history.findIndex((item) => samePiece(item, first));
4733
+ if (anchor < 0) return extended;
4734
+ if (!this._history[anchor]?.id.startsWith("live:")) return false;
4735
+ for (let index = anchor - 1; index >= 0; index -= 1) {
4736
+ const held = this._history[index];
4737
+ if (!held?.id.startsWith("live:")) return false;
4738
+ if (!rows.some((row) => samePiece(held, row))) return true;
4739
+ }
4740
+ return false;
4741
+ }
4742
+ // The recovery rereads only the newest 100 rows while the turn runs: the older pages already
4743
+ // read stay, or what sits in them (the cards of subagents still running) vanishes until
4744
+ // `loadOlder` (#145). A page that does not reach the history it already has replaces it.
4774
4745
  replaceHistory(page) {
4775
- this.historyGeneration += 1;
4746
+ const oldest = oldestRowOf(this._history)?.id;
4747
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4748
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4749
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4776
4750
  this.rowsInChannelLog = true;
4777
- this._hasOlder = hasOlderRows(page);
4778
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
4751
+ const first = rows[0];
4752
+ const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
4753
+ const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
4754
+ const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
4755
+ if (anchor < 0) this._hasOlder = hasOlderRows(page);
4756
+ const used = /* @__PURE__ */ new Set();
4757
+ const merged = rows.map((row) => {
4758
+ const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
4759
+ if (held === void 0) return row;
4760
+ used.add(held);
4761
+ return rowOrHeld(held, row, liveComparable);
4762
+ });
4763
+ const cursor = liveComparable ? historyCursorOf(rows) : void 0;
4764
+ const unrecorded = cursor === void 0 ? [] : replaced.filter(
4765
+ (item) => !used.has(item) && item.id.startsWith("live:") && item.sequence !== void 0 && (item.kind === "plan" || item.sequence > cursor.sequence)
4766
+ );
4767
+ this._history = [...kept, ...merged, ...unrecorded];
4768
+ if (anchor < 0 || oldestRowOf(this._history)?.id !== oldest) this.historyGeneration += 1;
4769
+ if (cursor === void 0) return;
4770
+ for (const subagent of this.subagentsById.values()) {
4771
+ const row = this._history.find(
4772
+ (item) => item.kind === "tool" && item.tool.toolId === subagent.toolId
4773
+ );
4774
+ const rowStatus = row?.kind === "tool" ? row.subagent?.status : void 0;
4775
+ if (rowStatus !== void 0 && SUBAGENT_END_STATUSES.has(rowStatus)) continue;
4776
+ const applied = this.subagentSequences.get(subagent.subagentId);
4777
+ if (SUBAGENT_END_STATUSES.has(subagent.status) || applied !== void 0 && applied > cursor.sequence) {
4778
+ this.writeSubagentOnSpawn(subagent);
4779
+ }
4780
+ }
4779
4781
  }
4780
4782
  editQueueItem(id, text) {
4781
4783
  this.requireOpen();
@@ -4874,7 +4876,7 @@ var CoreAgentTaskSession = class {
4874
4876
  });
4875
4877
  const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4876
4878
  waiter?.reject(error);
4877
- this.emitError("Failed to send Agent prompt", error);
4879
+ this.emitSendError(error);
4878
4880
  if (this._status === "streaming") {
4879
4881
  this.settleSteers((steered) => steered.reject(error));
4880
4882
  this.setStatus("idle");
@@ -4942,7 +4944,7 @@ var CoreAgentTaskSession = class {
4942
4944
  taken = await admitted;
4943
4945
  } catch (error) {
4944
4946
  handedOver();
4945
- this.emitError("Failed to send Agent prompt", error);
4947
+ this.emitSendError(error);
4946
4948
  return fail(error);
4947
4949
  }
4948
4950
  if (!taken) {
@@ -5012,7 +5014,7 @@ var CoreAgentTaskSession = class {
5012
5014
  }).catch((error) => {
5013
5015
  this.forgetSteer(steered);
5014
5016
  waiter?.reject(error);
5015
- this.emitError("Failed to send Agent prompt", error);
5017
+ this.emitSendError(error);
5016
5018
  }).finally(() => {
5017
5019
  this.pendingSteers -= 1;
5018
5020
  });
@@ -5204,7 +5206,7 @@ var CoreAgentTaskSession = class {
5204
5206
  kinds: "all",
5205
5207
  include: "plan"
5206
5208
  });
5207
- this.replaceHistory(page);
5209
+ await this.rereadHistory(page);
5208
5210
  this.emit("historyLoaded", { history: this.history });
5209
5211
  const rows = page.content.filter(isChatRow);
5210
5212
  const recovered = rows.find(
@@ -5358,6 +5360,7 @@ var CoreAgentTaskSession = class {
5358
5360
  break;
5359
5361
  case "hello": {
5360
5362
  const lastSequence = payload?.lastSequence;
5363
+ if (typeof payload?.boxLog === "number") this.channelLog = payload.boxLog;
5361
5364
  const history = historyCursorOf(this._history);
5362
5365
  const rowsLog = [...this._history].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5363
5366
  if (typeof payload?.boxLog === "number" && rowsLog !== void 0 && payload.boxLog !== rowsLog || typeof lastSequence === "number" && history !== void 0 && lastSequence < history.sequence) {
@@ -5834,6 +5837,12 @@ var CoreAgentTaskSession = class {
5834
5837
  ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
5835
5838
  };
5836
5839
  this.subagentsById.set(subagentId, subagent);
5840
+ this.writeSubagentOnSpawn(subagent);
5841
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5842
+ }
5843
+ // The call that spawned it carries its last state, as the history records it.
5844
+ writeSubagentOnSpawn(subagent) {
5845
+ const { toolId, subagentId, status } = subagent;
5837
5846
  const index = this._history.findIndex(
5838
5847
  (item) => item.kind === "tool" && item.tool.toolId === toolId
5839
5848
  );
@@ -5851,7 +5860,6 @@ var CoreAgentTaskSession = class {
5851
5860
  }
5852
5861
  };
5853
5862
  }
5854
- this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5855
5863
  }
5856
5864
  finishTurn(reason, usage, end = {}) {
5857
5865
  if (this._status !== "streaming" && this._status !== "cancelled") return;
@@ -5949,6 +5957,15 @@ var CoreAgentTaskSession = class {
5949
5957
  error: `${prefix}: ${errorMessage2(error)}`
5950
5958
  });
5951
5959
  }
5960
+ emitSendError(error) {
5961
+ const sentence = refusalSentence(error);
5962
+ if (sentence === void 0) {
5963
+ this.emitError("Failed to send Agent prompt", error);
5964
+ return;
5965
+ }
5966
+ const code = errorCode(error);
5967
+ this.emit("error", { ...code ? { code } : {}, error: sentence });
5968
+ }
5952
5969
  setStatus(status) {
5953
5970
  if (this._status === status) return;
5954
5971
  if (status !== "streaming" && status !== "cancelled") {
@@ -6060,6 +6077,7 @@ export {
6060
6077
  createAgentTaskSessionManager,
6061
6078
  createAgentTasksModule,
6062
6079
  createAgentsModule,
6080
+ createAiProvidersModule,
6063
6081
  createAppsModule,
6064
6082
  createAuthModule,
6065
6083
  createContextModule,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,