@unblocklabs/unblock-memory 0.12.3 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -18
- package/defaults.json +162 -0
- package/dist/src/analysis.js +1 -1
- package/dist/src/cluster-review.d.ts +2 -0
- package/dist/src/cluster-review.js +9 -8
- package/dist/src/config.d.ts +9 -6
- package/dist/src/config.js +59 -45
- package/dist/src/curation.d.ts +1 -1
- package/dist/src/decision-client.d.ts +45 -0
- package/dist/src/decision-client.js +87 -0
- package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
- package/dist/src/decision-ranking.js +155 -0
- package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
- package/dist/src/decision-review.js +193 -0
- package/dist/src/defaults.d.ts +8 -0
- package/dist/src/defaults.js +128 -0
- package/dist/src/diagnostics.d.ts +5 -5
- package/dist/src/emotion-baselines.d.ts +28 -3
- package/dist/src/emotion-baselines.js +312 -115
- package/dist/src/evidence-review.d.ts +22 -8
- package/dist/src/evidence-review.js +11 -8
- package/dist/src/extraction-chunk.d.ts +3 -0
- package/dist/src/extraction-chunk.js +25 -6
- package/dist/src/extraction-config.js +4 -2
- package/dist/src/extraction-model.d.ts +25 -17
- package/dist/src/extraction-model.js +232 -104
- package/dist/src/extraction-runtime.d.ts +3 -1
- package/dist/src/extraction-runtime.js +48 -20
- package/dist/src/extraction-source.d.ts +1 -1
- package/dist/src/extraction-source.js +21 -12
- package/dist/src/extraction-store.d.ts +29 -3
- package/dist/src/extraction-store.js +149 -25
- package/dist/src/extraction-worker.d.ts +3 -3
- package/dist/src/extraction-worker.js +250 -95
- package/dist/src/inside-out-runtime.js +43 -30
- package/dist/src/inside-out-sources.js +2 -1
- package/dist/src/inside-out-store.d.ts +2 -2
- package/dist/src/inside-out-store.js +111 -69
- package/dist/src/inside-out.d.ts +10 -9
- package/dist/src/inside-out.js +194 -106
- package/dist/src/manager.d.ts +22 -9
- package/dist/src/manager.js +279 -172
- package/dist/src/memory-database.js +3 -2
- package/dist/src/memory-passage.d.ts +2 -2
- package/dist/src/memory-passage.js +3 -2
- package/dist/src/memory-search.d.ts +4 -2
- package/dist/src/memory-search.js +5 -5
- package/dist/src/memory-whisperer.d.ts +1 -1
- package/dist/src/memory-whisperer.js +195 -129
- package/dist/src/my-turn.d.ts +1 -1
- package/dist/src/my-turn.js +90 -70
- package/dist/src/people-background.d.ts +5 -1
- package/dist/src/people-background.js +31 -7
- package/dist/src/people-dossier-review.d.ts +20 -8
- package/dist/src/people-dossier-review.js +15 -11
- package/dist/src/people-hooks.js +127 -22
- package/dist/src/people-learning-cron.d.ts +1 -1
- package/dist/src/people-learning-cron.js +107 -57
- package/dist/src/people-learning-inventory.d.ts +1 -0
- package/dist/src/people-learning-inventory.js +283 -172
- package/dist/src/people-learning-prompt.js +1 -1
- package/dist/src/people-learning-runtime.d.ts +1 -1
- package/dist/src/people-learning-runtime.js +360 -203
- package/dist/src/people-learning-store.d.ts +27 -4
- package/dist/src/people-learning-store.js +312 -96
- package/dist/src/people-primer-tool.js +13 -10
- package/dist/src/people-primer.d.ts +3 -1
- package/dist/src/people-primer.js +66 -48
- package/dist/src/people-store.d.ts +18 -21
- package/dist/src/people-store.js +188 -64
- package/dist/src/people-tools.js +138 -93
- package/dist/src/plugin.js +19 -18
- package/dist/src/quality-audit.d.ts +2 -0
- package/dist/src/quality-audit.js +11 -9
- package/dist/src/quality-triage.js +4 -3
- package/dist/src/query-generator.js +5 -2
- package/dist/src/response-audit.d.ts +1 -1
- package/dist/src/response-audit.js +78 -44
- package/dist/src/response-config.js +3 -1
- package/dist/src/response-episodes.d.ts +1 -1
- package/dist/src/response-episodes.js +15 -19
- package/dist/src/response-identity.js +2 -1
- package/dist/src/response-judge.d.ts +151 -145
- package/dist/src/response-judge.js +535 -204
- package/dist/src/response-memory.js +2 -1
- package/dist/src/response-outcome.js +9 -8
- package/dist/src/response-reviews.d.ts +29 -1
- package/dist/src/response-reviews.js +113 -15
- package/dist/src/response-runtime.js +10 -9
- package/dist/src/response-stages.d.ts +50 -53
- package/dist/src/response-stages.js +10 -4
- package/dist/src/response-store.d.ts +7 -6
- package/dist/src/response-store.js +335 -212
- package/dist/src/review-tools.d.ts +8 -2
- package/dist/src/review-tools.js +22 -21
- package/dist/src/runtime.d.ts +7 -4
- package/dist/src/runtime.js +625 -98
- package/dist/src/safety-config.js +3 -2
- package/dist/src/safety-whisperer.d.ts +2 -2
- package/dist/src/safety-whisperer.js +90 -73
- package/dist/src/session-sync.d.ts +3 -1
- package/dist/src/session-sync.js +202 -96
- package/dist/src/skill-whisperer.d.ts +2 -2
- package/dist/src/skill-whisperer.js +55 -32
- package/dist/src/slack-directory.js +3 -2
- package/dist/src/training-gate.d.ts +9 -22
- package/dist/src/training-gate.js +34 -36
- package/dist/src/training-input.js +4 -3
- package/dist/src/training-judge.d.ts +9 -16
- package/dist/src/training-judge.js +6 -5
- package/dist/src/training-models.d.ts +1 -1
- package/dist/src/training-models.js +9 -7
- package/dist/src/training-queries.d.ts +14 -9
- package/dist/src/training-queries.js +374 -231
- package/dist/src/training-retrieval.d.ts +17 -27
- package/dist/src/training-retrieval.js +186 -139
- package/dist/src/training-runtime.d.ts +3 -0
- package/dist/src/training-runtime.js +76 -18
- package/dist/src/training-store.d.ts +18 -3
- package/dist/src/training-store.js +141 -52
- package/dist/src/training.js +9 -11
- package/dist/src/whisperer-context.d.ts +13 -0
- package/dist/src/whisperer-context.js +22 -1
- package/docs/configuration.md +83 -64
- package/docs/extraction.md +26 -35
- package/docs/memory-training.md +7 -6
- package/docs/people-learning.md +2 -2
- package/docs/peoplesql.md +6 -6
- package/docs/response-audit.md +10 -8
- package/docs/retrieval.md +43 -47
- package/openclaw.plugin.json +76 -75
- package/package.json +5 -2
- package/skills/memory-curator/SKILL.md +1 -1
- package/skills/people-whisperer/SKILL.md +1 -1
- package/dist/src/typesafe-client.d.ts +0 -30
- package/dist/src/typesafe-client.js +0 -92
- package/dist/src/typesafe-review.js +0 -154
- package/dist/src/typesafe.js +0 -147
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
1
2
|
import { normalizeAgentIdStrict } from "openclaw/plugin-sdk/routing";
|
|
2
|
-
const DEFAULT_SAFETY_MIN_PROBABILITY =
|
|
3
|
+
const DEFAULT_SAFETY_MIN_PROBABILITY = DEFAULTS.safetyWhisperer.defaultMinProbability;
|
|
3
4
|
const MAX_SCENARIOS = 20;
|
|
4
5
|
const MAX_TEXT_CHARS = 2000;
|
|
5
6
|
const MAX_ENTRIES = 500;
|
|
@@ -86,7 +87,7 @@ function scenario(value, index) {
|
|
|
86
87
|
};
|
|
87
88
|
}
|
|
88
89
|
export function resolveSafetyWhisperer(value) {
|
|
89
|
-
const defaults = { enabled: false, historyMessages:
|
|
90
|
+
const defaults = { enabled: false, historyMessages: DEFAULTS.safetyWhisperer.defaultHistoryMessages, timeoutMs: DEFAULTS.safetyWhisperer.defaultTimeoutMs, excludedChannels: [], scenarios: [] };
|
|
90
91
|
if (value === undefined)
|
|
91
92
|
return defaults;
|
|
92
93
|
const config = record(value, "safetyWhisperer");
|
|
@@ -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" | "
|
|
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?:
|
|
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,14 +1,12 @@
|
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
1
2
|
import { Value } from "typebox/value";
|
|
2
|
-
import {
|
|
3
|
-
import { messageText } from "./whisperer-context.js";
|
|
3
|
+
import { estimateDecisionTokens, isDecisionTimeout, requestDecision, resolveDecisionCredential, NOUL_SCHEMA, DecisionRequestError } from "./decision-client.js";
|
|
4
|
+
import { messageText, takeRecentWithinTokens } from "./whisperer-context.js";
|
|
4
5
|
import { CONVERSATION_INFO, conversationEnvelope, conversationUserText } from "./response-text.js";
|
|
5
6
|
import { SKILL_WHISPERER_TIMEOUT_MS } from "./skill-whisperer.js";
|
|
6
7
|
import { abortable } from "./abortable.js";
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
const MAX_STATE_TOKENS = 24_000;
|
|
10
|
-
const MAX_SESSIONS = 1000;
|
|
11
|
-
const RUNS_PER_SESSION = 4;
|
|
8
|
+
import { nonBlank, record } from "./guards.js";
|
|
9
|
+
const { stateMaxTokens: MAX_STATE_TOKENS, maxTrackedSessions: MAX_SESSIONS, maxRunsPerSession: RUNS_PER_SESSION } = DEFAULTS.safetyWhisperer;
|
|
12
10
|
class SafetyInputError extends Error {
|
|
13
11
|
}
|
|
14
12
|
/** Thread replies and forum topics belong to their parent conversation (`C1:thread:1712.01`, `-100:topic:5`). */
|
|
@@ -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
|
|
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 ??
|
|
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
|
-
|
|
59
|
-
if (
|
|
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
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
|
119
|
-
const 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(
|
|
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
|
|
143
|
-
const
|
|
144
|
-
const
|
|
145
|
-
const
|
|
146
|
-
const
|
|
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 =
|
|
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 =
|
|
156
|
-
const
|
|
157
|
-
|
|
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,
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
204
|
+
recordOutcome("empty_request");
|
|
205
205
|
return;
|
|
206
206
|
}
|
|
207
|
-
const apiKey = await abortable(
|
|
207
|
+
const apiKey = await abortable(resolveDecisionCredential(decisionModel), signal);
|
|
208
208
|
if (!apiKey) {
|
|
209
|
-
|
|
209
|
+
recordOutcome(decisionModel.enabled ? "missing_key" : "decision_disabled");
|
|
210
210
|
if (!warnedMissingKey) {
|
|
211
|
-
api.logger.warn(`unblock-memory safety whisperer could not check: ${
|
|
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
|
|
223
|
-
|
|
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
|
-
|
|
228
|
+
recordOutcome("partial_response");
|
|
229
229
|
warn({ event: "partial_response", agentId, runId: context.runId, unanswered, eligibleScenarios: scenarios.length });
|
|
230
230
|
}
|
|
231
|
-
|
|
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" :
|
|
239
|
-
|
|
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
|
|
243
|
-
httpStatus: error instanceof
|
|
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.
|
|
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.
|
|
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
|
-
|
|
280
|
-
|
|
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
|
|
34
|
+
lastSuccessfulSyncAt?: number;
|
|
33
35
|
lastCheckedAt?: number;
|
|
34
36
|
lastIndexedAt?: number;
|
|
35
37
|
skipReason?: "no_changes" | "no_indexable_changes";
|