chainlesschain 0.166.145 → 0.166.146
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -10
- package/package.json +2 -2
- package/src/assets/linux-subreaper/linux-arm64/manifest.json +1 -1
- package/src/assets/linux-subreaper/linux-x64/manifest.json +1 -1
- package/src/command-help-index.json +2 -2
- package/src/commands/agent.js +20 -1
- package/src/commands/mcp-tasks.js +37 -4
- package/src/commands/mcp.js +24 -0
- package/src/commands/memory.js +131 -7
- package/src/data/changelog.json +13 -0
- package/src/generated/cc-agent-protocol.schema.json +175 -69
- package/src/harness/jsonl-session-store.js +4 -0
- package/src/harness/mcp-client.js +273 -48
- package/src/harness/prompt-compressor.js +1 -0
- package/src/harness/session-index.js +8 -0
- package/src/harness/session-list-index.js +2 -0
- package/src/lib/agent-session-export.js +19 -0
- package/src/lib/app-server/context-memory-notifications.js +11 -2
- package/src/lib/app-server/server.js +1 -0
- package/src/lib/background-launch-profile.js +38 -6
- package/src/lib/context-memory-kernel/local-semantic-source.js +426 -0
- package/src/lib/context-memory-kernel/local-semantic-worker.py +109 -0
- package/src/lib/context-memory-kernel/memory-service.js +35 -2
- package/src/lib/context-memory-kernel/provider-context.js +1 -1
- package/src/lib/context-memory-kernel/runtime.js +40 -0
- package/src/lib/evolution/evolution-artifact-ports.js +36 -1
- package/src/lib/formal-budget-authority.js +56 -3
- package/src/lib/formal-budget-contract.js +90 -5
- package/src/lib/mcp-client.js +1 -0
- package/src/lib/mcp-stateless-protocol.js +158 -0
- package/src/lib/mcp-task-continuation-contract.js +129 -0
- package/src/lib/mcp-task-continuation.js +147 -0
- package/src/lib/mcp-task-journal-projection.js +49 -4
- package/src/lib/mcp-task-runtime.js +148 -1
- package/src/lib/mcp-tasks.js +24 -0
- package/src/lib/session-host-snapshot.js +31 -0
- package/src/lib/session-input-lifecycle.js +147 -0
- package/src/lib/session-input-receipt.js +64 -0
- package/src/lib/session-message-provenance.js +6 -5
- package/src/lib/session-model-usage-recovery.js +115 -0
- package/src/lib/session-transcript-history.js +3 -0
- package/src/lib/session-transcript-structure.js +8 -1
- package/src/lib/storage-failure-cause-codes.js +79 -0
- package/src/repl/agent-repl.js +348 -23
- package/src/runtime/agent-core.js +29 -11
- package/src/runtime/headless-runner.js +1 -0
- package/src/runtime/headless-stream.js +40 -33
- package/src/runtime/mcp-config.js +5 -3
- package/src/runtime/policies/agent-policy.js +1 -0
|
@@ -12,7 +12,8 @@ import { dirname, join, parse, resolve } from "node:path";
|
|
|
12
12
|
import { getConfigPath } from "./paths.js";
|
|
13
13
|
import { assertBackgroundArgvDurable } from "./background-command-argv.js";
|
|
14
14
|
|
|
15
|
-
export const BACKGROUND_LAUNCH_PROFILE_VERSION =
|
|
15
|
+
export const BACKGROUND_LAUNCH_PROFILE_VERSION = 2;
|
|
16
|
+
const LEGACY_BACKGROUND_LAUNCH_PROFILE_VERSION = 1;
|
|
16
17
|
|
|
17
18
|
const PERMISSION_MODES = new Set([
|
|
18
19
|
"manual",
|
|
@@ -247,7 +248,7 @@ function splitLongOption(token) {
|
|
|
247
248
|
|
|
248
249
|
function emptyParsedProfile(cwd, worktree, governance) {
|
|
249
250
|
return {
|
|
250
|
-
version:
|
|
251
|
+
version: LEGACY_BACKGROUND_LAUNCH_PROFILE_VERSION,
|
|
251
252
|
command: "agent",
|
|
252
253
|
llm: {
|
|
253
254
|
provider: null,
|
|
@@ -514,6 +515,14 @@ export function captureBackgroundLaunchProfile({
|
|
|
514
515
|
"thinkingTokens",
|
|
515
516
|
);
|
|
516
517
|
break;
|
|
518
|
+
case "--max-output-tokens":
|
|
519
|
+
// Older readers must reject this profile rather than drop its cap.
|
|
520
|
+
profile.version = BACKGROUND_LAUNCH_PROFILE_VERSION;
|
|
521
|
+
profile.budget.maxOutputTokens = policyBudget(
|
|
522
|
+
takePolicy(),
|
|
523
|
+
"maxOutputTokens",
|
|
524
|
+
);
|
|
525
|
+
break;
|
|
517
526
|
case "--max-rewakes":
|
|
518
527
|
profile.budget.maxRewakes = policyBudget(takePolicy(), "maxRewakes");
|
|
519
528
|
break;
|
|
@@ -718,11 +727,24 @@ function normalizeSource(source) {
|
|
|
718
727
|
|
|
719
728
|
/** Whitelist and normalize a profile supplied across an API boundary. */
|
|
720
729
|
export function normalizeBackgroundLaunchProfile(input) {
|
|
721
|
-
|
|
730
|
+
const version = Number(input?.version);
|
|
731
|
+
if (
|
|
732
|
+
!input ||
|
|
733
|
+
![
|
|
734
|
+
LEGACY_BACKGROUND_LAUNCH_PROFILE_VERSION,
|
|
735
|
+
BACKGROUND_LAUNCH_PROFILE_VERSION,
|
|
736
|
+
].includes(version)
|
|
737
|
+
) {
|
|
722
738
|
throw new Error(
|
|
723
739
|
`Unsupported background launch profile version: ${input?.version ?? "missing"}`,
|
|
724
740
|
);
|
|
725
741
|
}
|
|
742
|
+
if (
|
|
743
|
+
version === LEGACY_BACKGROUND_LAUNCH_PROFILE_VERSION &&
|
|
744
|
+
input.budget?.maxOutputTokens != null
|
|
745
|
+
) {
|
|
746
|
+
throw invalidProfileField("version");
|
|
747
|
+
}
|
|
726
748
|
const rejectField = (field) => {
|
|
727
749
|
throw invalidProfileField(field);
|
|
728
750
|
};
|
|
@@ -800,6 +822,7 @@ export function normalizeBackgroundLaunchProfile(input) {
|
|
|
800
822
|
"maxTurns",
|
|
801
823
|
"maxCostUsd",
|
|
802
824
|
"thinkingTokens",
|
|
825
|
+
"maxOutputTokens",
|
|
803
826
|
"maxRewakes",
|
|
804
827
|
"maxOuterTurns",
|
|
805
828
|
"goalMaxTokens",
|
|
@@ -830,7 +853,7 @@ export function normalizeBackgroundLaunchProfile(input) {
|
|
|
830
853
|
.filter(Boolean)
|
|
831
854
|
.sort((a, b) => a.path.localeCompare(b.path));
|
|
832
855
|
return {
|
|
833
|
-
version
|
|
856
|
+
version,
|
|
834
857
|
command: "agent",
|
|
835
858
|
llm: {
|
|
836
859
|
provider: scalar(input.llm?.provider),
|
|
@@ -891,6 +914,14 @@ export function normalizeBackgroundLaunchProfile(input) {
|
|
|
891
914
|
maxTurns: positive(input.budget?.maxTurns, true),
|
|
892
915
|
maxCostUsd: positive(input.budget?.maxCostUsd),
|
|
893
916
|
thinkingTokens: positive(input.budget?.thinkingTokens, true),
|
|
917
|
+
...(input.budget?.maxOutputTokens == null
|
|
918
|
+
? {}
|
|
919
|
+
: {
|
|
920
|
+
maxOutputTokens: policyBudget(
|
|
921
|
+
input.budget.maxOutputTokens,
|
|
922
|
+
"maxOutputTokens",
|
|
923
|
+
),
|
|
924
|
+
}),
|
|
894
925
|
maxRewakes: positive(input.budget?.maxRewakes, true),
|
|
895
926
|
maxOuterTurns: positive(input.budget?.maxOuterTurns, true),
|
|
896
927
|
goalMaxTokens: positive(input.budget?.goalMaxTokens, true),
|
|
@@ -1001,8 +1032,8 @@ function same(a, b) {
|
|
|
1001
1032
|
}
|
|
1002
1033
|
|
|
1003
1034
|
function isBudgetLooser(before, after) {
|
|
1004
|
-
if (before
|
|
1005
|
-
return after
|
|
1035
|
+
if (before == null) return false;
|
|
1036
|
+
return after == null || Number(after) > Number(before);
|
|
1006
1037
|
}
|
|
1007
1038
|
|
|
1008
1039
|
function isToolPolicyLooser(before, after) {
|
|
@@ -1151,6 +1182,7 @@ export function buildArgvFromBackgroundLaunchProfile(profile) {
|
|
|
1151
1182
|
pushValue(argv, "--max-turns", p.budget.maxTurns);
|
|
1152
1183
|
pushValue(argv, "--max-budget-usd", p.budget.maxCostUsd);
|
|
1153
1184
|
pushValue(argv, "--thinking-budget", p.budget.thinkingTokens);
|
|
1185
|
+
pushValue(argv, "--max-output-tokens", p.budget.maxOutputTokens);
|
|
1154
1186
|
pushValue(argv, "--max-rewakes", p.budget.maxRewakes);
|
|
1155
1187
|
pushValue(argv, "--max-outer-turns", p.budget.maxOuterTurns);
|
|
1156
1188
|
pushValue(argv, "--goal-max-tokens", p.budget.goalMaxTokens);
|
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const WORKER = fileURLToPath(
|
|
7
|
+
new URL("./local-semantic-worker.py", import.meta.url),
|
|
8
|
+
);
|
|
9
|
+
const MAX_INPUT_BYTES = 8 * 1024 * 1024;
|
|
10
|
+
const MAX_RECORDS = 10_000;
|
|
11
|
+
const MAX_OUTPUT_BYTES = 12 * 1024 * 1024;
|
|
12
|
+
const UNCONFIRMED_WORKERS = new Set();
|
|
13
|
+
let workerActive = false;
|
|
14
|
+
export const LOCAL_SEMANTIC_SCHEMA = "chainlesschain.memory-local-semantic/v1";
|
|
15
|
+
|
|
16
|
+
function failure(code, message) {
|
|
17
|
+
return Object.assign(new Error(message), { code });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function absoluteFile(value, label) {
|
|
21
|
+
if (
|
|
22
|
+
typeof value !== "string" ||
|
|
23
|
+
!path.isAbsolute(value) ||
|
|
24
|
+
value.includes("\0")
|
|
25
|
+
) {
|
|
26
|
+
throw failure(
|
|
27
|
+
"CC_MEMORY_SEMANTIC_CONFIG",
|
|
28
|
+
`${label} must be an absolute path`,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
return fs.realpathSync(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function digestFile(file) {
|
|
35
|
+
return createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Local-only opt-in. No PATH lookup, download, inherited provider credentials or fallback encoder. */
|
|
39
|
+
export function resolveLocalSemanticConfiguration(env = process.env) {
|
|
40
|
+
const mode = env.CC_MEMORY_SEMANTIC_MODE || "off";
|
|
41
|
+
if (mode === "off") return null;
|
|
42
|
+
if (mode !== "local-bge")
|
|
43
|
+
throw failure("CC_MEMORY_SEMANTIC_CONFIG", "Unknown Memory semantic mode");
|
|
44
|
+
const python = absoluteFile(
|
|
45
|
+
env.CC_MEMORY_SEMANTIC_PYTHON,
|
|
46
|
+
"Python executable",
|
|
47
|
+
);
|
|
48
|
+
const modelDirectory = absoluteFile(
|
|
49
|
+
env.CC_MEMORY_SEMANTIC_MODEL_DIR,
|
|
50
|
+
"BGE model directory",
|
|
51
|
+
);
|
|
52
|
+
const pythonDigest = env.CC_MEMORY_SEMANTIC_PYTHON_SHA256;
|
|
53
|
+
if (!/^[a-f0-9]{64}$/.test(pythonDigest || "")) {
|
|
54
|
+
throw failure(
|
|
55
|
+
"CC_MEMORY_SEMANTIC_CONFIG",
|
|
56
|
+
"Python executable SHA-256 is required",
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
const threads = Number(env.CC_MEMORY_SEMANTIC_THREADS || 2);
|
|
60
|
+
const timeoutMs = Number(env.CC_MEMORY_SEMANTIC_TIMEOUT_MS || 60_000);
|
|
61
|
+
if (
|
|
62
|
+
!Number.isInteger(threads) ||
|
|
63
|
+
threads < 1 ||
|
|
64
|
+
threads > 8 ||
|
|
65
|
+
!Number.isInteger(timeoutMs) ||
|
|
66
|
+
timeoutMs < 1000 ||
|
|
67
|
+
timeoutMs > 300_000
|
|
68
|
+
) {
|
|
69
|
+
throw failure(
|
|
70
|
+
"CC_MEMORY_SEMANTIC_CONFIG",
|
|
71
|
+
"Invalid semantic CPU/time bounds",
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
const environment = {};
|
|
75
|
+
for (const name of [
|
|
76
|
+
"SystemRoot",
|
|
77
|
+
"SYSTEMROOT",
|
|
78
|
+
"WINDIR",
|
|
79
|
+
"TEMP",
|
|
80
|
+
"TMP",
|
|
81
|
+
"TMPDIR",
|
|
82
|
+
]) {
|
|
83
|
+
if (process.env[name]) environment[name] = process.env[name];
|
|
84
|
+
}
|
|
85
|
+
Object.assign(environment, {
|
|
86
|
+
HF_HUB_OFFLINE: "1",
|
|
87
|
+
TRANSFORMERS_OFFLINE: "1",
|
|
88
|
+
TOKENIZERS_PARALLELISM: "false",
|
|
89
|
+
CUDA_VISIBLE_DEVICES: "",
|
|
90
|
+
OMP_NUM_THREADS: String(threads),
|
|
91
|
+
MKL_NUM_THREADS: String(threads),
|
|
92
|
+
});
|
|
93
|
+
return Object.freeze({
|
|
94
|
+
python,
|
|
95
|
+
pythonDigest,
|
|
96
|
+
modelDirectory,
|
|
97
|
+
threads,
|
|
98
|
+
timeoutMs,
|
|
99
|
+
environment: Object.freeze(environment),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Only one encoder per CLI process; concurrent requests fail explicitly instead of oversubscribing CPU. */
|
|
104
|
+
export async function runLocalSemanticWorker(
|
|
105
|
+
configuration,
|
|
106
|
+
request,
|
|
107
|
+
controls = {},
|
|
108
|
+
) {
|
|
109
|
+
controls.signal?.throwIfAborted();
|
|
110
|
+
if (workerActive)
|
|
111
|
+
throw failure(
|
|
112
|
+
"CC_MEMORY_SEMANTIC_BUSY",
|
|
113
|
+
"Another local Memory encoder is running; retry after it completes",
|
|
114
|
+
);
|
|
115
|
+
workerActive = true;
|
|
116
|
+
try {
|
|
117
|
+
return await executeLocalSemanticWorker(configuration, request, controls);
|
|
118
|
+
} finally {
|
|
119
|
+
workerActive = false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Normal Stop waits for close; unconfirmed cleanup rejects with an execution fence. */
|
|
124
|
+
async function executeLocalSemanticWorker(
|
|
125
|
+
configuration,
|
|
126
|
+
request,
|
|
127
|
+
{ signal } = {},
|
|
128
|
+
) {
|
|
129
|
+
signal?.throwIfAborted();
|
|
130
|
+
if (UNCONFIRMED_WORKERS.size) {
|
|
131
|
+
throw failure(
|
|
132
|
+
"CC_MEMORY_SEMANTIC_CLEANUP_UNCONFIRMED",
|
|
133
|
+
"A previous semantic worker has not confirmed exit; no new worker may start",
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
const { executionBroker } =
|
|
137
|
+
await import("../process-execution-broker/index.js");
|
|
138
|
+
signal?.throwIfAborted();
|
|
139
|
+
if (digestFile(configuration.python) !== configuration.pythonDigest) {
|
|
140
|
+
throw failure(
|
|
141
|
+
"CC_MEMORY_SEMANTIC_IDENTITY",
|
|
142
|
+
"Python executable identity changed",
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
const workerDigest = digestFile(WORKER);
|
|
146
|
+
const input = JSON.stringify({
|
|
147
|
+
...request,
|
|
148
|
+
schema: LOCAL_SEMANTIC_SCHEMA,
|
|
149
|
+
modelDirectory: configuration.modelDirectory,
|
|
150
|
+
threads: configuration.threads,
|
|
151
|
+
});
|
|
152
|
+
if (Buffer.byteLength(input) > MAX_INPUT_BYTES) {
|
|
153
|
+
throw failure(
|
|
154
|
+
"CC_MEMORY_SEMANTIC_CAPACITY",
|
|
155
|
+
"Memory semantic input exceeds 8 MiB",
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
signal?.throwIfAborted();
|
|
159
|
+
const output = await new Promise((resolve, reject) => {
|
|
160
|
+
const child = executionBroker.spawn(
|
|
161
|
+
configuration.python,
|
|
162
|
+
["-I", "-B", WORKER],
|
|
163
|
+
{
|
|
164
|
+
cwd: path.dirname(WORKER),
|
|
165
|
+
env: { ...configuration.environment },
|
|
166
|
+
shell: false,
|
|
167
|
+
windowsHide: true,
|
|
168
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
169
|
+
origin: "memory-local-semantic",
|
|
170
|
+
scope: "memory",
|
|
171
|
+
policy: "allow",
|
|
172
|
+
},
|
|
173
|
+
);
|
|
174
|
+
let pendingError = null;
|
|
175
|
+
let cleanupTimer = null;
|
|
176
|
+
let settled = false;
|
|
177
|
+
let outputBytes = 0;
|
|
178
|
+
let stderrBytes = 0;
|
|
179
|
+
const chunks = [];
|
|
180
|
+
const stop = (error) => {
|
|
181
|
+
if (pendingError) return;
|
|
182
|
+
pendingError = error;
|
|
183
|
+
UNCONFIRMED_WORKERS.add(child);
|
|
184
|
+
cleanupTimer = setTimeout(() => {
|
|
185
|
+
if (settled) return;
|
|
186
|
+
settled = true;
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
signal?.removeEventListener("abort", abort);
|
|
189
|
+
const error = failure(
|
|
190
|
+
"CC_MEMORY_SEMANTIC_CLEANUP_UNCONFIRMED",
|
|
191
|
+
"Local semantic worker termination was not confirmed; semantic execution remains blocked until close",
|
|
192
|
+
);
|
|
193
|
+
error.recoveryRequired = true;
|
|
194
|
+
error.cause = pendingError;
|
|
195
|
+
reject(error);
|
|
196
|
+
}, 5000);
|
|
197
|
+
try {
|
|
198
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
199
|
+
child.kill("SIGKILL");
|
|
200
|
+
} catch {
|
|
201
|
+
/* The cleanup deadline reports unconfirmed termination without claiming success. */
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
const abort = () =>
|
|
205
|
+
stop(
|
|
206
|
+
signal.reason ||
|
|
207
|
+
failure("ABORT_ERR", "Memory semantic recall interrupted"),
|
|
208
|
+
);
|
|
209
|
+
const timer = setTimeout(
|
|
210
|
+
() =>
|
|
211
|
+
stop(
|
|
212
|
+
failure(
|
|
213
|
+
"CC_MEMORY_SEMANTIC_TIMEOUT",
|
|
214
|
+
"Local semantic worker timed out",
|
|
215
|
+
),
|
|
216
|
+
),
|
|
217
|
+
configuration.timeoutMs,
|
|
218
|
+
);
|
|
219
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
220
|
+
child.on("error", () =>
|
|
221
|
+
stop(
|
|
222
|
+
failure(
|
|
223
|
+
"CC_MEMORY_SEMANTIC_SPAWN",
|
|
224
|
+
"Could not launch local semantic worker",
|
|
225
|
+
),
|
|
226
|
+
),
|
|
227
|
+
);
|
|
228
|
+
child.stdin.once("error", () =>
|
|
229
|
+
stop(
|
|
230
|
+
failure(
|
|
231
|
+
"CC_MEMORY_SEMANTIC_INPUT",
|
|
232
|
+
"Local semantic worker input failed",
|
|
233
|
+
),
|
|
234
|
+
),
|
|
235
|
+
);
|
|
236
|
+
child.stdout.on("data", (chunk) => {
|
|
237
|
+
if (pendingError) return;
|
|
238
|
+
outputBytes += chunk.length;
|
|
239
|
+
if (outputBytes > MAX_OUTPUT_BYTES) {
|
|
240
|
+
stop(
|
|
241
|
+
failure(
|
|
242
|
+
"CC_MEMORY_SEMANTIC_OUTPUT",
|
|
243
|
+
"Local semantic worker output exceeded its bound",
|
|
244
|
+
),
|
|
245
|
+
);
|
|
246
|
+
} else chunks.push(chunk);
|
|
247
|
+
});
|
|
248
|
+
// Never echo stderr: a failed dependency may include private query/record text.
|
|
249
|
+
child.stderr.on("data", (chunk) => {
|
|
250
|
+
stderrBytes += chunk.length;
|
|
251
|
+
if (stderrBytes > 64 * 1024)
|
|
252
|
+
stop(
|
|
253
|
+
failure(
|
|
254
|
+
"CC_MEMORY_SEMANTIC_OUTPUT",
|
|
255
|
+
"Local semantic worker diagnostics exceeded their bound",
|
|
256
|
+
),
|
|
257
|
+
);
|
|
258
|
+
});
|
|
259
|
+
child.once("close", (code, exitSignal) => {
|
|
260
|
+
clearTimeout(timer);
|
|
261
|
+
clearTimeout(cleanupTimer);
|
|
262
|
+
UNCONFIRMED_WORKERS.delete(child);
|
|
263
|
+
signal?.removeEventListener("abort", abort);
|
|
264
|
+
if (settled) return;
|
|
265
|
+
settled = true;
|
|
266
|
+
if (pendingError) return reject(pendingError);
|
|
267
|
+
if (code !== 0 || exitSignal) {
|
|
268
|
+
return reject(
|
|
269
|
+
failure(
|
|
270
|
+
"CC_MEMORY_SEMANTIC_WORKER",
|
|
271
|
+
"Local semantic worker failed; verify the pinned model and local Python dependencies",
|
|
272
|
+
),
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
276
|
+
});
|
|
277
|
+
if (signal?.aborted) abort();
|
|
278
|
+
if (!pendingError) child.stdin.end(input);
|
|
279
|
+
});
|
|
280
|
+
signal?.throwIfAborted();
|
|
281
|
+
if (
|
|
282
|
+
digestFile(WORKER) !== workerDigest ||
|
|
283
|
+
digestFile(configuration.python) !== configuration.pythonDigest
|
|
284
|
+
) {
|
|
285
|
+
throw failure(
|
|
286
|
+
"CC_MEMORY_SEMANTIC_IDENTITY",
|
|
287
|
+
"Semantic executable identity changed during inference",
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
let result;
|
|
291
|
+
try {
|
|
292
|
+
result = JSON.parse(output);
|
|
293
|
+
} catch {
|
|
294
|
+
throw failure(
|
|
295
|
+
"CC_MEMORY_SEMANTIC_OUTPUT",
|
|
296
|
+
"Malformed local semantic result",
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
if (
|
|
300
|
+
result?.schema !== LOCAL_SEMANTIC_SCHEMA ||
|
|
301
|
+
result.requestDigest !== createHash("sha256").update(input).digest("hex") ||
|
|
302
|
+
result.modelRevision !== "a5beb1e3e68b9ab74eb54cfd186867f64f240e1a" ||
|
|
303
|
+
result.networkCalls !== 0 ||
|
|
304
|
+
!Array.isArray(result.scores) ||
|
|
305
|
+
result.scores.length !== request.records.length
|
|
306
|
+
) {
|
|
307
|
+
throw failure(
|
|
308
|
+
"CC_MEMORY_SEMANTIC_OUTPUT",
|
|
309
|
+
"Local semantic result identity or cardinality mismatch",
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
const ids = new Set(request.records.map((record) => record.memoryId));
|
|
313
|
+
const seen = new Set();
|
|
314
|
+
for (const row of result.scores) {
|
|
315
|
+
if (
|
|
316
|
+
!ids.has(row.memoryId) ||
|
|
317
|
+
seen.has(row.memoryId) ||
|
|
318
|
+
!Number.isFinite(row.score) ||
|
|
319
|
+
row.score < 0 ||
|
|
320
|
+
row.score > 1
|
|
321
|
+
) {
|
|
322
|
+
throw failure(
|
|
323
|
+
"CC_MEMORY_SEMANTIC_OUTPUT",
|
|
324
|
+
"Invalid local semantic score",
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
seen.add(row.memoryId);
|
|
328
|
+
}
|
|
329
|
+
return result.scores;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function createLocalSemanticSource({
|
|
333
|
+
memoryPort,
|
|
334
|
+
env,
|
|
335
|
+
clock = Date.now,
|
|
336
|
+
}) {
|
|
337
|
+
// Resolve lazily: disabled recall/shadow must never inspect or launch a model.
|
|
338
|
+
return Object.freeze({
|
|
339
|
+
isEnabled() {
|
|
340
|
+
return ((env || process.env).CC_MEMORY_SEMANTIC_MODE || "off") !== "off";
|
|
341
|
+
},
|
|
342
|
+
async candidates(request, { signal } = {}) {
|
|
343
|
+
signal?.throwIfAborted();
|
|
344
|
+
const configuration = resolveLocalSemanticConfiguration(env);
|
|
345
|
+
if (!configuration || request.query === "*") return undefined;
|
|
346
|
+
if (
|
|
347
|
+
!Array.isArray(request.scopeAdmissions) ||
|
|
348
|
+
request.scopeAdmissions.length === 0 ||
|
|
349
|
+
typeof request.sink !== "string" ||
|
|
350
|
+
!request.sink ||
|
|
351
|
+
typeof request.query !== "string" ||
|
|
352
|
+
!request.query.trim() ||
|
|
353
|
+
request.query.length > 32 * 1024
|
|
354
|
+
) {
|
|
355
|
+
throw failure(
|
|
356
|
+
"CC_MEMORY_SEMANTIC_REQUEST",
|
|
357
|
+
"Semantic recall requires query, scope admissions and sink",
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
// Retrieval limits apply only after the full admitted corpus has been scored.
|
|
361
|
+
const records = await memoryPort.query(
|
|
362
|
+
{
|
|
363
|
+
query: "*",
|
|
364
|
+
sink: request.sink,
|
|
365
|
+
scopeAdmissions: request.scopeAdmissions,
|
|
366
|
+
},
|
|
367
|
+
{ signal },
|
|
368
|
+
);
|
|
369
|
+
signal?.throwIfAborted();
|
|
370
|
+
const now = Number(clock());
|
|
371
|
+
const eligible = records.filter(
|
|
372
|
+
(record) =>
|
|
373
|
+
["active", "reinforced"].includes(record.state) &&
|
|
374
|
+
(!record.retentionPolicy.expiresAt ||
|
|
375
|
+
Date.parse(record.retentionPolicy.expiresAt) > now) &&
|
|
376
|
+
request.scopeAdmissions.some(
|
|
377
|
+
(scope) =>
|
|
378
|
+
scope.scope === record.scope &&
|
|
379
|
+
(scope.scopeId === record.scopeId ||
|
|
380
|
+
(scope.scope === "global" &&
|
|
381
|
+
scope.scopeId == null &&
|
|
382
|
+
record.scopeId == null)),
|
|
383
|
+
) &&
|
|
384
|
+
(record.allowedSinks.includes("*") ||
|
|
385
|
+
record.allowedSinks.includes(request.sink)),
|
|
386
|
+
);
|
|
387
|
+
if (eligible.length > MAX_RECORDS) {
|
|
388
|
+
throw failure(
|
|
389
|
+
"CC_MEMORY_SEMANTIC_CAPACITY",
|
|
390
|
+
"Local semantic recall exceeds 10000 admitted records; no partial corpus was searched",
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
if (!eligible.length) return [];
|
|
394
|
+
const scores = await runLocalSemanticWorker(
|
|
395
|
+
configuration,
|
|
396
|
+
{
|
|
397
|
+
query: request.query,
|
|
398
|
+
records: eligible.map((record) => ({
|
|
399
|
+
memoryId: record.memoryId,
|
|
400
|
+
content: record.content,
|
|
401
|
+
})),
|
|
402
|
+
},
|
|
403
|
+
{ signal },
|
|
404
|
+
);
|
|
405
|
+
signal?.throwIfAborted();
|
|
406
|
+
const byId = new Map(eligible.map((record) => [record.memoryId, record]));
|
|
407
|
+
return scores
|
|
408
|
+
.filter((row) => row.score > 0)
|
|
409
|
+
.sort(
|
|
410
|
+
(left, right) =>
|
|
411
|
+
right.score - left.score ||
|
|
412
|
+
left.memoryId.localeCompare(right.memoryId, "en"),
|
|
413
|
+
)
|
|
414
|
+
.slice(0, 1000)
|
|
415
|
+
.map((row) => {
|
|
416
|
+
const record = byId.get(row.memoryId);
|
|
417
|
+
return {
|
|
418
|
+
memoryId: record.memoryId,
|
|
419
|
+
revision: record.revision,
|
|
420
|
+
recordDigest: record.digest,
|
|
421
|
+
score: row.score,
|
|
422
|
+
};
|
|
423
|
+
});
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Production opt-in Memory encoder. Existing local BGE snapshot only; no downloads."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import socket
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
SCHEMA = "chainlesschain.memory-local-semantic/v1"
|
|
10
|
+
REVISION = "a5beb1e3e68b9ab74eb54cfd186867f64f240e1a"
|
|
11
|
+
MODEL_FILES = {
|
|
12
|
+
"config.json": "bc00af31a4a31b74040d73370aa83b62da34c90b75eb77bfa7db039d90abd591",
|
|
13
|
+
"tokenizer.json": "d241a60d5e8f04cc1b2b3e9ef7a4921b27bf526d9f6050ab90f9267a1f9e5c66",
|
|
14
|
+
"tokenizer_config.json": "9261e7d79b44c8195c1cada2b453e55b00aeb81e907a6664974b4d7776172ab3",
|
|
15
|
+
"special_tokens_map.json": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3",
|
|
16
|
+
"vocab.txt": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3",
|
|
17
|
+
"model.safetensors": "c7c1988aae201f80cf91a5dbbd5866409503b89dcaba877ca6dba7dd0a5167d7",
|
|
18
|
+
}
|
|
19
|
+
INSTRUCTION = "Represent this sentence for searching relevant passages: "
|
|
20
|
+
NETWORK_CALLS = 0
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def refuse_network(*_args, **_kwargs):
|
|
24
|
+
global NETWORK_CALLS
|
|
25
|
+
NETWORK_CALLS += 1
|
|
26
|
+
raise RuntimeError("Offline Memory worker refused networking")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def check_model(directory):
|
|
30
|
+
for name, expected in MODEL_FILES.items():
|
|
31
|
+
with (directory / name).open("rb") as stream:
|
|
32
|
+
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
|
33
|
+
if actual != expected:
|
|
34
|
+
raise ValueError("BGE model/tokenizer identity mismatch")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main():
|
|
38
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
39
|
+
os.environ.update({"HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1",
|
|
40
|
+
"TOKENIZERS_PARALLELISM": "false", "CUDA_VISIBLE_DEVICES": ""})
|
|
41
|
+
socket.socket.connect = refuse_network
|
|
42
|
+
socket.socket.connect_ex = refuse_network
|
|
43
|
+
socket.create_connection = refuse_network
|
|
44
|
+
socket.getaddrinfo = refuse_network
|
|
45
|
+
raw = sys.stdin.buffer.read(8 * 1024 * 1024 + 1)
|
|
46
|
+
if len(raw) > 8 * 1024 * 1024:
|
|
47
|
+
raise ValueError("Semantic input too large")
|
|
48
|
+
request = json.loads(raw)
|
|
49
|
+
if request.get("schema") != SCHEMA:
|
|
50
|
+
raise ValueError("Invalid semantic schema")
|
|
51
|
+
query = request.get("query")
|
|
52
|
+
records = request.get("records")
|
|
53
|
+
threads = request.get("threads")
|
|
54
|
+
if (not isinstance(query, str) or not query.strip() or len(query) > 32768 or
|
|
55
|
+
not isinstance(records, list) or not 1 <= len(records) <= 10000 or
|
|
56
|
+
type(threads) is not int or not 1 <= threads <= 8):
|
|
57
|
+
raise ValueError("Invalid bounded semantic input")
|
|
58
|
+
seen = set()
|
|
59
|
+
for record in records:
|
|
60
|
+
identifier = record.get("memoryId")
|
|
61
|
+
if (not isinstance(identifier, str) or not identifier or identifier in seen or
|
|
62
|
+
not isinstance(record.get("content"), str)):
|
|
63
|
+
raise ValueError("Invalid semantic record")
|
|
64
|
+
seen.add(identifier)
|
|
65
|
+
directory = Path(request["modelDirectory"])
|
|
66
|
+
if not directory.is_absolute():
|
|
67
|
+
raise ValueError("Model directory must be absolute")
|
|
68
|
+
check_model(directory)
|
|
69
|
+
import torch
|
|
70
|
+
from transformers import AutoModel, AutoTokenizer
|
|
71
|
+
torch.set_num_threads(threads)
|
|
72
|
+
torch.set_num_interop_threads(1)
|
|
73
|
+
torch.manual_seed(0)
|
|
74
|
+
torch.use_deterministic_algorithms(True)
|
|
75
|
+
tokenizer = AutoTokenizer.from_pretrained(str(directory), local_files_only=True, trust_remote_code=False)
|
|
76
|
+
model = AutoModel.from_pretrained(str(directory), local_files_only=True,
|
|
77
|
+
trust_remote_code=False, use_safetensors=True).eval().to("cpu")
|
|
78
|
+
|
|
79
|
+
def encode(texts):
|
|
80
|
+
batch = tokenizer(texts, truncation=True, max_length=512, padding=True, return_tensors="pt")
|
|
81
|
+
result = torch.nn.functional.normalize(model(**batch).last_hidden_state[:, 0], p=2, dim=1)
|
|
82
|
+
if not torch.isfinite(result).all():
|
|
83
|
+
raise ValueError("Nonfinite model embedding")
|
|
84
|
+
return result
|
|
85
|
+
|
|
86
|
+
scores = []
|
|
87
|
+
with torch.inference_mode():
|
|
88
|
+
query_vector = encode([INSTRUCTION + query])[0]
|
|
89
|
+
for start in range(0, len(records), 8):
|
|
90
|
+
batch = records[start:start + 8]
|
|
91
|
+
values = (encode([record["content"] for record in batch]) @ query_vector).tolist()
|
|
92
|
+
scores.extend({"memoryId": record["memoryId"], "score": max(0.0, min(1.0, value))}
|
|
93
|
+
for record, value in zip(batch, values))
|
|
94
|
+
check_model(directory)
|
|
95
|
+
if NETWORK_CALLS:
|
|
96
|
+
raise RuntimeError("Network was attempted")
|
|
97
|
+
print(json.dumps({"schema": SCHEMA, "modelRevision": REVISION,
|
|
98
|
+
"requestDigest": hashlib.sha256(raw).hexdigest(),
|
|
99
|
+
"networkCalls": NETWORK_CALLS, "scores": scores}, allow_nan=False, ensure_ascii=False))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
if __name__ == "__main__":
|
|
103
|
+
try:
|
|
104
|
+
main()
|
|
105
|
+
except Exception:
|
|
106
|
+
# Input content and library exception text never cross the diagnostic boundary.
|
|
107
|
+
sys.stderr.write("Local semantic worker failed; check model identity and local dependencies.\n")
|
|
108
|
+
sys.exit(1)
|
|
109
|
+
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import {
|
|
3
3
|
canonicalDigest,
|
|
4
|
+
assertContextMemoryDefinition,
|
|
4
5
|
createMemoryCandidate,
|
|
5
6
|
normalizeMemoryRecord,
|
|
6
7
|
} from "@chainlesschain/context-memory-kernel";
|
|
@@ -556,7 +557,10 @@ export class CliCanonicalMemoryService {
|
|
|
556
557
|
async recallScoped(query, options = {}) {
|
|
557
558
|
const scope = normalizedScope(options.scope, options.scopeId);
|
|
558
559
|
const limit = Math.max(1, Math.min(1000, Number(options.limit) || 10));
|
|
559
|
-
const recalled = await
|
|
560
|
+
const recalled = await (
|
|
561
|
+
this.runtime.recallMemory ||
|
|
562
|
+
this.runtime.kernel.recallMemory.bind(this.runtime.kernel)
|
|
563
|
+
)(
|
|
560
564
|
{
|
|
561
565
|
query: String(query || "").trim() || "*",
|
|
562
566
|
sink: options.sink || "cli.display",
|
|
@@ -579,7 +583,10 @@ export class CliCanonicalMemoryService {
|
|
|
579
583
|
}
|
|
580
584
|
|
|
581
585
|
async search(query, { limit = 20, sink = "cli.display", signal } = {}) {
|
|
582
|
-
const recalled = await
|
|
586
|
+
const recalled = await (
|
|
587
|
+
this.runtime.recallMemory ||
|
|
588
|
+
this.runtime.kernel.recallMemory.bind(this.runtime.kernel)
|
|
589
|
+
)(
|
|
583
590
|
{
|
|
584
591
|
query,
|
|
585
592
|
sink,
|
|
@@ -597,6 +604,32 @@ export class CliCanonicalMemoryService {
|
|
|
597
604
|
};
|
|
598
605
|
}
|
|
599
606
|
|
|
607
|
+
async inspect(memoryId) {
|
|
608
|
+
assertContextMemoryDefinition("Identifier", memoryId);
|
|
609
|
+
const record = await this.runtime.memoryPort.read(memoryId);
|
|
610
|
+
return record ? publicEntry(record) : null;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
async correct(memoryId, { content, expectedRevision, reason } = {}) {
|
|
614
|
+
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1) {
|
|
615
|
+
throw new TypeError("expectedRevision must be a positive safe integer");
|
|
616
|
+
}
|
|
617
|
+
// The caller's revision is never refreshed or replayed after a conflict or
|
|
618
|
+
// an uncertain commit. The Kernel owns the single-record atomic transition.
|
|
619
|
+
const mutation = await this.runtime.kernel.decideMemory({
|
|
620
|
+
memoryId,
|
|
621
|
+
type: "correct",
|
|
622
|
+
content,
|
|
623
|
+
expectedRevision,
|
|
624
|
+
authority: "cli-user-correction",
|
|
625
|
+
...(reason === undefined ? {} : { reason }),
|
|
626
|
+
});
|
|
627
|
+
return {
|
|
628
|
+
...publicEntry(mutation.record),
|
|
629
|
+
receipt: mutation.receipt,
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
600
633
|
async delete(idOrPrefix) {
|
|
601
634
|
const exact = await this.runtime.memoryPort.read(idOrPrefix);
|
|
602
635
|
let candidates;
|