@anuma/sdk 6.30.2 → 6.31.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.
@@ -19,12 +19,28 @@ var noopLogger = {
19
19
  error: () => {
20
20
  }
21
21
  };
22
- var currentLogger = consoleLogger;
22
+ var LOGGER_STATE_KEY = /* @__PURE__ */ Symbol.for("@anuma/sdk/logger/v1");
23
+ var loggerGlobal = globalThis;
24
+ var fallbackLoggerState = { logger: consoleLogger };
25
+ var fallbackWarned = false;
26
+ function getLoggerState() {
27
+ try {
28
+ return loggerGlobal[LOGGER_STATE_KEY] ?? (loggerGlobal[LOGGER_STATE_KEY] = fallbackLoggerState);
29
+ } catch {
30
+ if (!fallbackWarned) {
31
+ fallbackWarned = true;
32
+ fallbackLoggerState.logger.warn(
33
+ "@anuma/sdk: the global object rejects new properties. This entrypoint keeps its own logger, so setLogger does not reach other entrypoints."
34
+ );
35
+ }
36
+ return fallbackLoggerState;
37
+ }
38
+ }
23
39
  function setLogger(logger) {
24
- currentLogger = logger;
40
+ getLoggerState().logger = logger;
25
41
  }
26
42
  function getLogger() {
27
- return currentLogger;
43
+ return getLoggerState().logger;
28
44
  }
29
45
 
30
46
  // src/lib/pii/patterns.ts
@@ -2,7 +2,7 @@ import {
2
2
  callPortalJsonCompletion,
3
3
  notifyConsolidationFallback,
4
4
  resolvePiiRedactor
5
- } from "./chunk-VD5M6QAI.mjs";
5
+ } from "./chunk-XD6WOQ5I.mjs";
6
6
  import "./chunk-GYKJOWEO.mjs";
7
7
 
8
8
  // src/lib/memory/consolidate.ts
@@ -44,13 +44,26 @@ var __decorateClass = (decorators, target, key, kind) => {
44
44
  };
45
45
 
46
46
  // src/lib/logger.ts
47
+ function getLoggerState() {
48
+ try {
49
+ return loggerGlobal[LOGGER_STATE_KEY] ?? (loggerGlobal[LOGGER_STATE_KEY] = fallbackLoggerState);
50
+ } catch {
51
+ if (!fallbackWarned) {
52
+ fallbackWarned = true;
53
+ fallbackLoggerState.logger.warn(
54
+ "@anuma/sdk: the global object rejects new properties. This entrypoint keeps its own logger, so setLogger does not reach other entrypoints."
55
+ );
56
+ }
57
+ return fallbackLoggerState;
58
+ }
59
+ }
47
60
  function setLogger(logger) {
48
- currentLogger = logger;
61
+ getLoggerState().logger = logger;
49
62
  }
50
63
  function getLogger() {
51
- return currentLogger;
64
+ return getLoggerState().logger;
52
65
  }
53
- var consoleLogger, noopLogger, currentLogger;
66
+ var consoleLogger, noopLogger, LOGGER_STATE_KEY, loggerGlobal, fallbackLoggerState, fallbackWarned;
54
67
  var init_logger = __esm({
55
68
  "src/lib/logger.ts"() {
56
69
  "use strict";
@@ -70,7 +83,10 @@ var init_logger = __esm({
70
83
  error: () => {
71
84
  }
72
85
  };
73
- currentLogger = consoleLogger;
86
+ LOGGER_STATE_KEY = /* @__PURE__ */ Symbol.for("@anuma/sdk/logger/v1");
87
+ loggerGlobal = globalThis;
88
+ fallbackLoggerState = { logger: consoleLogger };
89
+ fallbackWarned = false;
74
90
  }
75
91
  });
76
92
 
@@ -3734,6 +3750,9 @@ async function updateMessageEmbeddingOp(ctx, uniqueId, vector, embeddingModel) {
3734
3750
  await ctx.database.write(async () => {
3735
3751
  await message.update((msg) => {
3736
3752
  msg._setRaw("vector", JSON.stringify(vector));
3753
+ if (msg.origin === "chunks_discarded" && vector.length > 0) {
3754
+ msg._setRaw("origin", "message");
3755
+ }
3737
3756
  msg._setRaw("embedding_model", embeddingModel);
3738
3757
  });
3739
3758
  });
@@ -3750,6 +3769,9 @@ async function updateMessageChunksOp(ctx, uniqueId, chunks, embeddingModel) {
3750
3769
  await ctx.database.write(async () => {
3751
3770
  await message.update((msg) => {
3752
3771
  msg._setRaw("chunks", JSON.stringify(storedChunks));
3772
+ if (msg.origin === "chunks_discarded" && storedChunks.length > 0 && storedChunks.every((chunk) => chunk.vector.length > 0)) {
3773
+ msg._setRaw("origin", "message");
3774
+ }
3753
3775
  msg._setRaw("embedding_model", embeddingModel);
3754
3776
  });
3755
3777
  });
@@ -5974,6 +5996,9 @@ function clientToolToResponsesFormat(tool) {
5974
5996
  ...toolConfig.removeAfterExecution !== void 0 && {
5975
5997
  removeAfterExecution: toolConfig.removeAfterExecution
5976
5998
  },
5999
+ ...toolConfig.removeAfterResult !== void 0 && {
6000
+ removeAfterResult: toolConfig.removeAfterResult
6001
+ },
5977
6002
  ...toolConfig.executorTimeout !== void 0 && {
5978
6003
  executorTimeout: toolConfig.executorTimeout
5979
6004
  },
@@ -6007,6 +6032,9 @@ function clientToolToCompletionsFormat(tool) {
6007
6032
  ...toolConfig.removeAfterExecution !== void 0 && {
6008
6033
  removeAfterExecution: toolConfig.removeAfterExecution
6009
6034
  },
6035
+ ...toolConfig.removeAfterResult !== void 0 && {
6036
+ removeAfterResult: toolConfig.removeAfterResult
6037
+ },
6010
6038
  ...toolConfig.executorTimeout !== void 0 && {
6011
6039
  executorTimeout: toolConfig.executorTimeout
6012
6040
  },
@@ -6941,6 +6969,7 @@ function toolsToApiFormat(tools, apiType) {
6941
6969
  executor: _executor,
6942
6970
  skipContinuation: _skipContinuation,
6943
6971
  removeAfterExecution: _removeAfterExecution,
6972
+ removeAfterResult: _removeAfterResult,
6944
6973
  executorTimeout: _executorTimeout,
6945
6974
  dependsOn: _dependsOn,
6946
6975
  deAnonymizeArgs: _deAnonymizeArgs,
@@ -9385,9 +9414,11 @@ Executing tool: ${toolInfo}
9385
9414
  }
9386
9415
  if (tools && apiTools) {
9387
9416
  const successfullyExecutedNames = /* @__PURE__ */ new Set();
9417
+ const successfulResults = [];
9388
9418
  for (const r of executionResults) {
9389
9419
  if (!r.error && !isToolErrorResult(r.result) && "name" in r && r.name) {
9390
9420
  successfullyExecutedNames.add(r.name);
9421
+ successfulResults.push(r.result);
9391
9422
  }
9392
9423
  }
9393
9424
  if (successfullyExecutedNames.size > 0) {
@@ -9396,7 +9427,15 @@ Executing tool: ${toolInfo}
9396
9427
  const tc = t;
9397
9428
  const func = tc.function;
9398
9429
  const toolName = typeof func?.name === "string" ? func.name : typeof tc.name === "string" ? tc.name : void 0;
9399
- if (tc.removeAfterExecution === true && toolName && successfullyExecutedNames.has(toolName)) {
9430
+ if (!toolName) continue;
9431
+ const removeAfterResult = tc.removeAfterResult;
9432
+ if (tc.removeAfterExecution === true && successfullyExecutedNames.has(toolName) || typeof removeAfterResult === "function" && successfulResults.some((result) => {
9433
+ try {
9434
+ return removeAfterResult(result);
9435
+ } catch {
9436
+ return false;
9437
+ }
9438
+ })) {
9400
9439
  toolsToRemove.add(toolName);
9401
9440
  }
9402
9441
  }
@@ -13237,7 +13276,7 @@ async function getMemoriesNeedingTopicExtractionOp(ctx, options) {
13237
13276
  const id = raw.id;
13238
13277
  const topics = parseTopics(raw.topics);
13239
13278
  const linked = linkedNames.get(id);
13240
- if (topics !== null && topics.length > 0 && linksDivergeFromTopics(topics, linked ?? /* @__PURE__ */ new Set())) {
13279
+ if (topics !== null && linksDivergeFromTopics(topics, linked ?? /* @__PURE__ */ new Set())) {
13241
13280
  topicsToRelinkAll.push(id);
13242
13281
  continue;
13243
13282
  }
@@ -13331,18 +13370,20 @@ async function relinkMemoryTopicsOp(ctx, memoryIds) {
13331
13370
  }
13332
13371
  const relinked = [];
13333
13372
  for (const id of Array.from(new Set(memoryIds))) {
13334
- let record;
13335
- try {
13336
- record = await ctx.vaultMemoryCollection.find(id);
13337
- } catch {
13338
- continue;
13339
- }
13340
- if (record.isDeleted || !isOwnedByCtxUser(ctx, record)) continue;
13341
- const topics = parseTopics(record.topics);
13342
- if (topics === null || topics.length === 0) continue;
13343
13373
  try {
13344
- await relinkMemoryEntitiesFromTopicsOp(entityCtx, id, topics);
13345
- relinked.push(id);
13374
+ await ctx.database.write(async (writer) => {
13375
+ let record;
13376
+ try {
13377
+ record = await ctx.vaultMemoryCollection.find(id);
13378
+ } catch {
13379
+ return;
13380
+ }
13381
+ if (record.isDeleted || !isOwnedByCtxUser(ctx, record)) return;
13382
+ const topics = parseTopics(record.topics);
13383
+ if (topics === null) return;
13384
+ await writer.callWriter(() => relinkMemoryEntitiesFromTopicsOp(entityCtx, id, topics));
13385
+ relinked.push(id);
13386
+ });
13346
13387
  } catch (err) {
13347
13388
  getLogger().warn("[memory/topics] relink failed", err);
13348
13389
  }
@@ -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>;
@@ -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) {
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