@unblocklabs/unblock-memory 0.10.1 → 0.10.2

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 (69) hide show
  1. package/dist/src/abortable.d.ts +2 -0
  2. package/dist/src/abortable.js +4 -0
  3. package/dist/src/agent-paths.d.ts +5 -0
  4. package/dist/src/agent-paths.js +10 -0
  5. package/dist/src/analysis.js +13 -18
  6. package/dist/src/cluster-review.js +9 -7
  7. package/dist/src/config.js +2 -2
  8. package/dist/src/curation.js +3 -10
  9. package/dist/src/emotion-baselines.d.ts +0 -2
  10. package/dist/src/emotion-baselines.js +18 -39
  11. package/dist/src/evidence-review.js +2 -1
  12. package/dist/src/extraction-chunk.js +3 -4
  13. package/dist/src/extraction-index.d.ts +2 -0
  14. package/dist/src/extraction-index.js +4 -2
  15. package/dist/src/extraction-runtime.js +3 -3
  16. package/dist/src/extraction-store.js +7 -19
  17. package/dist/src/extraction-worker.js +3 -2
  18. package/dist/src/guards.d.ts +6 -0
  19. package/dist/src/guards.js +12 -0
  20. package/dist/src/inside-out-runtime.js +4 -3
  21. package/dist/src/inside-out-store.js +4 -10
  22. package/dist/src/inside-out.js +5 -3
  23. package/dist/src/json-hash.d.ts +2 -0
  24. package/dist/src/json-hash.js +6 -0
  25. package/dist/src/manager.js +62 -91
  26. package/dist/src/memory-database.d.ts +3 -0
  27. package/dist/src/memory-database.js +18 -1
  28. package/dist/src/people-hooks.js +3 -6
  29. package/dist/src/people-primer-tool.js +0 -2
  30. package/dist/src/people-primer.js +3 -6
  31. package/dist/src/people-store.d.ts +2 -1
  32. package/dist/src/people-store.js +29 -82
  33. package/dist/src/people-tools.js +4 -5
  34. package/dist/src/plugin.js +15 -13
  35. package/dist/src/quality-audit.js +2 -2
  36. package/dist/src/query-generator.js +1 -1
  37. package/dist/src/response-audit.js +7 -8
  38. package/dist/src/response-episodes.js +5 -8
  39. package/dist/src/response-judge.js +2 -3
  40. package/dist/src/response-reviews.js +8 -18
  41. package/dist/src/response-runtime.js +4 -3
  42. package/dist/src/response-stages.js +4 -4
  43. package/dist/src/response-store.js +15 -44
  44. package/dist/src/response-text.d.ts +1 -0
  45. package/dist/src/response-text.js +6 -4
  46. package/dist/src/runtime.js +9 -8
  47. package/dist/src/safety-whisperer.js +4 -12
  48. package/dist/src/session-projector.js +7 -14
  49. package/dist/src/session-sync.d.ts +1 -0
  50. package/dist/src/session-sync.js +13 -17
  51. package/dist/src/skill-whisperer.js +3 -9
  52. package/dist/src/slack-directory.js +1 -5
  53. package/dist/src/sources.js +17 -37
  54. package/dist/src/tool-context.d.ts +2 -0
  55. package/dist/src/tool-context.js +5 -1
  56. package/dist/src/training-input.d.ts +0 -1
  57. package/dist/src/training-input.js +3 -6
  58. package/dist/src/training-queries.d.ts +1 -1
  59. package/dist/src/training-queries.js +9 -8
  60. package/dist/src/training-retrieval.js +2 -2
  61. package/dist/src/training-runtime.js +3 -3
  62. package/dist/src/training-store.js +14 -25
  63. package/dist/src/typesafe-client.d.ts +8 -0
  64. package/dist/src/typesafe-client.js +7 -1
  65. package/dist/src/typesafe-review.d.ts +1 -1
  66. package/dist/src/typesafe-review.js +1 -3
  67. package/dist/src/typesafe.js +4 -7
  68. package/openclaw.plugin.json +1 -1
  69. package/package.json +1 -1
@@ -1,20 +1,21 @@
1
1
  import { hasMemoryTable, MEMORY_DATABASE } from "./memory-database.js";
2
2
  import { join } from "node:path";
3
- import { resolveAgentDir, resolveAgentWorkspaceDir, resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
3
+ import { resolveAgentWorkspaceDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
4
4
  import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
5
5
  import { normalizeAgentIdStrict } from "openclaw/plugin-sdk/routing";
6
6
  import { resolveSources } from "./sources.js";
7
7
  import { auditResponses, responseCohort } from "./response-audit.js";
8
8
  import { ResponseAuditStore } from "./response-store.js";
9
9
  import { dateOption } from "./date-option.js";
10
+ import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
10
11
  export function registerResponseAudit(api, config) {
11
12
  const options = (cfg, id) => {
12
13
  const normalized = normalizeAgentIdStrict(id);
13
14
  if (!normalized.ok || !listAgentIds(cfg).includes(normalized.value))
14
15
  throw new Error("Unknown response-audit agent");
15
16
  const agentId = normalized.value;
16
- const state = join(resolveStateDir(), "agents", agentId, "unblock-memory");
17
- return { agentId, config, databasePath: join(resolveAgentDir(cfg, agentId), "openclaw-agent.sqlite"),
17
+ const state = agentStateDir(agentId);
18
+ return { agentId, config, databasePath: agentTranscriptDatabase(cfg, agentId),
18
19
  storePath: join(state, MEMORY_DATABASE), indexPath: join(state, "index.sqlite"),
19
20
  peoplePath: join(state, MEMORY_DATABASE),
20
21
  sources: resolveSources(resolveAgentWorkspaceDir(cfg, agentId), config.corpora.filter(c => c.kind === "files")
@@ -1,14 +1,14 @@
1
- import { createHash } from "node:crypto";
2
1
  import { RESPONSE_EXTRACTOR_VERSION } from "./response-episodes.js";
3
2
  import { judgeResponse, judgeResponseFollowup, RESPONSE_STAGE_VERSIONS } from "./response-judge.js";
4
- import { TYPESAFE_REVIEW_MODEL } from "./typesafe-review.js";
3
+ import { TYPESAFE_MODEL } from "./typesafe-client.js";
4
+ import { jsonHash } from "./json-hash.js";
5
5
  export async function assessResponseStages(store, cohort, e, params, sentimentEnabled, usage) {
6
6
  const original = { before: e.before, request: e.request, answer: e.answer, contextLimited: e.contextLimited };
7
7
  const feedback = { ...original, feedback: e.feedback };
8
8
  const evidence = { quality: original, feedback, sentiment: feedback, retrospective: { ...feedback, followup: e.followup } };
9
9
  const keys = Object.fromEntries(Object.keys(evidence).map(stage => [stage,
10
- createHash("sha256").update(JSON.stringify([RESPONSE_EXTRACTOR_VERSION, TYPESAFE_REVIEW_MODEL, RESPONSE_STAGE_VERSIONS[stage],
11
- e.id, e.session, e.senderId, e.thread, evidence[stage]])).digest("hex"),
10
+ jsonHash([RESPONSE_EXTRACTOR_VERSION, TYPESAFE_MODEL, RESPONSE_STAGE_VERSIONS[stage],
11
+ e.id, e.session, e.senderId, e.thread, evidence[stage]]),
12
12
  ]));
13
13
  const cache = {
14
14
  quality: store.stage(cohort, e, "quality", keys.quality),
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { openMemoryDatabase } from "./memory-database.js";
2
+ import { immediateTransaction, openMemoryDatabase } from "./memory-database.js";
3
3
  import { responseOutcome, RESPONSE_REPORT_VERSION } from "./response-outcome.js";
4
4
  import { ResponsePeople } from "./response-identity.js";
5
5
  import { ResponseReviews, RESPONSE_REVIEW_POLICY } from "./response-reviews.js";
@@ -46,20 +46,14 @@ export class ResponseAuditStore {
46
46
  }
47
47
  /** Claim one bounded scheduled attempt, never replay every missed interval. */
48
48
  claimScheduled(now, intervalMs) {
49
- this.#db.exec("BEGIN IMMEDIATE");
50
- try {
49
+ return immediateTransaction(this.#db, () => {
51
50
  this.#db.prepare(`INSERT INTO response_schedule VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET
52
51
  next_due=next_due + excluded.interval_ms - interval_ms, interval_ms=excluded.interval_ms`)
53
52
  .run(intervalMs, now + intervalMs);
54
53
  const claimed = this.#db.prepare("UPDATE response_schedule SET next_due=? WHERE id=1 AND next_due<=?")
55
54
  .run(now + intervalMs, now).changes > 0;
56
- this.#db.exec("COMMIT");
57
55
  return claimed;
58
- }
59
- catch (error) {
60
- this.#db.exec("ROLLBACK");
61
- throw error;
62
- }
56
+ });
63
57
  }
64
58
  acquire(now) {
65
59
  const token = randomUUID();
@@ -74,8 +68,7 @@ export class ResponseAuditStore {
74
68
  WHERE cohort=? AND active=1 AND episode_at>=? ORDER BY session_id`).all(cohort, since).map(row => String(row.session_id));
75
69
  }
76
70
  observe(cohort, sessionId, episodes) {
77
- this.#db.exec("BEGIN IMMEDIATE");
78
- try {
71
+ immediateTransaction(this.#db, () => {
79
72
  this.#db.prepare("UPDATE response_results SET active=0 WHERE cohort=? AND session_id=?").run(cohort, sessionId);
80
73
  const insert = this.#db.prepare(`INSERT INTO response_results(cohort,id,session_id,input_hash,episode_at,active,status)
81
74
  VALUES(?,?,?,?,?,1,'pending') ON CONFLICT(cohort,id) DO UPDATE SET active=1,
@@ -88,12 +81,7 @@ export class ResponseAuditStore {
88
81
  for (const e of episodes)
89
82
  insert.run(cohort, e.id, sessionId, e.inputHash, e.timestamp);
90
83
  this.reviews.reconcile(cohort, sessionId);
91
- this.#db.exec("COMMIT");
92
- }
93
- catch (error) {
94
- this.#db.exec("ROLLBACK");
95
- throw error;
96
- }
84
+ });
97
85
  }
98
86
  needsJudgment(cohort, e, now) {
99
87
  const row = this.#db.prepare("SELECT status,attempts,attempted_at FROM response_results WHERE cohort=? AND id=? AND input_hash=? AND active=1")
@@ -111,18 +99,12 @@ export class ResponseAuditStore {
111
99
  }
112
100
  save(cohort, e, result, now) {
113
101
  result = { ...result, human: result.human ?? new ResponsePeople().resolve(e) };
114
- this.#db.exec("BEGIN IMMEDIATE");
115
- try {
102
+ immediateTransaction(this.#db, () => {
116
103
  const changed = this.#db.prepare("UPDATE response_results SET status='ok',assessed_at=?,result=? WHERE cohort=? AND id=? AND input_hash=? AND active=1")
117
104
  .run(now, JSON.stringify(result), cohort, e.id, e.inputHash).changes;
118
105
  if (changed)
119
106
  this.reviews.sync(cohort, e.id, e.inputHash, result, now);
120
- this.#db.exec("COMMIT");
121
- }
122
- catch (error) {
123
- this.#db.exec("ROLLBACK");
124
- throw error;
125
- }
107
+ });
126
108
  }
127
109
  cursor(cohort) { return String(this.#db.prepare("SELECT cursor FROM response_cursors WHERE cohort=?").get(cohort)?.cursor ?? ""); }
128
110
  advance(cohort, cursor) {
@@ -157,27 +139,20 @@ export class ResponseAuditStore {
157
139
  return row ? JSON.parse(String(row.result)) : undefined;
158
140
  }
159
141
  stageBegin(keys, now) {
160
- this.#db.exec("BEGIN IMMEDIATE");
161
- try {
142
+ immediateTransaction(this.#db, () => {
162
143
  for (const key of keys) {
163
144
  const changed = this.#db.prepare(`UPDATE response_stages SET attempts=attempts+1,attempted_at=?,status='failed'
164
145
  WHERE key=? AND status!='ok' AND attempts<3 AND (attempted_at IS NULL OR attempted_at<=?)`).run(now, key, now - 600_000).changes;
165
146
  if (!changed)
166
147
  throw new Error("Response stage in backoff or retry exhausted");
167
148
  }
168
- this.#db.exec("COMMIT");
169
- }
170
- catch (error) {
171
- this.#db.exec("ROLLBACK");
172
- throw error;
173
- }
149
+ });
174
150
  }
175
151
  stageSave(key, result, now) {
176
152
  this.#db.prepare("UPDATE response_stages SET status='ok',result=?,assessed_at=? WHERE key=?").run(JSON.stringify(result), now, key);
177
153
  }
178
154
  retryFailed(cohort) {
179
- this.#db.exec("BEGIN IMMEDIATE");
180
- try {
155
+ return immediateTransaction(this.#db, () => {
181
156
  const episodes = this.#db.prepare(`UPDATE response_results AS r SET attempts=0,attempted_at=NULL,status='pending'
182
157
  WHERE cohort=? AND active=1 AND (status!='ok' OR json_extract(result,'$.memory.status')='unavailable' OR EXISTS (
183
158
  SELECT 1 FROM response_stage_links l JOIN response_stages s ON s.key=l.key
@@ -186,13 +161,8 @@ export class ResponseAuditStore {
186
161
  WHERE status!='ok' AND key IN (SELECT l.key FROM response_stage_links l JOIN response_results r
187
162
  ON r.cohort=l.cohort AND r.id=l.episode_id AND r.input_hash=l.input_hash WHERE r.cohort=? AND r.active=1)`)
188
163
  .run(cohort).changes;
189
- this.#db.exec("COMMIT");
190
164
  return { stages, episodes };
191
- }
192
- catch (error) {
193
- this.#db.exec("ROLLBACK");
194
- throw error;
195
- }
165
+ });
196
166
  }
197
167
  scan(cohort, coverage, now) {
198
168
  this.#db.prepare("INSERT INTO response_scans VALUES(?,?,?) ON CONFLICT(cohort) DO UPDATE SET observed_at=excluded.observed_at,coverage=excluded.coverage")
@@ -364,16 +334,17 @@ export class ResponseAuditStore {
364
334
  const scoreDimension = dimension === "fulfillment" || dimension === "deliverableFit" || dimension === "dissatisfactionIntensity" ? dimension : null;
365
335
  const sentimentDimension = dimension === "dissatisfactionRate" || dimension === "sentimentUnknownRate";
366
336
  const emotionDimension = dimension === "annoyanceRate" || dimension === "frustrationRate";
337
+ const assessedSubset = scoreDimension || sentimentDimension || emotionDimension;
367
338
  const beforeN = scoreDimension ? previous[`${scoreDimension}Scored`] : sentimentDimension ? previous.sentimentAssessed : emotionDimension ? previous.emotionAssessed : previous.evaluated;
368
339
  const afterN = scoreDimension ? current[`${scoreDimension}Scored`] : sentimentDimension ? current.sentimentAssessed : emotionDimension ? current.emotionAssessed : current.evaluated;
369
340
  const before = dimension === "fulfillment" || dimension === "deliverableFit" || dimension === "dissatisfactionIntensity" ? previous[`${dimension}Mean`] : previous[dimension];
370
341
  const after = dimension === "fulfillment" || dimension === "deliverableFit" || dimension === "dissatisfactionIntensity" ? current[`${dimension}Mean`] : current[dimension];
371
- const beforeCoverage = scoreDimension || sentimentDimension || emotionDimension ? beforeN / previous.evaluated : previous.outcomeCoverage;
372
- const afterCoverage = scoreDimension || sentimentDimension || emotionDimension ? afterN / current.evaluated : current.outcomeCoverage;
342
+ const beforeCoverage = assessedSubset ? beforeN / previous.evaluated : previous.outcomeCoverage;
343
+ const afterCoverage = assessedSubset ? afterN / current.evaluated : current.outcomeCoverage;
373
344
  const coverageChanged = beforeCoverage !== afterCoverage;
374
345
  const enough = beforeN >= 20 && afterN >= 20 && current.taskType !== "uncertain" && current.agentModel !== "unknown";
375
346
  const status = !current.human || !current.human.accountScope || current.taskType === "uncertain" || current.agentModel === "unknown" ? "unknown_stratum" :
376
- !enough ? "insufficient_samples" : (scoreDimension || sentimentDimension || emotionDimension) && coverageChanged ? "coverage_changed" : "descriptive_comparison";
347
+ !enough ? "insufficient_samples" : assessedSubset && coverageChanged ? "coverage_changed" : "descriptive_comparison";
377
348
  return { fromWeek: previous.week, toWeek: current.week, taskType: current.taskType, agentModel: current.agentModel,
378
349
  fromPeriod: previous.week, toPeriod: current.week, human: current.human,
379
350
  dimension, beforeN, afterN, status,
@@ -1,3 +1,4 @@
1
+ export declare const CONVERSATION_INFO: RegExp;
1
2
  /** Infer legacy transport sender metadata only to unwrap visible conversation text. */
2
3
  export declare function conversationUserText(raw: string, sender?: unknown): {
3
4
  text: string;
@@ -1,3 +1,5 @@
1
+ export const CONVERSATION_INFO = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n([^]*?)\r?\n```\r?\n/;
2
+ const FROM_HEADER = /^From: [^\r\n]+ \(([^()\r\n]+)\)\r?\n/;
1
3
  /** Infer legacy transport sender metadata only to unwrap visible conversation text. */
2
4
  export function conversationUserText(raw, sender) {
3
5
  const parsed = conversationEnvelope(raw, sender);
@@ -8,7 +10,7 @@ export function conversationUserText(raw, sender) {
8
10
  export function conversationEnvelope(raw, sender) {
9
11
  let senderId = typeof sender === "string" ? sender : undefined;
10
12
  if (senderId === undefined) {
11
- const header = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n([^]*?)\r?\n```\r?\n/.exec(raw.trim());
13
+ const header = CONVERSATION_INFO.exec(raw.trim());
12
14
  if (header) {
13
15
  let metadata;
14
16
  try {
@@ -22,7 +24,7 @@ export function conversationEnvelope(raw, sender) {
22
24
  senderId = metadata.sender.id;
23
25
  }
24
26
  }
25
- senderId ??= /^From: [^\r\n]+ \(([^()\r\n]+)\)\r?\n/.exec(raw.trim())?.[1];
27
+ senderId ??= FROM_HEADER.exec(raw.trim())?.[1];
26
28
  }
27
29
  return userEnvelope(raw, senderId ?? "");
28
30
  }
@@ -36,7 +38,7 @@ function userEnvelope(input, senderId) {
36
38
  let text = input.trim();
37
39
  let contextLimited = false;
38
40
  let context;
39
- const header = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n([^]*?)\r?\n```\r?\n/.exec(text);
41
+ const header = CONVERSATION_INFO.exec(text);
40
42
  if (header) {
41
43
  let meta;
42
44
  try {
@@ -70,7 +72,7 @@ function userEnvelope(input, senderId) {
70
72
  }
71
73
  }
72
74
  else {
73
- const from = /^From: [^\r\n]+ \(([^()\r\n]+)\)\r?\n/.exec(text);
75
+ const from = FROM_HEADER.exec(text);
74
76
  if (from) {
75
77
  if (from[1] !== senderId)
76
78
  return undefined;
@@ -2,13 +2,14 @@ import { randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
3
  import { MEMORY_DATABASE } from "./memory-database.js";
4
4
  import { join } from "node:path";
5
- import { resolveAgentDir, resolveAgentWorkspaceDir, resolveStateDir, } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
5
+ import { resolveAgentWorkspaceDir, resolveStateDir, } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
6
6
  import { listAgentIds, resolveAgentIdentity } from "openclaw/plugin-sdk/agent-runtime";
7
7
  import { QmdMemoryManager } from "./manager.js";
8
8
  import { resolveTimezone } from "./session-projector.js";
9
9
  import { unchangedSessionSync } from "./session-sync.js";
10
10
  import { resolveConfiguredSkillPath, resolveSessionSource, resolveSources } from "./sources.js";
11
11
  import { classifyWorkspaceMemoryPaths } from "./workspace-path-classifier.js";
12
+ import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
12
13
  const activeSessionSyncs = new Map();
13
14
  async function readJson(path) {
14
15
  try {
@@ -122,7 +123,7 @@ export class QmdMemoryRuntime {
122
123
  error: 'memory session sync requires a configured "sessions" corpus',
123
124
  };
124
125
  }
125
- const directory = this.#sessionSyncDirectory(params.agentId);
126
+ const directory = this.#stateDir(params.agentId);
126
127
  const statusPath = join(directory, "session-sync-status.json");
127
128
  const running = activeSessionSyncs.get(directory);
128
129
  if (running)
@@ -193,7 +194,7 @@ export class QmdMemoryRuntime {
193
194
  return { status: "started", startedAt };
194
195
  }
195
196
  async sessionSyncStatus(agentId) {
196
- const directory = this.#sessionSyncDirectory(agentId);
197
+ const directory = this.#stateDir(agentId);
197
198
  const statusPath = join(directory, "session-sync-status.json");
198
199
  const status = await readJson(statusPath);
199
200
  const running = activeSessionSyncs.get(directory);
@@ -232,7 +233,7 @@ export class QmdMemoryRuntime {
232
233
  }
233
234
  async #createManager(cfg, agentId) {
234
235
  const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
235
- const stateDir = join(this.#stateRoot, "agents", agentId, "unblock-memory");
236
+ const stateDir = this.#stateDir(agentId);
236
237
  const fileCorpora = this.#corpora.filter((corpus) => corpus.kind === "files" || corpus.kind === "skills");
237
238
  const sessions = this.#sessionConfig(cfg, agentId);
238
239
  const sources = resolveSources(workspaceDir, fileCorpora);
@@ -265,18 +266,18 @@ export class QmdMemoryRuntime {
265
266
  const corpus = this.#corpora.find(corpus => corpus.kind === "sessions");
266
267
  if (!corpus)
267
268
  return;
268
- const stateDir = this.#sessionSyncDirectory(agentId);
269
+ const stateDir = this.#stateDir(agentId);
269
270
  const source = resolveSessionSource(join(stateDir, "sessions"), corpus.chatTypes);
270
271
  return {
271
272
  agentId, agentName: resolveAgentIdentity(cfg, agentId)?.name?.trim() || agentId,
272
273
  chatTypes: corpus.chatTypes, maxExpandedTokens: corpus.maxExpandedTokens,
273
274
  collection: source.collection, outputDir: source.root,
274
- databasePath: join(resolveAgentDir(cfg, agentId), "openclaw-agent.sqlite"),
275
+ databasePath: agentTranscriptDatabase(cfg, agentId),
275
276
  manifestPath: join(stateDir, "sessions-manifest.json"),
276
277
  timezone: resolveTimezone(cfg.agents?.defaults?.userTimezone?.trim()),
277
278
  };
278
279
  }
279
- #sessionSyncDirectory(agentId) {
280
- return join(this.#stateRoot, "agents", agentId, "unblock-memory");
280
+ #stateDir(agentId) {
281
+ return agentStateDir(agentId, this.#stateRoot);
281
282
  }
282
283
  }
@@ -1,22 +1,16 @@
1
1
  import { Value } from "typebox/value";
2
- import { estimateJevTokens, requestTypeSafe, resolveTypeSafeApiKey, TYPESAFE_NOUL_SCHEMA, TypeSafeRequestError } from "./typesafe-client.js";
2
+ import { estimateJevTokens, isTypeSafeTimeout, requestTypeSafe, resolveTypeSafeApiKey, TYPESAFE_NOUL_SCHEMA, TypeSafeRequestError } from "./typesafe-client.js";
3
3
  import { messageText } from "./whisperer-context.js";
4
- import { conversationEnvelope, conversationUserText } from "./response-text.js";
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";
7
8
  // Leaves room for the longest scenario question under Jev's 32k state-plus-question limit.
8
9
  const MAX_STATE_TOKENS = 24_000;
9
10
  const MAX_SESSIONS = 1000;
10
11
  const RUNS_PER_SESSION = 4;
11
- const CONVERSATION_INFO = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n[^]*?\r?\n```\r?\n/;
12
12
  class SafetyInputError extends Error {
13
13
  }
14
- function isRecord(value) {
15
- return value !== null && typeof value === "object" && !Array.isArray(value);
16
- }
17
- function nonBlank(value) {
18
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
19
- }
20
14
  /** Thread replies and forum topics belong to their parent conversation (`C1:thread:1712.01`, `-100:topic:5`). */
21
15
  function conversationId(value) {
22
16
  const lower = value?.toLowerCase();
@@ -241,9 +235,7 @@ export function registerSafetyWhisperer(api, plugin, diagnostics) {
241
235
  }
242
236
  catch (error) {
243
237
  // Fail open by design, but never silently: "could not check" is recorded separately from "no match".
244
- const timedOut = (error instanceof TypeSafeRequestError && error.code === "timeout") ||
245
- (signal.aborted && signal.reason instanceof Error && signal.reason.name === "TimeoutError");
246
- const outcome = error instanceof SafetyInputError ? "input_too_large" : timedOut ? "timed_out" : signal.aborted ? "cancelled" : "failed";
238
+ const outcome = error instanceof SafetyInputError ? "input_too_large" : isTypeSafeTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed";
247
239
  record(outcome);
248
240
  if (outcome !== "cancelled") {
249
241
  warn({ event: "check_failed", agentId, runId: context.runId, outcome, eligibleScenarios: scenarios.length,
@@ -1,15 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { projectLoggieMessage } from "./loggie-projection.js";
3
3
  import { applyProposal, parseAttachments, parseInternalMessage } from "./session-noise.js";
4
+ import { nonBlank, record } from "./guards.js";
4
5
  const MESSAGE_HEADING = /^## (User|Assistant) — (.+) — (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \S.*)$/u;
5
- function record(value) {
6
- return value !== null && typeof value === "object" && !Array.isArray(value)
7
- ? value
8
- : undefined;
9
- }
10
- function nonEmptyString(value) {
11
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
12
- }
13
6
  function timestamp(value) {
14
7
  if (typeof value === "number" && Number.isFinite(value))
15
8
  return value;
@@ -72,12 +65,12 @@ export function projectMessage(row, input) {
72
65
  const metadata = record(message.__openclaw);
73
66
  const speaker = role === "assistant"
74
67
  ? input.agentName
75
- : nonEmptyString(metadata?.senderName) ??
76
- nonEmptyString(metadata?.senderUsername) ??
77
- nonEmptyString(metadata?.senderId) ??
78
- nonEmptyString(message.senderName) ??
79
- nonEmptyString(message.senderLabel) ??
80
- nonEmptyString(message.senderId) ??
68
+ : nonBlank(metadata?.senderName) ??
69
+ nonBlank(metadata?.senderUsername) ??
70
+ nonBlank(metadata?.senderId) ??
71
+ nonBlank(message.senderName) ??
72
+ nonBlank(message.senderLabel) ??
73
+ nonBlank(message.senderId) ??
81
74
  "User";
82
75
  if (role === "user" && speaker !== "User") {
83
76
  text = text.replace(/^From:[^\n]*\n/u, "").trim();
@@ -46,6 +46,7 @@ type ProjectionOptions = {
46
46
  };
47
47
  export declare function unchangedSessionSync(params: ProjectionOptions, indexPath: string): Promise<SessionSyncResult | undefined>;
48
48
  export declare function readSessionManifest(path: string): Promise<SessionManifest>;
49
+ export declare function projectionHash(content: string): string;
49
50
  export declare function sessionMetadataByPath(manifest: SessionManifest): Map<string, SessionMetadata>;
50
51
  export declare function syncSessionProjections(params: ProjectionOptions & {
51
52
  force?: boolean;
@@ -27,6 +27,16 @@ const REQUIRED_COLUMNS = {
27
27
  session_transcript_active_events: ["session_id", "active_position", "event_seq", "message_position"],
28
28
  transcript_rewrite_watermarks: ["session_id", "generation"],
29
29
  };
30
+ function windowMetadata(window) {
31
+ return {
32
+ sessionId: window.sessionId,
33
+ provider: window.provider ?? undefined,
34
+ chatType: window.chatType,
35
+ accountId: window.accountId ?? undefined,
36
+ conversationId: window.conversationId ?? undefined,
37
+ startedAt: window.startedAt,
38
+ };
39
+ }
30
40
  function projectionKey(params) {
31
41
  return JSON.stringify([PROJECTOR_VERSION, params.databasePath, params.agentId,
32
42
  params.agentName, params.timezone, [...params.chatTypes].sort()]);
@@ -122,14 +132,7 @@ function readSnapshot(params) {
122
132
  const changed = new Set();
123
133
  const unavailable = new Set();
124
134
  for (const window of windows) {
125
- const metadata = {
126
- sessionId: window.sessionId,
127
- provider: window.provider ?? undefined,
128
- chatType: window.chatType,
129
- accountId: window.accountId ?? undefined,
130
- conversationId: window.conversationId ?? undefined,
131
- startedAt: window.startedAt,
132
- };
135
+ const metadata = windowMetadata(window);
133
136
  const previous = params.previousManifest.sessions[window.sessionId];
134
137
  const documentPath = sessionDocumentPath(metadata);
135
138
  const sourceFingerprint = JSON.stringify(window);
@@ -230,7 +233,7 @@ async function remove(path) {
230
233
  throw error;
231
234
  }
232
235
  }
233
- function projectionHash(content) {
236
+ export function projectionHash(content) {
234
237
  return createHash("sha256").update(content).digest("hex");
235
238
  }
236
239
  export function sessionMetadataByPath(manifest) {
@@ -259,14 +262,7 @@ export async function syncSessionProjections(params) {
259
262
  for (const window of snapshot.windows) {
260
263
  const previous = previousManifest.sessions[window.sessionId];
261
264
  const events = snapshot.events.get(window.sessionId);
262
- const metadata = {
263
- sessionId: window.sessionId,
264
- provider: window.provider ?? undefined,
265
- chatType: window.chatType,
266
- accountId: window.accountId ?? undefined,
267
- conversationId: window.conversationId ?? undefined,
268
- startedAt: window.startedAt,
269
- };
265
+ const metadata = windowMetadata(window);
270
266
  const documentPath = sessionDocumentPath(metadata);
271
267
  if (snapshot.unavailable.has(window.sessionId)) {
272
268
  counts.failed += 1;
@@ -1,15 +1,13 @@
1
1
  import { basename } from "node:path";
2
2
  import { selectTypeSafeSkill } from "./typesafe.js";
3
- import { resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
3
+ import { isTypeSafeTimeout, resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
4
4
  import { buildSkillWhispererQuery, recentSkillMessages } from "./whisperer-context.js";
5
5
  import { abortable } from "./abortable.js";
6
+ import { isRecord } from "./guards.js";
6
7
  const CANDIDATE_LIMIT = 10;
7
8
  const MAX_QUERY_CHARS = 12_000;
8
9
  const TYPESAFE_CANDIDATE_LIMIT = 3;
9
10
  export const SKILL_WHISPERER_TIMEOUT_MS = 3000;
10
- function isRecord(value) {
11
- return value !== null && typeof value === "object" && !Array.isArray(value);
12
- }
13
11
  function typeSafeConversation(prompt, messages) {
14
12
  const currentRequest = prompt.trim().slice(-MAX_QUERY_CHARS);
15
13
  let remaining = MAX_QUERY_CHARS - currentRequest.length;
@@ -67,12 +65,10 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
67
65
  try {
68
66
  const runtimeParams = active(agentId);
69
67
  const apiKey = await abortable(resolveTypeSafeApiKey(typesafe), signal);
70
- signal.throwIfAborted();
71
68
  if (!apiKey)
72
69
  diagnostics?.record(agentId, "skill", typesafe.enabled ? "missing_key" : "typesafe_disabled");
73
70
  const recentMessages = recentSkillMessages(event.messages, config.historyMessages);
74
71
  const candidates = await abortable(runtime.searchSkills(runtimeParams, buildSkillWhispererQuery(event.prompt, recentMessages), apiKey ? -1 : config.minScore, CANDIDATE_LIMIT), signal);
75
- signal.throwIfAborted();
76
72
  const resolvedCandidates = candidates.flatMap((candidate) => {
77
73
  const canonicalPath = runtime.resolveSkillPath(runtimeParams, candidate.path);
78
74
  return canonicalPath ? [{ candidate, canonicalPath }] : [];
@@ -138,9 +134,7 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
138
134
  };
139
135
  }
140
136
  catch (error) {
141
- const timedOut = (error instanceof TypeSafeRequestError && error.code === "timeout") ||
142
- (signal.aborted && signal.reason instanceof Error && signal.reason.name === "TimeoutError");
143
- diagnostics?.record(agentId, "skill", timedOut ? "timed_out" : signal.aborted ? "cancelled" : "failed");
137
+ diagnostics?.record(agentId, "skill", isTypeSafeTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed");
144
138
  if (!signal.aborted)
145
139
  api.logger.warn("unblock-memory skill whisperer failed; no hint emitted");
146
140
  return;
@@ -1,12 +1,8 @@
1
1
  import { inspectReadOnlyChannelAccount } from "openclaw/plugin-sdk/directory-runtime";
2
+ import { record } from "./guards.js";
2
3
  function text(value, maxLength) {
3
4
  return typeof value === "string" && value.trim() ? value.trim().slice(0, maxLength) : undefined;
4
5
  }
5
- function record(value) {
6
- return value && typeof value === "object" && !Array.isArray(value)
7
- ? value
8
- : undefined;
9
- }
10
6
  function slackToken(account) {
11
7
  return text(account.userToken, 10_000) ?? text(account.botToken, 10_000);
12
8
  }
@@ -10,14 +10,16 @@ function expandHome(value) {
10
10
  function collectionName(source) {
11
11
  return `source-${createHash("sha256").update(source).digest("hex").slice(0, 12)}`;
12
12
  }
13
+ /** Whether a `relative()` result escapes its base directory. */
14
+ function escapes(relativePath) {
15
+ return relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath);
16
+ }
13
17
  function assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, root) {
14
18
  if (isAbsolute(expandHome(configuredPath)))
15
19
  return;
16
20
  const workspace = resolve(workspaceDir);
17
- const rootRelative = relative(workspace, root);
18
- if (rootRelative === ".." || rootRelative.startsWith(`..${sep}`) || isAbsolute(rootRelative)) {
21
+ if (escapes(relative(workspace, root)))
19
22
  return;
20
- }
21
23
  let current = root;
22
24
  while (current !== workspace) {
23
25
  if (existsSync(current) && lstatSync(current).isSymbolicLink()) {
@@ -32,25 +34,12 @@ function assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, roo
32
34
  export function resolveSource(workspaceDir, configuredPath, corpus = "memory") {
33
35
  const expanded = expandHome(configuredPath);
34
36
  const absolute = isAbsolute(expanded) ? resolve(expanded) : resolve(workspaceDir, expanded);
35
- if (existsSync(absolute)) {
36
- const stat = statSync(absolute);
37
- const root = stat.isDirectory() ? absolute : dirname(absolute);
38
- const pattern = stat.isDirectory() ? "**/*.md" : basename(absolute);
39
- assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, root);
40
- return {
41
- collection: collectionName(absolute),
42
- corpus,
43
- configuredPath,
44
- kind: "files",
45
- root,
46
- pattern,
47
- watchPath: absolute,
48
- };
49
- }
37
+ const exists = existsSync(absolute);
50
38
  const magicIndex = absolute.search(GLOB_MAGIC);
51
- if (magicIndex < 0) {
52
- const isExactMarkdownFile = basename(absolute).toLowerCase().endsWith(".md");
53
- const root = isExactMarkdownFile ? dirname(absolute) : absolute;
39
+ if (exists || magicIndex < 0) {
40
+ // An existing path is taken literally; a missing one is a file only when it names Markdown.
41
+ const isFile = exists ? !statSync(absolute).isDirectory() : basename(absolute).toLowerCase().endsWith(".md");
42
+ const root = isFile ? dirname(absolute) : absolute;
54
43
  assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, root);
55
44
  return {
56
45
  collection: collectionName(absolute),
@@ -58,7 +47,7 @@ export function resolveSource(workspaceDir, configuredPath, corpus = "memory") {
58
47
  configuredPath,
59
48
  kind: "files",
60
49
  root,
61
- pattern: isExactMarkdownFile ? basename(absolute) : "**/*.md",
50
+ pattern: isFile ? basename(absolute) : "**/*.md",
62
51
  watchPath: absolute,
63
52
  };
64
53
  }
@@ -110,21 +99,14 @@ export function resolveConfiguredSkillPath(workspaceDir, inputPath, sources) {
110
99
  catch {
111
100
  return undefined;
112
101
  }
113
- for (const source of sources) {
114
- if (source.kind !== "skills")
115
- continue;
116
- const relativePath = relative(source.root, target);
117
- if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath))
118
- continue;
119
- if (picomatch.isMatch(relativePath.split(sep).join("/"), source.pattern, { dot: true }))
120
- return canonicalTarget;
121
- }
122
- return undefined;
102
+ return sources.some((source) => source.kind === "skills" && sourceMatchesPath(source, target))
103
+ ? canonicalTarget
104
+ : undefined;
123
105
  }
124
106
  export function sourceMatchesPath(source, inputPath) {
125
107
  const target = resolve(inputPath);
126
108
  const relativePath = relative(source.root, target);
127
- if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath))
109
+ if (escapes(relativePath))
128
110
  return false;
129
111
  return picomatch.isMatch(relativePath.split(sep).join("/"), source.pattern, { dot: true });
130
112
  }
@@ -140,16 +122,14 @@ export function parseSafeVirtualPath(virtualPath, sources) {
140
122
  if (!picomatch.isMatch(portableRelativePath, source.pattern, { dot: true }))
141
123
  return undefined;
142
124
  const target = resolve(source.root, relativePath);
143
- if (relative(source.root, target).startsWith(`..${sep}`) || relative(source.root, target) === "..") {
125
+ if (escapes(relative(source.root, target)))
144
126
  return undefined;
145
- }
146
127
  if (!target.toLowerCase().endsWith(".md"))
147
128
  return undefined;
148
129
  try {
149
130
  const realRoot = realpathSync(source.root);
150
131
  const realTarget = realpathSync(target);
151
- const rel = relative(realRoot, realTarget);
152
- if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
132
+ if (escapes(relative(realRoot, realTarget)))
153
133
  return undefined;
154
134
  }
155
135
  catch {
@@ -1,5 +1,7 @@
1
1
  import type { OpenClawConfig, OpenClawPluginToolContext } from "openclaw/plugin-sdk/plugin-entry";
2
2
  import type { MemoryRequestContext } from "./contracts.js";
3
+ /** The freshest config the host offers for this tool call. */
4
+ export declare function runtimeConfig(ctx: OpenClawPluginToolContext): OpenClawConfig | undefined;
3
5
  export declare function getContext(ctx: OpenClawPluginToolContext): {
4
6
  cfg: OpenClawConfig;
5
7
  agentId: string;
@@ -1,5 +1,9 @@
1
+ /** The freshest config the host offers for this tool call. */
2
+ export function runtimeConfig(ctx) {
3
+ return ctx.getRuntimeConfig?.() ?? ctx.runtimeConfig ?? ctx.config;
4
+ }
1
5
  export function getContext(ctx) {
2
- const cfg = ctx.getRuntimeConfig?.() ?? ctx.runtimeConfig ?? ctx.config;
6
+ const cfg = runtimeConfig(ctx);
3
7
  if (!cfg || !ctx.agentId)
4
8
  return undefined;
5
9
  return {
@@ -13,7 +13,6 @@ type Row = {
13
13
  eventJson: string;
14
14
  createdAt: number;
15
15
  };
16
- export declare const trainingHash: (value: unknown) => string;
17
16
  /** The following answer establishes eligibility, but is never part of that example's input. */
18
17
  export declare function trainingExamples(rows: Iterable<Row>, renew?: () => void): {
19
18
  examples: TrainingExample[];