@unblocklabs/unblock-memory 0.12.1 → 0.12.3

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.
@@ -135,32 +135,80 @@ function reviewCohort(manifest) {
135
135
  function analysisBasis(config, manifest) {
136
136
  return jsonHash([responseCohort(config.responseAudit), config.responseAudit.lookbackDays, manifest]);
137
137
  }
138
+ const STARTUP_RETRY_DELAY_MS = 5_000;
139
+ const RETRY_DELAY_MS = 60_000;
140
+ const MAX_QUIET_STARTUP_RETRIES = 8;
141
+ function isStartupPrepError(error) {
142
+ return /not completed startup inspection and preparation/i.test(String(error));
143
+ }
138
144
  export function registerPeopleLearning(api, initial, stores) {
139
145
  let cfg = api.config, config = initial, stateRoot = resolveStateDir(), live = false;
140
- let jobs = [], reconciliation;
146
+ let jobs = [], reconciliation, followUp;
147
+ let rerun = false, startupRetries = 0;
141
148
  let getCron;
142
149
  let generation = 0;
143
150
  let scheduler;
151
+ let retryTask;
152
+ const clearRetry = () => { retryTask?.cancel?.(); retryTask = undefined; };
153
+ const scheduleRetry = (delayMs) => {
154
+ clearRetry();
155
+ if (!live || !scheduler || scheduler.signal?.aborted)
156
+ return;
157
+ try {
158
+ retryTask = scheduler.schedule({ id: "people-learning-reconcile", delayMs, run: reconcile });
159
+ }
160
+ catch {
161
+ // Host scheduler can close concurrently during gateway shutdown or reload.
162
+ }
163
+ };
144
164
  const reconcile = () => {
145
165
  if (!live)
146
166
  return Promise.resolve();
147
- if (reconciliation)
148
- return reconciliation.then(() => live ? reconcile() : undefined);
167
+ if (reconciliation) {
168
+ rerun = true;
169
+ if (!followUp) {
170
+ const next = () => {
171
+ followUp = undefined;
172
+ if (!live || !rerun)
173
+ return;
174
+ rerun = false;
175
+ return reconcile();
176
+ };
177
+ followUp = reconciliation.then(next, next);
178
+ }
179
+ return followUp;
180
+ }
149
181
  const cron = getCron?.();
150
182
  if (!cron) {
151
183
  api.logger.warn("unblock-memory people learning incomplete: this host does not expose service getCron; upgrade the host");
152
184
  return Promise.resolve();
153
185
  }
186
+ rerun = false;
154
187
  const version = generation;
155
188
  const learning = config.people.enabled && config.people.whisperer.enabled ? config.people.learning
156
189
  : { ...config.people.learning, enabled: false, agents: {} };
157
190
  reconciliation = reconcilePeopleLearning(cron, cfg, learning, () => live && version === generation)
158
- .then(result => { if (live && version === generation)
159
- jobs = result; })
191
+ .then(result => {
192
+ if (live && version === generation) {
193
+ jobs = result;
194
+ startupRetries = 0;
195
+ clearRetry();
196
+ }
197
+ })
160
198
  .catch(error => {
199
+ if (!live || version !== generation)
200
+ return;
201
+ rerun = false;
202
+ if (isStartupPrepError(error) && scheduler && !scheduler.signal?.aborted && startupRetries < MAX_QUIET_STARTUP_RETRIES) {
203
+ startupRetries++;
204
+ if (startupRetries === 1) {
205
+ api.logger.info?.("unblock-memory people learning scheduling deferred until agent startup preparation completes");
206
+ }
207
+ scheduleRetry(STARTUP_RETRY_DELAY_MS);
208
+ return;
209
+ }
161
210
  api.logger.warn(`unblock-memory people learning scheduling incomplete: ${String(error)}`);
162
- if (live)
163
- scheduler?.schedule({ id: "people-learning-reconcile", delayMs: 60_000, run: reconcile });
211
+ scheduleRetry(RETRY_DELAY_MS);
164
212
  })
165
213
  .finally(() => { reconciliation = undefined; });
166
214
  return reconciliation;
@@ -173,21 +221,35 @@ export function registerPeopleLearning(api, initial, stores) {
173
221
  stateRoot = context.stateDir;
174
222
  const entry = cfg.plugins?.entries?.["unblock-memory"];
175
223
  config = resolveConfig(entry ? entry.config : api.pluginConfig);
224
+ clearRetry();
176
225
  live = true;
177
226
  generation++;
227
+ startupRetries = 0;
228
+ rerun = false;
178
229
  getCron = context.getCron?.bind(context);
179
230
  scheduler = context.scheduler;
180
231
  void reconcile();
181
232
  },
182
- async stop() { live = false; generation++; await reconciliation; jobs = []; },
233
+ async stop() {
234
+ live = false;
235
+ const stopVersion = ++generation;
236
+ rerun = false;
237
+ startupRetries = 0;
238
+ clearRetry();
239
+ await reconciliation?.catch(() => { });
240
+ await followUp?.catch(() => { });
241
+ if (stopVersion === generation)
242
+ jobs = [];
243
+ },
183
244
  });
184
245
  api.on("gateway_start", () => reconcile());
185
246
  api.on("cron_reconciled", (_event, context) => {
186
247
  if (context.config) {
248
+ const entry = context.config.plugins?.entries?.["unblock-memory"];
249
+ const nextConfig = resolveConfig(entry ? entry.config : api.pluginConfig);
187
250
  generation++;
188
251
  cfg = context.config;
189
- const entry = cfg.plugins?.entries?.["unblock-memory"];
190
- config = resolveConfig(entry ? entry.config : api.pluginConfig);
252
+ config = nextConfig;
191
253
  }
192
254
  return reconcile();
193
255
  });
@@ -138,7 +138,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
138
138
  finally {
139
139
  measurement.elapsedMs = performance.now() - started;
140
140
  measurement.setupMs ??= measurement.elapsedMs;
141
- // Manual search is sequential. Whisperer stages overlap and cannot use this subtraction.
141
+ // Residual overhead for manual search; whisperer tracks stage timings separately without a whole-run residual.
142
142
  measurement.otherMs = Math.max(0, measurement.elapsedMs - measurement.setupMs -
143
143
  (measurement.retrievalMs ?? 0) - (measurement.candidatePrepMs ?? 0) - (measurement.judgeMs ?? 0));
144
144
  if (signal?.aborted)
@@ -1,11 +1,15 @@
1
1
  import type { UnblockMemoryConfig } from "./config.js";
2
2
  import { type QueryConversation, type QueryPair } from "./query-contract.js";
3
3
  /** Preserve whole visible messages and the complete current request, never tool/thinking text. */
4
- export declare function queryConversation(prompt: string, messages: readonly unknown[]): QueryConversation;
4
+ export declare function queryConversation(prompt: string, messages: readonly unknown[], currentUserMessage?: string): QueryConversation;
5
+ /** Deterministic query pair used when the resident query API fails or times out. */
6
+ export declare function fallbackQueries(conversation: QueryConversation): QueryPair;
7
+ /** Bound conversation context repeated across automatic passage usefulness judgments. */
8
+ export declare function compactJudgeConversation(conversation: QueryConversation): QueryConversation;
5
9
  export declare class QueryApiError extends Error {
6
- readonly code: "credentials" | "http_error" | "invalid_response" | "unavailable";
10
+ readonly code: "credentials" | "http_error" | "invalid_response" | "timeout" | "unavailable";
7
11
  readonly status?: number | undefined;
8
- constructor(code: "credentials" | "http_error" | "invalid_response" | "unavailable", status?: number | undefined);
12
+ constructor(code: "credentials" | "http_error" | "invalid_response" | "timeout" | "unavailable", status?: number | undefined);
9
13
  }
10
14
  /** The host owns model warmth/lifecycle; the plugin only sends bounded, cancellable requests. */
11
15
  export declare class ApiQueryGenerator {
@@ -1,13 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
- import { abortable } from "./abortable.js";
3
+ import { abortable, abortedByTimeout } from "./abortable.js";
4
4
  import { messageText } from "./whisperer-context.js";
5
- import { conversationUserText } from "./response-text.js";
5
+ import { CONVERSATION_INFO, queryUserText } from "./response-text.js";
6
6
  import { parseQueryPair, prepareQueryConversation } from "./query-contract.js";
7
- import { record } from "./guards.js";
7
+ import { nonBlank, record } from "./guards.js";
8
8
  /** Preserve whole visible messages and the complete current request, never tool/thinking text. */
9
- export function queryConversation(prompt, messages) {
10
- const currentRequest = conversationUserText(prompt)?.text ?? "";
9
+ export function queryConversation(prompt, messages, currentUserMessage) {
10
+ const currentRequest = queryUserText(currentUserMessage !== undefined ? currentUserMessage : prompt) ?? "";
11
11
  const visible = [];
12
12
  const assistantTexts = new Map();
13
13
  for (const item of messages) {
@@ -31,11 +31,17 @@ export function queryConversation(prompt, messages) {
31
31
  (mirror && record(message.openclawDeliveryMirror)?.kind === "channel-final-suppressed")))
32
32
  continue;
33
33
  const text = messageText(message);
34
- const raw = text?.role === "user" && typeof meta?.upstreamUserText === "string" ? meta.upstreamUserText : text?.text;
35
- const content = text?.role === "user" && raw ? conversationUserText(raw, meta?.senderId ?? message.senderId)?.text : raw;
34
+ const sender = nonBlank(meta?.senderId) ?? nonBlank(message.senderId);
35
+ const upstream = typeof meta?.upstreamUserText === "string" ? meta.upstreamUserText : undefined;
36
+ const content = text?.role === "user"
37
+ ? (upstream ? queryUserText(upstream, sender) : undefined) ??
38
+ // Fall back to canonical message.content only when upstreamUserText is absent or has a decorated non-envelope prefix,
39
+ // never to bypass a rejected Conversation info envelope.
40
+ (upstream && CONVERSATION_INFO.test(upstream.trim()) ? undefined : (text.text ? queryUserText(text.text, sender) : undefined))
41
+ : text?.text;
36
42
  if (message.role === "user") {
37
43
  assistantTexts.clear();
38
- if (!content || /^(?:\[OpenClaw heartbeat poll\]|\[Queued messages while agent was busy\]|\[Subagent Context\]|<relevant-memories>)/.test(content)) {
44
+ if (!content || /^(?:\[cron:|\[OpenClaw heartbeat poll\]|\[Inter-session message\]|\[Queued messages while agent was busy\]|\[Subagent Context\]|<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>|<relevant-memories>|<unblock_memory>|<conversation_context>)/.test(content)) {
39
45
  visible.length = 0;
40
46
  continue;
41
47
  }
@@ -50,10 +56,139 @@ export function queryConversation(prompt, messages) {
50
56
  }
51
57
  visible.push({ role: text.role, content });
52
58
  }
53
- if (visible.at(-1)?.role === "user" && visible.at(-1)?.content === currentRequest)
59
+ const last = visible.at(-1);
60
+ if (last?.role === "user" && last.content.replaceAll("\r\n", "\n") === currentRequest.replaceAll("\r\n", "\n"))
54
61
  visible.pop();
55
62
  return prepareQueryConversation(visible, currentRequest).conversation;
56
63
  }
64
+ const FALLBACK_STOP_WORDS = new Set(("a about all also am an and any are as at be been before being but by can could did do does doing done " +
65
+ "for from get got had has have having he her here hers him his how i if in into is it its just know " +
66
+ "like make may me more most my no not now of on one only or other our out over please said say see " +
67
+ "she should so some still such than that the their them then there these they think this those through " +
68
+ "to too under up very was we were what whats when where which who why will with would you your").split(" "));
69
+ const MAX_FALLBACK_LEX_TERMS = 12;
70
+ const MAX_FALLBACK_TERM_CHARS = 64;
71
+ const MAX_FALLBACK_LEX_CHARS = 256;
72
+ const MAX_FALLBACK_VEC_CHARS = 450;
73
+ const MAX_JUDGE_HISTORY_MESSAGES = 2;
74
+ const MAX_JUDGE_CONVERSATION_CHARS = 1_500;
75
+ const MIN_COMPACT_HISTORY_CHARS = 80;
76
+ function sliceHeadSafe(text, maxChars) {
77
+ if (maxChars <= 0)
78
+ return "";
79
+ if (text.length <= maxChars)
80
+ return text;
81
+ let end = maxChars;
82
+ const last = text.charCodeAt(end - 1);
83
+ if (last >= 0xd800 && last <= 0xdbff)
84
+ end--;
85
+ return text.slice(0, end);
86
+ }
87
+ function sliceTailSafe(text, maxChars) {
88
+ if (maxChars <= 0)
89
+ return "";
90
+ if (text.length <= maxChars)
91
+ return text;
92
+ let start = text.length - maxChars;
93
+ const first = text.charCodeAt(start);
94
+ if (first >= 0xdc00 && first <= 0xdfff)
95
+ start++;
96
+ return text.slice(start);
97
+ }
98
+ function extractFallbackTerms(text) {
99
+ const seen = new Set();
100
+ const terms = [];
101
+ for (const token of text.match(/[\p{L}\p{N}_]+/gu) ?? []) {
102
+ const lower = token.toLowerCase();
103
+ if (token.length > MAX_FALLBACK_TERM_CHARS || (lower.length === 1 && /^[a-z]$/u.test(lower)) ||
104
+ seen.has(lower) || FALLBACK_STOP_WORDS.has(lower))
105
+ continue;
106
+ seen.add(lower);
107
+ terms.push(token);
108
+ if (terms.length >= MAX_FALLBACK_LEX_TERMS)
109
+ break;
110
+ }
111
+ return terms;
112
+ }
113
+ function joinBoundedTerms(tokens) {
114
+ const parts = [];
115
+ let length = 0;
116
+ for (const token of tokens) {
117
+ const bounded = sliceHeadSafe(token, MAX_FALLBACK_TERM_CHARS);
118
+ if (!bounded)
119
+ continue;
120
+ const added = bounded.length + (parts.length ? 1 : 0);
121
+ if (length + added > MAX_FALLBACK_LEX_CHARS)
122
+ break;
123
+ parts.push(bounded);
124
+ length += added;
125
+ }
126
+ return parts.join(" ");
127
+ }
128
+ /** Deterministic query pair used when the resident query API fails or times out. */
129
+ export function fallbackQueries(conversation) {
130
+ const request = conversation.currentRequest.trim();
131
+ if (!request)
132
+ throw new Error("Missing or unparseable current request");
133
+ const requestTerms = extractFallbackTerms(request);
134
+ const terms = [...requestTerms];
135
+ const seen = new Set(terms.map(term => term.toLowerCase()));
136
+ const recentUsers = conversation.history.filter(message => message.role === "user").slice(-2);
137
+ if (terms.length < 4) {
138
+ for (let index = recentUsers.length - 1; index >= 0 && terms.length < MAX_FALLBACK_LEX_TERMS; index--) {
139
+ for (const token of extractFallbackTerms(recentUsers[index].content)) {
140
+ const lower = token.toLowerCase();
141
+ if (seen.has(lower))
142
+ continue;
143
+ seen.add(lower);
144
+ terms.push(token);
145
+ if (terms.length >= MAX_FALLBACK_LEX_TERMS)
146
+ break;
147
+ }
148
+ }
149
+ }
150
+ const rawTokens = [...new Set((request.match(/[\p{L}\p{N}_]+/gu) ?? [])
151
+ .map(token => sliceHeadSafe(token, MAX_FALLBACK_TERM_CHARS).toLowerCase())
152
+ .filter(Boolean))].slice(0, MAX_FALLBACK_LEX_TERMS);
153
+ const lex = (joinBoundedTerms(terms) || joinBoundedTerms(rawTokens) || sliceHeadSafe(request, MAX_FALLBACK_LEX_CHARS)).trim();
154
+ const vecSource = requestTerms.length < 4 && recentUsers.length
155
+ ? `${recentUsers.at(-1).content.trim()}\n${request}`
156
+ : request;
157
+ const vec = (vecSource.length <= MAX_FALLBACK_VEC_CHARS
158
+ ? vecSource
159
+ : request.length >= MAX_FALLBACK_VEC_CHARS
160
+ ? sliceHeadSafe(request, MAX_FALLBACK_VEC_CHARS)
161
+ : sliceTailSafe(vecSource, MAX_FALLBACK_VEC_CHARS)).trim();
162
+ return { lex, vec };
163
+ }
164
+ function clampHeadTail(text, maxChars) {
165
+ if (text.length <= maxChars)
166
+ return text;
167
+ const ellipsis = "\n…\n";
168
+ const half = Math.floor((maxChars - ellipsis.length) / 2);
169
+ return `${sliceHeadSafe(text, half).trimEnd()}${ellipsis}${sliceTailSafe(text, half).trimStart()}`;
170
+ }
171
+ /** Bound conversation context repeated across automatic passage usefulness judgments. */
172
+ export function compactJudgeConversation(conversation) {
173
+ const currentRequest = clampHeadTail(conversation.currentRequest, MAX_JUDGE_CONVERSATION_CHARS);
174
+ let remaining = MAX_JUDGE_CONVERSATION_CHARS - currentRequest.length;
175
+ const history = [];
176
+ for (let index = conversation.history.length - 1; index >= 0 && history.length < MAX_JUDGE_HISTORY_MESSAGES && remaining > 0; index--) {
177
+ const message = conversation.history[index];
178
+ if (message.content.length <= remaining) {
179
+ history.unshift(message);
180
+ remaining -= message.content.length;
181
+ }
182
+ else if (remaining >= MIN_COMPACT_HISTORY_CHARS) {
183
+ history.unshift({ role: message.role, content: clampHeadTail(message.content, remaining) });
184
+ remaining = 0;
185
+ }
186
+ else {
187
+ break;
188
+ }
189
+ }
190
+ return { history, currentRequest };
191
+ }
57
192
  export class QueryApiError extends Error {
58
193
  code;
59
194
  status;
@@ -64,6 +199,11 @@ export class QueryApiError extends Error {
64
199
  this.name = "QueryApiError";
65
200
  }
66
201
  }
202
+ function throwIfQueryAborted(signal) {
203
+ if (abortedByTimeout(signal))
204
+ throw new QueryApiError("timeout");
205
+ signal.throwIfAborted();
206
+ }
67
207
  /** The host owns model warmth/lifecycle; the plugin only sends bounded, cancellable requests. */
68
208
  export class ApiQueryGenerator {
69
209
  config;
@@ -71,30 +211,34 @@ export class ApiQueryGenerator {
71
211
  this.config = config;
72
212
  }
73
213
  async generate(conversation, signal) {
74
- signal = AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
75
- signal.throwIfAborted();
214
+ const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
215
+ throwIfQueryAborted(requestSignal);
76
216
  if (!this.config.apiKeyFile)
77
217
  throw new QueryApiError("credentials");
78
218
  let token;
79
219
  try {
80
- token = (await readFile(this.config.apiKeyFile, { encoding: "utf8", signal })).trim();
220
+ token = (await readFile(this.config.apiKeyFile, { encoding: "utf8", signal: requestSignal })).trim();
81
221
  }
82
222
  catch {
223
+ if (abortedByTimeout(requestSignal))
224
+ throw new QueryApiError("timeout");
83
225
  throw new QueryApiError("credentials");
84
226
  }
85
227
  if (!token || /\s/u.test(token))
86
228
  throw new QueryApiError("credentials");
87
- signal.throwIfAborted();
229
+ throwIfQueryAborted(requestSignal);
88
230
  const id = randomUUID();
89
231
  let response;
90
232
  try {
91
233
  response = await fetch(`${this.config.endpoint}/generate`, {
92
- method: "POST", redirect: "error", signal,
234
+ method: "POST", redirect: "error", signal: requestSignal,
93
235
  headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
94
236
  body: JSON.stringify({ id, conversation }),
95
237
  });
96
238
  }
97
239
  catch {
240
+ if (abortedByTimeout(requestSignal))
241
+ throw new QueryApiError("timeout");
98
242
  throw new QueryApiError("unavailable");
99
243
  }
100
244
  if (!response.ok) {
@@ -109,7 +253,7 @@ export class ApiQueryGenerator {
109
253
  const chunks = [];
110
254
  let size = 0;
111
255
  for (;;) {
112
- const { done, value } = await abortable(reader.read(), signal);
256
+ const { done, value } = await abortable(reader.read(), requestSignal);
113
257
  if (done)
114
258
  break;
115
259
  size += value.byteLength;
@@ -117,7 +261,7 @@ export class ApiQueryGenerator {
117
261
  throw new QueryApiError("invalid_response");
118
262
  chunks.push(value);
119
263
  }
120
- signal.throwIfAborted();
264
+ throwIfQueryAborted(requestSignal);
121
265
  const envelope = record(JSON.parse(Buffer.concat(chunks).toString("utf8")));
122
266
  const result = record(envelope?.response);
123
267
  if (result?.id !== id || typeof result.text !== "string" || result.error !== undefined) {
@@ -125,7 +269,11 @@ export class ApiQueryGenerator {
125
269
  }
126
270
  return parseQueryPair(JSON.parse(result.text));
127
271
  }
128
- catch {
272
+ catch (error) {
273
+ if (error instanceof QueryApiError)
274
+ throw error;
275
+ if (abortedByTimeout(requestSignal))
276
+ throw new QueryApiError("timeout");
129
277
  throw new QueryApiError("invalid_response");
130
278
  }
131
279
  finally {
@@ -4,6 +4,8 @@ export declare function conversationUserText(raw: string, sender?: unknown): {
4
4
  text: string;
5
5
  contextLimited: boolean;
6
6
  } | undefined;
7
+ /** Unwrap human text for recall query generation, including non-Slack OpenClaw inbound envelopes. */
8
+ export declare function queryUserText(raw: string, sender?: unknown): string | undefined;
7
9
  /** Like conversationUserText, plus the untrusted inbound context (thread starter, reply target,
8
10
  * chat history) that a recognized envelope carries before the current message. */
9
11
  export declare function conversationEnvelope(raw: string, sender?: unknown): {