@unblocklabs/unblock-memory 0.12.2 → 0.13.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.
Files changed (123) hide show
  1. package/README.md +19 -18
  2. package/dist/src/analysis.js +1 -1
  3. package/dist/src/cluster-review.d.ts +2 -0
  4. package/dist/src/cluster-review.js +3 -3
  5. package/dist/src/config.d.ts +9 -6
  6. package/dist/src/config.js +31 -20
  7. package/dist/src/curation.d.ts +1 -1
  8. package/dist/src/decision-client.d.ts +39 -0
  9. package/dist/src/decision-client.js +74 -0
  10. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  11. package/dist/src/decision-ranking.js +154 -0
  12. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  13. package/dist/src/decision-review.js +192 -0
  14. package/dist/src/diagnostics.d.ts +5 -5
  15. package/dist/src/emotion-baselines.d.ts +28 -3
  16. package/dist/src/emotion-baselines.js +309 -113
  17. package/dist/src/evidence-review.d.ts +22 -8
  18. package/dist/src/evidence-review.js +4 -4
  19. package/dist/src/extraction-chunk.d.ts +3 -0
  20. package/dist/src/extraction-chunk.js +23 -5
  21. package/dist/src/extraction-model.d.ts +2 -0
  22. package/dist/src/extraction-model.js +73 -48
  23. package/dist/src/extraction-runtime.d.ts +3 -1
  24. package/dist/src/extraction-runtime.js +43 -16
  25. package/dist/src/extraction-source.d.ts +1 -1
  26. package/dist/src/extraction-source.js +19 -11
  27. package/dist/src/extraction-store.d.ts +28 -3
  28. package/dist/src/extraction-store.js +145 -23
  29. package/dist/src/extraction-worker.d.ts +1 -0
  30. package/dist/src/extraction-worker.js +246 -93
  31. package/dist/src/inside-out-runtime.js +41 -29
  32. package/dist/src/inside-out-store.d.ts +2 -2
  33. package/dist/src/inside-out-store.js +110 -69
  34. package/dist/src/inside-out.d.ts +10 -9
  35. package/dist/src/inside-out.js +190 -105
  36. package/dist/src/manager.d.ts +22 -9
  37. package/dist/src/manager.js +275 -169
  38. package/dist/src/memory-search.d.ts +4 -2
  39. package/dist/src/memory-search.js +5 -5
  40. package/dist/src/memory-whisperer.d.ts +1 -1
  41. package/dist/src/memory-whisperer.js +189 -127
  42. package/dist/src/my-turn.d.ts +1 -1
  43. package/dist/src/my-turn.js +87 -68
  44. package/dist/src/people-background.d.ts +4 -0
  45. package/dist/src/people-background.js +29 -6
  46. package/dist/src/people-dossier-review.d.ts +20 -8
  47. package/dist/src/people-dossier-review.js +11 -8
  48. package/dist/src/people-hooks.js +127 -22
  49. package/dist/src/people-learning-cron.d.ts +1 -1
  50. package/dist/src/people-learning-cron.js +106 -57
  51. package/dist/src/people-learning-inventory.d.ts +1 -0
  52. package/dist/src/people-learning-inventory.js +281 -171
  53. package/dist/src/people-learning-prompt.js +1 -1
  54. package/dist/src/people-learning-runtime.d.ts +1 -1
  55. package/dist/src/people-learning-runtime.js +423 -204
  56. package/dist/src/people-learning-store.d.ts +27 -4
  57. package/dist/src/people-learning-store.js +312 -96
  58. package/dist/src/people-primer-tool.js +8 -6
  59. package/dist/src/people-primer.d.ts +3 -1
  60. package/dist/src/people-primer.js +61 -44
  61. package/dist/src/people-store.d.ts +18 -21
  62. package/dist/src/people-store.js +186 -63
  63. package/dist/src/people-tools.js +136 -92
  64. package/dist/src/plugin.js +16 -16
  65. package/dist/src/quality-audit.d.ts +2 -0
  66. package/dist/src/quality-audit.js +8 -7
  67. package/dist/src/query-generator.d.ts +1 -1
  68. package/dist/src/query-generator.js +15 -8
  69. package/dist/src/response-audit.d.ts +1 -1
  70. package/dist/src/response-audit.js +76 -43
  71. package/dist/src/response-episodes.d.ts +1 -1
  72. package/dist/src/response-episodes.js +12 -17
  73. package/dist/src/response-judge.d.ts +151 -145
  74. package/dist/src/response-judge.js +535 -204
  75. package/dist/src/response-reviews.d.ts +29 -1
  76. package/dist/src/response-reviews.js +110 -13
  77. package/dist/src/response-runtime.js +8 -8
  78. package/dist/src/response-stages.d.ts +50 -53
  79. package/dist/src/response-stages.js +10 -4
  80. package/dist/src/response-store.d.ts +7 -6
  81. package/dist/src/response-store.js +332 -210
  82. package/dist/src/response-text.d.ts +2 -0
  83. package/dist/src/response-text.js +182 -36
  84. package/dist/src/review-tools.d.ts +8 -2
  85. package/dist/src/review-tools.js +18 -18
  86. package/dist/src/runtime.d.ts +7 -4
  87. package/dist/src/runtime.js +624 -98
  88. package/dist/src/safety-whisperer.d.ts +2 -2
  89. package/dist/src/safety-whisperer.js +88 -71
  90. package/dist/src/session-sync.d.ts +3 -1
  91. package/dist/src/session-sync.js +200 -95
  92. package/dist/src/skill-whisperer.d.ts +1 -1
  93. package/dist/src/skill-whisperer.js +52 -30
  94. package/dist/src/training-gate.d.ts +8 -21
  95. package/dist/src/training-gate.js +32 -35
  96. package/dist/src/training-judge.d.ts +9 -16
  97. package/dist/src/training-judge.js +5 -5
  98. package/dist/src/training-queries.d.ts +13 -8
  99. package/dist/src/training-queries.js +370 -228
  100. package/dist/src/training-retrieval.d.ts +14 -24
  101. package/dist/src/training-retrieval.js +182 -136
  102. package/dist/src/training-runtime.d.ts +3 -0
  103. package/dist/src/training-runtime.js +76 -18
  104. package/dist/src/training-store.d.ts +18 -3
  105. package/dist/src/training-store.js +138 -50
  106. package/dist/src/training.js +8 -11
  107. package/dist/src/whisperer-context.d.ts +14 -0
  108. package/dist/src/whisperer-context.js +22 -1
  109. package/docs/configuration.md +76 -63
  110. package/docs/extraction.md +9 -7
  111. package/docs/memory-training.md +7 -6
  112. package/docs/people-learning.md +2 -2
  113. package/docs/peoplesql.md +6 -6
  114. package/docs/response-audit.md +10 -8
  115. package/docs/retrieval.md +40 -37
  116. package/openclaw.plugin.json +40 -26
  117. package/package.json +3 -2
  118. package/skills/memory-curator/SKILL.md +1 -1
  119. package/skills/people-whisperer/SKILL.md +1 -1
  120. package/dist/src/typesafe-client.d.ts +0 -30
  121. package/dist/src/typesafe-client.js +0 -92
  122. package/dist/src/typesafe-review.js +0 -154
  123. package/dist/src/typesafe.js +0 -147
@@ -1,7 +1,7 @@
1
1
  import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
2
2
  import type { UnblockMemoryConfig } from "./config.js";
3
3
  import type { WhispererDiagnostics } from "./diagnostics.js";
4
- type SafetyPluginConfig = Pick<UnblockMemoryConfig, "safetyWhisperer" | "typesafe" | "memoryWhisperer" | "skillWhisperer">;
4
+ type SafetyPluginConfig = Pick<UnblockMemoryConfig, "safetyWhisperer" | "decisionModel" | "memoryWhisperer" | "skillWhisperer">;
5
5
  /**
6
6
  * The complete current human message, the channel context that arrived with it, and whole recent
7
7
  * messages. OpenClaw's identity header is never sent; an oversized current message is not truncated.
@@ -23,7 +23,7 @@ export declare function safetyStatus(cfg: unknown, config: SafetyPluginConfig):
23
23
  hostTimeoutMs?: number | undefined;
24
24
  slowestWhispererMs?: number | undefined;
25
25
  warnings?: string[] | undefined;
26
- reason?: string | undefined;
26
+ reason?: "decision_disabled" | "conversation_access_not_allowed" | "prompt_injection_not_allowed" | "no_enabled_scenarios" | undefined;
27
27
  enabled: boolean;
28
28
  active: boolean;
29
29
  };
@@ -1,12 +1,10 @@
1
1
  import { Value } from "typebox/value";
2
- import { estimateJevTokens, isTypeSafeTimeout, requestTypeSafe, resolveTypeSafeApiKey, TYPESAFE_NOUL_SCHEMA, TypeSafeRequestError } from "./typesafe-client.js";
3
- import { messageText } from "./whisperer-context.js";
2
+ import { estimateDecisionTokens, isDecisionTimeout, requestDecision, resolveDecisionCredential, NOUL_SCHEMA, DecisionRequestError } from "./decision-client.js";
3
+ import { MAX_STATE_TOKENS, messageText, takeRecentWithinTokens } from "./whisperer-context.js";
4
4
  import { CONVERSATION_INFO, conversationEnvelope, conversationUserText } from "./response-text.js";
5
5
  import { SKILL_WHISPERER_TIMEOUT_MS } from "./skill-whisperer.js";
6
6
  import { abortable } from "./abortable.js";
7
- import { isRecord, nonBlank } from "./guards.js";
8
- // Leaves room for the longest scenario question under Jev's 32k state-plus-question limit.
9
- const MAX_STATE_TOKENS = 24_000;
7
+ import { nonBlank, record } from "./guards.js";
10
8
  const MAX_SESSIONS = 1000;
11
9
  const RUNS_PER_SESSION = 4;
12
10
  class SafetyInputError extends Error {
@@ -41,9 +39,10 @@ function historyMessage(message) {
41
39
  const parsed = messageText(message);
42
40
  if (!parsed || parsed.role === "assistant")
43
41
  return parsed && { role: parsed.role, content: parsed.text };
44
- const meta = isRecord(message) && isRecord(message.__openclaw) ? message.__openclaw : undefined;
42
+ const rawMessage = record(message);
43
+ const meta = record(rawMessage?.__openclaw);
45
44
  const raw = typeof meta?.upstreamUserText === "string" ? meta.upstreamUserText : parsed.text;
46
- const sender = meta?.senderId ?? (isRecord(message) ? message.senderId : undefined);
45
+ const sender = meta?.senderId ?? rawMessage?.senderId;
47
46
  const content = conversationUserText(raw, sender)?.text ?? raw.trim().replace(CONVERSATION_INFO, "").trim();
48
47
  return content ? { role: parsed.role, content } : undefined;
49
48
  }
@@ -55,36 +54,24 @@ export function safetyConversation(prompt, messages, historyMessages, senderId)
55
54
  const envelope = conversationEnvelope(prompt, senderId);
56
55
  // An unrecognized wrapper is judged whole, minus the identity header: over-flagging beats missing a request.
57
56
  const currentRequest = envelope?.text ?? prompt.trim().replace(CONVERSATION_INFO, "").trim();
58
- let size = estimateJevTokens({ currentRequest, history: [] });
59
- if (size > MAX_STATE_TOKENS)
57
+ const baseTokens = estimateDecisionTokens({ currentRequest, history: [] });
58
+ if (baseTokens > MAX_STATE_TOKENS)
60
59
  throw new SafetyInputError("Current request exceeds the safety check budget");
61
60
  // Thread starter, reply target and chat history since the last reply resolve "answer the question above".
62
61
  const lines = envelope?.context?.split("\n") ?? [];
63
- const kept = [];
64
- for (let i = lines.length - 1; i >= 0; i--) {
65
- const cost = estimateJevTokens(lines[i]) + 1;
66
- if (size + cost > MAX_STATE_TOKENS)
67
- break;
68
- kept.unshift(lines[i]);
69
- size += cost;
70
- }
71
- const channelContext = kept.join("\n").trim();
72
- const history = [];
62
+ const contextBudget = takeRecentWithinTokens(lines, {
63
+ maxTokens: MAX_STATE_TOKENS, usedTokens: baseTokens, estimateTokens: estimateDecisionTokens,
64
+ });
65
+ const channelContext = contextBudget.items.join("\n").trim();
73
66
  let last = messages.length - 1;
74
67
  // The host can already include the current message in the transcript; do not count it twice.
75
68
  const newest = last >= 0 ? historyMessage(messages[last]) : undefined;
76
69
  if (newest?.role === "user" && newest.content === currentRequest)
77
70
  last--;
78
- for (let i = last; i >= 0 && history.length < historyMessages; i--) {
79
- const message = historyMessage(messages[i]);
80
- if (!message)
81
- continue;
82
- const cost = estimateJevTokens(message) + 1;
83
- if (size + cost > MAX_STATE_TOKENS)
84
- break;
85
- history.unshift(message);
86
- size += cost;
87
- }
71
+ const { items: history } = takeRecentWithinTokens(messages, {
72
+ endIndex: last, maxItems: historyMessages, maxTokens: MAX_STATE_TOKENS, usedTokens: contextBudget.usedTokens,
73
+ estimateTokens: estimateDecisionTokens, transform: historyMessage,
74
+ });
88
75
  return { currentRequest, ...(channelContext ? { channelContext } : {}), history };
89
76
  }
90
77
  function scenarioQuestion(policy) {
@@ -112,14 +99,14 @@ function scenarioQuestion(policy) {
112
99
  };
113
100
  }
114
101
  /** One request with one independent yes/no question per scenario; an invalid answer is undefined. */
115
- async function judgeSafetyScenarios(apiKey, signal, state, scenarios) {
102
+ async function judgeSafetyScenarios(apiKey, signal, state, scenarios, options) {
116
103
  const key = (index) => `scenario_${index}`;
117
104
  const questions = Object.fromEntries(scenarios.map((scenario, index) => [key(index), scenarioQuestion(scenario.instructions)]));
118
- const result = await requestTypeSafe({ apiKey, signal }, state, questions);
119
- const answers = isRecord(result) && isRecord(result.answers) ? result.answers : {};
105
+ const result = await requestDecision({ apiKey, endpoint: options?.endpoint, model: options?.model, signal }, state, questions);
106
+ const answers = record(record(result)?.answers) ?? {};
120
107
  return scenarios.map((_scenario, index) => {
121
108
  const answer = answers[key(index)];
122
- return Value.Check(TYPESAFE_NOUL_SCHEMA, answer) && Number.isFinite(answer.noul) ? answer.noul : undefined;
109
+ return Value.Check(NOUL_SCHEMA, answer) && Number.isFinite(answer.noul) ? answer.noul : undefined;
123
110
  });
124
111
  }
125
112
  function safetyContext(prompts) {
@@ -134,34 +121,44 @@ function queueMode(value) {
134
121
  return ["interrupt", "interrupts", "abort", "followup", "follow-ups", "followups", "collect", "coalesce"].includes(mode) ?
135
122
  "other" : undefined;
136
123
  }
124
+ function disabledReason(hooks, config) {
125
+ if (!config.decisionModel.enabled)
126
+ return "decision_disabled";
127
+ if (hooks.allowConversationAccess !== true)
128
+ return "conversation_access_not_allowed";
129
+ if (hooks.allowPromptInjection === false)
130
+ return "prompt_injection_not_allowed";
131
+ if (!config.safetyWhisperer.scenarios.some(scenario => scenario.enabled))
132
+ return "no_enabled_scenarios";
133
+ return undefined;
134
+ }
137
135
  /** Whether the host lets the check run at all; a skipped hook is not active protection. */
138
136
  export function safetyStatus(cfg, config) {
139
137
  const safety = config.safetyWhisperer;
140
138
  if (!safety.enabled)
141
139
  return { enabled: false, active: false, reason: "disabled" };
142
- const plugins = isRecord(cfg) && isRecord(cfg.plugins) ? cfg.plugins : {};
143
- const entry = isRecord(plugins.entries) && isRecord(plugins.entries["unblock-memory"]) ? plugins.entries["unblock-memory"] : {};
144
- const hooks = isRecord(entry.hooks) ? entry.hooks : {};
145
- const timeouts = isRecord(hooks.timeouts) ? hooks.timeouts : {};
146
- const hostTimeoutMs = typeof timeouts.before_prompt_build === "number" ? timeouts.before_prompt_build :
140
+ const root = record(cfg);
141
+ const plugins = record(root?.plugins);
142
+ const entry = record(record(plugins?.entries)?.["unblock-memory"]);
143
+ const hooks = record(entry?.hooks) ?? {};
144
+ const timeouts = record(hooks.timeouts);
145
+ const hostTimeoutMs = typeof timeouts?.before_prompt_build === "number" ? timeouts.before_prompt_build :
147
146
  typeof hooks.timeoutMs === "number" ? hooks.timeoutMs : undefined;
148
- const reason = !config.typesafe.enabled ? "typesafe_disabled" :
149
- hooks.allowConversationAccess !== true ? "conversation_access_not_allowed" :
150
- hooks.allowPromptInjection === false ? "prompt_injection_not_allowed" :
151
- !safety.scenarios.some(scenario => scenario.enabled) ? "no_enabled_scenarios" : undefined;
147
+ const reason = disabledReason(hooks, config);
152
148
  // The host times out the plugin's whole prompt contribution, so the slowest whisperer sets the bar.
153
149
  const slowestMs = Math.max(safety.timeoutMs, config.memoryWhisperer.enabled ? config.memoryWhisperer.timeoutMs : 0, config.skillWhisperer.enabled ? SKILL_WHISPERER_TIMEOUT_MS : 0);
154
150
  // OpenClaw defaults to steering: a message sent during an active run joins it without a new prompt build.
155
- const queue = isRecord(cfg) && isRecord(cfg.messages) && isRecord(cfg.messages.queue) ? cfg.messages.queue : {};
156
- const steers = queueMode(queue.mode) !== "other" ||
157
- (isRecord(queue.byChannel) && Object.values(queue.byChannel).some(mode => queueMode(mode) === "steer"));
151
+ const queue = record(record(root?.messages)?.queue);
152
+ const byChannel = record(queue?.byChannel);
153
+ const steers = queueMode(queue?.mode) !== "other" ||
154
+ Boolean(byChannel && Object.values(byChannel).some(mode => queueMode(mode) === "steer"));
158
155
  const timeoutTooShort = hostTimeoutMs !== undefined && hostTimeoutMs < slowestMs;
159
156
  const warnings = [...timeoutTooShort ? ["host_hook_timeout_below_whisperer_timeouts"] : [], ...steers ? ["queue_mode_steer"] : []];
160
157
  return { enabled: true, active: !reason, ...(reason ? { reason } : {}),
161
158
  ...(warnings.length ? { warnings } : {}), ...(timeoutTooShort ? { hostTimeoutMs, slowestWhispererMs: slowestMs } : {}) };
162
159
  }
163
160
  export function registerSafetyWhisperer(api, plugin, diagnostics) {
164
- const config = plugin.safetyWhisperer, typesafe = plugin.typesafe;
161
+ const config = plugin.safetyWhisperer, decisionModel = plugin.decisionModel;
165
162
  if (!config.enabled)
166
163
  return;
167
164
  const status = safetyStatus(api.config, plugin);
@@ -169,18 +166,21 @@ export function registerSafetyWhisperer(api, plugin, diagnostics) {
169
166
  api.logger.warn("unblock-memory safety_whisperer " + JSON.stringify({ event: "status", ...status }));
170
167
  }
171
168
  const sessions = new Map();
169
+ // Track every in-flight check (even without run/session identity) so teardown always aborts cleanly.
170
+ const activeControllers = new Map();
172
171
  let warnedMissingKey = false, warnedMissingIdentity = false;
173
172
  const warn = (fields) => api.logger.warn("unblock-memory safety_whisperer " + JSON.stringify(fields));
174
173
  const check = async (event, context, agentId, controller) => {
175
174
  const { signal } = controller;
176
- const record = (outcome) => diagnostics?.record(agentId, "safety", outcome);
175
+ const recordOutcome = (outcome) => diagnostics?.record(agentId, "safety", outcome);
177
176
  const turn = trustedTurn(context);
178
177
  let scenarios = [];
179
178
  const timer = setTimeout(() => controller.abort(new DOMException("Safety deadline", "TimeoutError")), config.timeoutMs);
179
+ activeControllers.set(controller, { sessionId: nonBlank(context.sessionId), sessionKey: nonBlank(context.sessionKey) });
180
180
  try {
181
181
  if (!turn.provider || !turn.accountId || !turn.senderId) {
182
182
  // Some runtimes omit sender identity: nobody can be approved and per-channel exclusions may not apply.
183
- record("missing_identity");
183
+ recordOutcome("missing_identity");
184
184
  if (!warnedMissingIdentity) {
185
185
  warn({ event: "missing_identity", agentId, provider: turn.provider ?? null, hasAccountId: Boolean(turn.accountId),
186
186
  hasSenderId: Boolean(turn.senderId), hasChannelId: Boolean(turn.channelId) });
@@ -188,7 +188,7 @@ export function registerSafetyWhisperer(api, plugin, diagnostics) {
188
188
  warnedMissingIdentity = true;
189
189
  }
190
190
  if (config.excludedChannels.some(channel => inChannel(channel, turn))) {
191
- record("excluded");
191
+ recordOutcome("excluded");
192
192
  return;
193
193
  }
194
194
  scenarios = config.scenarios.filter(scenario => scenario.enabled &&
@@ -196,51 +196,51 @@ export function registerSafetyWhisperer(api, plugin, diagnostics) {
196
196
  !scenario.excludedChannels.some(channel => inChannel(channel, turn)) &&
197
197
  !scenario.approvedRequestors.some(requestor => approved(requestor, turn)));
198
198
  if (!scenarios.length) {
199
- record("no_scenarios");
199
+ recordOutcome("no_scenarios");
200
200
  return;
201
201
  }
202
202
  const state = safetyConversation(event.prompt, event.messages, config.historyMessages, turn.senderId);
203
203
  if (!state.currentRequest) {
204
- record("empty_request");
204
+ recordOutcome("empty_request");
205
205
  return;
206
206
  }
207
- const apiKey = await abortable(resolveTypeSafeApiKey(typesafe), signal);
207
+ const apiKey = await abortable(resolveDecisionCredential(decisionModel), signal);
208
208
  if (!apiKey) {
209
- record(typesafe.enabled ? "missing_key" : "typesafe_disabled");
209
+ recordOutcome(decisionModel.enabled ? "missing_key" : "decision_disabled");
210
210
  if (!warnedMissingKey) {
211
- api.logger.warn(`unblock-memory safety whisperer could not check: ${typesafe.enabled ? "TypeSafe key unavailable" : "TypeSafe disabled"}`);
211
+ api.logger.warn(`unblock-memory safety whisperer could not check: ${decisionModel.enabled ? "decision model key unavailable" : "decision model disabled"}`);
212
212
  }
213
213
  warnedMissingKey = true;
214
214
  return;
215
215
  }
216
216
  warnedMissingKey = false;
217
- const probabilities = await abortable(judgeSafetyScenarios(apiKey, signal, state, scenarios), signal);
217
+ const probabilities = await abortable(judgeSafetyScenarios(apiKey, signal, state, scenarios, { endpoint: decisionModel.endpoint, model: decisionModel.model }), signal);
218
218
  const unanswered = probabilities.filter(probability => probability === undefined).length;
219
219
  const matched = scenarios.filter((scenario, index) => (probabilities[index] ?? -1) >= scenario.minProbability);
220
220
  if (!matched.length) {
221
221
  if (unanswered)
222
- throw new TypeSafeRequestError("Invalid safety response", "invalid_response");
223
- record("no_match");
222
+ throw new DecisionRequestError("Invalid safety response", "invalid_response");
223
+ recordOutcome("no_match");
224
224
  return;
225
225
  }
226
226
  // Keep confident matches even if another scenario's answer was unusable.
227
227
  if (unanswered) {
228
- record("partial_response");
228
+ recordOutcome("partial_response");
229
229
  warn({ event: "partial_response", agentId, runId: context.runId, unanswered, eligibleScenarios: scenarios.length });
230
230
  }
231
- record("flagged");
231
+ recordOutcome("flagged");
232
232
  for (const scenario of matched)
233
233
  diagnostics?.recordSafetyMatch(agentId, scenario.id);
234
234
  return safetyContext(matched.map(scenario => scenario.flaggedPrompt));
235
235
  }
236
236
  catch (error) {
237
237
  // Fail open by design, but never silently: "could not check" is recorded separately from "no match".
238
- const outcome = error instanceof SafetyInputError ? "input_too_large" : isTypeSafeTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed";
239
- record(outcome);
238
+ const outcome = error instanceof SafetyInputError ? "input_too_large" : isDecisionTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed";
239
+ recordOutcome(outcome);
240
240
  if (outcome !== "cancelled") {
241
241
  warn({ event: "check_failed", agentId, runId: context.runId, outcome, eligibleScenarios: scenarios.length,
242
- errorCode: error instanceof TypeSafeRequestError ? error.code : undefined,
243
- httpStatus: error instanceof TypeSafeRequestError ? error.status : undefined });
242
+ errorCode: error instanceof DecisionRequestError ? error.code : undefined,
243
+ httpStatus: error instanceof DecisionRequestError ? error.status : undefined });
244
244
  }
245
245
  // The requestor controls message size, so an oversized message gets every eligible prompt rather than none.
246
246
  if (outcome === "input_too_large")
@@ -249,6 +249,7 @@ export function registerSafetyWhisperer(api, plugin, diagnostics) {
249
249
  }
250
250
  finally {
251
251
  clearTimeout(timer);
252
+ activeControllers.delete(controller);
252
253
  }
253
254
  };
254
255
  const beforePrompt = async (event, context) => {
@@ -258,33 +259,49 @@ export function registerSafetyWhisperer(api, plugin, diagnostics) {
258
259
  const scope = nonBlank(context.sessionId) ?? nonBlank(context.sessionKey);
259
260
  const runs = scope ? sessions.get(scope) : undefined;
260
261
  const previous = runId ? runs?.get(runId) : undefined;
261
- if (previous)
262
+ if (previous && scope && runs) {
263
+ sessions.delete(scope);
264
+ sessions.set(scope, runs);
262
265
  return previous.result;
266
+ }
263
267
  const controller = new AbortController();
264
268
  const result = check(event, context, agentId, controller);
265
269
  // Every new human turn is checked; without a run identity the result is not reused.
266
270
  if (scope && runId) {
267
271
  const entry = runs ?? new Map();
268
272
  entry.set(runId, { controller, result });
269
- if (entry.size > RUNS_PER_SESSION)
270
- entry.delete(entry.keys().next().value);
273
+ if (entry.size > RUNS_PER_SESSION) {
274
+ const oldestRunId = entry.keys().next().value;
275
+ entry.get(oldestRunId)?.controller.abort();
276
+ entry.delete(oldestRunId);
277
+ }
271
278
  sessions.delete(scope);
272
279
  sessions.set(scope, entry);
273
- if (sessions.size > MAX_SESSIONS)
274
- sessions.delete(sessions.keys().next().value);
280
+ if (sessions.size > MAX_SESSIONS) {
281
+ const oldestScope = sessions.keys().next().value;
282
+ for (const run of sessions.get(oldestScope)?.values() ?? [])
283
+ run.controller.abort();
284
+ sessions.delete(oldestScope);
285
+ }
275
286
  }
276
287
  return result;
277
288
  };
278
289
  api.on("session_end", (event, context) => {
279
- for (const scope of [event.sessionId, event.sessionKey, context.sessionKey]) {
280
- if (!scope)
281
- continue;
290
+ const scopes = new Set([event.sessionId, event.sessionKey, context.sessionKey].filter((scope) => Boolean(scope)));
291
+ for (const scope of scopes) {
282
292
  for (const run of sessions.get(scope)?.values() ?? [])
283
293
  run.controller.abort();
284
294
  sessions.delete(scope);
285
295
  }
296
+ for (const [controller, identity] of activeControllers) {
297
+ if ((identity.sessionId && scopes.has(identity.sessionId)) || (identity.sessionKey && scopes.has(identity.sessionKey))) {
298
+ controller.abort();
299
+ }
300
+ }
286
301
  });
287
302
  api.on("gateway_stop", () => {
303
+ for (const controller of activeControllers.keys())
304
+ controller.abort();
288
305
  for (const runs of sessions.values())
289
306
  for (const run of runs.values())
290
307
  run.controller.abort();
@@ -9,6 +9,7 @@ type IndexedSession = SessionMetadata & {
9
9
  projectionHash: string;
10
10
  documentPath: string;
11
11
  projectorVersion: number;
12
+ projectionKey?: string;
12
13
  sourceFingerprint?: string;
13
14
  messages?: SessionMessageSpan[];
14
15
  };
@@ -19,6 +20,7 @@ export type SessionManifest = {
19
20
  projectionKey?: string;
20
21
  indexSignature?: string;
21
22
  ignoredSessions?: Record<string, string>;
23
+ failedSessions?: Record<string, string>;
22
24
  sessions: Record<string, IndexedSession>;
23
25
  };
24
26
  export type SessionSyncResult = {
@@ -29,7 +31,7 @@ export type SessionSyncResult = {
29
31
  skipped: number;
30
32
  failed: number;
31
33
  embedded: number;
32
- lastSuccessfulSyncAt: number;
34
+ lastSuccessfulSyncAt?: number;
33
35
  lastCheckedAt?: number;
34
36
  lastIndexedAt?: number;
35
37
  skipReason?: "no_changes" | "no_indexable_changes";