@anuma/sdk 6.30.2 → 6.31.1

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.
@@ -2209,6 +2209,21 @@ type ToolConfig = LlmapiChatCompletionTool & {
2209
2209
  * execution fails, allowing the model to retry.
2210
2210
  */
2211
2211
  removeAfterExecution?: boolean;
2212
+ /**
2213
+ * Remove this tool for the rest of the turn once ANY tool returns a
2214
+ * successful result this predicate accepts — its own or another's. Errors
2215
+ * never count, as for `removeAfterExecution`.
2216
+ *
2217
+ * Only results of tools executed on this client are offered; tools the
2218
+ * portal runs server-side never reach the predicate. A predicate that throws
2219
+ * is treated as not matching.
2220
+ *
2221
+ * For a family of tools that has to leave together: when one of them
2222
+ * declines an out-of-scope request, the model otherwise works through its
2223
+ * siblings round after round until the round cap. Give every member the same
2224
+ * predicate and the first refusal removes the whole family.
2225
+ */
2226
+ removeAfterResult?: (result: unknown) => boolean;
2212
2227
  /**
2213
2228
  * Timeout in milliseconds for this tool's executor.
2214
2229
  * Overrides the default 30-second timeout.
@@ -3512,6 +3527,7 @@ type MessageFeedback = "like" | "dislike" | null;
3512
3527
  * - `tool_result`: the hidden `[Tool Execution Results]` row built from a
3513
3528
  * turn's auto-executed tool results. Skipped by the embedding sweep (see
3514
3529
  * `memoryEngine/embeddings`) AND hidden from the transcript.
3530
+ * - `message`: an ordinary message with an index after explicit repair.
3515
3531
  * - `chunks_discarded`: an ordinary, still-rendered message whose chunk vectors
3516
3532
  * were built over `enc:v3:` ciphertext (sdk#864) and have been discarded
3517
3533
  * rather than re-embedded at the user's own expense (client#5618). Skipped by
@@ -3524,7 +3540,7 @@ type MessageFeedback = "like" | "dislike" | null;
3524
3540
  * encrypted flag would be unreadable exactly where it matters and the skip
3525
3541
  * would fail open.
3526
3542
  */
3527
- type MessageOrigin = "tool_result" | "chunks_discarded";
3543
+ type MessageOrigin = "tool_result" | "chunks_discarded" | "message";
3528
3544
  /**
3529
3545
  * Metadata for files attached to messages.
3530
3546
  *
@@ -7299,7 +7315,8 @@ declare function stampTopicsExtractedAtOp(ctx: VaultMemoryOperationsContext, mem
7299
7315
  * `topics_user_managed` in particular is left exactly as it arrived, so the
7300
7316
  * autotagger stays off a curated memory whose links this just restored.
7301
7317
  *
7302
- * Skips deleted, foreign-user, and record-less rows. Returns the ids relinked.
7318
+ * Skips deleted rows, foreign-user rows, and rows with null topics.
7319
+ * Empty topics remove stale links. Returns the relinked IDs.
7303
7320
  */
7304
7321
  declare function relinkMemoryTopicsOp(ctx: VaultMemoryOperationsContext, memoryIds: readonly string[]): Promise<string[]>;
7305
7322
  /**
@@ -9756,14 +9773,10 @@ declare function generateEmbeddings(texts: string[], options: EmbeddingOptions):
9756
9773
  * re-index. Off by default, so no background pass can spend a user's credits
9757
9774
  * without being asked to.
9758
9775
  *
9759
- * That flag opens the gate for one call and nothing more. It does not heal the
9760
- * row: a message that re-indexes successfully still carries `chunks_discarded`
9761
- * afterwards, so the next pass skips it again unless that pass sets the flag
9762
- * too. An embedding-model migration is where this bites. It reaches this gate
9763
- * before it can do anything, so the repaired rows stay on the old model, and
9764
- * `searchChunksOp` already drops stale-model vectors — they go quiet with
9765
- * nothing telling them apart from rows that were never repaired. Clearing the
9766
- * marker on a successful re-index is the real fix, tracked in #879.
9776
+ * A successful repair replaces the marker with `message` in the index write.
9777
+ * The new marker preserves ordinary message provenance during chat replay.
9778
+ * Later model migrations can then include the repaired row without this flag.
9779
+ * Failed embedding requests and empty index data do not clear the marker.
9767
9780
  *
9768
9781
  * `satisfies MessageOrigin` so the constant and the union cannot drift apart
9769
9782
  * silently — the column's type is the union, and a typo here would otherwise
@@ -9800,9 +9813,8 @@ declare function embedAllMessages(ctx: StorageOperationsContext, options: Embedd
9800
9813
  * to an explicit user action, never to a background pass. Opens that marker
9801
9814
  * only — `tool_result` rows stay excluded.
9802
9815
  *
9803
- * Per call, not a state change: a row that re-indexes successfully keeps its
9804
- * marker, so a later pass that omits this flag skips it again. See
9805
- * {@link CHUNKS_DISCARDED_ORIGIN}.
9816
+ * A successful repair clears the marker. Later model migrations include
9817
+ * the repaired row without this flag. See {@link CHUNKS_DISCARDED_ORIGIN}.
9806
9818
  */
9807
9819
  reembedDiscarded?: boolean;
9808
9820
  }): Promise<number>;
@@ -9860,9 +9872,8 @@ declare function chunkAndEmbedAllMessages(ctx: StorageOperationsContext, options
9860
9872
  * chunks nor vector, so it never reaches that check and falls straight to the
9861
9873
  * origin gate.
9862
9874
  *
9863
- * Per call, not a state change: a row that re-indexes successfully keeps its
9864
- * marker, so a later pass that omits this flag skips it again. See
9865
- * {@link CHUNKS_DISCARDED_ORIGIN}.
9875
+ * A successful repair clears the marker. Later model migrations include
9876
+ * the repaired row without this flag. See {@link CHUNKS_DISCARDED_ORIGIN}.
9866
9877
  */
9867
9878
  reembedDiscarded?: boolean;
9868
9879
  }): Promise<number>;
@@ -19,7 +19,7 @@ import {
19
19
  taskTypeHeader,
20
20
  validateEndpointOverride,
21
21
  withInternalFlowMarker
22
- } from "./chunk-VD5M6QAI.mjs";
22
+ } from "./chunk-XD6WOQ5I.mjs";
23
23
  import {
24
24
  BASE_URL,
25
25
  MCP_R2_DOMAIN,
@@ -2120,6 +2120,9 @@ async function updateMessageEmbeddingOp(ctx, uniqueId, vector, embeddingModel) {
2120
2120
  await ctx.database.write(async () => {
2121
2121
  await message.update((msg) => {
2122
2122
  msg._setRaw("vector", JSON.stringify(vector));
2123
+ if (msg.origin === "chunks_discarded" && vector.length > 0) {
2124
+ msg._setRaw("origin", "message");
2125
+ }
2123
2126
  msg._setRaw("embedding_model", embeddingModel);
2124
2127
  });
2125
2128
  });
@@ -2136,6 +2139,9 @@ async function updateMessageChunksOp(ctx, uniqueId, chunks, embeddingModel) {
2136
2139
  await ctx.database.write(async () => {
2137
2140
  await message.update((msg) => {
2138
2141
  msg._setRaw("chunks", JSON.stringify(storedChunks));
2142
+ if (msg.origin === "chunks_discarded" && storedChunks.length > 0 && storedChunks.every((chunk) => chunk.vector.length > 0)) {
2143
+ msg._setRaw("origin", "message");
2144
+ }
2139
2145
  msg._setRaw("embedding_model", embeddingModel);
2140
2146
  });
2141
2147
  });
@@ -4345,6 +4351,9 @@ function clientToolToResponsesFormat(tool) {
4345
4351
  ...toolConfig.removeAfterExecution !== void 0 && {
4346
4352
  removeAfterExecution: toolConfig.removeAfterExecution
4347
4353
  },
4354
+ ...toolConfig.removeAfterResult !== void 0 && {
4355
+ removeAfterResult: toolConfig.removeAfterResult
4356
+ },
4348
4357
  ...toolConfig.executorTimeout !== void 0 && {
4349
4358
  executorTimeout: toolConfig.executorTimeout
4350
4359
  },
@@ -4378,6 +4387,9 @@ function clientToolToCompletionsFormat(tool) {
4378
4387
  ...toolConfig.removeAfterExecution !== void 0 && {
4379
4388
  removeAfterExecution: toolConfig.removeAfterExecution
4380
4389
  },
4390
+ ...toolConfig.removeAfterResult !== void 0 && {
4391
+ removeAfterResult: toolConfig.removeAfterResult
4392
+ },
4381
4393
  ...toolConfig.executorTimeout !== void 0 && {
4382
4394
  executorTimeout: toolConfig.executorTimeout
4383
4395
  },
@@ -5308,6 +5320,7 @@ function toolsToApiFormat(tools, apiType) {
5308
5320
  executor: _executor,
5309
5321
  skipContinuation: _skipContinuation,
5310
5322
  removeAfterExecution: _removeAfterExecution,
5323
+ removeAfterResult: _removeAfterResult,
5311
5324
  executorTimeout: _executorTimeout,
5312
5325
  dependsOn: _dependsOn,
5313
5326
  deAnonymizeArgs: _deAnonymizeArgs,
@@ -7752,9 +7765,11 @@ Executing tool: ${toolInfo}
7752
7765
  }
7753
7766
  if (tools && apiTools) {
7754
7767
  const successfullyExecutedNames = /* @__PURE__ */ new Set();
7768
+ const successfulResults = [];
7755
7769
  for (const r of executionResults) {
7756
7770
  if (!r.error && !isToolErrorResult(r.result) && "name" in r && r.name) {
7757
7771
  successfullyExecutedNames.add(r.name);
7772
+ successfulResults.push(r.result);
7758
7773
  }
7759
7774
  }
7760
7775
  if (successfullyExecutedNames.size > 0) {
@@ -7763,7 +7778,15 @@ Executing tool: ${toolInfo}
7763
7778
  const tc = t;
7764
7779
  const func = tc.function;
7765
7780
  const toolName = typeof func?.name === "string" ? func.name : typeof tc.name === "string" ? tc.name : void 0;
7766
- if (tc.removeAfterExecution === true && toolName && successfullyExecutedNames.has(toolName)) {
7781
+ if (!toolName) continue;
7782
+ const removeAfterResult = tc.removeAfterResult;
7783
+ if (tc.removeAfterExecution === true && successfullyExecutedNames.has(toolName) || typeof removeAfterResult === "function" && successfulResults.some((result) => {
7784
+ try {
7785
+ return removeAfterResult(result);
7786
+ } catch {
7787
+ return false;
7788
+ }
7789
+ })) {
7767
7790
  toolsToRemove.add(toolName);
7768
7791
  }
7769
7792
  }
@@ -11589,7 +11612,7 @@ async function getMemoriesNeedingTopicExtractionOp(ctx, options) {
11589
11612
  const id = raw.id;
11590
11613
  const topics = parseTopics(raw.topics);
11591
11614
  const linked = linkedNames.get(id);
11592
- if (topics !== null && topics.length > 0 && linksDivergeFromTopics(topics, linked ?? /* @__PURE__ */ new Set())) {
11615
+ if (topics !== null && linksDivergeFromTopics(topics, linked ?? /* @__PURE__ */ new Set())) {
11593
11616
  topicsToRelinkAll.push(id);
11594
11617
  continue;
11595
11618
  }
@@ -11683,18 +11706,20 @@ async function relinkMemoryTopicsOp(ctx, memoryIds) {
11683
11706
  }
11684
11707
  const relinked = [];
11685
11708
  for (const id of Array.from(new Set(memoryIds))) {
11686
- let record;
11687
11709
  try {
11688
- record = await ctx.vaultMemoryCollection.find(id);
11689
- } catch {
11690
- continue;
11691
- }
11692
- if (record.isDeleted || !isOwnedByCtxUser(ctx, record)) continue;
11693
- const topics = parseTopics(record.topics);
11694
- if (topics === null || topics.length === 0) continue;
11695
- try {
11696
- await relinkMemoryEntitiesFromTopicsOp(entityCtx, id, topics);
11697
- relinked.push(id);
11710
+ await ctx.database.write(async (writer) => {
11711
+ let record;
11712
+ try {
11713
+ record = await ctx.vaultMemoryCollection.find(id);
11714
+ } catch {
11715
+ return;
11716
+ }
11717
+ if (record.isDeleted || !isOwnedByCtxUser(ctx, record)) return;
11718
+ const topics = parseTopics(record.topics);
11719
+ if (topics === null) return;
11720
+ await writer.callWriter(() => relinkMemoryEntitiesFromTopicsOp(entityCtx, id, topics));
11721
+ relinked.push(id);
11722
+ });
11698
11723
  } catch (err) {
11699
11724
  getLogger().warn("[memory/topics] relink failed", err);
11700
11725
  }
@@ -14952,7 +14977,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
14952
14977
  content: m.content,
14953
14978
  similarity: m.similarity
14954
14979
  }));
14955
- const { consolidateMemory: doConsolidate } = await import("./consolidate-6J5HHAJY.mjs");
14980
+ const { consolidateMemory: doConsolidate } = await import("./consolidate-7DBUHQRK.mjs");
14956
14981
  const decision = await doConsolidate(trimmed, candidates, consolidateOptions);
14957
14982
  if (decision.action === "create") return decision.fallbackReason ? null : { create: true };
14958
14983
  if (decision.action === "supersede" && decision.content) {
@@ -19697,14 +19722,14 @@ async function autoFilterClientTools(clientTools, promptEmbeddings, cache, embed
19697
19722
  const alwaysInclude = clientTools.filter(isAlwaysIncluded);
19698
19723
  const filterCandidates = clientTools.filter((t) => !isAlwaysIncluded(t));
19699
19724
  if (filterCandidates.length === 0) {
19700
- return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
19725
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set(), matchedSetNames: /* @__PURE__ */ new Set() };
19701
19726
  }
19702
19727
  if (!promptEmbeddings && noEmbeddingsReason === "error") {
19703
- return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
19728
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set(), matchedSetNames: /* @__PURE__ */ new Set() };
19704
19729
  }
19705
19730
  if (!promptEmbeddings) {
19706
19731
  if (activeToolSets.length === 0) {
19707
- return { tools: [], activatedSetNames: /* @__PURE__ */ new Set() };
19732
+ return { tools: [], activatedSetNames: /* @__PURE__ */ new Set(), matchedSetNames: /* @__PURE__ */ new Set() };
19708
19733
  }
19709
19734
  const allSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
19710
19735
  const activeSets = allSets.filter((s) => activeToolSets.includes(s.name));
@@ -19714,7 +19739,8 @@ async function autoFilterClientTools(clientTools, promptEmbeddings, cache, embed
19714
19739
  ...alwaysInclude,
19715
19740
  ...filterCandidates.filter((t) => stickyMembers.has(getToolName2(t)))
19716
19741
  ],
19717
- activatedSetNames: new Set(activeSets.map((s) => s.name))
19742
+ activatedSetNames: new Set(activeSets.map((s) => s.name)),
19743
+ matchedSetNames: /* @__PURE__ */ new Set()
19718
19744
  };
19719
19745
  }
19720
19746
  const toolsNeedingEmbeddings = [];
@@ -19732,7 +19758,7 @@ async function autoFilterClientTools(clientTools, promptEmbeddings, cache, embed
19732
19758
  cache.set(toolsNeedingEmbeddings[i].name, embeddings[i]);
19733
19759
  }
19734
19760
  } catch {
19735
- return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
19761
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set(), matchedSetNames: /* @__PURE__ */ new Set() };
19736
19762
  }
19737
19763
  }
19738
19764
  const pseudoServerTools = [];
@@ -19778,16 +19804,171 @@ async function autoFilterClientTools(clientTools, promptEmbeddings, cache, embed
19778
19804
  activeSetNames
19779
19805
  );
19780
19806
  const activatedSetNames = activatedToolSetNames(scores, toolSets, activeSetNames);
19807
+ const matchedSetNames = activatedToolSetNames(scores, toolSets);
19781
19808
  if (finalNames.size === 0) {
19782
- return { tools: alwaysInclude, activatedSetNames };
19809
+ return { tools: alwaysInclude, activatedSetNames, matchedSetNames };
19783
19810
  }
19784
19811
  const filtered = filterCandidates.filter((t) => {
19785
19812
  const name = getToolName2(t);
19786
19813
  return name && finalNames.has(name);
19787
19814
  });
19788
- return { tools: [...alwaysInclude, ...filtered], activatedSetNames };
19815
+ return { tools: [...alwaysInclude, ...filtered], activatedSetNames, matchedSetNames };
19816
+ }
19817
+
19818
+ // src/lib/tools/toolCatalog.ts
19819
+ var TOOL_CATALOG = {
19820
+ // Gmail (src/tools/gmail.ts)
19821
+ gmail_search_messages: { label: "Search emails", provider: "gmail", connector: "Gmail" },
19822
+ gmail_get_message: { label: "Read an email", provider: "gmail", connector: "Gmail" },
19823
+ gmail_create_draft: { label: "Draft a reply", provider: "gmail", connector: "Gmail" },
19824
+ gmail_send_message: { label: "Send an email", provider: "gmail", connector: "Gmail" },
19825
+ // Google Calendar (src/tools/googleCalendar.ts)
19826
+ google_calendar_list_events: {
19827
+ label: "Search calendar events",
19828
+ provider: "gcalendar",
19829
+ connector: "Calendar"
19830
+ },
19831
+ google_calendar_create_event: {
19832
+ label: "Create calendar event",
19833
+ provider: "gcalendar",
19834
+ connector: "Calendar"
19835
+ },
19836
+ google_calendar_update_event: {
19837
+ label: "Update calendar event",
19838
+ provider: "gcalendar",
19839
+ connector: "Calendar"
19840
+ },
19841
+ // Google Drive (src/tools/googleDrive.ts)
19842
+ google_drive_search: { label: "Search files", provider: "gdrive", connector: "Drive" },
19843
+ google_drive_list_recent: { label: "List recent files", provider: "gdrive", connector: "Drive" },
19844
+ google_drive_get_content: { label: "Read file content", provider: "gdrive", connector: "Drive" },
19845
+ google_drive_create_file: {
19846
+ label: "Create a file in Drive",
19847
+ provider: "gdrive",
19848
+ connector: "Drive"
19849
+ },
19850
+ google_drive_update_file: {
19851
+ label: "Update a Drive file",
19852
+ provider: "gdrive",
19853
+ connector: "Drive"
19854
+ },
19855
+ // Notion (src/tools/notion.ts)
19856
+ "notion-search": { label: "Search", provider: "notion", connector: "Notion" },
19857
+ "notion-fetch": { label: "Read page", provider: "notion", connector: "Notion" },
19858
+ "notion-create-pages": { label: "Create page", provider: "notion", connector: "Notion" },
19859
+ "notion-update-page": { label: "Update page", provider: "notion", connector: "Notion" },
19860
+ "notion-move-pages": { label: "Move pages", provider: "notion", connector: "Notion" },
19861
+ "notion-duplicate-page": { label: "Duplicate page", provider: "notion", connector: "Notion" },
19862
+ "notion-create-database": { label: "Create database", provider: "notion", connector: "Notion" },
19863
+ "notion-update-data-source": {
19864
+ label: "Update data source",
19865
+ provider: "notion",
19866
+ connector: "Notion"
19867
+ },
19868
+ "notion-create-comment": { label: "Add a comment", provider: "notion", connector: "Notion" },
19869
+ "notion-get-comments": { label: "Read comments", provider: "notion", connector: "Notion" },
19870
+ "notion-get-users": {
19871
+ label: "List workspace members",
19872
+ provider: "notion",
19873
+ connector: "Notion"
19874
+ },
19875
+ "notion-get-teams": { label: "List teamspaces", provider: "notion", connector: "Notion" },
19876
+ // GitHub (src/tools/github.ts)
19877
+ github_api: { label: "Use GitHub", provider: "github", connector: "GitHub" },
19878
+ github_get_authenticated_user: {
19879
+ label: "Read GitHub profile",
19880
+ provider: "github",
19881
+ connector: "GitHub"
19882
+ },
19883
+ // X / Twitter (src/tools/x.ts)
19884
+ x_get_me: { label: "Get my X profile", provider: "x", connector: "X" },
19885
+ x_get_my_posts: { label: "Read my recent posts", provider: "x", connector: "X" },
19886
+ // Dropbox (src/tools/dropbox.ts)
19887
+ dropbox_list_folders: { label: "List files", provider: "dropbox", connector: "Dropbox" },
19888
+ dropbox_get_file_content: {
19889
+ label: "Read file content",
19890
+ provider: "dropbox",
19891
+ connector: "Dropbox"
19892
+ },
19893
+ dropbox_search: { label: "Search files", provider: "dropbox", connector: "Dropbox" },
19894
+ // Slack (src/tools/slack.ts)
19895
+ slack_get_me: { label: "Get my Slack profile", provider: "slack", connector: "Slack" },
19896
+ slack_list_channels: { label: "List channels", provider: "slack", connector: "Slack" },
19897
+ slack_list_dms: { label: "List direct messages", provider: "slack", connector: "Slack" },
19898
+ slack_search_messages: { label: "Search messages", provider: "slack", connector: "Slack" },
19899
+ slack_list_users: { label: "List members", provider: "slack", connector: "Slack" },
19900
+ slack_get_channel_history: {
19901
+ label: "Read channel history",
19902
+ provider: "slack",
19903
+ connector: "Slack"
19904
+ },
19905
+ slack_get_thread_replies: {
19906
+ label: "Read thread replies",
19907
+ provider: "slack",
19908
+ connector: "Slack"
19909
+ },
19910
+ slack_post_message: { label: "Post a message", provider: "slack", connector: "Slack" }
19911
+ };
19912
+
19913
+ // src/lib/tools/selection/activeToolSets.ts
19914
+ function mergeActiveToolSets(current, derived) {
19915
+ if (derived.length === 0) return current;
19916
+ const merged = Array.from(/* @__PURE__ */ new Set([...current, ...derived]));
19917
+ return merged.length === current.length ? current : merged;
19789
19918
  }
19790
19919
 
19920
+ // src/lib/tools/selection/recentToolSets.ts
19921
+ var RECENT_TOOL_SET_TURNS = 2;
19922
+ var RECENT_TOOL_SET_CONVERSATION_LIMIT = 50;
19923
+ var CARRYABLE_TOOL_SETS = new Set(
19924
+ BUILT_IN_TOOL_SETS.filter(
19925
+ (s) => s.anchors.length > 0 && s.anchors.every((a) => a in TOOL_CATALOG)
19926
+ ).map((s) => s.name)
19927
+ );
19928
+ var recentToolSets = /* @__PURE__ */ new WeakMap();
19929
+ function touch(conversations, conversationId) {
19930
+ const turns = conversations.get(conversationId);
19931
+ if (!turns) return void 0;
19932
+ conversations.delete(conversationId);
19933
+ conversations.set(conversationId, turns);
19934
+ return turns;
19935
+ }
19936
+ function carriedToolSets(database, conversationId) {
19937
+ if (!conversationId) return [];
19938
+ const conversations = recentToolSets.get(database);
19939
+ if (!conversations) return [];
19940
+ return [...touch(conversations, conversationId)?.keys() ?? []];
19941
+ }
19942
+ function recordToolSetTurn(database, conversationId, matched) {
19943
+ if (!conversationId) return;
19944
+ let conversations = recentToolSets.get(database);
19945
+ if (!conversations) {
19946
+ conversations = /* @__PURE__ */ new Map();
19947
+ recentToolSets.set(database, conversations);
19948
+ }
19949
+ const turns = touch(conversations, conversationId) ?? /* @__PURE__ */ new Map();
19950
+ for (const [name, left] of turns) {
19951
+ if (left > 1) turns.set(name, left - 1);
19952
+ else turns.delete(name);
19953
+ }
19954
+ for (const name of matched) {
19955
+ if (CARRYABLE_TOOL_SETS.has(name)) turns.set(name, RECENT_TOOL_SET_TURNS);
19956
+ }
19957
+ if (turns.size === 0) {
19958
+ conversations.delete(conversationId);
19959
+ return;
19960
+ }
19961
+ conversations.set(conversationId, turns);
19962
+ if (conversations.size > RECENT_TOOL_SET_CONVERSATION_LIMIT) {
19963
+ const oldest = conversations.keys().next().value;
19964
+ if (oldest !== void 0) conversations.delete(oldest);
19965
+ }
19966
+ }
19967
+ function resetRecentToolSets() {
19968
+ recentToolSets = /* @__PURE__ */ new WeakMap();
19969
+ }
19970
+ onClearAllEncryptionState(resetRecentToolSets);
19971
+
19791
19972
  // src/expo/useChatStorage.ts
19792
19973
  var CONVERSATION_REDACTOR_LIMIT = 50;
19793
19974
  var NO_CONVERSATION_KEY = "__no_conversation__";
@@ -20667,6 +20848,7 @@ function useChatStorage(options) {
20667
20848
  }
20668
20849
  let narrowedClientTools2 = clientTools;
20669
20850
  let clientActivatedSetNames2;
20851
+ let matchedToolSets2 = /* @__PURE__ */ new Set();
20670
20852
  if (clientTools?.length) {
20671
20853
  try {
20672
20854
  if (!skipUserEmbedding && getTokenRef.current && messageContent.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
@@ -20687,17 +20869,25 @@ function useChatStorage(options) {
20687
20869
  narrowedClientTools2 = clientTools.filter((t) => keep.has(getToolName2(t)));
20688
20870
  }
20689
20871
  } else if (getTokenRef.current) {
20690
- const { tools: autoTools, activatedSetNames } = await autoFilterClientTools(
20872
+ const {
20873
+ tools: autoTools,
20874
+ activatedSetNames,
20875
+ matchedSetNames
20876
+ } = await autoFilterClientTools(
20691
20877
  clientTools,
20692
20878
  skipUserEmbedding ?? null,
20693
20879
  clientToolFilterCache,
20694
20880
  { getToken: getTokenRef.current, baseUrl, model: embeddingModel },
20695
20881
  extraToolSets ?? [],
20696
- activeToolSetsRef.current ?? [],
20882
+ mergeActiveToolSets(
20883
+ activeToolSetsRef.current ?? [],
20884
+ carriedToolSets(database, currentConversationId)
20885
+ ),
20697
20886
  skipEmbeddingFailed ? "error" : "short-prompt"
20698
20887
  );
20699
20888
  narrowedClientTools2 = autoTools;
20700
20889
  clientActivatedSetNames2 = activatedSetNames;
20890
+ matchedToolSets2 = matchedSetNames;
20701
20891
  }
20702
20892
  } catch (error) {
20703
20893
  getLogger().warn("[useChatStorage] client tool filtering failed (skipStorage):", error);
@@ -20749,6 +20939,7 @@ function useChatStorage(options) {
20749
20939
  headers
20750
20940
  });
20751
20941
  if ("detached" in result2 && result2.detached) {
20942
+ recordToolSetTurn(database, currentConversationId, matchedToolSets2);
20752
20943
  return {
20753
20944
  data: result2.data,
20754
20945
  error: result2.error,
@@ -20762,6 +20953,7 @@ function useChatStorage(options) {
20762
20953
  error: result2.error || "Unknown error"
20763
20954
  };
20764
20955
  }
20956
+ recordToolSetTurn(database, currentConversationId, matchedToolSets2);
20765
20957
  const skipRefreshGetToken = getTokenRef.current;
20766
20958
  const skipRefreshData = result2.data;
20767
20959
  if (skipRefreshGetToken) {
@@ -20977,6 +21169,7 @@ function useChatStorage(options) {
20977
21169
  }
20978
21170
  let narrowedClientTools = clientTools;
20979
21171
  let clientActivatedSetNames;
21172
+ let matchedToolSets = /* @__PURE__ */ new Set();
20980
21173
  if (clientTools?.length) {
20981
21174
  try {
20982
21175
  if (!userMessageEmbedding && getTokenRef.current && contentForStorage.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
@@ -20993,17 +21186,25 @@ function useChatStorage(options) {
20993
21186
  narrowedClientTools = clientTools.filter((t) => keep.has(getToolName2(t)));
20994
21187
  }
20995
21188
  } else if (getTokenRef.current) {
20996
- const { tools: autoTools, activatedSetNames } = await autoFilterClientTools(
21189
+ const {
21190
+ tools: autoTools,
21191
+ activatedSetNames,
21192
+ matchedSetNames
21193
+ } = await autoFilterClientTools(
20997
21194
  clientTools,
20998
21195
  userMessageEmbedding ?? null,
20999
21196
  clientToolFilterCache,
21000
21197
  { getToken: getTokenRef.current, baseUrl, model: embeddingModel },
21001
21198
  extraToolSets ?? [],
21002
- activeToolSetsRef.current ?? [],
21199
+ mergeActiveToolSets(
21200
+ activeToolSetsRef.current ?? [],
21201
+ carriedToolSets(database, convId)
21202
+ ),
21003
21203
  userMessageEmbeddingFailed ? "error" : "short-prompt"
21004
21204
  );
21005
21205
  narrowedClientTools = autoTools;
21006
21206
  clientActivatedSetNames = activatedSetNames;
21207
+ matchedToolSets = matchedSetNames;
21007
21208
  }
21008
21209
  mergedTools = filteredServerTools.length > 0 || (narrowedClientTools?.length ?? 0) > 0 ? mergeTools(
21009
21210
  filteredServerTools,
@@ -21090,6 +21291,7 @@ function useChatStorage(options) {
21090
21291
  const responseDuration = (Date.now() - startTime) / 1e3;
21091
21292
  const detachedResult = result;
21092
21293
  if (detachedResult.detached) {
21294
+ recordToolSetTurn(database, convId, matchedToolSets);
21093
21295
  const rowId = effectiveAssistantUniqueId ?? `msg_${uuidv75()}`;
21094
21296
  pendingResumeRef.current = {
21095
21297
  handle: detachedResult.resume ?? null,
@@ -21158,6 +21360,7 @@ function useChatStorage(options) {
21158
21360
  ],
21159
21361
  usage: void 0
21160
21362
  };
21363
+ recordToolSetTurn(database, convId, matchedToolSets);
21161
21364
  return {
21162
21365
  data: responseData2,
21163
21366
  error: null,
@@ -21196,6 +21399,7 @@ function useChatStorage(options) {
21196
21399
  userMessage: { ...storedUserMessage, error: errorMessage }
21197
21400
  };
21198
21401
  }
21402
+ recordToolSetTurn(database, convId, matchedToolSets);
21199
21403
  const responseData = result.data;
21200
21404
  let assistantContent = "";
21201
21405
  let thinkingContent;
package/dist/index.cjs CHANGED
@@ -1694,12 +1694,28 @@ var noopLogger = {
1694
1694
  error: () => {
1695
1695
  }
1696
1696
  };
1697
- var currentLogger = consoleLogger;
1697
+ var LOGGER_STATE_KEY = /* @__PURE__ */ Symbol.for("@anuma/sdk/logger/v1");
1698
+ var loggerGlobal = globalThis;
1699
+ var fallbackLoggerState = { logger: consoleLogger };
1700
+ var fallbackWarned = false;
1701
+ function getLoggerState() {
1702
+ try {
1703
+ return loggerGlobal[LOGGER_STATE_KEY] ?? (loggerGlobal[LOGGER_STATE_KEY] = fallbackLoggerState);
1704
+ } catch {
1705
+ if (!fallbackWarned) {
1706
+ fallbackWarned = true;
1707
+ fallbackLoggerState.logger.warn(
1708
+ "@anuma/sdk: the global object rejects new properties. This entrypoint keeps its own logger, so setLogger does not reach other entrypoints."
1709
+ );
1710
+ }
1711
+ return fallbackLoggerState;
1712
+ }
1713
+ }
1698
1714
  function setLogger(logger) {
1699
- currentLogger = logger;
1715
+ getLoggerState().logger = logger;
1700
1716
  }
1701
1717
  function getLogger() {
1702
- return currentLogger;
1718
+ return getLoggerState().logger;
1703
1719
  }
1704
1720
 
1705
1721
  // src/lib/memoryEngine/chunking.ts
package/dist/index.d.mts CHANGED
@@ -7664,6 +7664,21 @@ type ToolConfig = LlmapiChatCompletionTool & {
7664
7664
  * execution fails, allowing the model to retry.
7665
7665
  */
7666
7666
  removeAfterExecution?: boolean;
7667
+ /**
7668
+ * Remove this tool for the rest of the turn once ANY tool returns a
7669
+ * successful result this predicate accepts — its own or another's. Errors
7670
+ * never count, as for `removeAfterExecution`.
7671
+ *
7672
+ * Only results of tools executed on this client are offered; tools the
7673
+ * portal runs server-side never reach the predicate. A predicate that throws
7674
+ * is treated as not matching.
7675
+ *
7676
+ * For a family of tools that has to leave together: when one of them
7677
+ * declines an out-of-scope request, the model otherwise works through its
7678
+ * siblings round after round until the round cap. Give every member the same
7679
+ * predicate and the first refusal removes the whole family.
7680
+ */
7681
+ removeAfterResult?: (result: unknown) => boolean;
7667
7682
  /**
7668
7683
  * Timeout in milliseconds for this tool's executor.
7669
7684
  * Overrides the default 30-second timeout.
@@ -8724,14 +8739,10 @@ interface LazyStoredConversation extends Omit<StoredConversation, "title"> {
8724
8739
  * re-index. Off by default, so no background pass can spend a user's credits
8725
8740
  * without being asked to.
8726
8741
  *
8727
- * That flag opens the gate for one call and nothing more. It does not heal the
8728
- * row: a message that re-indexes successfully still carries `chunks_discarded`
8729
- * afterwards, so the next pass skips it again unless that pass sets the flag
8730
- * too. An embedding-model migration is where this bites. It reaches this gate
8731
- * before it can do anything, so the repaired rows stay on the old model, and
8732
- * `searchChunksOp` already drops stale-model vectors — they go quiet with
8733
- * nothing telling them apart from rows that were never repaired. Clearing the
8734
- * marker on a successful re-index is the real fix, tracked in #879.
8742
+ * A successful repair replaces the marker with `message` in the index write.
8743
+ * The new marker preserves ordinary message provenance during chat replay.
8744
+ * Later model migrations can then include the repaired row without this flag.
8745
+ * Failed embedding requests and empty index data do not clear the marker.
8735
8746
  *
8736
8747
  * `satisfies MessageOrigin` so the constant and the union cannot drift apart
8737
8748
  * silently — the column's type is the union, and a typo here would otherwise
package/dist/index.d.ts CHANGED
@@ -7664,6 +7664,21 @@ type ToolConfig = LlmapiChatCompletionTool & {
7664
7664
  * execution fails, allowing the model to retry.
7665
7665
  */
7666
7666
  removeAfterExecution?: boolean;
7667
+ /**
7668
+ * Remove this tool for the rest of the turn once ANY tool returns a
7669
+ * successful result this predicate accepts — its own or another's. Errors
7670
+ * never count, as for `removeAfterExecution`.
7671
+ *
7672
+ * Only results of tools executed on this client are offered; tools the
7673
+ * portal runs server-side never reach the predicate. A predicate that throws
7674
+ * is treated as not matching.
7675
+ *
7676
+ * For a family of tools that has to leave together: when one of them
7677
+ * declines an out-of-scope request, the model otherwise works through its
7678
+ * siblings round after round until the round cap. Give every member the same
7679
+ * predicate and the first refusal removes the whole family.
7680
+ */
7681
+ removeAfterResult?: (result: unknown) => boolean;
7667
7682
  /**
7668
7683
  * Timeout in milliseconds for this tool's executor.
7669
7684
  * Overrides the default 30-second timeout.
@@ -8724,14 +8739,10 @@ interface LazyStoredConversation extends Omit<StoredConversation, "title"> {
8724
8739
  * re-index. Off by default, so no background pass can spend a user's credits
8725
8740
  * without being asked to.
8726
8741
  *
8727
- * That flag opens the gate for one call and nothing more. It does not heal the
8728
- * row: a message that re-indexes successfully still carries `chunks_discarded`
8729
- * afterwards, so the next pass skips it again unless that pass sets the flag
8730
- * too. An embedding-model migration is where this bites. It reaches this gate
8731
- * before it can do anything, so the repaired rows stay on the old model, and
8732
- * `searchChunksOp` already drops stale-model vectors — they go quiet with
8733
- * nothing telling them apart from rows that were never repaired. Clearing the
8734
- * marker on a successful re-index is the real fix, tracked in #879.
8742
+ * A successful repair replaces the marker with `message` in the index write.
8743
+ * The new marker preserves ordinary message provenance during chat replay.
8744
+ * Later model migrations can then include the repaired row without this flag.
8745
+ * Failed embedding requests and empty index data do not clear the marker.
8735
8746
  *
8736
8747
  * `satisfies MessageOrigin` so the constant and the union cannot drift apart
8737
8748
  * silently — the column's type is the union, and a typo here would otherwise