@mitralab.io/sdk-core 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -120,6 +120,9 @@ function isObject(value) {
120
120
  function isNullableString(value) {
121
121
  return value === null || typeof value === "string";
122
122
  }
123
+ function isNonEmptyString(value) {
124
+ return typeof value === "string" && value.length > 0;
125
+ }
123
126
  function isNullableBoolean(value) {
124
127
  return value === null || typeof value === "boolean";
125
128
  }
@@ -753,6 +756,83 @@ function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFacto
753
756
  if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
754
757
  return response;
755
758
  }
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
+ }
756
836
  function expectAgentDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
757
837
  const agent = expectObject(value, context, errors);
758
838
  if (typeof agent.id !== "string") invalidField(context, "id", errors);
@@ -1127,6 +1207,14 @@ function expectCredentialUsage(value, context, errors = defaultSdkCoreErrorFacto
1127
1207
  }
1128
1208
  return usage;
1129
1209
  }
1210
+ function expectAgentReadyProvider(value, context, errors = defaultSdkCoreErrorFactory) {
1211
+ const entry = expectObject(value, context, errors);
1212
+ if (typeof entry.provider !== "string") invalidField(context, "provider", errors);
1213
+ if (!isNullableString(entry.providerName)) invalidField(context, "providerName", errors);
1214
+ expectObjectArray(entry.models, `${context} models`, errors, expectAgentModel);
1215
+ if (entry.usage !== null) expectCredentialUsage(entry.usage, `${context} usage`, errors);
1216
+ return entry;
1217
+ }
1130
1218
  var CREDENTIAL_USAGE_NOT_FOUND = "CREDENTIAL_USAGE_NOT_FOUND";
1131
1219
  async function readCredentialUsage(request, context, errors = defaultSdkCoreErrorFactory) {
1132
1220
  let value;
@@ -1415,6 +1503,17 @@ function createAgentCredentialsModule(transport, errors = defaultSdkCoreErrorFac
1415
1503
  expectAgentModel
1416
1504
  );
1417
1505
  },
1506
+ async providers(agentId, options) {
1507
+ return expectObjectArray(
1508
+ await transport.request("/api/v1/models/providers", {
1509
+ method: "GET",
1510
+ params: { agentId, ...scopeParams(options).params }
1511
+ }),
1512
+ "Ready provider response",
1513
+ errors,
1514
+ expectAgentReadyProvider
1515
+ );
1516
+ },
1418
1517
  async usage(provider, options) {
1419
1518
  return readCredentialUsage(
1420
1519
  transport.request(`/api/v1/credentials/${providerSegment(provider)}/usage`, {
@@ -1691,7 +1790,8 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1691
1790
  page: options.page,
1692
1791
  size: options.size,
1693
1792
  sort: options.sort,
1694
- kinds: options.kinds
1793
+ kinds: options.kinds,
1794
+ before: options.before
1695
1795
  }
1696
1796
  }),
1697
1797
  context,
@@ -2930,7 +3030,23 @@ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
2930
3030
  }
2931
3031
 
2932
3032
  // src/modules/messenger.ts
2933
- function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
3033
+ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory, getAppId) {
3034
+ const templatePath = (type) => `/api/v1/email/templates/${encodePathSegment(type, "email template type", errors)}`;
3035
+ const senderPath = (senderId) => `/api/v1/email/identities/${encodePathSegment(senderId, "email sender id", errors)}`;
3036
+ const currentAppId = () => {
3037
+ const appId = getAppId?.();
3038
+ if (!appId) configurationError("An appId is required for app email calls", errors);
3039
+ return appId;
3040
+ };
3041
+ const settingsPath = () => `/api/v1/email/apps/${encodePathSegment(currentAppId(), "app id", errors)}/settings`;
3042
+ const preview = async (type, appId) => expectEmailTemplatePreview(
3043
+ await transport.request(`${templatePath(type)}/preview`, {
3044
+ method: "GET",
3045
+ params: { appId }
3046
+ }),
3047
+ "Email template preview response",
3048
+ errors
3049
+ );
2934
3050
  return {
2935
3051
  async notify(content) {
2936
3052
  return expectMessageAccepted(
@@ -2951,6 +3067,120 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2951
3067
  "Send email response",
2952
3068
  errors
2953
3069
  );
3070
+ },
3071
+ async listEmailTemplates() {
3072
+ return expectObjectArray(
3073
+ await transport.request("/api/v1/email/templates", {
3074
+ method: "GET",
3075
+ params: { appId: currentAppId() }
3076
+ }),
3077
+ "Email template list response",
3078
+ errors,
3079
+ expectEmailTemplate
3080
+ );
3081
+ },
3082
+ async getEmailTemplateType(type) {
3083
+ return expectEmailTemplateTypeCatalog(
3084
+ await transport.request(
3085
+ `/api/v1/email/template-types/${encodePathSegment(type, "email template type", errors)}`,
3086
+ { method: "GET" }
3087
+ ),
3088
+ "Email template type response",
3089
+ errors
3090
+ );
3091
+ },
3092
+ async getEmailTemplate(type) {
3093
+ return expectEmailTemplate(
3094
+ await transport.request(templatePath(type), {
3095
+ method: "GET",
3096
+ params: { appId: currentAppId() }
3097
+ }),
3098
+ "Email template response",
3099
+ errors
3100
+ );
3101
+ },
3102
+ async upsertEmailTemplate(type, input) {
3103
+ const appId = currentAppId();
3104
+ const template = expectEmailTemplate(
3105
+ await transport.request(templatePath(type), {
3106
+ method: "PUT",
3107
+ body: templateBody(appId, input)
3108
+ }),
3109
+ "Upsert email template response",
3110
+ errors
3111
+ );
3112
+ try {
3113
+ return { template, preview: await preview(type, appId) };
3114
+ } catch (previewError) {
3115
+ return { template, preview: null, previewError };
3116
+ }
3117
+ },
3118
+ async previewEmailTemplate(type) {
3119
+ return preview(type, currentAppId());
3120
+ },
3121
+ async deleteEmailTemplate(type) {
3122
+ expectEmpty(
3123
+ await transport.request(templatePath(type), {
3124
+ method: "DELETE",
3125
+ params: { appId: currentAppId() }
3126
+ }),
3127
+ "Delete email template response",
3128
+ errors
3129
+ );
3130
+ },
3131
+ async listEmailSenders() {
3132
+ return expectObjectArray(
3133
+ await transport.request("/api/v1/email/identities/workspace", { method: "GET" }),
3134
+ "Email sender list response",
3135
+ errors,
3136
+ expectEmailSender
3137
+ );
3138
+ },
3139
+ async registerEmailSender(input) {
3140
+ return expectEmailSender(
3141
+ await transport.request("/api/v1/email/identities", {
3142
+ method: "POST",
3143
+ body: { email: input.email, displayName: input.displayName }
3144
+ }),
3145
+ "Register email sender response",
3146
+ errors
3147
+ );
3148
+ },
3149
+ async resendEmailSenderVerification(senderId) {
3150
+ return expectEmailSender(
3151
+ await transport.request(`${senderPath(senderId)}/resend-verification`, {
3152
+ method: "POST"
3153
+ }),
3154
+ "Resend email sender verification response",
3155
+ errors
3156
+ );
3157
+ },
3158
+ async confirmEmailSender(senderId, code) {
3159
+ return expectEmailSender(
3160
+ await transport.request(`${senderPath(senderId)}/confirm`, {
3161
+ method: "POST",
3162
+ body: { code }
3163
+ }),
3164
+ "Confirm email sender response",
3165
+ errors
3166
+ );
3167
+ },
3168
+ async getEmailSettings() {
3169
+ return expectEmailSettings(
3170
+ await transport.request(settingsPath(), { method: "GET" }),
3171
+ "Email settings response",
3172
+ errors
3173
+ );
3174
+ },
3175
+ async updateEmailSettings(input) {
3176
+ return expectEmailSettings(
3177
+ await transport.request(settingsPath(), {
3178
+ method: "PUT",
3179
+ body: settingsBody(input)
3180
+ }),
3181
+ "Update email settings response",
3182
+ errors
3183
+ );
2954
3184
  }
2955
3185
  };
2956
3186
  }
@@ -2966,6 +3196,21 @@ function rawEmailPayload(input) {
2966
3196
  ...input.text === void 0 ? {} : { text: input.text }
2967
3197
  };
2968
3198
  }
3199
+ function templateBody(appId, input) {
3200
+ return {
3201
+ appId,
3202
+ subject: input.subject,
3203
+ htmlBody: input.htmlBody,
3204
+ ...input.textBody === void 0 ? {} : { textBody: input.textBody }
3205
+ };
3206
+ }
3207
+ function settingsBody(input) {
3208
+ return {
3209
+ ...input.senderIdentityId === void 0 ? {} : { senderIdentityId: input.senderIdentityId },
3210
+ ...input.displayName === void 0 ? {} : { displayName: input.displayName },
3211
+ ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo }
3212
+ };
3213
+ }
2969
3214
 
2970
3215
  // src/modules/publicFunctions.ts
2971
3216
  function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
@@ -3283,7 +3528,7 @@ function createSdkCore(options) {
3283
3528
  integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
3284
3529
  integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
3285
3530
  members,
3286
- messenger: createMessengerModule(messengerTransport, errors),
3531
+ messenger: createMessengerModule(messengerTransport, errors, options.getAppId),
3287
3532
  publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
3288
3533
  queries: createQueriesModule(options.transports.dataManager, errors),
3289
3534
  sql: createSqlModule(options.transports.dataManager, errors),
@@ -4141,7 +4386,8 @@ function providerUsageOf(payload) {
4141
4386
  if (!payload) return null;
4142
4387
  try {
4143
4388
  const { harness, observedAt, status, windows } = expectCredentialUsage(payload, "providerUsage");
4144
- return { harness, observedAt, status, windows };
4389
+ const provider = typeof payload.provider === "string" && payload.provider ? payload.provider : null;
4390
+ return { harness, observedAt, status, windows, ...provider ? { provider } : {} };
4145
4391
  } catch {
4146
4392
  return null;
4147
4393
  }
@@ -4240,6 +4486,9 @@ function historyCursorOf(history) {
4240
4486
  }
4241
4487
  return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4242
4488
  }
4489
+ function hasOlderRows(page) {
4490
+ return page.page.totalPages > page.page.number + 1;
4491
+ }
4243
4492
  function isChatRow(message) {
4244
4493
  return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4245
4494
  }
@@ -4422,6 +4671,11 @@ var CoreAgentTaskSession = class {
4422
4671
  acceptedIds = [];
4423
4672
  // Taken by the first channel of `session({ taskId })`; no later channel asks for a replay.
4424
4673
  openingCursor;
4674
+ historyLimit;
4675
+ _hasOlder = false;
4676
+ // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4677
+ historyGeneration = 0;
4678
+ olderRead = null;
4425
4679
  get taskId() {
4426
4680
  return this._taskId;
4427
4681
  }
@@ -4518,11 +4772,52 @@ var CoreAgentTaskSession = class {
4518
4772
  sort: "createdAt,desc",
4519
4773
  kinds: "all"
4520
4774
  });
4521
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
4775
+ this.historyLimit = options.limit;
4776
+ this.replaceHistory(page);
4522
4777
  const history = this.history;
4523
4778
  this.emit("historyLoaded", { history });
4524
4779
  return history;
4525
4780
  }
4781
+ get hasOlder() {
4782
+ return this._hasOlder;
4783
+ }
4784
+ loadOlder() {
4785
+ if (this.olderRead?.generation !== this.historyGeneration) {
4786
+ const generation = this.historyGeneration;
4787
+ const promise = this.readOlder(generation).finally(() => {
4788
+ if (this.olderRead?.promise === promise) this.olderRead = null;
4789
+ });
4790
+ this.olderRead = { generation, promise };
4791
+ }
4792
+ return this.olderRead.promise;
4793
+ }
4794
+ async readOlder(generation) {
4795
+ const oldest = this._history.find((item) => !item.id.startsWith("live:"));
4796
+ if (!this._taskId || !this._hasOlder || !oldest) return [];
4797
+ let page;
4798
+ try {
4799
+ page = await this.dependencies.tasks.listMessages(this._taskId, {
4800
+ before: oldest.id,
4801
+ ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4802
+ sort: "createdAt,desc",
4803
+ kinds: "all"
4804
+ });
4805
+ } catch (error) {
4806
+ if (generation !== this.historyGeneration || this.isClosed()) return [];
4807
+ throw error;
4808
+ }
4809
+ if (generation !== this.historyGeneration || this.isClosed()) return [];
4810
+ const older = [...page.content].reverse().map(toAgentTimelineItem);
4811
+ this._hasOlder = hasOlderRows(page);
4812
+ this._history = [...older, ...this._history];
4813
+ this.emit("historyLoaded", { history: this.history });
4814
+ return older;
4815
+ }
4816
+ replaceHistory(page) {
4817
+ this.historyGeneration += 1;
4818
+ this._hasOlder = hasOlderRows(page);
4819
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
4820
+ }
4526
4821
  editQueueItem(id, text) {
4527
4822
  this.requireOpen();
4528
4823
  if (this.sentTexts.has(id)) this.sentTexts.set(id, text);
@@ -4636,19 +4931,19 @@ var CoreAgentTaskSession = class {
4636
4931
  this.dispatch = dispatch;
4637
4932
  }
4638
4933
  async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
4639
- if (this.openingPromise && !await this.openingPromise) {
4934
+ if (this.openingPromise && !await this.openingPromise && !this.isClosed()) {
4640
4935
  throw new Error("Agent task session could not be opened.");
4641
4936
  }
4642
- if (this.isClosed()) return false;
4937
+ if (this.isClosed() && !this._taskId) return false;
4643
4938
  await this.ensureTask();
4644
4939
  const input = messageInput(prompt, options);
4645
- if (this.isClosed()) {
4646
- await this.handOver(input, clientMessageId).catch(() => void 0);
4647
- return false;
4648
- }
4649
- await this.ensureChannel();
4650
- if (this.isClosed()) return false;
4940
+ if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4941
+ await this.ensureChannel().catch((error) => {
4942
+ if (!this.isClosed()) throw error;
4943
+ });
4944
+ if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4651
4945
  await this.captureTurnBaseline();
4946
+ if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4652
4947
  this._content = "";
4653
4948
  this.recoveryUsed = false;
4654
4949
  this.recoveredTerminalReason = void 0;
@@ -4666,6 +4961,17 @@ var CoreAgentTaskSession = class {
4666
4961
  this.acceptOnce(clientMessageId);
4667
4962
  return true;
4668
4963
  }
4964
+ // A prompt whose task exists is never dropped by close; the task outlives the session. Apps
4965
+ // close the creating session inside taskCreated and reopen by task id, so the input still goes
4966
+ // out over REST. Only a prompt that never reached `handOver` comes here: the Copilot does not
4967
+ // dedupe POST /inputs by `clientMessageId`, and a second copy would run a second turn. No
4968
+ // channel, status, or event for a closed session, and a failure has no listener left to hear it.
4969
+ // `close()` rejects only the waiter of a turn already open; this one has none yet.
4970
+ async handOverAfterClose(input, clientMessageId, waiter) {
4971
+ await this.handOver(input, clientMessageId).catch(() => void 0);
4972
+ waiter?.reject(new Error("Agent task session is closed."));
4973
+ return false;
4974
+ }
4669
4975
  // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
4670
4976
  // that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
4671
4977
  // that turn already ended. Nothing waits in this session. On the direct channel it goes with an
@@ -4886,7 +5192,7 @@ var CoreAgentTaskSession = class {
4886
5192
  sort: "createdAt,desc",
4887
5193
  kinds: "all"
4888
5194
  });
4889
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
5195
+ this.replaceHistory(page);
4890
5196
  this.emit("historyLoaded", { history: this.history });
4891
5197
  const rows = page.content.filter(isChatRow);
4892
5198
  const recovered = rows.find(
@@ -4943,11 +5249,13 @@ var CoreAgentTaskSession = class {
4943
5249
  }
4944
5250
  const turnRunning = this._status === "streaming" || this._status === "cancelled";
4945
5251
  const id = clientMessageId === void 0 ? {} : { clientMessageId };
4946
- const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
5252
+ const mode = input.type === "message" && input.mode ? { mode: input.mode } : {};
5253
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...mode, ...id } : {
4947
5254
  type: "message",
4948
5255
  content: input.content,
4949
5256
  ...input.agentType ? { agentType: input.agentType } : {},
4950
5257
  ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
5258
+ ...mode,
4951
5259
  ...id
4952
5260
  };
4953
5261
  await this.dependencies.tasks.sendInput(this._taskId, rest);