@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.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);
@@ -1055,6 +1135,14 @@ function expectCredentialUsage(value, context, errors = defaultSdkCoreErrorFacto
1055
1135
  }
1056
1136
  return usage;
1057
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
+ }
1058
1146
  var CREDENTIAL_USAGE_NOT_FOUND = "CREDENTIAL_USAGE_NOT_FOUND";
1059
1147
  async function readCredentialUsage(request, context, errors = defaultSdkCoreErrorFactory) {
1060
1148
  let value;
@@ -1343,6 +1431,17 @@ function createAgentCredentialsModule(transport, errors = defaultSdkCoreErrorFac
1343
1431
  expectAgentModel
1344
1432
  );
1345
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
+ },
1346
1445
  async usage(provider, options) {
1347
1446
  return readCredentialUsage(
1348
1447
  transport.request(`/api/v1/credentials/${providerSegment(provider)}/usage`, {
@@ -1619,7 +1718,8 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1619
1718
  page: options.page,
1620
1719
  size: options.size,
1621
1720
  sort: options.sort,
1622
- kinds: options.kinds
1721
+ kinds: options.kinds,
1722
+ before: options.before
1623
1723
  }
1624
1724
  }),
1625
1725
  context,
@@ -2858,7 +2958,23 @@ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
2858
2958
  }
2859
2959
 
2860
2960
  // src/modules/messenger.ts
2861
- 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
+ );
2862
2978
  return {
2863
2979
  async notify(content) {
2864
2980
  return expectMessageAccepted(
@@ -2879,6 +2995,120 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2879
2995
  "Send email response",
2880
2996
  errors
2881
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
+ );
2882
3112
  }
2883
3113
  };
2884
3114
  }
@@ -2894,6 +3124,21 @@ function rawEmailPayload(input) {
2894
3124
  ...input.text === void 0 ? {} : { text: input.text }
2895
3125
  };
2896
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
+ }
2897
3142
 
2898
3143
  // src/modules/publicFunctions.ts
2899
3144
  function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
@@ -3211,7 +3456,7 @@ function createSdkCore(options) {
3211
3456
  integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
3212
3457
  integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
3213
3458
  members,
3214
- messenger: createMessengerModule(messengerTransport, errors),
3459
+ messenger: createMessengerModule(messengerTransport, errors, options.getAppId),
3215
3460
  publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
3216
3461
  queries: createQueriesModule(options.transports.dataManager, errors),
3217
3462
  sql: createSqlModule(options.transports.dataManager, errors),
@@ -4069,7 +4314,8 @@ function providerUsageOf(payload) {
4069
4314
  if (!payload) return null;
4070
4315
  try {
4071
4316
  const { harness, observedAt, status, windows } = expectCredentialUsage(payload, "providerUsage");
4072
- return { harness, observedAt, status, windows };
4317
+ const provider = typeof payload.provider === "string" && payload.provider ? payload.provider : null;
4318
+ return { harness, observedAt, status, windows, ...provider ? { provider } : {} };
4073
4319
  } catch {
4074
4320
  return null;
4075
4321
  }
@@ -4168,6 +4414,9 @@ function historyCursorOf(history) {
4168
4414
  }
4169
4415
  return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4170
4416
  }
4417
+ function hasOlderRows(page) {
4418
+ return page.page.totalPages > page.page.number + 1;
4419
+ }
4171
4420
  function isChatRow(message) {
4172
4421
  return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4173
4422
  }
@@ -4350,6 +4599,11 @@ var CoreAgentTaskSession = class {
4350
4599
  acceptedIds = [];
4351
4600
  // Taken by the first channel of `session({ taskId })`; no later channel asks for a replay.
4352
4601
  openingCursor;
4602
+ historyLimit;
4603
+ _hasOlder = false;
4604
+ // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4605
+ historyGeneration = 0;
4606
+ olderRead = null;
4353
4607
  get taskId() {
4354
4608
  return this._taskId;
4355
4609
  }
@@ -4446,11 +4700,52 @@ var CoreAgentTaskSession = class {
4446
4700
  sort: "createdAt,desc",
4447
4701
  kinds: "all"
4448
4702
  });
4449
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
4703
+ this.historyLimit = options.limit;
4704
+ this.replaceHistory(page);
4450
4705
  const history = this.history;
4451
4706
  this.emit("historyLoaded", { history });
4452
4707
  return history;
4453
4708
  }
4709
+ get hasOlder() {
4710
+ return this._hasOlder;
4711
+ }
4712
+ loadOlder() {
4713
+ if (this.olderRead?.generation !== this.historyGeneration) {
4714
+ const generation = this.historyGeneration;
4715
+ const promise = this.readOlder(generation).finally(() => {
4716
+ if (this.olderRead?.promise === promise) this.olderRead = null;
4717
+ });
4718
+ this.olderRead = { generation, promise };
4719
+ }
4720
+ return this.olderRead.promise;
4721
+ }
4722
+ async readOlder(generation) {
4723
+ const oldest = this._history.find((item) => !item.id.startsWith("live:"));
4724
+ if (!this._taskId || !this._hasOlder || !oldest) return [];
4725
+ let page;
4726
+ try {
4727
+ page = await this.dependencies.tasks.listMessages(this._taskId, {
4728
+ before: oldest.id,
4729
+ ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4730
+ sort: "createdAt,desc",
4731
+ kinds: "all"
4732
+ });
4733
+ } catch (error) {
4734
+ if (generation !== this.historyGeneration || this.isClosed()) return [];
4735
+ throw error;
4736
+ }
4737
+ if (generation !== this.historyGeneration || this.isClosed()) return [];
4738
+ const older = [...page.content].reverse().map(toAgentTimelineItem);
4739
+ this._hasOlder = hasOlderRows(page);
4740
+ this._history = [...older, ...this._history];
4741
+ this.emit("historyLoaded", { history: this.history });
4742
+ return older;
4743
+ }
4744
+ replaceHistory(page) {
4745
+ this.historyGeneration += 1;
4746
+ this._hasOlder = hasOlderRows(page);
4747
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
4748
+ }
4454
4749
  editQueueItem(id, text) {
4455
4750
  this.requireOpen();
4456
4751
  if (this.sentTexts.has(id)) this.sentTexts.set(id, text);
@@ -4564,19 +4859,19 @@ var CoreAgentTaskSession = class {
4564
4859
  this.dispatch = dispatch;
4565
4860
  }
4566
4861
  async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
4567
- if (this.openingPromise && !await this.openingPromise) {
4862
+ if (this.openingPromise && !await this.openingPromise && !this.isClosed()) {
4568
4863
  throw new Error("Agent task session could not be opened.");
4569
4864
  }
4570
- if (this.isClosed()) return false;
4865
+ if (this.isClosed() && !this._taskId) return false;
4571
4866
  await this.ensureTask();
4572
4867
  const input = messageInput(prompt, options);
4573
- if (this.isClosed()) {
4574
- await this.handOver(input, clientMessageId).catch(() => void 0);
4575
- return false;
4576
- }
4577
- await this.ensureChannel();
4578
- if (this.isClosed()) return false;
4868
+ if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4869
+ await this.ensureChannel().catch((error) => {
4870
+ if (!this.isClosed()) throw error;
4871
+ });
4872
+ if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4579
4873
  await this.captureTurnBaseline();
4874
+ if (this.isClosed()) return this.handOverAfterClose(input, clientMessageId, waiter);
4580
4875
  this._content = "";
4581
4876
  this.recoveryUsed = false;
4582
4877
  this.recoveredTerminalReason = void 0;
@@ -4594,6 +4889,17 @@ var CoreAgentTaskSession = class {
4594
4889
  this.acceptOnce(clientMessageId);
4595
4890
  return true;
4596
4891
  }
4892
+ // A prompt whose task exists is never dropped by close; the task outlives the session. Apps
4893
+ // close the creating session inside taskCreated and reopen by task id, so the input still goes
4894
+ // out over REST. Only a prompt that never reached `handOver` comes here: the Copilot does not
4895
+ // dedupe POST /inputs by `clientMessageId`, and a second copy would run a second turn. No
4896
+ // channel, status, or event for a closed session, and a failure has no listener left to hear it.
4897
+ // `close()` rejects only the waiter of a turn already open; this one has none yet.
4898
+ async handOverAfterClose(input, clientMessageId, waiter) {
4899
+ await this.handOver(input, clientMessageId).catch(() => void 0);
4900
+ waiter?.reject(new Error("Agent task session is closed."));
4901
+ return false;
4902
+ }
4597
4903
  // A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
4598
4904
  // that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
4599
4905
  // that turn already ended. Nothing waits in this session. On the direct channel it goes with an
@@ -4814,7 +5120,7 @@ var CoreAgentTaskSession = class {
4814
5120
  sort: "createdAt,desc",
4815
5121
  kinds: "all"
4816
5122
  });
4817
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
5123
+ this.replaceHistory(page);
4818
5124
  this.emit("historyLoaded", { history: this.history });
4819
5125
  const rows = page.content.filter(isChatRow);
4820
5126
  const recovered = rows.find(
@@ -4871,11 +5177,13 @@ var CoreAgentTaskSession = class {
4871
5177
  }
4872
5178
  const turnRunning = this._status === "streaming" || this._status === "cancelled";
4873
5179
  const id = clientMessageId === void 0 ? {} : { clientMessageId };
4874
- const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
5180
+ const mode = input.type === "message" && input.mode ? { mode: input.mode } : {};
5181
+ const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...mode, ...id } : {
4875
5182
  type: "message",
4876
5183
  content: input.content,
4877
5184
  ...input.agentType ? { agentType: input.agentType } : {},
4878
5185
  ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
5186
+ ...mode,
4879
5187
  ...id
4880
5188
  };
4881
5189
  await this.dependencies.tasks.sendInput(this._taskId, rest);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,