@axiom-lattice/core 13.0.2 → 13.2.0

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.mjs CHANGED
@@ -562,6 +562,10 @@ import {
562
562
  } from "@axiom-lattice/protocols";
563
563
 
564
564
  // src/store_lattice/InMemoryThreadStore.ts
565
+ import {
566
+ classifyThreadMetadata,
567
+ toThreadMonitorRecord
568
+ } from "@axiom-lattice/protocols";
565
569
  var InMemoryThreadStore = class {
566
570
  constructor() {
567
571
  // Map<tenantId, Map<assistantId, Map<threadId, Thread>>>
@@ -589,6 +593,35 @@ var InMemoryThreadStore = class {
589
593
  }
590
594
  return threads;
591
595
  }
596
+ async listThreadsByTenant(tenantId2, query = {}) {
597
+ const limit = Math.min(200, Math.max(1, Math.floor(query.limit ?? 50)));
598
+ const offset = Math.max(0, Math.floor(query.offset ?? 0));
599
+ const createdAfter = query.createdAfter ? Date.parse(query.createdAfter) : void 0;
600
+ const tenantThreads = this.threads.get(tenantId2);
601
+ if (!tenantThreads) return { records: [], total: 0 };
602
+ const all = [];
603
+ for (const assistantThreads of tenantThreads.values()) {
604
+ all.push(...assistantThreads.values());
605
+ }
606
+ const filtered = all.filter((thread) => {
607
+ if (query.assistantId && thread.assistantId !== query.assistantId) {
608
+ return false;
609
+ }
610
+ if (createdAfter !== void 0 && Number.isFinite(createdAfter) && thread.createdAt.getTime() < createdAfter) {
611
+ return false;
612
+ }
613
+ if (query.kind && classifyThreadMetadata(thread.metadata) !== query.kind) {
614
+ return false;
615
+ }
616
+ return true;
617
+ }).sort(
618
+ (left, right) => right.createdAt.getTime() - left.createdAt.getTime() || right.id.localeCompare(left.id)
619
+ );
620
+ return {
621
+ records: filtered.slice(offset, offset + limit).map(toThreadMonitorRecord),
622
+ total: filtered.length
623
+ };
624
+ }
592
625
  /**
593
626
  * Get a thread by ID for a specific tenant
594
627
  */
@@ -3286,11 +3319,13 @@ var InMemoryUserStore = class {
3286
3319
  if (updates.email !== void 0) {
3287
3320
  this.assertEmailAvailable(updates.email, id);
3288
3321
  }
3322
+ const authEpoch = updates.authEpoch !== void 0 ? updates.authEpoch : existing.authEpoch;
3289
3323
  const updated = {
3290
3324
  id: existing.id,
3291
3325
  email: updates.email ?? existing.email,
3292
3326
  name: updates.name ?? existing.name,
3293
3327
  status: updates.status ?? existing.status,
3328
+ ...authEpoch !== void 0 ? { authEpoch } : {},
3294
3329
  metadata: updates.metadata ?? existing.metadata,
3295
3330
  createdAt: existing.createdAt,
3296
3331
  updatedAt: /* @__PURE__ */ new Date()
@@ -4124,12 +4159,13 @@ var InMemoryThreadMessageQueueStore = class {
4124
4159
  const pending = await this.getPendingMessages(threadId, scope);
4125
4160
  return pending.length;
4126
4161
  }
4127
- async getThreadsWithPendingMessages() {
4162
+ async getThreadsWithPendingMessages(tenantId2) {
4128
4163
  const result = [];
4129
4164
  const seen = /* @__PURE__ */ new Set();
4130
4165
  for (const [threadId, messages] of this.messages.entries()) {
4131
4166
  const scopes = /* @__PURE__ */ new Map();
4132
4167
  for (const message of messages) {
4168
+ if (tenantId2 && (message.tenantId || "default") !== tenantId2) continue;
4133
4169
  if (message.status !== "pending" && message.status !== "processing" && message.status) continue;
4134
4170
  const scopeKey = JSON.stringify([message.tenantId, message.assistantId, message.workspaceId, message.projectId, threadId]);
4135
4171
  const hasPending = message.status === "pending" || !message.status;
@@ -4754,13 +4790,18 @@ var InMemoryOpenAuditStore = class {
4754
4790
  async append(record) {
4755
4791
  this.records.push({ ...record, id: randomUUID7(), createdAt: /* @__PURE__ */ new Date() });
4756
4792
  }
4793
+ async get(tenantId2, id) {
4794
+ return this.records.find((record) => record.tenantId === tenantId2 && record.id === id) ?? null;
4795
+ }
4757
4796
  async query(params) {
4758
4797
  const from = params.from ? new Date(params.from).getTime() : void 0;
4759
4798
  const to = params.to ? new Date(params.to).getTime() : void 0;
4760
4799
  const filtered = this.records.filter((r) => {
4761
4800
  if (r.tenantId !== params.tenantId) return false;
4762
4801
  if (params.credentialId && r.credentialId !== params.credentialId) return false;
4802
+ if (params.projectId && r.projectId !== params.projectId) return false;
4763
4803
  if (params.domain && r.domain !== params.domain) return false;
4804
+ if (params.action && r.action !== params.action) return false;
4764
4805
  if (params.status && r.status !== params.status) return false;
4765
4806
  const t = r.createdAt.getTime();
4766
4807
  if (from !== void 0 && t < from) return false;
@@ -8592,6 +8633,63 @@ var InMemoryAgentRunStore = class {
8592
8633
  (left, right) => right.record.createdAt - left.record.createdAt || right.sequence - left.sequence
8593
8634
  ).slice(offset, offset + limit).map(({ record }) => cloneRun(record));
8594
8635
  }
8636
+ async listRunsByTenant(tenantId2, query = {}) {
8637
+ const limit = clampLimit(query.limit);
8638
+ const offset = Math.max(0, Math.floor(query.offset ?? 0));
8639
+ const createdAfter = query.createdAfter ? Date.parse(query.createdAfter) : void 0;
8640
+ const matches = [...this.runs.values()].filter(({ record }) => {
8641
+ if (record.tenantId !== tenantId2) return false;
8642
+ if (query.status && record.status !== query.status) return false;
8643
+ if (query.source && (record.source ?? "legacy") !== query.source) {
8644
+ return false;
8645
+ }
8646
+ if (query.assistantId && record.assistantId !== query.assistantId) {
8647
+ return false;
8648
+ }
8649
+ if (createdAfter !== void 0 && Number.isFinite(createdAfter) && record.createdAt < createdAfter) {
8650
+ return false;
8651
+ }
8652
+ return true;
8653
+ }).sort(
8654
+ (left, right) => right.record.createdAt - left.record.createdAt || right.sequence - left.sequence
8655
+ );
8656
+ return {
8657
+ records: matches.slice(offset, offset + limit).map(({ record }) => cloneRun(record)),
8658
+ total: matches.length
8659
+ };
8660
+ }
8661
+ async summaryByTenant(tenantId2, options = {}) {
8662
+ const now = this.now();
8663
+ const since = options.since ? Date.parse(options.since) : now - 24 * 60 * 60 * 1e3;
8664
+ const counts = emptyCounts();
8665
+ let oldestPending = null;
8666
+ let stuckRunning = 0;
8667
+ for (const { record } of this.runs.values()) {
8668
+ if (record.tenantId !== tenantId2) continue;
8669
+ if (record.status === "pending") {
8670
+ counts.pending += 1;
8671
+ if (oldestPending === null || record.createdAt < oldestPending) {
8672
+ oldestPending = record.createdAt;
8673
+ }
8674
+ continue;
8675
+ }
8676
+ if (record.status === "running") {
8677
+ counts.running += 1;
8678
+ if (record.leaseExpiresAt !== null && record.leaseExpiresAt < now) {
8679
+ stuckRunning += 1;
8680
+ }
8681
+ continue;
8682
+ }
8683
+ if (record.createdAt >= since) {
8684
+ counts[record.status] += 1;
8685
+ }
8686
+ }
8687
+ return {
8688
+ counts,
8689
+ oldestPendingAgeMs: oldestPending === null ? null : Math.max(0, now - oldestPending),
8690
+ stuckRunning
8691
+ };
8692
+ }
8595
8693
  /** Finds the thread's running run, if any. */
8596
8694
  async findRunning(tenantId2, threadId) {
8597
8695
  for (const entry of this.runs.values()) {
@@ -8860,6 +8958,17 @@ function clampLimit(limit) {
8860
8958
  if (!Number.isFinite(floored)) return DEFAULT_LIST_LIMIT;
8861
8959
  return Math.min(MAX_LIST_LIMIT, Math.max(1, floored));
8862
8960
  }
8961
+ function emptyCounts() {
8962
+ return {
8963
+ pending: 0,
8964
+ running: 0,
8965
+ success: 0,
8966
+ error: 0,
8967
+ interrupted: 0,
8968
+ cancelled: 0,
8969
+ timeout: 0
8970
+ };
8971
+ }
8863
8972
  function terminalTimestamp(record) {
8864
8973
  return record.finishedAt ?? record.updatedAt ?? record.createdAt;
8865
8974
  }
@@ -9015,11 +9124,62 @@ var InMemoryChannelReplyJobStore = class {
9015
9124
  }
9016
9125
  };
9017
9126
 
9127
+ // src/store_lattice/InMemorySessionStore.ts
9128
+ var InMemorySessionStore = class {
9129
+ constructor() {
9130
+ this.byId = /* @__PURE__ */ new Map();
9131
+ this.byHash = /* @__PURE__ */ new Map();
9132
+ }
9133
+ async create(record) {
9134
+ this.byId.set(record.id, { ...record });
9135
+ this.byHash.set(record.refreshTokenHash, record.id);
9136
+ }
9137
+ async findByRefreshTokenHash(hash) {
9138
+ const id = this.byHash.get(hash);
9139
+ return id ? { ...this.byId.get(id) } : null;
9140
+ }
9141
+ async findByFamilyId(familyId) {
9142
+ const rows = [...this.byId.values()].filter((row) => row.familyId === familyId);
9143
+ const active = rows.filter((row) => !row.replacedBy && !row.revokedAt);
9144
+ const pool = active.length > 0 ? active : rows;
9145
+ pool.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
9146
+ return pool[0] ? { ...pool[0] } : null;
9147
+ }
9148
+ async rotate(oldId, next) {
9149
+ const old = this.byId.get(oldId);
9150
+ if (!old) return;
9151
+ old.replacedBy = next.id;
9152
+ old.lastUsedAt = next.createdAt;
9153
+ this.byId.set(oldId, old);
9154
+ await this.create(next);
9155
+ }
9156
+ async revokeFamily(familyId, _reason) {
9157
+ const now = /* @__PURE__ */ new Date();
9158
+ for (const row of this.byId.values()) {
9159
+ if (row.familyId === familyId && !row.revokedAt) row.revokedAt = now;
9160
+ }
9161
+ }
9162
+ async revokeAllForUser(userId, _reason) {
9163
+ const now = /* @__PURE__ */ new Date();
9164
+ for (const row of this.byId.values()) {
9165
+ if (row.userId === userId && !row.revokedAt) row.revokedAt = now;
9166
+ }
9167
+ }
9168
+ async touch(id, lastUsedAt) {
9169
+ const row = this.byId.get(id);
9170
+ if (row) row.lastUsedAt = lastUsedAt;
9171
+ }
9172
+ async listForUser(userId) {
9173
+ return [...this.byId.values()].filter((row) => row.userId === userId).map((row) => ({ ...row }));
9174
+ }
9175
+ };
9176
+
9018
9177
  // src/store_lattice/configureStores.ts
9019
9178
  var _disposables = [];
9020
9179
  var _cleanupRegistered = false;
9021
9180
  var _inMemoryAgentRunWarningEmitted = false;
9022
9181
  var _inMemoryChannelReplyJobWarningEmitted = false;
9182
+ var _inMemorySessionWarningEmitted = false;
9023
9183
  function registerSignalCleanup() {
9024
9184
  if (_cleanupRegistered) return;
9025
9185
  _cleanupRegistered = true;
@@ -9079,6 +9239,20 @@ async function configureStores(stores, options = {}) {
9079
9239
  }
9080
9240
  storeLatticeManager.registerLattice("default", "channelReplyJob", channelReplyJob);
9081
9241
  }
9242
+ if (stores.session === void 0 && options.customStores?.session === void 0) {
9243
+ if (!_inMemorySessionWarningEmitted) {
9244
+ _inMemorySessionWarningEmitted = true;
9245
+ console.warn(
9246
+ "[configureStores] session is using InMemorySessionStore: sessions are non-durable and lost on restart. Configure a PostgreSQL session store for production."
9247
+ );
9248
+ }
9249
+ const session = new InMemorySessionStore();
9250
+ await initAndRegister(session, localDisposables);
9251
+ if (storeLatticeManager.hasLattice("default", "session")) {
9252
+ storeLatticeManager.removeLattice("default", "session");
9253
+ }
9254
+ storeLatticeManager.registerLattice("default", "session", session);
9255
+ }
9082
9256
  if (storeLatticeManager.hasLattice("default", "connection")) {
9083
9257
  const connectionStore = storeLatticeManager.getStoreLattice("default", "connection").store;
9084
9258
  ConnectionRegistry.setStore(connectionStore);
@@ -14546,6 +14720,7 @@ function getBindingRegistry() {
14546
14720
  }
14547
14721
 
14548
14722
  // src/tool_lattice/manage_binding/index.ts
14723
+ import { maskChannelInstallationSecrets } from "@axiom-lattice/protocols";
14549
14724
  function getInstallationStore() {
14550
14725
  return getStoreLattice("default", "channelInstallation").store;
14551
14726
  }
@@ -14582,6 +14757,8 @@ A sender can only be bound to ONE agent per channel+installation combination.`,
14582
14757
  const tenantId2 = getTenantId(config);
14583
14758
  if (!tenantId2) return failure("manage_binding requires tenant execution context");
14584
14759
  if (input.channel === "room") return failure("Internal room bindings cannot be managed");
14760
+ const personalAssistantId = await resolvePersonalAssistantId(tenantId2, config);
14761
+ const personalInstallationIds = personalAssistantId ? await listPersonalInstallationIds(registry4, tenantId2, personalAssistantId) : null;
14585
14762
  switch (input.action) {
14586
14763
  case "list_installations": {
14587
14764
  const store2 = getInstallationStore();
@@ -14589,27 +14766,42 @@ A sender can only be bound to ONE agent per channel+installation combination.`,
14589
14766
  tenantId2,
14590
14767
  input.channel
14591
14768
  );
14592
- return JSON.stringify({ success: true, data: installations.filter(isPublicInstallation) });
14769
+ return JSON.stringify({
14770
+ success: true,
14771
+ data: installations.filter(isPublicInstallation).filter((installation) => !personalInstallationIds || personalInstallationIds.has(installation.id)).map(maskChannelInstallationSecrets)
14772
+ });
14593
14773
  }
14594
14774
  case "create": {
14595
- if (!input.channel || !input.senderId || !input.agentId) {
14775
+ if (!input.channel || !input.senderId) {
14776
+ return JSON.stringify({ success: false, error: "create requires channel, senderId, and agentId" });
14777
+ }
14778
+ if (personalAssistantId && input.agentId && input.agentId !== personalAssistantId) {
14779
+ return failure("A personal assistant can only bind senders to itself");
14780
+ }
14781
+ const agentId = personalAssistantId ?? input.agentId;
14782
+ if (!agentId) {
14596
14783
  return JSON.stringify({ success: false, error: "create requires channel, senderId, and agentId" });
14597
14784
  }
14598
- const installId = input.channelInstallationId || await resolveInstallationId(input.channel, tenantId2);
14785
+ const installId = input.channelInstallationId || await resolveInstallationId(input.channel, tenantId2, personalInstallationIds);
14599
14786
  if (!installId) {
14600
14787
  return JSON.stringify({
14601
14788
  success: false,
14602
14789
  error: `No channelInstallationId provided and unable to auto-detect. Use action=list_installations to find available installations for channel "${input.channel}".`
14603
14790
  });
14604
14791
  }
14605
- const validation = await validatePublicInstallation(installId, tenantId2, input.channel);
14792
+ const validation = await validatePublicInstallation(
14793
+ installId,
14794
+ tenantId2,
14795
+ input.channel,
14796
+ personalInstallationIds
14797
+ );
14606
14798
  if (validation) return failure(validation);
14607
14799
  const binding = await registry4.create({
14608
14800
  channel: input.channel,
14609
14801
  channelInstallationId: installId,
14610
14802
  tenantId: tenantId2,
14611
14803
  senderId: input.senderId,
14612
- agentId: input.agentId,
14804
+ agentId,
14613
14805
  threadMode: input.threadMode,
14614
14806
  senderDisplayName: input.senderDisplayName
14615
14807
  });
@@ -14619,14 +14811,22 @@ A sender can only be bound to ONE agent per channel+installation combination.`,
14619
14811
  if (!input.channel || !input.senderId) {
14620
14812
  return JSON.stringify({ success: false, error: "update requires channel and senderId" });
14621
14813
  }
14622
- const installId = input.channelInstallationId || await resolveInstallationId(input.channel, tenantId2);
14814
+ if (personalAssistantId && input.agentId && input.agentId !== personalAssistantId) {
14815
+ return failure("A personal assistant can only bind senders to itself");
14816
+ }
14817
+ const installId = input.channelInstallationId || await resolveInstallationId(input.channel, tenantId2, personalInstallationIds);
14623
14818
  if (!installId) {
14624
14819
  return JSON.stringify({
14625
14820
  success: false,
14626
14821
  error: `No channelInstallationId provided and unable to auto-detect. Use action=list_installations first.`
14627
14822
  });
14628
14823
  }
14629
- const validation = await validatePublicInstallation(installId, tenantId2, input.channel);
14824
+ const validation = await validatePublicInstallation(
14825
+ installId,
14826
+ tenantId2,
14827
+ input.channel,
14828
+ personalInstallationIds
14829
+ );
14630
14830
  if (validation) return failure(validation);
14631
14831
  const existing = await registry4.findBySubject({
14632
14832
  channel: input.channel,
@@ -14640,8 +14840,11 @@ A sender can only be bound to ONE agent per channel+installation combination.`,
14640
14840
  if (existing.channel === "room") {
14641
14841
  return failure("Internal room bindings cannot be managed");
14642
14842
  }
14843
+ if (personalAssistantId && existing.agentId !== personalAssistantId) {
14844
+ return JSON.stringify({ success: false, error: "Binding not found" });
14845
+ }
14643
14846
  const updated = await registry4.update(tenantId2, existing.id, {
14644
- agentId: input.agentId,
14847
+ agentId: personalAssistantId ?? input.agentId,
14645
14848
  threadMode: input.threadMode,
14646
14849
  senderDisplayName: input.senderDisplayName
14647
14850
  });
@@ -14651,14 +14854,19 @@ A sender can only be bound to ONE agent per channel+installation combination.`,
14651
14854
  if (!input.channel || !input.senderId) {
14652
14855
  return JSON.stringify({ success: false, error: "delete requires channel and senderId" });
14653
14856
  }
14654
- const installId = input.channelInstallationId || await resolveInstallationId(input.channel, tenantId2);
14857
+ const installId = input.channelInstallationId || await resolveInstallationId(input.channel, tenantId2, personalInstallationIds);
14655
14858
  if (!installId) {
14656
14859
  return JSON.stringify({
14657
14860
  success: false,
14658
14861
  error: `No channelInstallationId provided and unable to auto-detect.`
14659
14862
  });
14660
14863
  }
14661
- const validation = await validatePublicInstallation(installId, tenantId2, input.channel);
14864
+ const validation = await validatePublicInstallation(
14865
+ installId,
14866
+ tenantId2,
14867
+ input.channel,
14868
+ personalInstallationIds
14869
+ );
14662
14870
  if (validation) return failure(validation);
14663
14871
  const existing = await registry4.findBySubject({
14664
14872
  channel: input.channel,
@@ -14672,17 +14880,25 @@ A sender can only be bound to ONE agent per channel+installation combination.`,
14672
14880
  if (existing.channel === "room") {
14673
14881
  return failure("Internal room bindings cannot be managed");
14674
14882
  }
14883
+ if (personalAssistantId && existing.agentId !== personalAssistantId) {
14884
+ return JSON.stringify({ success: false, error: "Binding not found" });
14885
+ }
14675
14886
  await registry4.delete(tenantId2, existing.id);
14676
14887
  return JSON.stringify({ success: true, message: "Binding deleted" });
14677
14888
  }
14678
14889
  case "list": {
14679
- const bindings = await registry4.list({
14890
+ if (personalAssistantId && input.agentId && input.agentId !== personalAssistantId) {
14891
+ return failure("A personal assistant can only list its own bindings");
14892
+ }
14893
+ const listed = await registry4.list({
14680
14894
  channel: input.channel,
14681
- agentId: input.agentId,
14895
+ agentId: personalAssistantId ?? input.agentId,
14682
14896
  tenantId: tenantId2,
14683
14897
  channelInstallationId: input.channelInstallationId,
14684
- excludeChannels: ["room"]
14898
+ excludeChannels: ["room"],
14899
+ ...personalAssistantId ? { limit: 500 } : {}
14685
14900
  });
14901
+ const bindings = personalInstallationIds ? listed.filter((binding) => personalInstallationIds.has(binding.channelInstallationId)) : listed;
14686
14902
  return JSON.stringify({ success: true, data: bindings });
14687
14903
  }
14688
14904
  default:
@@ -14690,33 +14906,83 @@ A sender can only be bound to ONE agent per channel+installation combination.`,
14690
14906
  }
14691
14907
  }
14692
14908
  );
14693
- async function resolveInstallationId(channel, tenantId2) {
14909
+ async function resolveInstallationId(channel, tenantId2, allowedIds) {
14694
14910
  const store2 = getInstallationStore();
14695
14911
  const installations = await store2.getInstallationsByTenant(tenantId2, channel);
14696
- const publicInstallations = installations.filter(isPublicInstallation);
14912
+ const publicInstallations = installations.filter(isPublicInstallation).filter((installation) => !allowedIds || allowedIds.has(installation.id));
14697
14913
  if (publicInstallations.length === 1) {
14698
14914
  return publicInstallations[0].id;
14699
14915
  }
14700
14916
  return null;
14701
14917
  }
14702
- function getTenantId(config) {
14918
+ function getRunConfig(config) {
14703
14919
  if (typeof config !== "object" || config === null) return null;
14704
14920
  const configurable = config.configurable;
14705
14921
  if (typeof configurable !== "object" || configurable === null) return null;
14706
14922
  const runConfig = configurable.runConfig;
14707
14923
  if (typeof runConfig !== "object" || runConfig === null) return null;
14708
- const tenantId2 = runConfig.tenantId;
14709
- return typeof tenantId2 === "string" && tenantId2 ? tenantId2 : null;
14924
+ return runConfig;
14925
+ }
14926
+ function getString(record, key6) {
14927
+ const value = record?.[key6];
14928
+ return typeof value === "string" && value.length > 0 ? value : null;
14929
+ }
14930
+ function getTenantId(config) {
14931
+ return getString(getRunConfig(config), "tenantId");
14932
+ }
14933
+ async function resolvePersonalAssistantId(tenantId2, config) {
14934
+ const runConfig = getRunConfig(config);
14935
+ const assistantId = getString(runConfig, "assistant_id") ?? getString(runConfig, "assistantId");
14936
+ if (!assistantId) return null;
14937
+ try {
14938
+ const assistant = await getStoreLattice("default", "assistant").store.getAssistantById(tenantId2, assistantId);
14939
+ return assistant?.ownerUserId ? assistantId : null;
14940
+ } catch {
14941
+ return null;
14942
+ }
14710
14943
  }
14711
14944
  function isPublicInstallation(installation) {
14712
14945
  return installation.channel !== "room";
14713
14946
  }
14714
- async function validatePublicInstallation(installationId, tenantId2, channel) {
14947
+ function installationReferencesAssistant(installation, assistantId) {
14948
+ if (installation.fallbackAgentId === assistantId) return true;
14949
+ const config = installation.config;
14950
+ return Boolean(
14951
+ config && typeof config === "object" && !Array.isArray(config) && config.assistantId === assistantId
14952
+ );
14953
+ }
14954
+ async function listPersonalInstallationIds(registry4, tenantId2, assistantId) {
14955
+ const ids = /* @__PURE__ */ new Set();
14956
+ const installations = await getInstallationStore().getInstallationsByTenant(tenantId2);
14957
+ for (const installation of installations) {
14958
+ if (isPublicInstallation(installation) && installationReferencesAssistant(installation, assistantId)) {
14959
+ ids.add(installation.id);
14960
+ }
14961
+ }
14962
+ for (let offset = 0; ; offset += 500) {
14963
+ const bindings = await registry4.list({
14964
+ tenantId: tenantId2,
14965
+ agentId: assistantId,
14966
+ excludeChannels: ["room"],
14967
+ limit: 500,
14968
+ offset
14969
+ });
14970
+ for (const binding of bindings) {
14971
+ if (binding.channelInstallationId) ids.add(binding.channelInstallationId);
14972
+ }
14973
+ if (bindings.length < 500) break;
14974
+ }
14975
+ return ids;
14976
+ }
14977
+ async function validatePublicInstallation(installationId, tenantId2, channel, allowedIds) {
14715
14978
  try {
14716
14979
  const installation = await getInstallationStore().getInstallationById(installationId);
14717
14980
  if (!installation || !isPublicInstallation(installation) || installation.tenantId !== tenantId2 || installation.channel !== channel) {
14718
14981
  return "Invalid public channel installation";
14719
14982
  }
14983
+ if (allowedIds && !allowedIds.has(installationId)) {
14984
+ return "Invalid public channel installation";
14985
+ }
14720
14986
  return null;
14721
14987
  } catch {
14722
14988
  return "Unable to validate public channel installation";
@@ -32751,7 +33017,7 @@ import { v4 as uuidv44 } from "uuid";
32751
33017
  import { ScheduledTaskStatus as ScheduledTaskStatus3, ScheduleExecutionType as ScheduleExecutionType3 } from "@axiom-lattice/protocols";
32752
33018
  var SCHEDULE_LATTICE_KEY = "default";
32753
33019
  var AGENT_ADD_MESSAGE_TASK_TYPE = "agent.add_message";
32754
- function getRunConfig(config) {
33020
+ function getRunConfig2(config) {
32755
33021
  const configurable = config;
32756
33022
  return configurable?.configurable?.runConfig ?? {};
32757
33023
  }
@@ -32832,7 +33098,7 @@ function createSchedulerMiddleware(options = {}) {
32832
33098
  tools: [
32833
33099
  tool43(
32834
33100
  async (input, config) => {
32835
- const runConfig = getRunConfig(config);
33101
+ const runConfig = getRunConfig2(config);
32836
33102
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
32837
33103
  const taskId = uuidv44();
32838
33104
  const executeAt = input.executeAt;
@@ -32867,7 +33133,7 @@ function createSchedulerMiddleware(options = {}) {
32867
33133
  ),
32868
33134
  tool43(
32869
33135
  async (input, config) => {
32870
- const runConfig = getRunConfig(config);
33136
+ const runConfig = getRunConfig2(config);
32871
33137
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
32872
33138
  const taskId = uuidv44();
32873
33139
  const executeAt = Date.now() + input.delayMs;
@@ -32902,7 +33168,7 @@ function createSchedulerMiddleware(options = {}) {
32902
33168
  ),
32903
33169
  tool43(
32904
33170
  async (input, config) => {
32905
- const runConfig = getRunConfig(config);
33171
+ const runConfig = getRunConfig2(config);
32906
33172
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
32907
33173
  const taskId = uuidv44();
32908
33174
  const success = await scheduleLattice.client.scheduleCron(
@@ -32960,7 +33226,7 @@ function createSchedulerMiddleware(options = {}) {
32960
33226
  ),
32961
33227
  tool43(
32962
33228
  async (input, config) => {
32963
- const runConfig = getRunConfig(config);
33229
+ const runConfig = getRunConfig2(config);
32964
33230
  const scheduleLattice = getScheduleLattice(SCHEDULE_LATTICE_KEY);
32965
33231
  const storage = scheduleLattice.client.getStorage();
32966
33232
  if (!storage) {
@@ -36238,7 +36504,9 @@ function getPersonalMcpMaxServers() {
36238
36504
  return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : PERSONAL_MCP_MAX_SERVERS;
36239
36505
  }
36240
36506
  function getPersonalMcpSyncBudgetMs() {
36241
- const raw = Number(process.env.PERSONAL_MCP_SYNC_BUDGET_MS);
36507
+ const value = process.env.PERSONAL_MCP_SYNC_BUDGET_MS;
36508
+ if (value === void 0 || value.trim() === "") return PERSONAL_MCP_SYNC_BUDGET_MS;
36509
+ const raw = Number(value);
36242
36510
  return Number.isFinite(raw) && raw >= 0 ? raw : PERSONAL_MCP_SYNC_BUDGET_MS;
36243
36511
  }
36244
36512
  var syncCache = /* @__PURE__ */ new Map();
@@ -36666,6 +36934,14 @@ function getTenantId2(exeConfig) {
36666
36934
  const runConfig = exeConfig?.configurable?.runConfig || {};
36667
36935
  return runConfig.tenantId || "default";
36668
36936
  }
36937
+ function getRuntimeUserId(exeConfig) {
36938
+ const runConfig = exeConfig?.configurable?.runConfig || {};
36939
+ const value = runConfig.user_id ?? runConfig.userId;
36940
+ return typeof value === "string" && value.length > 0 ? value : null;
36941
+ }
36942
+ function canAccessAssistant(assistant, userId) {
36943
+ return !assistant.ownerUserId || userId !== null && assistant.ownerUserId === userId;
36944
+ }
36669
36945
  function getAssistStore() {
36670
36946
  return getStoreLattice("default", "assistant").store;
36671
36947
  }
@@ -36758,17 +37034,21 @@ async function validateAgentReferences(input, tenantId2) {
36758
37034
  function slugify(name) {
36759
37035
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-+/g, "-") || "agent";
36760
37036
  }
37037
+ var MAX_AGENT_ID_ALLOCATION_ATTEMPTS = 1e3;
36761
37038
  async function generateAgentId(tenantId2, name) {
36762
37039
  const store2 = getAssistStore();
36763
37040
  const base = slugify(name);
36764
37041
  let id = base;
36765
37042
  let counter = 2;
36766
- while (true) {
37043
+ for (let attempt = 0; attempt < MAX_AGENT_ID_ALLOCATION_ATTEMPTS; attempt += 1) {
36767
37044
  const existing = await store2.getAssistantById(tenantId2, id);
36768
37045
  if (!existing) return id;
36769
37046
  id = `${base}-${counter}`;
36770
- counter++;
37047
+ counter += 1;
36771
37048
  }
37049
+ throw new Error(
37050
+ `Unable to allocate a unique agent id for "${name}" after ${MAX_AGENT_ID_ALLOCATION_ATTEMPTS} attempts`
37051
+ );
36772
37052
  }
36773
37053
  registerToolLattice(
36774
37054
  "list_agents",
@@ -36780,8 +37060,9 @@ registerToolLattice(
36780
37060
  async (_input, exeConfig) => {
36781
37061
  try {
36782
37062
  const tenantId2 = getTenantId2(exeConfig);
37063
+ const userId = getRuntimeUserId(exeConfig);
36783
37064
  const store2 = getAssistStore();
36784
- const agents = await store2.getAllAssistants(tenantId2);
37065
+ const agents = (await store2.getAllAssistants(tenantId2)).filter((agent) => canAccessAssistant(agent, userId));
36785
37066
  return JSON.stringify({
36786
37067
  agents: agents.map((a) => ({
36787
37068
  id: a.id,
@@ -36811,7 +37092,7 @@ registerToolLattice(
36811
37092
  const tenantId2 = getTenantId2(exeConfig);
36812
37093
  const store2 = getAssistStore();
36813
37094
  const agent = await store2.getAssistantById(tenantId2, input.id);
36814
- if (!agent) {
37095
+ if (!agent || !canAccessAssistant(agent, getRuntimeUserId(exeConfig))) {
36815
37096
  return JSON.stringify({ error: `Agent '${input.id}' not found` });
36816
37097
  }
36817
37098
  return JSON.stringify(agent.graphDefinition);
@@ -37187,7 +37468,7 @@ registerToolLattice(
37187
37468
  const tenantId2 = getTenantId2(exeConfig);
37188
37469
  const store2 = getAssistStore();
37189
37470
  const existing = await store2.getAssistantById(tenantId2, input.id);
37190
- if (!existing) {
37471
+ if (!existing || !canAccessAssistant(existing, getRuntimeUserId(exeConfig))) {
37191
37472
  return JSON.stringify({ error: `Agent '${input.id}' not found` });
37192
37473
  }
37193
37474
  const existingConfig = existing.graphDefinition || {};
@@ -37301,9 +37582,16 @@ registerToolLattice(
37301
37582
  const tenantId2 = getTenantId2(exeConfig);
37302
37583
  const store2 = getAssistStore();
37303
37584
  const existing = await store2.getAssistantById(tenantId2, input.id);
37304
- if (!existing) {
37585
+ if (!existing || !canAccessAssistant(existing, getRuntimeUserId(exeConfig))) {
37305
37586
  return JSON.stringify({ error: `Agent '${input.id}' not found`, success: false });
37306
37587
  }
37588
+ if (existing.ownerUserId) {
37589
+ return JSON.stringify({
37590
+ success: false,
37591
+ code: "PERSONAL_ASSISTANT_DELETE_UNSUPPORTED",
37592
+ error: "Personal assistants must be deleted from the Personal Assistant page"
37593
+ });
37594
+ }
37307
37595
  const success = await store2.deleteAssistant(tenantId2, input.id);
37308
37596
  if (success) {
37309
37597
  try {
@@ -39747,10 +40035,23 @@ var MicrosandboxRemoteInstance = class {
39747
40035
  );
39748
40036
  },
39749
40037
  downloadFile: async (params) => {
39750
- const result = await this.client.downloadFile(
39751
- this.name,
39752
- normalizeExternalSandboxPath(params.file)
39753
- );
40038
+ const normalized = normalizeExternalSandboxPath(params.file);
40039
+ const rawClient = this.client;
40040
+ if (typeof rawClient.downloadFileRaw === "function") {
40041
+ try {
40042
+ return await rawClient.downloadFileRaw(this.name, normalized);
40043
+ } catch (err) {
40044
+ const statusCode = err.statusCode;
40045
+ const code = err.code;
40046
+ if (statusCode !== 404 && statusCode !== 405) {
40047
+ throw err;
40048
+ }
40049
+ if (code) {
40050
+ throw err;
40051
+ }
40052
+ }
40053
+ }
40054
+ const result = await this.client.downloadFile(this.name, normalized);
39754
40055
  if (result.contentBase64) {
39755
40056
  return Buffer.from(result.contentBase64, "base64");
39756
40057
  }
@@ -39942,6 +40243,45 @@ var MicrosandboxServiceClient = class {
39942
40243
  method: "GET"
39943
40244
  });
39944
40245
  }
40246
+ /**
40247
+ * Download file bytes using the binary route.
40248
+ *
40249
+ * Avoids the base64/JSON envelope (2-3x memory amplification). Callers should
40250
+ * fall back to {@link downloadFile} when this route is unavailable (older
40251
+ * gateway).
40252
+ */
40253
+ async downloadFileRaw(sandboxName, path8) {
40254
+ const query = new URLSearchParams({ sandboxName, path: path8 });
40255
+ const headers = {};
40256
+ if (this.apiKey) {
40257
+ headers.Authorization = `Bearer ${this.apiKey}`;
40258
+ }
40259
+ const response = await fetch(`${this.baseURL}/api/files/download/raw?${query.toString()}`, {
40260
+ headers
40261
+ });
40262
+ if (!response.ok) {
40263
+ let detail = `${response.status} ${response.statusText}`;
40264
+ let code;
40265
+ try {
40266
+ const errorBody = await response.json();
40267
+ const responseError = errorBody.error;
40268
+ if (typeof responseError === "object" && responseError) {
40269
+ detail = responseError.message ?? detail;
40270
+ code = responseError.code;
40271
+ } else if (responseError) {
40272
+ detail = responseError;
40273
+ }
40274
+ } catch {
40275
+ }
40276
+ const error = new Error(`Microsandbox service request failed: ${detail}`);
40277
+ error.statusCode = response.status;
40278
+ if (code) {
40279
+ error.code = code;
40280
+ }
40281
+ throw error;
40282
+ }
40283
+ return Buffer.from(await response.arrayBuffer());
40284
+ }
39945
40285
  async execCommand(input) {
39946
40286
  return this.request("/api/shell/exec", {
39947
40287
  method: "POST",
@@ -40160,6 +40500,14 @@ var MicrosandboxRemoteProvider = class {
40160
40500
  image,
40161
40501
  cpus: this.config.cpus ?? defaultMicrosandboxRemoteConfig.cpus,
40162
40502
  memoryMib: this.config.memoryMib ?? defaultMicrosandboxRemoteConfig.memoryMib,
40503
+ requests: config.requests,
40504
+ snapshotId: config.snapshotId,
40505
+ secureAccess: config.secureAccess,
40506
+ networkPolicy: config.networkPolicy,
40507
+ credentialProxy: config.credentialProxy,
40508
+ extensions: config.extensions,
40509
+ platform: config.platform,
40510
+ metadata: config.metadata,
40163
40511
  env: {
40164
40512
  ...this.config.env,
40165
40513
  ...buildSandboxMetadataEnv(config)
@@ -50629,7 +50977,7 @@ async function postProcessTaskMutationResponse(input) {
50629
50977
  }
50630
50978
 
50631
50979
  // src/middlewares/taskMiddleware.ts
50632
- function getRunConfig2(config) {
50980
+ function getRunConfig3(config) {
50633
50981
  const c = config;
50634
50982
  return c?.configurable?.runConfig ?? {};
50635
50983
  }
@@ -51355,7 +51703,7 @@ function updateValuesEqual(field, requested, persisted) {
51355
51703
  }
51356
51704
  function createTaskMiddleware(options = {}) {
51357
51705
  const handleManageTaskAction = async (input, config, validateExecutionResult, markMutation) => {
51358
- const rc = getRunConfig2(config);
51706
+ const rc = getRunConfig3(config);
51359
51707
  const authority = classifyTaskAuthority(rc);
51360
51708
  if (authority.kind === "invalid") return trustedContextError();
51361
51709
  const delegatedTaskId = authority.kind === "delegated" ? authority.taskId : void 0;
@@ -52483,7 +52831,7 @@ function createTaskMiddleware(options = {}) {
52483
52831
  };
52484
52832
  const reconcileExplicitExecutionResult = async (input, config, response, validationError, didMutate) => {
52485
52833
  if (input.action !== "update" && input.action !== "set_status" && input.action !== "add_activity" || !input.id) return response;
52486
- const authority = classifyTaskAuthority(getRunConfig2(config));
52834
+ const authority = classifyTaskAuthority(getRunConfig3(config));
52487
52835
  if (authority.kind === "projectRoom" || authority.kind === "projectTask" || authority.kind === "invalid") {
52488
52836
  return response;
52489
52837
  }
@@ -52496,7 +52844,7 @@ function createTaskMiddleware(options = {}) {
52496
52844
  mutationCommitted: didMutate,
52497
52845
  validationError,
52498
52846
  reconcile: async (parsed) => {
52499
- const rc = getRunConfig2(config);
52847
+ const rc = getRunConfig3(config);
52500
52848
  const tenantId2 = rc.tenantId || "default";
52501
52849
  const workItemStore = getTaskWorkItemStore();
52502
52850
  const task = await getTaskStore().getById(tenantId2, taskId);
@@ -52525,11 +52873,11 @@ function createTaskMiddleware(options = {}) {
52525
52873
  let didMutate = false;
52526
52874
  const validateExecutionResult = async () => {
52527
52875
  if (!input.executionResultId || validationAttempted) return;
52528
- const authority = classifyTaskAuthority(getRunConfig2(config));
52876
+ const authority = classifyTaskAuthority(getRunConfig3(config));
52529
52877
  if (authority.kind === "projectRoom" || authority.kind === "projectTask" || authority.kind === "invalid") return;
52530
52878
  validationAttempted = true;
52531
52879
  try {
52532
- const rc = getRunConfig2(config);
52880
+ const rc = getRunConfig3(config);
52533
52881
  const tenantId2 = rc.tenantId || "default";
52534
52882
  const workItemStore = getTaskWorkItemStore();
52535
52883
  const executionResult = await workItemStore.findByEventKey(
@@ -52579,7 +52927,7 @@ function createTaskMiddleware(options = {}) {
52579
52927
  );
52580
52928
  };
52581
52929
  const handleStartTask = async (input, config) => {
52582
- const rc = getRunConfig2(config);
52930
+ const rc = getRunConfig3(config);
52583
52931
  const authority = classifyTaskAuthority(rc);
52584
52932
  if (authority.kind === "invalid") return trustedContextError();
52585
52933
  if (authority.kind === "delegated") {
@@ -58390,6 +58738,9 @@ var DEFAULT_CONFIG = {
58390
58738
  type: "skill",
58391
58739
  name: "Skills",
58392
58740
  description: "Skill system for specialized instructions and workflows",
58741
+ // Temporary default until skills have a per-PA resource/collection model:
58742
+ // keep dynamic discovery by reading all. Do NOT set `skills: []` here —
58743
+ // load_skills treats an explicit empty list as "no static access".
58393
58744
  enabled: true,
58394
58745
  config: {
58395
58746
  readAll: true
@@ -58434,17 +58785,12 @@ var DEFAULT_CONFIG = {
58434
58785
  description: "Persistent task system for human-agent coordination",
58435
58786
  enabled: true,
58436
58787
  config: {}
58437
- },
58438
- {
58439
- id: "document-parser",
58440
- type: "document-parser",
58441
- name: "Document Parser",
58442
- description: "Parse docx/pdf files into markdown via document service",
58443
- enabled: true,
58444
- config: { connectAll: true }
58445
58788
  }
58446
58789
  ],
58447
- tools: ["list_agents", "list_tools", "get_agent", "create_agent", "invoke_agent", "manage_binding"]
58790
+ // The PA is a user-facing assistant, not a tenant agent builder. It may
58791
+ // discover available agents and dispatch work via `task`, but must not read,
58792
+ // create, or invoke agents directly.
58793
+ tools: ["list_agents", "manage_binding"]
58448
58794
  };
58449
58795
  var PersonalAssistantConfig = class {
58450
58796
  /**
@@ -58840,6 +59186,7 @@ export {
58840
59186
  InMemoryProjectRoomReadStateStore,
58841
59187
  InMemoryProjectRoomStore,
58842
59188
  InMemoryProjectStore,
59189
+ InMemorySessionStore,
58843
59190
  InMemorySharedResourceStore,
58844
59191
  InMemoryStore,
58845
59192
  InMemoryTaskStore,