@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.cjs CHANGED
@@ -30,6 +30,7 @@ __export(index_exports, {
30
30
  createAgentTaskSessionManager: () => createAgentTaskSessionManager,
31
31
  createAgentTasksModule: () => createAgentTasksModule,
32
32
  createAgentsModule: () => createAgentsModule,
33
+ createAiProvidersModule: () => createAiProvidersModule,
33
34
  createAppsModule: () => createAppsModule,
34
35
  createAuthModule: () => createAuthModule,
35
36
  createContextModule: () => createContextModule,
@@ -120,9 +121,6 @@ function isObject(value) {
120
121
  function isNullableString(value) {
121
122
  return value === null || typeof value === "string";
122
123
  }
123
- function isNonEmptyString(value) {
124
- return typeof value === "string" && value.length > 0;
125
- }
126
124
  function isNullableBoolean(value) {
127
125
  return value === null || typeof value === "boolean";
128
126
  }
@@ -511,9 +509,6 @@ function expectAppFields(app, context, errors) {
511
509
  if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
512
510
  if (!isNullableString(app.template)) invalidField(context, "template", errors);
513
511
  if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
514
- for (const field of ["emailLoginEnabled", "passwordLoginEnabled"]) {
515
- if (field in app && typeof app[field] !== "boolean") invalidField(context, field, errors);
516
- }
517
512
  if (typeof app.externalAccessEnabled !== "boolean") {
518
513
  invalidField(context, "externalAccessEnabled", errors);
519
514
  }
@@ -756,83 +751,6 @@ function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFacto
756
751
  if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
757
752
  return response;
758
753
  }
759
- function expectEmailTemplate(value, context, errors = defaultSdkCoreErrorFactory) {
760
- const template = expectObject(value, context, errors);
761
- if (typeof template.id !== "string") invalidField(context, "id", errors);
762
- if (!isNonEmptyString(template.type)) invalidField(context, "type", errors);
763
- if (!isNullableString(template.senderIdentityId)) {
764
- invalidField(context, "senderIdentityId", errors);
765
- }
766
- if (typeof template.subject !== "string") invalidField(context, "subject", errors);
767
- if (typeof template.htmlBody !== "string") invalidField(context, "htmlBody", errors);
768
- if (!isNullableString(template.textBody)) invalidField(context, "textBody", errors);
769
- if (typeof template.platformDefault !== "boolean") {
770
- invalidField(context, "platformDefault", errors);
771
- }
772
- if (typeof template.createdAt !== "string") invalidField(context, "createdAt", errors);
773
- if (typeof template.updatedAt !== "string") invalidField(context, "updatedAt", errors);
774
- return template;
775
- }
776
- function expectEmailTemplateTypeCatalog(value, context, errors = defaultSdkCoreErrorFactory) {
777
- const catalog = expectObject(value, context, errors);
778
- if (!isNonEmptyString(catalog.type)) invalidField(context, "type", errors);
779
- expectObjectArray(catalog.variables, `${context} variables`, errors).forEach(
780
- (variable, position) => {
781
- const variableContext = `${context} variable ${position}`;
782
- if (typeof variable.name !== "string") invalidField(variableContext, "name", errors);
783
- if (typeof variable.required !== "boolean") {
784
- invalidField(variableContext, "required", errors);
785
- }
786
- if (!isNullableString(variable.description)) {
787
- invalidField(variableContext, "description", errors);
788
- }
789
- if (!isNullableString(variable.preview)) invalidField(variableContext, "preview", errors);
790
- }
791
- );
792
- return catalog;
793
- }
794
- function expectEmailTemplatePreview(value, context, errors = defaultSdkCoreErrorFactory) {
795
- const preview = expectObject(value, context, errors);
796
- if (typeof preview.subject !== "string") invalidField(context, "subject", errors);
797
- if (typeof preview.htmlBody !== "string") invalidField(context, "htmlBody", errors);
798
- if (!isNullableString(preview.textBody)) invalidField(context, "textBody", errors);
799
- return preview;
800
- }
801
- function expectEmailSender(value, context, errors = defaultSdkCoreErrorFactory) {
802
- const sender = expectObject(value, context, errors);
803
- if (typeof sender.id !== "string") invalidField(context, "id", errors);
804
- if (typeof sender.email !== "string") invalidField(context, "email", errors);
805
- if (typeof sender.displayName !== "string") invalidField(context, "displayName", errors);
806
- if (!isNonEmptyString(sender.status)) invalidField(context, "status", errors);
807
- if (typeof sender.sharedWithCurrentWorkspace !== "boolean") {
808
- invalidField(context, "sharedWithCurrentWorkspace", errors);
809
- }
810
- if (typeof sender.ownerConfirmationPending !== "boolean") {
811
- invalidField(context, "ownerConfirmationPending", errors);
812
- }
813
- if (typeof sender.createdAt !== "string") invalidField(context, "createdAt", errors);
814
- if (typeof sender.updatedAt !== "string") invalidField(context, "updatedAt", errors);
815
- return sender;
816
- }
817
- function expectEmailSettings(value, context, errors = defaultSdkCoreErrorFactory) {
818
- const settings = expectObject(value, context, errors);
819
- if (typeof settings.appId !== "string") invalidField(context, "appId", errors);
820
- if (!isNullableString(settings.senderIdentityId)) {
821
- invalidField(context, "senderIdentityId", errors);
822
- }
823
- if (!isNullableString(settings.displayName)) invalidField(context, "displayName", errors);
824
- if (!isNullableString(settings.replyTo)) invalidField(context, "replyTo", errors);
825
- if (typeof settings.ownTemplateSendsFromBrand !== "boolean") {
826
- invalidField(context, "ownTemplateSendsFromBrand", errors);
827
- }
828
- const senderContext = `${context} effectiveSender`;
829
- const sender = expectObject(settings.effectiveSender, senderContext, errors);
830
- if (typeof sender.email !== "string") invalidField(senderContext, "email", errors);
831
- if (!isNullableString(sender.displayName)) invalidField(senderContext, "displayName", errors);
832
- if (!isNonEmptyString(sender.source)) invalidField(senderContext, "source", errors);
833
- if (!isNullableString(sender.reason)) invalidField(senderContext, "reason", errors);
834
- return settings;
835
- }
836
754
  function expectAgentDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
837
755
  const agent = expectObject(value, context, errors);
838
756
  if (typeof agent.id !== "string") invalidField(context, "id", errors);
@@ -1181,6 +1099,78 @@ function expectAgentModel(value, context, errors = defaultSdkCoreErrorFactory) {
1181
1099
  }
1182
1100
  return model;
1183
1101
  }
1102
+ function expectAiProviders(value, context, errors = defaultSdkCoreErrorFactory) {
1103
+ const providers = expectObject(value, context, errors);
1104
+ if (typeof providers.activeEngine !== "string") {
1105
+ invalidField(context, "activeEngine", errors);
1106
+ }
1107
+ if (typeof providers.includedAiAvailable !== "boolean") {
1108
+ invalidField(context, "includedAiAvailable", errors);
1109
+ }
1110
+ if (!isNullableString(providers.activeCustomProviderId)) {
1111
+ invalidField(context, "activeCustomProviderId", errors);
1112
+ }
1113
+ expectObjectArray(
1114
+ providers.customProviders,
1115
+ `${context} customProviders`,
1116
+ errors,
1117
+ expectAgentConnectionCustomProvider
1118
+ );
1119
+ if (providers.includedAiQuota !== null) {
1120
+ expectIncludedAiQuota(providers.includedAiQuota, `${context} includedAiQuota`, errors);
1121
+ }
1122
+ const opencode = expectObject(providers.opencode, `${context} opencode`, errors);
1123
+ if (typeof opencode.connected !== "boolean") invalidField(context, "opencode.connected", errors);
1124
+ for (const field of ["presetId", "presetName", "providerId", "baseUrl"]) {
1125
+ if (!isNullableString(opencode[field])) invalidField(context, `opencode.${field}`, errors);
1126
+ }
1127
+ if (!isNullableString(opencode.authMethod)) {
1128
+ invalidField(context, "opencode.authMethod", errors);
1129
+ }
1130
+ if (opencode.models !== null && !isStringArray(opencode.models)) {
1131
+ invalidField(context, "opencode.models", errors);
1132
+ }
1133
+ if (hasOwn(providers, "managedAiProfile") && providers.managedAiProfile !== null) {
1134
+ const profile = expectObject(
1135
+ providers.managedAiProfile,
1136
+ `${context} managedAiProfile`,
1137
+ errors
1138
+ );
1139
+ for (const field of [
1140
+ "profile",
1141
+ "agentType",
1142
+ "selectionMode",
1143
+ "model",
1144
+ "requiredScope"
1145
+ ]) {
1146
+ if (typeof profile[field] !== "string") {
1147
+ invalidField(context, `managedAiProfile.${field}`, errors);
1148
+ }
1149
+ }
1150
+ }
1151
+ return providers;
1152
+ }
1153
+ function expectIncludedAiQuota(value, context, errors) {
1154
+ const quota = expectObject(value, context, errors);
1155
+ if (typeof quota.planCode !== "string") invalidField(context, "planCode", errors);
1156
+ if (hasOwn(quota, "blockingWindow") && typeof quota.blockingWindow !== "string") {
1157
+ invalidField(context, "blockingWindow", errors);
1158
+ }
1159
+ if (hasOwn(quota, "remainingTokens") && !isInteger(quota.remainingTokens)) {
1160
+ invalidField(context, "remainingTokens", errors);
1161
+ }
1162
+ const windows = expectObject(quota.windows, `${context} windows`, errors);
1163
+ for (const kind of ["day", "month"]) {
1164
+ if (!hasOwn(windows, kind)) continue;
1165
+ const window = expectObject(windows[kind], `${context} windows.${kind}`, errors);
1166
+ for (const field of ["limit", "left", "leftCenticredits"]) {
1167
+ if (!isInteger(window[field])) invalidField(context, `windows.${kind}.${field}`, errors);
1168
+ }
1169
+ if (typeof window.resetsAt !== "string") {
1170
+ invalidField(context, `windows.${kind}.resetsAt`, errors);
1171
+ }
1172
+ }
1173
+ }
1184
1174
  function expectCredentialStatus(value, context, errors = defaultSdkCoreErrorFactory) {
1185
1175
  const status = expectObject(value, context, errors);
1186
1176
  if (typeof status.provider !== "string") invalidField(context, "provider", errors);
@@ -1815,6 +1805,19 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1815
1805
  };
1816
1806
  }
1817
1807
 
1808
+ // src/modules/aiProviders.ts
1809
+ function createAiProvidersModule(transport, errors = defaultSdkCoreErrorFactory) {
1810
+ return {
1811
+ async get() {
1812
+ return expectAiProviders(
1813
+ await transport.request("/api/v1/ai-providers", { method: "GET" }),
1814
+ "AI providers response",
1815
+ errors
1816
+ );
1817
+ }
1818
+ };
1819
+ }
1820
+
1818
1821
  // src/modules/apps.ts
1819
1822
  function createAppsModule(transport, errors = defaultSdkCoreErrorFactory) {
1820
1823
  const appPath = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}`;
@@ -3031,23 +3034,7 @@ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
3031
3034
  }
3032
3035
 
3033
3036
  // src/modules/messenger.ts
3034
- function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory, getAppId) {
3035
- const templatePath = (type) => `/api/v1/email/templates/${encodePathSegment(type, "email template type", errors)}`;
3036
- const senderPath = (senderId) => `/api/v1/email/identities/${encodePathSegment(senderId, "email sender id", errors)}`;
3037
- const currentAppId = () => {
3038
- const appId = getAppId?.();
3039
- if (!appId) configurationError("An appId is required for app email calls", errors);
3040
- return appId;
3041
- };
3042
- const settingsPath = () => `/api/v1/email/apps/${encodePathSegment(currentAppId(), "app id", errors)}/settings`;
3043
- const preview = async (type, appId) => expectEmailTemplatePreview(
3044
- await transport.request(`${templatePath(type)}/preview`, {
3045
- method: "GET",
3046
- params: { appId }
3047
- }),
3048
- "Email template preview response",
3049
- errors
3050
- );
3037
+ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
3051
3038
  return {
3052
3039
  async notify(content) {
3053
3040
  return expectMessageAccepted(
@@ -3068,120 +3055,6 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory, g
3068
3055
  "Send email response",
3069
3056
  errors
3070
3057
  );
3071
- },
3072
- async listEmailTemplates() {
3073
- return expectObjectArray(
3074
- await transport.request("/api/v1/email/templates", {
3075
- method: "GET",
3076
- params: { appId: currentAppId() }
3077
- }),
3078
- "Email template list response",
3079
- errors,
3080
- expectEmailTemplate
3081
- );
3082
- },
3083
- async getEmailTemplateType(type) {
3084
- return expectEmailTemplateTypeCatalog(
3085
- await transport.request(
3086
- `/api/v1/email/template-types/${encodePathSegment(type, "email template type", errors)}`,
3087
- { method: "GET" }
3088
- ),
3089
- "Email template type response",
3090
- errors
3091
- );
3092
- },
3093
- async getEmailTemplate(type) {
3094
- return expectEmailTemplate(
3095
- await transport.request(templatePath(type), {
3096
- method: "GET",
3097
- params: { appId: currentAppId() }
3098
- }),
3099
- "Email template response",
3100
- errors
3101
- );
3102
- },
3103
- async upsertEmailTemplate(type, input) {
3104
- const appId = currentAppId();
3105
- const template = expectEmailTemplate(
3106
- await transport.request(templatePath(type), {
3107
- method: "PUT",
3108
- body: templateBody(appId, input)
3109
- }),
3110
- "Upsert email template response",
3111
- errors
3112
- );
3113
- try {
3114
- return { template, preview: await preview(type, appId) };
3115
- } catch (previewError) {
3116
- return { template, preview: null, previewError };
3117
- }
3118
- },
3119
- async previewEmailTemplate(type) {
3120
- return preview(type, currentAppId());
3121
- },
3122
- async deleteEmailTemplate(type) {
3123
- expectEmpty(
3124
- await transport.request(templatePath(type), {
3125
- method: "DELETE",
3126
- params: { appId: currentAppId() }
3127
- }),
3128
- "Delete email template response",
3129
- errors
3130
- );
3131
- },
3132
- async listEmailSenders() {
3133
- return expectObjectArray(
3134
- await transport.request("/api/v1/email/identities/workspace", { method: "GET" }),
3135
- "Email sender list response",
3136
- errors,
3137
- expectEmailSender
3138
- );
3139
- },
3140
- async registerEmailSender(input) {
3141
- return expectEmailSender(
3142
- await transport.request("/api/v1/email/identities", {
3143
- method: "POST",
3144
- body: { email: input.email, displayName: input.displayName }
3145
- }),
3146
- "Register email sender response",
3147
- errors
3148
- );
3149
- },
3150
- async resendEmailSenderVerification(senderId) {
3151
- return expectEmailSender(
3152
- await transport.request(`${senderPath(senderId)}/resend-verification`, {
3153
- method: "POST"
3154
- }),
3155
- "Resend email sender verification response",
3156
- errors
3157
- );
3158
- },
3159
- async confirmEmailSender(senderId, code) {
3160
- return expectEmailSender(
3161
- await transport.request(`${senderPath(senderId)}/confirm`, {
3162
- method: "POST",
3163
- body: { code }
3164
- }),
3165
- "Confirm email sender response",
3166
- errors
3167
- );
3168
- },
3169
- async getEmailSettings() {
3170
- return expectEmailSettings(
3171
- await transport.request(settingsPath(), { method: "GET" }),
3172
- "Email settings response",
3173
- errors
3174
- );
3175
- },
3176
- async updateEmailSettings(input) {
3177
- return expectEmailSettings(
3178
- await transport.request(settingsPath(), {
3179
- method: "PUT",
3180
- body: settingsBody(input)
3181
- }),
3182
- "Update email settings response",
3183
- errors
3184
- );
3185
3058
  }
3186
3059
  };
3187
3060
  }
@@ -3197,21 +3070,6 @@ function rawEmailPayload(input) {
3197
3070
  ...input.text === void 0 ? {} : { text: input.text }
3198
3071
  };
3199
3072
  }
3200
- function templateBody(appId, input) {
3201
- return {
3202
- appId,
3203
- subject: input.subject,
3204
- htmlBody: input.htmlBody,
3205
- ...input.textBody === void 0 ? {} : { textBody: input.textBody }
3206
- };
3207
- }
3208
- function settingsBody(input) {
3209
- return {
3210
- ...input.senderIdentityId === void 0 ? {} : { senderIdentityId: input.senderIdentityId },
3211
- ...input.displayName === void 0 ? {} : { displayName: input.displayName },
3212
- ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo }
3213
- };
3214
- }
3215
3073
 
3216
3074
  // src/modules/publicFunctions.ts
3217
3075
  function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
@@ -3504,6 +3362,7 @@ function createSdkCore(options) {
3504
3362
  agentCredentials: createAgentCredentialsModule(copilot, errors),
3505
3363
  agents,
3506
3364
  agentTasks: createAgentTasksModule(copilot, errors),
3365
+ aiProviders: createAiProvidersModule(copilot, errors),
3507
3366
  apps,
3508
3367
  auth: createAuthModule(options.transports.auth, errors),
3509
3368
  context: createContextModule(
@@ -3529,7 +3388,7 @@ function createSdkCore(options) {
3529
3388
  integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
3530
3389
  integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
3531
3390
  members,
3532
- messenger: createMessengerModule(messengerTransport, errors, options.getAppId),
3391
+ messenger: createMessengerModule(messengerTransport, errors),
3533
3392
  publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
3534
3393
  queries: createQueriesModule(options.transports.dataManager, errors),
3535
3394
  sql: createSqlModule(options.transports.dataManager, errors),
@@ -4413,6 +4272,14 @@ function errorCode(error) {
4413
4272
  const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
4414
4273
  return typeof code === "string" ? code : void 0;
4415
4274
  }
4275
+ function refusalSentence(error) {
4276
+ if (!error || typeof error !== "object" || errorCode(error) === void 0) return void 0;
4277
+ const candidate = error;
4278
+ const refused = error instanceof AgentTaskTurnError || typeof candidate.status === "number" && candidate.status >= 400;
4279
+ if (!refused) return void 0;
4280
+ const sentence = asObject2(candidate.details)?.message ?? asObject2(candidate.body)?.message ?? errorMessage2(error);
4281
+ return typeof sentence === "string" && sentence.trim() ? sentence : void 0;
4282
+ }
4416
4283
  function delay(milliseconds) {
4417
4284
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
4418
4285
  }
@@ -4492,6 +4359,46 @@ function historyCursorOf(history) {
4492
4359
  }
4493
4360
  return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4494
4361
  }
4362
+ var SUBAGENT_END_STATUSES = /* @__PURE__ */ new Set([
4363
+ "completed",
4364
+ "failed",
4365
+ "cancelled",
4366
+ "interrupted"
4367
+ ]);
4368
+ function samePiece(held, row) {
4369
+ if (held.id === row.id) return true;
4370
+ if (!held.id.startsWith("live:")) return false;
4371
+ if (held.kind === "user" && row.kind === "user" && held.clientMessageId !== void 0) {
4372
+ return held.clientMessageId === row.clientMessageId;
4373
+ }
4374
+ if (row.itemId === void 0) return false;
4375
+ if (held.kind !== row.kind || held.itemId !== row.itemId) return false;
4376
+ return held.kind !== "tool" || row.kind === "tool" && held.tool.phase === row.tool.phase;
4377
+ }
4378
+ function heldIsNewer(held, row) {
4379
+ const heldLast = held.lastSequence ?? held.sequence;
4380
+ const rowLast = row.lastSequence ?? row.sequence;
4381
+ if (heldLast === void 0 || rowLast === void 0) return false;
4382
+ if (held.boxLog !== void 0 && held.boxLog !== row.boxLog) return false;
4383
+ return heldLast > rowLast;
4384
+ }
4385
+ function heldHasRow(held, row) {
4386
+ if (held.kind !== "agent" && held.kind !== "reasoning") return true;
4387
+ return held.sequence !== void 0 && row.sequence !== void 0 && held.sequence <= row.sequence;
4388
+ }
4389
+ function oldestRowOf(history) {
4390
+ return history.find((item) => !item.id.startsWith("live:"));
4391
+ }
4392
+ function rowOrHeld(held, row, liveComparable) {
4393
+ if (!liveComparable || !heldIsNewer(held, row) || !heldHasRow(held, row)) return row;
4394
+ return {
4395
+ ...held,
4396
+ id: row.id,
4397
+ ...row.sequence === void 0 ? {} : { sequence: row.sequence },
4398
+ ...held.lastSequence === void 0 && held.sequence === void 0 ? {} : { lastSequence: held.lastSequence ?? held.sequence },
4399
+ ...row.boxLog === void 0 ? {} : { boxLog: row.boxLog }
4400
+ };
4401
+ }
4495
4402
  function hasOlderRows(page) {
4496
4403
  return page.page.totalPages > page.page.number + 1;
4497
4404
  }
@@ -4703,6 +4610,9 @@ var CoreAgentTaskSession = class {
4703
4610
  // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
4704
4611
  // names another log, or reports a log shorter than the history's, has sequences that start over.
4705
4612
  rowsInChannelLog = true;
4613
+ // The log the hello of the channel named. A reread compares its rows with it every time: the
4614
+ // flag above starts over at each reread, and a page from the old log may come again.
4615
+ channelLog;
4706
4616
  olderRead = null;
4707
4617
  get taskId() {
4708
4618
  return this._taskId;
@@ -4802,7 +4712,7 @@ var CoreAgentTaskSession = class {
4802
4712
  include: "plan"
4803
4713
  });
4804
4714
  this.historyLimit = options.limit;
4805
- this.replaceHistory(page);
4715
+ await this.rereadHistory(page);
4806
4716
  const history = this.history;
4807
4717
  this.emit("historyLoaded", { history });
4808
4718
  return history;
@@ -4821,7 +4731,7 @@ var CoreAgentTaskSession = class {
4821
4731
  return this.olderRead.promise;
4822
4732
  }
4823
4733
  async readOlder(generation) {
4824
- const oldest = this._history.find((item) => !item.id.startsWith("live:"));
4734
+ const oldest = oldestRowOf(this._history);
4825
4735
  if (!this._taskId || !this._hasOlder || !oldest) return [];
4826
4736
  let page;
4827
4737
  try {
@@ -4837,17 +4747,110 @@ var CoreAgentTaskSession = class {
4837
4747
  throw error;
4838
4748
  }
4839
4749
  if (generation !== this.historyGeneration || this.isClosed()) return [];
4840
- const older = [...page.content].reverse().map(toAgentTimelineItem);
4750
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4751
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4752
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4753
+ const taken = /* @__PURE__ */ new Set();
4754
+ const older = rows.map((row) => {
4755
+ const held = this._history.find(
4756
+ (item) => !taken.has(item) && item.id.startsWith("live:") && samePiece(item, row)
4757
+ );
4758
+ if (held === void 0) return row;
4759
+ taken.add(held);
4760
+ return rowOrHeld(held, row, liveComparable);
4761
+ });
4841
4762
  this._hasOlder = hasOlderRows(page);
4842
- this._history = [...older, ...this._history];
4763
+ this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
4843
4764
  this.emit("historyLoaded", { history: this.history });
4844
4765
  return older;
4845
4766
  }
4767
+ // A page that starts at a piece held live, with live pieces before it that no row of the page
4768
+ // takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
4769
+ // they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
4770
+ // The rows before the page are read as `loadOlder` reads them, until the page reaches a row the
4771
+ // history holds or the gap's pieces all have their rows. A read of a history since replaced
4772
+ // lands nowhere (#145).
4773
+ async rereadHistory(page) {
4774
+ const generation = this.historyGeneration;
4775
+ let current = page;
4776
+ let extended = false;
4777
+ while (this._taskId && hasOlderRows(current) && this.skipsRows(current, extended)) {
4778
+ const oldest = current.content[current.content.length - 1];
4779
+ if (!oldest) break;
4780
+ let older;
4781
+ try {
4782
+ older = await this.dependencies.tasks.listMessages(this._taskId, {
4783
+ before: oldest.id,
4784
+ ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4785
+ sort: "createdAt,desc",
4786
+ kinds: "all",
4787
+ include: "plan"
4788
+ });
4789
+ } catch (error) {
4790
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4791
+ throw error;
4792
+ }
4793
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4794
+ current = { content: [...current.content, ...older.content], page: older.page };
4795
+ extended = true;
4796
+ }
4797
+ this.replaceHistory(current);
4798
+ }
4799
+ // Newest first, as the Copilot answers. Once rows before the page were read, a row the history
4800
+ // does not hold at all (one the session never heard) is still inside the gap.
4801
+ skipsRows(page, extended) {
4802
+ const rows = page.content.map(toAgentTimelineItem);
4803
+ const first = rows[rows.length - 1];
4804
+ if (!first) return false;
4805
+ const anchor = this._history.findIndex((item) => samePiece(item, first));
4806
+ if (anchor < 0) return extended;
4807
+ if (!this._history[anchor]?.id.startsWith("live:")) return false;
4808
+ for (let index = anchor - 1; index >= 0; index -= 1) {
4809
+ const held = this._history[index];
4810
+ if (!held?.id.startsWith("live:")) return false;
4811
+ if (!rows.some((row) => samePiece(held, row))) return true;
4812
+ }
4813
+ return false;
4814
+ }
4815
+ // The recovery rereads only the newest 100 rows while the turn runs: the older pages already
4816
+ // read stay, or what sits in them (the cards of subagents still running) vanishes until
4817
+ // `loadOlder` (#145). A page that does not reach the history it already has replaces it.
4846
4818
  replaceHistory(page) {
4847
- this.historyGeneration += 1;
4819
+ const oldest = oldestRowOf(this._history)?.id;
4820
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4821
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4822
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4848
4823
  this.rowsInChannelLog = true;
4849
- this._hasOlder = hasOlderRows(page);
4850
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
4824
+ const first = rows[0];
4825
+ const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
4826
+ const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
4827
+ const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
4828
+ if (anchor < 0) this._hasOlder = hasOlderRows(page);
4829
+ const used = /* @__PURE__ */ new Set();
4830
+ const merged = rows.map((row) => {
4831
+ const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
4832
+ if (held === void 0) return row;
4833
+ used.add(held);
4834
+ return rowOrHeld(held, row, liveComparable);
4835
+ });
4836
+ const cursor = liveComparable ? historyCursorOf(rows) : void 0;
4837
+ const unrecorded = cursor === void 0 ? [] : replaced.filter(
4838
+ (item) => !used.has(item) && item.id.startsWith("live:") && item.sequence !== void 0 && (item.kind === "plan" || item.sequence > cursor.sequence)
4839
+ );
4840
+ this._history = [...kept, ...merged, ...unrecorded];
4841
+ if (anchor < 0 || oldestRowOf(this._history)?.id !== oldest) this.historyGeneration += 1;
4842
+ if (cursor === void 0) return;
4843
+ for (const subagent of this.subagentsById.values()) {
4844
+ const row = this._history.find(
4845
+ (item) => item.kind === "tool" && item.tool.toolId === subagent.toolId
4846
+ );
4847
+ const rowStatus = row?.kind === "tool" ? row.subagent?.status : void 0;
4848
+ if (rowStatus !== void 0 && SUBAGENT_END_STATUSES.has(rowStatus)) continue;
4849
+ const applied = this.subagentSequences.get(subagent.subagentId);
4850
+ if (SUBAGENT_END_STATUSES.has(subagent.status) || applied !== void 0 && applied > cursor.sequence) {
4851
+ this.writeSubagentOnSpawn(subagent);
4852
+ }
4853
+ }
4851
4854
  }
4852
4855
  editQueueItem(id, text) {
4853
4856
  this.requireOpen();
@@ -4946,7 +4949,7 @@ var CoreAgentTaskSession = class {
4946
4949
  });
4947
4950
  const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4948
4951
  waiter?.reject(error);
4949
- this.emitError("Failed to send Agent prompt", error);
4952
+ this.emitSendError(error);
4950
4953
  if (this._status === "streaming") {
4951
4954
  this.settleSteers((steered) => steered.reject(error));
4952
4955
  this.setStatus("idle");
@@ -5014,7 +5017,7 @@ var CoreAgentTaskSession = class {
5014
5017
  taken = await admitted;
5015
5018
  } catch (error) {
5016
5019
  handedOver();
5017
- this.emitError("Failed to send Agent prompt", error);
5020
+ this.emitSendError(error);
5018
5021
  return fail(error);
5019
5022
  }
5020
5023
  if (!taken) {
@@ -5084,7 +5087,7 @@ var CoreAgentTaskSession = class {
5084
5087
  }).catch((error) => {
5085
5088
  this.forgetSteer(steered);
5086
5089
  waiter?.reject(error);
5087
- this.emitError("Failed to send Agent prompt", error);
5090
+ this.emitSendError(error);
5088
5091
  }).finally(() => {
5089
5092
  this.pendingSteers -= 1;
5090
5093
  });
@@ -5276,7 +5279,7 @@ var CoreAgentTaskSession = class {
5276
5279
  kinds: "all",
5277
5280
  include: "plan"
5278
5281
  });
5279
- this.replaceHistory(page);
5282
+ await this.rereadHistory(page);
5280
5283
  this.emit("historyLoaded", { history: this.history });
5281
5284
  const rows = page.content.filter(isChatRow);
5282
5285
  const recovered = rows.find(
@@ -5430,6 +5433,7 @@ var CoreAgentTaskSession = class {
5430
5433
  break;
5431
5434
  case "hello": {
5432
5435
  const lastSequence = payload?.lastSequence;
5436
+ if (typeof payload?.boxLog === "number") this.channelLog = payload.boxLog;
5433
5437
  const history = historyCursorOf(this._history);
5434
5438
  const rowsLog = [...this._history].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5435
5439
  if (typeof payload?.boxLog === "number" && rowsLog !== void 0 && payload.boxLog !== rowsLog || typeof lastSequence === "number" && history !== void 0 && lastSequence < history.sequence) {
@@ -5906,6 +5910,12 @@ var CoreAgentTaskSession = class {
5906
5910
  ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
5907
5911
  };
5908
5912
  this.subagentsById.set(subagentId, subagent);
5913
+ this.writeSubagentOnSpawn(subagent);
5914
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5915
+ }
5916
+ // The call that spawned it carries its last state, as the history records it.
5917
+ writeSubagentOnSpawn(subagent) {
5918
+ const { toolId, subagentId, status } = subagent;
5909
5919
  const index = this._history.findIndex(
5910
5920
  (item) => item.kind === "tool" && item.tool.toolId === toolId
5911
5921
  );
@@ -5923,7 +5933,6 @@ var CoreAgentTaskSession = class {
5923
5933
  }
5924
5934
  };
5925
5935
  }
5926
- this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5927
5936
  }
5928
5937
  finishTurn(reason, usage, end = {}) {
5929
5938
  if (this._status !== "streaming" && this._status !== "cancelled") return;
@@ -6021,6 +6030,15 @@ var CoreAgentTaskSession = class {
6021
6030
  error: `${prefix}: ${errorMessage2(error)}`
6022
6031
  });
6023
6032
  }
6033
+ emitSendError(error) {
6034
+ const sentence = refusalSentence(error);
6035
+ if (sentence === void 0) {
6036
+ this.emitError("Failed to send Agent prompt", error);
6037
+ return;
6038
+ }
6039
+ const code = errorCode(error);
6040
+ this.emit("error", { ...code ? { code } : {}, error: sentence });
6041
+ }
6024
6042
  setStatus(status) {
6025
6043
  if (this._status === status) return;
6026
6044
  if (status !== "streaming" && status !== "cancelled") {
@@ -6133,6 +6151,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
6133
6151
  createAgentTaskSessionManager,
6134
6152
  createAgentTasksModule,
6135
6153
  createAgentsModule,
6154
+ createAiProvidersModule,
6136
6155
  createAppsModule,
6137
6156
  createAuthModule,
6138
6157
  createContextModule,