@unblocklabs/unblock-memory 0.13.0 → 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.
Files changed (80) hide show
  1. package/defaults.json +162 -0
  2. package/dist/src/cluster-review.js +6 -5
  3. package/dist/src/config.js +33 -30
  4. package/dist/src/decision-client.d.ts +8 -2
  5. package/dist/src/decision-client.js +22 -9
  6. package/dist/src/decision-ranking.js +2 -1
  7. package/dist/src/decision-review.js +8 -7
  8. package/dist/src/defaults.d.ts +8 -0
  9. package/dist/src/defaults.js +128 -0
  10. package/dist/src/emotion-baselines.js +3 -2
  11. package/dist/src/evidence-review.js +7 -4
  12. package/dist/src/extraction-chunk.js +2 -1
  13. package/dist/src/extraction-config.js +4 -2
  14. package/dist/src/extraction-model.d.ts +23 -17
  15. package/dist/src/extraction-model.js +164 -61
  16. package/dist/src/extraction-runtime.js +5 -4
  17. package/dist/src/extraction-source.js +2 -1
  18. package/dist/src/extraction-store.d.ts +1 -0
  19. package/dist/src/extraction-store.js +4 -2
  20. package/dist/src/extraction-worker.d.ts +2 -3
  21. package/dist/src/extraction-worker.js +12 -10
  22. package/dist/src/inside-out-runtime.js +2 -1
  23. package/dist/src/inside-out-sources.js +2 -1
  24. package/dist/src/inside-out-store.js +3 -2
  25. package/dist/src/inside-out.js +5 -2
  26. package/dist/src/manager.js +5 -4
  27. package/dist/src/memory-database.js +3 -2
  28. package/dist/src/memory-passage.d.ts +2 -2
  29. package/dist/src/memory-passage.js +3 -2
  30. package/dist/src/memory-whisperer.js +16 -8
  31. package/dist/src/my-turn.js +5 -4
  32. package/dist/src/people-background.d.ts +1 -1
  33. package/dist/src/people-background.js +2 -1
  34. package/dist/src/people-dossier-review.js +4 -3
  35. package/dist/src/people-learning-cron.js +2 -1
  36. package/dist/src/people-learning-inventory.js +2 -1
  37. package/dist/src/people-primer-tool.js +5 -4
  38. package/dist/src/people-primer.js +5 -4
  39. package/dist/src/people-store.js +2 -1
  40. package/dist/src/people-tools.js +2 -1
  41. package/dist/src/plugin.js +3 -2
  42. package/dist/src/quality-audit.js +3 -2
  43. package/dist/src/quality-triage.js +4 -3
  44. package/dist/src/query-generator.js +5 -2
  45. package/dist/src/response-audit.js +3 -2
  46. package/dist/src/response-config.js +3 -1
  47. package/dist/src/response-episodes.js +3 -2
  48. package/dist/src/response-identity.js +2 -1
  49. package/dist/src/response-memory.js +2 -1
  50. package/dist/src/response-outcome.js +9 -8
  51. package/dist/src/response-reviews.js +3 -2
  52. package/dist/src/response-runtime.js +2 -1
  53. package/dist/src/response-store.js +26 -25
  54. package/dist/src/review-tools.js +4 -3
  55. package/dist/src/runtime.js +2 -1
  56. package/dist/src/safety-config.js +3 -2
  57. package/dist/src/safety-whisperer.js +3 -3
  58. package/dist/src/session-sync.js +2 -1
  59. package/dist/src/skill-whisperer.d.ts +1 -1
  60. package/dist/src/skill-whisperer.js +4 -3
  61. package/dist/src/slack-directory.js +3 -2
  62. package/dist/src/training-gate.d.ts +2 -2
  63. package/dist/src/training-gate.js +3 -2
  64. package/dist/src/training-input.js +4 -3
  65. package/dist/src/training-judge.js +2 -1
  66. package/dist/src/training-models.d.ts +1 -1
  67. package/dist/src/training-models.js +9 -7
  68. package/dist/src/training-queries.d.ts +1 -1
  69. package/dist/src/training-queries.js +4 -3
  70. package/dist/src/training-retrieval.d.ts +3 -3
  71. package/dist/src/training-retrieval.js +4 -3
  72. package/dist/src/training-store.js +3 -2
  73. package/dist/src/training.js +2 -1
  74. package/dist/src/whisperer-context.d.ts +1 -2
  75. package/dist/src/whisperer-context.js +2 -2
  76. package/docs/configuration.md +7 -1
  77. package/docs/extraction.md +25 -36
  78. package/docs/retrieval.md +3 -10
  79. package/openclaw.plugin.json +42 -55
  80. package/package.json +5 -3
package/defaults.json ADDED
@@ -0,0 +1,162 @@
1
+ {
2
+ "decisionModel": {
3
+ "endpoint": "https://codex.unblocklabs.ai/v1/decisions",
4
+ "model": "liquid/d1.2-ultra",
5
+ "timeoutMs": 1500,
6
+ "unboundedTimeoutMs": 60000
7
+ },
8
+ "extraction": {
9
+ "version": "lasting-facts-v12-d1",
10
+ "proposalTimeoutMs": 30000,
11
+ "validationTimeoutMs": 10000,
12
+ "minProposalConfidence": 0.5,
13
+ "inputTargetTokens": 24000,
14
+ "inputLimitTokens": 28000,
15
+ "historyTokenBudget": 8000,
16
+ "promptReserveTokens": 512,
17
+ "perMessageTokenOverhead": 8,
18
+ "maxProposals": 20,
19
+ "maxFactChars": 600,
20
+ "maxQuoteChars": 512,
21
+ "maxEvidencePerProposal": 4,
22
+ "maxExistingFacts": 100,
23
+ "maxExistingChars": 40000,
24
+ "validatorBatchSize": 4,
25
+ "runTimeoutMs": 600000,
26
+ "leaseMs": 180000,
27
+ "heartbeatMs": 30000,
28
+ "pollIntervalMs": 60000,
29
+ "intervalMinutes": 60,
30
+ "historyMessages": 6,
31
+ "maxBatches": 5,
32
+ "minSupport": 0.9,
33
+ "minRetention": 0.9,
34
+ "minReplacement": 0.9
35
+ },
36
+ "training": {
37
+ "teacherModel": "openai/gpt-6-luna",
38
+ "teacherReasoning": "xhigh",
39
+ "teacherMaxTokens": 12000,
40
+ "teacherTimeoutMs": 300000,
41
+ "candidatesPerRound": 5,
42
+ "decisionTimeoutMs": 30000,
43
+ "gateThreshold": 0.7,
44
+ "leaseMs": 120000,
45
+ "heartbeatMs": 10000,
46
+ "retrievalDepth": 10,
47
+ "topScoreCount": 3,
48
+ "maxInputEvents": 50000,
49
+ "maxInputBytes": 32000000
50
+ },
51
+ "memoryWhisperer": {
52
+ "defaultApiEndpoint": "",
53
+ "maxJudgeCandidates": 6,
54
+ "maxFinalists": 4,
55
+ "maxQueryGenMs": 1500,
56
+ "queryClientTimeoutMs": 10000,
57
+ "queryResponseMaxBytes": 16384,
58
+ "maxInjectedChars": 5000,
59
+ "judgmentExcerptChars": 1200,
60
+ "memoryGetMaxChars": 12000,
61
+ "memoryGetMaxLines": 1000,
62
+ "maxTrackedSessions": 1000,
63
+ "maxRunsPerSession": 64,
64
+ "defaultMinUsefulness": 0.5,
65
+ "defaultMaxHints": 3,
66
+ "defaultCooldownTurns": 10,
67
+ "defaultTimeoutMs": 3000
68
+ },
69
+ "skillWhisperer": {
70
+ "maxCandidates": 10,
71
+ "maxParallelJudges": 3,
72
+ "minDecisionUsefulness": 0.7,
73
+ "timeoutMs": 3000,
74
+ "contextMaxChars": 12000,
75
+ "defaultHistoryMessages": 5,
76
+ "defaultMinScore": 0.5,
77
+ "defaultCooldownTurns": 10
78
+ },
79
+ "myTurn": {
80
+ "timeoutMs": 1500,
81
+ "nudgeMaxProbability": 0.2,
82
+ "stateMaxTokens": 24000,
83
+ "defaultHistoryMessages": 10
84
+ },
85
+ "safetyWhisperer": {
86
+ "stateMaxTokens": 24000,
87
+ "maxTrackedSessions": 1000,
88
+ "maxRunsPerSession": 4,
89
+ "defaultHistoryMessages": 6,
90
+ "defaultTimeoutMs": 3000,
91
+ "defaultMinProbability": 0.4
92
+ },
93
+ "review": {
94
+ "minClaimSupport": 0.9,
95
+ "minRedundancy": 0.9,
96
+ "maxRedundancyCandidates": 4,
97
+ "clusterCenterSamples": 3,
98
+ "clusterEdgeSamples": 3,
99
+ "minClusterConfidence": 0.9,
100
+ "minClusterAgreeingExamples": 2,
101
+ "toolTimeoutMs": 30000,
102
+ "maxClaimChars": 2000,
103
+ "maxCombinedCitationChars": 6000,
104
+ "maxCitationLines": 120
105
+ },
106
+ "quality": {
107
+ "defaultMinNoise": 0.8,
108
+ "triageNoiseThreshold": 0.8,
109
+ "triageEvidenceHigh": 0.8,
110
+ "triageEvidenceLow": 0.2,
111
+ "gradeMaxChars": 6000,
112
+ "previewChars": 400
113
+ },
114
+ "people": {
115
+ "defaultWhispererMaxChars": 1200,
116
+ "defaultTodosMaxOpen": 1000,
117
+ "backgroundMaxWords": 70,
118
+ "primerExcerptChars": 6000,
119
+ "primerWorkers": 4,
120
+ "primerUncertainFloor": 0.5,
121
+ "primerTimeoutMs": 120000,
122
+ "dossierMaxBytes": 65536,
123
+ "slackApiUrl": "https://slack.com/api/users.list",
124
+ "slackTimeoutMs": 30000,
125
+ "learningNightlyTimeoutSec": 2700,
126
+ "learningWeeklyTimeoutSec": 3600
127
+ },
128
+ "responseAudit": {
129
+ "deadlineMs": 120000,
130
+ "leaseMs": 180000,
131
+ "maxRetries": 3,
132
+ "retryBackoffMs": 600000,
133
+ "pollIntervalMs": 60000,
134
+ "maxEpisodeChars": 24000,
135
+ "maxSessionEvents": 2000,
136
+ "maxSessionBytes": 2000000,
137
+ "scoreHigh": 0.8,
138
+ "scoreLow": 0.2,
139
+ "defaultHistoryMessages": 6,
140
+ "defaultLookbackDays": 30,
141
+ "defaultMaxEpisodes": 20,
142
+ "defaultIntervalMinutes": 60
143
+ },
144
+ "insideOut": {
145
+ "retryFloorMs": 3600000,
146
+ "baselineRefreshMs": 86400000,
147
+ "batchSize": 500,
148
+ "readPageSize": 2000,
149
+ "defaultIntervalMinutes": 1440,
150
+ "defaultMaxInteractions": 100,
151
+ "defaultMaxContextTokens": 30000,
152
+ "defaultBaselineMinInteractions": 20
153
+ },
154
+ "sqlite": {
155
+ "mainBusyTimeoutMs": 5000,
156
+ "peopleInventoryBusyTimeoutMs": 2000,
157
+ "readerBusyTimeoutMs": 1000,
158
+ "watchDebounceMs": 250,
159
+ "watchRetryMs": 1000,
160
+ "flushReserveTokensFloor": 20000
161
+ }
162
+ }
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { readAnalysisSummary, readCluster } from "./analysis.js";
2
3
  import { parseSafeVirtualPath } from "./sources.js";
3
4
  import { decisionModelScope, DEFAULT_DECISION_MODEL } from "./decision-client.js";
@@ -14,10 +15,10 @@ export async function reviewClusterIngestion(params) {
14
15
  const sources = new Map(params.sources.filter(source => source.kind !== "skills").map(source => [source.collection, source]));
15
16
  const read = params.read ?? (async (run) => run());
16
17
  const snapshot = await read(() => {
17
- const center = readCluster(params.db, params.clusterId, 3, 0, "representative");
18
+ const center = readCluster(params.db, params.clusterId, DEFAULTS.review.clusterCenterSamples, 0, "representative");
18
19
  if (center.status !== "ok" || center.stale)
19
20
  return { status: "unavailable", reason: "Cluster missing or stale; refresh analysis first" };
20
- const edge = readCluster(params.db, params.clusterId, 3, 0, "score_asc");
21
+ const edge = readCluster(params.db, params.clusterId, DEFAULTS.review.clusterEdgeSamples, 0, "score_asc");
21
22
  const candidates = [...new Map([...(center.members ?? []), ...(edge.members ?? [])].map(member => [`${member.hash}:${member.seq}`, member])).values()];
22
23
  const sample = candidates.flatMap(member => {
23
24
  const path = member.sourcePaths.find(path => parseSafeVirtualPath(path, sources));
@@ -26,7 +27,7 @@ export async function reviewClusterIngestion(params) {
26
27
  const safe = parseSafeVirtualPath(path, sources);
27
28
  // Reload the full chunk; analysis previews may be truncated. Never judge a silently cut prefix.
28
29
  const row = indexedChunk(params.db, safe, member);
29
- if (!row || row.pos < 0 || row.chunk_len < 1 || row.pos + row.chunk_len > row.doc.length || row.chunk_len > 2000)
30
+ if (!row || row.pos < 0 || row.chunk_len < 1 || row.pos + row.chunk_len > row.doc.length || row.chunk_len > DEFAULTS.review.maxClaimChars)
30
31
  return [];
31
32
  const text = row.doc.slice(row.pos, row.pos + row.chunk_len);
32
33
  return [{ path, hash: member.hash, seq: member.seq, from: row.doc.slice(0, row.pos).split("\n").length,
@@ -54,10 +55,10 @@ export async function reviewClusterIngestion(params) {
54
55
  return { status: "unavailable", reason: "Sample changed during review; retry" };
55
56
  }
56
57
  const members = sample.map(({ text: _text, ...member }, index) => ({ ...member, ...judgments[index],
57
- flagged: judgments[index].defect !== "none_or_uncertain" && judgments[index].confidence >= 0.9 }));
58
+ flagged: judgments[index].defect !== "none_or_uncertain" && judgments[index].confidence >= DEFAULTS.review.minClusterConfidence }));
58
59
  const recurring = ["wrapper", "encoding", "boilerplate"].flatMap(defect => {
59
60
  const examples = members.filter(member => member.flagged && member.defect === defect);
60
- return examples.length >= 2 ? [{ defect, examples: examples.map(member => ({ path: member.path, from: member.from, fingerprint: member.fingerprint })) }] : [];
61
+ return examples.length >= DEFAULTS.review.minClusterAgreeingExamples ? [{ defect, examples: examples.map(member => ({ path: member.path, from: member.from, fingerprint: member.fingerprint })) }] : [];
61
62
  });
62
63
  return { status: "ok", runId: snapshot.runId, clusterId: params.clusterId, members, recurring,
63
64
  sampled: sample.length, considered: snapshot.considered, clusterSize: snapshot.clusterSize,
@@ -1,5 +1,6 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { isAbsolute } from "node:path";
2
- import { DEFAULT_DECISIONS_ENDPOINT, DEFAULT_DECISIONS_MODEL, resolveDecisionConfig, } from "@unblocklabs/decisions";
3
+ import { resolveDecisionConfig, } from "@unblocklabs/decisions";
3
4
  import { resolveExtraction } from "./extraction-config.js";
4
5
  import { resolveResponseAudit } from "./response-config.js";
5
6
  import { resolvePeoplePrimer } from "./people-primer-config.js";
@@ -20,18 +21,18 @@ export const DEFAULT_CORPORA = [
20
21
  ];
21
22
  export const DEFAULT_PEOPLE_CONFIG = {
22
23
  enabled: false,
23
- whisperer: { enabled: false, maxChars: 1200 },
24
- todos: { maxOpen: 1000 },
24
+ whisperer: { enabled: false, maxChars: DEFAULTS.people.defaultWhispererMaxChars },
25
+ todos: { maxOpen: DEFAULTS.people.defaultTodosMaxOpen },
25
26
  learning: DEFAULT_LEARNING,
26
27
  };
27
28
  const DEFAULT_DECISION_MODEL_CONFIG = {
28
29
  enabled: true,
29
- endpoint: DEFAULT_DECISIONS_ENDPOINT,
30
- model: DEFAULT_DECISIONS_MODEL,
31
- timeoutMs: 1500,
30
+ endpoint: DEFAULTS.decisionModel.endpoint,
31
+ model: DEFAULTS.decisionModel.model,
32
+ timeoutMs: DEFAULTS.decisionModel.timeoutMs,
32
33
  };
33
34
  const DEFAULT_QUALITY_AUDIT = {
34
- enabled: false, corpora: [], minNoise: 0.8,
35
+ enabled: false, corpora: [], minNoise: DEFAULTS.quality.defaultMinNoise,
35
36
  };
36
37
  function resolveQualityAudit(value, corpora) {
37
38
  if (value === undefined)
@@ -71,8 +72,8 @@ function resolveDecisionModel(value) {
71
72
  let resolved;
72
73
  try {
73
74
  resolved = resolveDecisionConfig({
74
- endpoint: config.endpoint,
75
- model: config.model === undefined ? DEFAULT_DECISIONS_MODEL : config.model,
75
+ endpoint: config.endpoint === undefined ? DEFAULTS.decisionModel.endpoint : config.endpoint,
76
+ model: config.model === undefined ? DEFAULTS.decisionModel.model : config.model,
76
77
  apiKey: config.apiKey,
77
78
  apiKeyFile: config.apiKeyFile,
78
79
  timeoutMs,
@@ -92,38 +93,40 @@ function resolveDecisionModel(value) {
92
93
  }
93
94
  const DEFAULT_SKILL_WHISPERER = {
94
95
  enabled: true,
95
- historyMessages: 5,
96
- minScore: 0.5,
97
- cooldownTurns: 10,
96
+ historyMessages: DEFAULTS.skillWhisperer.defaultHistoryMessages,
97
+ minScore: DEFAULTS.skillWhisperer.defaultMinScore,
98
+ cooldownTurns: DEFAULTS.skillWhisperer.defaultCooldownTurns,
98
99
  };
99
100
  const DEFAULT_MEMORY_WHISPERER = {
100
- enabled: false, complementaryHints: false, corpora: [], minUsefulness: 0.5,
101
- maxHints: 3, cooldownTurns: 10, timeoutMs: 3000,
102
- api: { endpoint: "http://192.168.1.191:18087" },
101
+ enabled: false, complementaryHints: false, corpora: [], minUsefulness: DEFAULTS.memoryWhisperer.defaultMinUsefulness,
102
+ maxHints: DEFAULTS.memoryWhisperer.defaultMaxHints, cooldownTurns: DEFAULTS.memoryWhisperer.defaultCooldownTurns,
103
+ timeoutMs: DEFAULTS.memoryWhisperer.defaultTimeoutMs, api: { endpoint: DEFAULTS.memoryWhisperer.defaultApiEndpoint },
103
104
  };
104
105
  function resolveQueryApi(value) {
105
106
  if (value === undefined)
106
- return { ...DEFAULT_MEMORY_WHISPERER.api };
107
+ value = {};
107
108
  if (!value || typeof value !== "object" || Array.isArray(value))
108
109
  throw new Error("memoryWhisperer.api must be an object");
109
110
  const config = value;
110
111
  assertOnlyKeys(config, ["endpoint", "apiKeyFile"], "memoryWhisperer.api");
111
112
  const endpoint = config.endpoint ?? DEFAULT_MEMORY_WHISPERER.api.endpoint;
112
113
  let url;
113
- try {
114
- url = new URL(typeof endpoint === "string" ? endpoint : "");
115
- }
116
- catch {
117
- throw new Error("memoryWhisperer.api.endpoint must be an HTTP(S) URL");
118
- }
119
- if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
120
- throw new Error("memoryWhisperer.api.endpoint must be an HTTP(S) URL without credentials, query or fragment");
114
+ if (endpoint !== "") {
115
+ try {
116
+ url = new URL(typeof endpoint === "string" ? endpoint : "");
117
+ }
118
+ catch {
119
+ throw new Error("memoryWhisperer.api.endpoint must be an HTTP(S) URL or empty");
120
+ }
121
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
122
+ throw new Error("memoryWhisperer.api.endpoint must be an HTTP(S) URL without credentials, query or fragment");
123
+ }
121
124
  }
122
125
  const apiKeyFile = config.apiKeyFile;
123
126
  if (apiKeyFile !== undefined && (typeof apiKeyFile !== "string" || !isAbsolute(apiKeyFile))) {
124
127
  throw new Error("memoryWhisperer.api.apiKeyFile must be an absolute path");
125
128
  }
126
- return { endpoint: url.href.replace(/\/$/u, ""), ...(apiKeyFile ? { apiKeyFile } : {}) };
129
+ return { endpoint: url?.href.replace(/\/$/u, "") ?? "", ...(apiKeyFile ? { apiKeyFile } : {}) };
127
130
  }
128
131
  function resolveMemoryWhisperer(value, corpora) {
129
132
  if (value === undefined)
@@ -156,7 +159,7 @@ function resolveMemoryWhisperer(value, corpora) {
156
159
  }
157
160
  if (enabled && !selected.length)
158
161
  throw new Error("unblock-memory enabled memoryWhisperer requires explicit corpora");
159
- const cooldownTurns = config.cooldownTurns ?? 10;
162
+ const cooldownTurns = config.cooldownTurns ?? DEFAULT_MEMORY_WHISPERER.cooldownTurns;
160
163
  if (typeof cooldownTurns !== "number" || !Number.isInteger(cooldownTurns) || cooldownTurns < 0 || cooldownTurns > 1000) {
161
164
  throw new Error("unblock-memory memoryWhisperer.cooldownTurns must be an integer between 0 and 1000");
162
165
  }
@@ -167,7 +170,7 @@ function resolveMemoryWhisperer(value, corpora) {
167
170
  return {
168
171
  enabled, complementaryHints, corpora: [...new Set(selected)], cooldownTurns, minUsefulness,
169
172
  maxHints: positiveInteger(config.maxHints, DEFAULT_MEMORY_WHISPERER.maxHints, "memoryWhisperer.maxHints", 3),
170
- timeoutMs: positiveInteger(config.timeoutMs, 3000, "memoryWhisperer.timeoutMs", 10_000),
173
+ timeoutMs: positiveInteger(config.timeoutMs, DEFAULT_MEMORY_WHISPERER.timeoutMs, "memoryWhisperer.timeoutMs", 10_000),
171
174
  api: resolveQueryApi(config.api),
172
175
  };
173
176
  }
@@ -360,9 +363,9 @@ export function resolveConfig(value) {
360
363
  const value = config.skillWhisperer;
361
364
  assertOnlyKeys(value, ["enabled", "historyMessages", "minScore", "cooldownTurns"], "skillWhisperer");
362
365
  const enabled = value.enabled ?? DEFAULT_SKILL_WHISPERER.enabled;
363
- const historyMessages = value.historyMessages ?? 5;
364
- const minScore = value.minScore ?? 0.5;
365
- const cooldownTurns = value.cooldownTurns ?? 10;
366
+ const historyMessages = value.historyMessages ?? DEFAULT_SKILL_WHISPERER.historyMessages;
367
+ const minScore = value.minScore ?? DEFAULT_SKILL_WHISPERER.minScore;
368
+ const cooldownTurns = value.cooldownTurns ?? DEFAULT_SKILL_WHISPERER.cooldownTurns;
366
369
  if (typeof enabled !== "boolean")
367
370
  throw new Error("unblock-memory skillWhisperer.enabled must be a boolean");
368
371
  if (typeof historyMessages !== "number" ||
@@ -1,7 +1,7 @@
1
- import { classifyDecisionFailure, DEFAULT_DECISIONS_MODEL, DecisionError, decisionModelScope, matchesDecisionModel, type DecisionResult, type QuestionMap } from "@unblocklabs/decisions";
1
+ import { classifyDecisionFailure, DecisionError, matchesDecisionModel, type DecisionResult, type ExtractionResult, type FieldMap, type QuestionMap } from "@unblocklabs/decisions";
2
2
  import { Type } from "typebox";
3
3
  import type { UnblockMemoryConfig } from "./config.js";
4
- export { classifyDecisionFailure, decisionModelScope, matchesDecisionModel, DEFAULT_DECISIONS_MODEL as DEFAULT_DECISION_MODEL, DecisionError as DecisionRequestError, };
4
+ export { classifyDecisionFailure, matchesDecisionModel, DecisionError as DecisionRequestError, };
5
5
  export declare const NOUL_SCHEMA: Type.TObject<{
6
6
  type: Type.TLiteral<"noul">;
7
7
  noul: Type.TNumber;
@@ -19,6 +19,8 @@ type DecisionRequestOptions = {
19
19
  timeoutMs?: number;
20
20
  signal?: AbortSignal;
21
21
  };
22
+ export declare const DEFAULT_DECISION_MODEL: string;
23
+ export declare function decisionModelScope(model?: string, endpoint?: string): string;
22
24
  /** A conservative estimate of serialized size, not a model-specific tokenizer. Non-ASCII is budgeted separately. */
23
25
  export declare function estimateDecisionTokens(value: unknown): number;
24
26
  /** A decision-model deadline: the request's own timeout, or the caller's timed-out signal. */
@@ -27,6 +29,10 @@ export declare function isDecisionTimeout(error: unknown, signal: AbortSignal):
27
29
  export declare function resolveDecisionCredential(config: Pick<UnblockMemoryConfig["decisionModel"], "enabled" | "apiKey" | "apiKeyFile"> & {
28
30
  endpoint?: string;
29
31
  }): Promise<string | undefined>;
32
+ /** Typed extraction call backed directly by @unblocklabs/decisions. */
33
+ export declare function extractWithModel<const F extends FieldMap>(params: DecisionRequestOptions, state: string, fields: F, options?: {
34
+ validateModel?: boolean;
35
+ }): Promise<ExtractionResult<F>>;
30
36
  /** Typed decision call backed directly by @unblocklabs/decisions. */
31
37
  export declare function decideWithModel<const Q extends QuestionMap>(params: DecisionRequestOptions, state: unknown, questions: Q, options?: {
32
38
  validateModel?: boolean;
@@ -1,11 +1,15 @@
1
- import { abortedByTimeout, classifyDecisionFailure, createDecisionClient, DEFAULT_DECISIONS_ENDPOINT, DEFAULT_DECISIONS_MODEL, DecisionError, decisionModelScope, matchesDecisionModel, resolveDecisionApiKey, resolveDecisionConfig, validateDecisionEndpoint, } from "@unblocklabs/decisions";
1
+ import { abortedByTimeout, classifyDecisionFailure, createDecisionClient, DEFAULT_DECISIONS_ENDPOINT, DecisionError, decisionModelScope as sdkDecisionModelScope, matchesDecisionModel, resolveDecisionApiKey, resolveDecisionConfig, validateDecisionEndpoint, } from "@unblocklabs/decisions";
2
2
  import { Type } from "typebox";
3
- export { classifyDecisionFailure, decisionModelScope, matchesDecisionModel, DEFAULT_DECISIONS_MODEL as DEFAULT_DECISION_MODEL, DecisionError as DecisionRequestError, };
3
+ import { DEFAULTS } from "./defaults.js";
4
+ export { classifyDecisionFailure, matchesDecisionModel, DecisionError as DecisionRequestError, };
4
5
  export const NOUL_SCHEMA = Type.Object({
5
6
  type: Type.Literal("noul"), noul: Type.Number({ minimum: 0, maximum: 1 }),
6
7
  });
7
8
  export const NOUL_ANSWERS_SCHEMA = Type.Object({ answers: Type.Record(Type.String(), NOUL_SCHEMA) });
8
- const DEFAULT_UNBOUNDED_TIMEOUT_MS = 60_000;
9
+ export const DEFAULT_DECISION_MODEL = DEFAULTS.decisionModel.model;
10
+ export function decisionModelScope(model = DEFAULT_DECISION_MODEL, endpoint = DEFAULTS.decisionModel.endpoint) {
11
+ return sdkDecisionModelScope(model, endpoint);
12
+ }
9
13
  const CODEX_ORIGIN = new URL(DEFAULT_DECISIONS_ENDPOINT).origin;
10
14
  /** A conservative estimate of serialized size, not a model-specific tokenizer. Non-ASCII is budgeted separately. */
11
15
  export function estimateDecisionTokens(value) {
@@ -31,11 +35,11 @@ export async function resolveDecisionCredential(config) {
31
35
  }
32
36
  return trimmed;
33
37
  }
34
- const endpoint = validateDecisionEndpoint(config.endpoint ?? DEFAULT_DECISIONS_ENDPOINT);
38
+ const endpoint = validateDecisionEndpoint(config.endpoint ?? DEFAULTS.decisionModel.endpoint);
35
39
  const codex = new URL(endpoint).origin === CODEX_ORIGIN;
36
40
  return resolveDecisionApiKey(resolveDecisionConfig({
37
41
  endpoint,
38
- model: DEFAULT_DECISIONS_MODEL,
42
+ model: DEFAULT_DECISION_MODEL,
39
43
  apiKeyFile: config.apiKeyFile,
40
44
  ambientEnvKeys: codex ? ["CODEX_LB_API_KEY"] : [],
41
45
  fileEnvKeys: codex ? ["CODEX_LB_API_KEY"] : ["CODEX_LB_API_KEY", "DECISION_MODEL_API_KEY"],
@@ -43,17 +47,26 @@ export async function resolveDecisionCredential(config) {
43
47
  }
44
48
  function requestClient(params, timeoutMs) {
45
49
  return createDecisionClient({
46
- endpoint: params.endpoint,
47
- model: params.model ?? DEFAULT_DECISIONS_MODEL,
50
+ endpoint: params.endpoint ?? DEFAULTS.decisionModel.endpoint,
51
+ model: params.model ?? DEFAULT_DECISION_MODEL,
48
52
  apiKey: params.apiKey,
49
53
  ambientEnvKeys: [],
50
54
  fileEnvKeys: [],
51
55
  timeoutMs,
52
56
  });
53
57
  }
58
+ /** Typed extraction call backed directly by @unblocklabs/decisions. */
59
+ export async function extractWithModel(params, state, fields, options) {
60
+ const timeoutMs = params.timeoutMs ?? DEFAULTS.decisionModel.unboundedTimeoutMs;
61
+ return requestClient(params, timeoutMs).extract(state, fields, {
62
+ timeoutMs,
63
+ signal: params.signal,
64
+ validateModel: options?.validateModel ?? true,
65
+ });
66
+ }
54
67
  /** Typed decision call backed directly by @unblocklabs/decisions. */
55
68
  export async function decideWithModel(params, state, questions, options) {
56
- const timeoutMs = params.timeoutMs ?? DEFAULT_UNBOUNDED_TIMEOUT_MS;
69
+ const timeoutMs = params.timeoutMs ?? DEFAULTS.decisionModel.unboundedTimeoutMs;
57
70
  return requestClient(params, timeoutMs).decide(state, questions, {
58
71
  timeoutMs,
59
72
  signal: params.signal,
@@ -66,7 +79,7 @@ export async function decideWithModel(params, state, questions, options) {
66
79
  * for callers that intentionally tolerate partial multi-question responses (e.g. Safety Whisperer).
67
80
  */
68
81
  export async function requestDecision(params, state, questions) {
69
- const timeoutMs = params.timeoutMs ?? DEFAULT_UNBOUNDED_TIMEOUT_MS;
82
+ const timeoutMs = params.timeoutMs ?? DEFAULTS.decisionModel.unboundedTimeoutMs;
70
83
  return requestClient(params, timeoutMs).decideRaw(state, questions, {
71
84
  timeoutMs,
72
85
  signal: params.signal,
@@ -1,7 +1,8 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { DecisionError, noul } from "@unblocklabs/decisions";
2
3
  import { decideWithModel, decisionModelScope, DEFAULT_DECISION_MODEL, } from "./decision-client.js";
3
4
  import { MEMORY_PASSAGE_CHARS } from "./memory-passage.js";
4
- const SKILL_MIN_USEFULNESS = 0.7;
5
+ const SKILL_MIN_USEFULNESS = DEFAULTS.skillWhisperer.minDecisionUsefulness;
5
6
  const SKILL_USEFUL_QUESTIONS = {
6
7
  useful: noul({
7
8
  question: "Would using the skill described by `candidate` materially help fulfill `currentRequest`?",
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { choice, noul } from "@unblocklabs/decisions";
2
3
  import { backgroundWordCount, PEOPLE_BACKGROUND_MAX_WORDS } from "./people-background.js";
3
4
  import { decideWithModel } from "./decision-client.js";
@@ -124,7 +125,7 @@ const CLUSTER_DEFECT_QUESTIONS = {
124
125
  export async function reviewClaim(params) {
125
126
  const interaction = params.personBackground?.kind === "interaction";
126
127
  if (params.personBackground && !interaction && backgroundWordCount(params.claim) > PEOPLE_BACKGROUND_MAX_WORDS) {
127
- throw new Error("Background snippet exceeds 70 words");
128
+ throw new Error(`Background snippet exceeds ${DEFAULTS.people.backgroundMaxWords} words`);
128
129
  }
129
130
  const state = {
130
131
  claim: params.claim,
@@ -146,8 +147,8 @@ export async function reviewClaim(params) {
146
147
  confidence: answer.confidence,
147
148
  probabilities: answer.probabilities,
148
149
  background,
149
- needsReview: answer.choice !== "supports" || answer.confidence < 0.9 ||
150
- background.backgroundOnly < 0.9 || background.explicitSupport < 0.9,
150
+ needsReview: answer.choice !== "supports" || answer.confidence < DEFAULTS.review.minClaimSupport ||
151
+ background.backgroundOnly < DEFAULTS.review.minClaimSupport || background.explicitSupport < DEFAULTS.review.minClaimSupport,
151
152
  };
152
153
  }
153
154
  const { answers } = await decideWithModel(params, state, CLAIM_ONLY_QUESTIONS, { validateModel: false });
@@ -156,12 +157,12 @@ export async function reviewClaim(params) {
156
157
  verdict: answer.choice,
157
158
  confidence: answer.confidence,
158
159
  probabilities: answer.probabilities,
159
- needsReview: answer.choice !== "supports" || answer.confidence < 0.9,
160
+ needsReview: answer.choice !== "supports" || answer.confidence < DEFAULTS.review.minClaimSupport,
160
161
  };
161
162
  }
162
163
  /** Directional coverage, not topic similarity. Bounded at six comparisons of four ranked candidates. */
163
164
  export async function reviewMemoryRedundancy(params) {
164
- if (params.excerpts.length > 4)
165
+ if (params.excerpts.length > DEFAULTS.review.maxRedundancyCandidates)
165
166
  throw new Error("Too many redundancy candidates");
166
167
  const pairs = params.excerpts.flatMap((_text, later) => params.excerpts.slice(0, later).map((_earlier, earlier) => ({ earlier, later })));
167
168
  if (!pairs.length)
@@ -174,14 +175,14 @@ export async function reviewMemoryRedundancy(params) {
174
175
  export function complementaryIndices(count, pairs, limit) {
175
176
  const selected = [];
176
177
  for (let index = 0; index < count && selected.length < limit; index++) {
177
- if (!pairs.some(pair => pair.later === index && selected.includes(pair.earlier) && pair.redundant >= 0.9))
178
+ if (!pairs.some(pair => pair.later === index && selected.includes(pair.earlier) && pair.redundant >= DEFAULTS.review.minRedundancy))
178
179
  selected.push(index);
179
180
  }
180
181
  return selected;
181
182
  }
182
183
  /** Classify defects per member. No cluster-wide judgment or generated repair instructions. */
183
184
  export async function reviewClusterDefects(params) {
184
- if (params.excerpts.length > 6)
185
+ if (params.excerpts.length > DEFAULTS.review.clusterCenterSamples + DEFAULTS.review.clusterEdgeSamples)
185
186
  throw new Error("Too many cluster members");
186
187
  if (!params.excerpts.length)
187
188
  return [];
@@ -0,0 +1,8 @@
1
+ import type bundledDefaults from "../defaults.json";
2
+ type OperationalDefaults = {
3
+ readonly [K in keyof typeof bundledDefaults]: Readonly<(typeof bundledDefaults)[K]>;
4
+ };
5
+ /** An explicit override path takes precedence over the process-wide environment setting. */
6
+ export declare function loadOperationalDefaults(overridePath?: string | undefined): OperationalDefaults;
7
+ export declare const DEFAULTS: OperationalDefaults;
8
+ export {};
@@ -0,0 +1,128 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { basename, isAbsolute } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const here = new URL(import.meta.url);
5
+ // Use the package-root copy even when tsc emits a type-import copy under dist/.
6
+ const bundledPath = new URL(basename(fileURLToPath(new URL("../", here))) === "dist"
7
+ ? "../../defaults.json" : "../defaults.json", here);
8
+ const reasoningLevels = ["none", "minimal", "low", "medium", "high", "xhigh"];
9
+ const probabilities = new Set([
10
+ "minProposalConfidence", "minSupport", "minRetention", "minReplacement", "gateThreshold",
11
+ "defaultMinUsefulness", "minDecisionUsefulness", "defaultMinScore", "nudgeMaxProbability",
12
+ "defaultMinProbability", "minClaimSupport", "minRedundancy", "minClusterConfidence",
13
+ "defaultMinNoise", "triageNoiseThreshold", "triageEvidenceHigh", "triageEvidenceLow",
14
+ "primerUncertainFloor", "scoreHigh", "scoreLow",
15
+ ]);
16
+ const ranges = {
17
+ "decisionModel.timeoutMs": [1, 10_000],
18
+ "decisionModel.unboundedTimeoutMs": [1, 60_000],
19
+ "extraction.proposalTimeoutMs": [1, 60_000],
20
+ "extraction.validationTimeoutMs": [1, 60_000],
21
+ "extraction.intervalMinutes": [0, 1440],
22
+ "extraction.historyMessages": [0, 20],
23
+ "extraction.maxBatches": [1, 50],
24
+ "extraction.inputLimitTokens": [1, 32_000],
25
+ "training.decisionTimeoutMs": [1, 60_000],
26
+ "memoryWhisperer.defaultMaxHints": [1, 3],
27
+ "memoryWhisperer.defaultCooldownTurns": [0, 1000],
28
+ "memoryWhisperer.defaultTimeoutMs": [1, 10_000],
29
+ "skillWhisperer.defaultHistoryMessages": [0, Number.MAX_SAFE_INTEGER],
30
+ "skillWhisperer.defaultCooldownTurns": [0, Number.MAX_SAFE_INTEGER],
31
+ "myTurn.defaultHistoryMessages": [1, 50],
32
+ "safetyWhisperer.defaultHistoryMessages": [0, 20],
33
+ "safetyWhisperer.defaultTimeoutMs": [1, 10_000],
34
+ "people.defaultWhispererMaxChars": [1, 4000],
35
+ "people.defaultTodosMaxOpen": [1, 10_000],
36
+ "responseAudit.defaultHistoryMessages": [0, 20],
37
+ "responseAudit.defaultLookbackDays": [1, 90],
38
+ "responseAudit.defaultMaxEpisodes": [1, 100],
39
+ "responseAudit.defaultIntervalMinutes": [0, 1440],
40
+ "insideOut.defaultIntervalMinutes": [0, 10080],
41
+ "insideOut.defaultMaxInteractions": [1, 10000],
42
+ "insideOut.defaultMaxContextTokens": [256, 30_000],
43
+ "insideOut.defaultBaselineMinInteractions": [1, 10000],
44
+ };
45
+ function record(value) {
46
+ return value !== null && typeof value === "object" && !Array.isArray(value);
47
+ }
48
+ function readJson(path) {
49
+ try {
50
+ return JSON.parse(readFileSync(path, "utf8"));
51
+ }
52
+ catch (error) {
53
+ throw new Error(`Cannot load operational defaults from ${path}: ${error instanceof Error ? error.message : String(error)}`);
54
+ }
55
+ }
56
+ function validUrl(value, http) {
57
+ try {
58
+ const url = new URL(value);
59
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
60
+ return !/[\s?#]/u.test(value) && (url.protocol === "https:" ||
61
+ (url.protocol === "http:" && (http === "any" || (http === "loopback" && loopback)))) &&
62
+ !url.username && !url.password && !url.hash && !url.search;
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ function validLeaf(base, value, path, key) {
69
+ if (typeof base === "number" && typeof value === "number") {
70
+ if (probabilities.has(key))
71
+ return Number.isFinite(value) && value >= 0 && value <= 1;
72
+ const [min, max] = ranges[path] ?? [1, key.endsWith("Ms") ? 2_147_483_647 : Number.MAX_SAFE_INTEGER];
73
+ return Number.isSafeInteger(value) && value >= min && value <= max;
74
+ }
75
+ if (typeof base !== "string" || typeof value !== "string")
76
+ return false;
77
+ if (path === "memoryWhisperer.defaultApiEndpoint")
78
+ return value === "" || validUrl(value, "any");
79
+ if (path === "decisionModel.endpoint")
80
+ return validUrl(value, "loopback");
81
+ if (path === "people.slackApiUrl")
82
+ return validUrl(value, "none");
83
+ if (path === "training.teacherReasoning")
84
+ return reasoningLevels.includes(value);
85
+ if (path === "training.teacherModel")
86
+ return /^[^/\s]+\/[^\s]+$/u.test(value);
87
+ return value.trim() === value && value.length > 0 && !/\s/u.test(value);
88
+ }
89
+ function merge(base, patch, parent = "") {
90
+ if (!record(patch))
91
+ throw new Error(`Invalid operational default ${parent || "(root)"}: expected an object`);
92
+ for (const key of Object.keys(patch)) {
93
+ if (!Object.hasOwn(base, key))
94
+ throw new Error(`Unknown operational default ${parent ? `${parent}.` : ""}${key}`);
95
+ }
96
+ return Object.freeze(Object.fromEntries(Object.entries(base).map(([key, fallback]) => {
97
+ const path = parent ? `${parent}.${key}` : key;
98
+ const value = Object.hasOwn(patch, key) ? patch[key] : fallback;
99
+ if (record(fallback))
100
+ return [key, merge(fallback, value, path)];
101
+ if (!validLeaf(fallback, value, path, key))
102
+ throw new Error(`Invalid operational default ${path}: wrong type or out of range`);
103
+ return [key, value];
104
+ })));
105
+ }
106
+ /** An explicit override path takes precedence over the process-wide environment setting. */
107
+ export function loadOperationalDefaults(overridePath = process.env.UNBLOCK_MEMORY_DEFAULTS_FILE) {
108
+ if (overridePath !== undefined && !isAbsolute(overridePath)) {
109
+ throw new Error("UNBLOCK_MEMORY_DEFAULTS_FILE / operational defaults path must be absolute");
110
+ }
111
+ const base = readJson(bundledPath);
112
+ if (!record(base))
113
+ throw new Error("Bundled defaults.json must be an object");
114
+ const result = merge(base, overridePath === undefined ? {} : readJson(overridePath));
115
+ const { extraction, training, quality, responseAudit } = result;
116
+ if (extraction.inputTargetTokens > extraction.inputLimitTokens ||
117
+ extraction.historyTokenBudget + extraction.promptReserveTokens >= extraction.inputTargetTokens) {
118
+ throw new Error("Invalid operational defaults: extraction history, reserve, target and limit token budgets conflict");
119
+ }
120
+ if (extraction.heartbeatMs >= extraction.leaseMs || training.heartbeatMs >= training.leaseMs) {
121
+ throw new Error("Invalid operational defaults: extraction and training heartbeats must be shorter than their leases");
122
+ }
123
+ if (quality.triageEvidenceLow > quality.triageEvidenceHigh || responseAudit.scoreLow > responseAudit.scoreHigh) {
124
+ throw new Error("Invalid operational defaults: low score threshold exceeds high score threshold");
125
+ }
126
+ return result;
127
+ }
128
+ export const DEFAULTS = loadOperationalDefaults();