@cydm/pie 4.10.2 → 4.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin/extensions/ask-user/index.js +2 -2
- package/dist/builtin/extensions/cron/index.js +1 -1
- package/dist/builtin/extensions/im-forward/index.js +9128 -7189
- package/dist/builtin/extensions/mcp-adapter/index.js +1 -1
- package/dist/builtin/extensions/memory/index.js +171 -66
- package/dist/builtin/extensions/pie-ipc/index.js +1 -1
- package/dist/builtin/extensions/pie-proc/index.js +542 -52
- package/dist/builtin/extensions/plan-mode/index.js +2 -2
- package/dist/builtin/extensions/subagent/README.md +1 -1
- package/dist/builtin/extensions/subagent/index.js +3 -3
- package/dist/builtin/extensions/todo/index.js +2 -2
- package/dist/chunks/{auth-storage-C3FZMT7J.js → auth-storage-IJEJ2TGE.js} +1 -1
- package/dist/chunks/chunk-26ILLZKQ.js +400 -0
- package/dist/chunks/{chunk-KWK7KTSZ.js → chunk-322WLBDY.js} +1 -1
- package/dist/chunks/{chunk-OU33ROFD.js → chunk-3GG342QY.js} +78 -78
- package/dist/chunks/{chunk-BB7ETSJK.js → chunk-6U6UGM4C.js} +119 -3
- package/dist/chunks/{chunk-ZPJ3BNQB.js → chunk-BSITHT43.js} +1 -0
- package/dist/chunks/{chunk-IZKHSUNQ.js → chunk-CAPBTMLI.js} +18 -1
- package/dist/chunks/{chunk-FC5AN5QP.js → chunk-IZ4DYCJ7.js} +268 -107
- package/dist/chunks/{chunk-HK3FHIAH.js → chunk-KW46ND3S.js} +1999 -767
- package/dist/chunks/{chunk-SW2E33UL.js → chunk-LMDWWT43.js} +123 -4
- package/dist/chunks/chunk-OGGL6LUN.js +331 -0
- package/dist/chunks/{chunk-BTUMBUDU.js → chunk-QSXBPTOA.js} +1 -1
- package/dist/chunks/{chunk-5QMS6RQC.js → chunk-SXBX2P5R.js} +160 -5
- package/dist/chunks/{chunk-7LICWWUE.js → chunk-W37NAT3N.js} +2 -2
- package/dist/chunks/chunk-WTBLV6F5.js +476 -0
- package/dist/chunks/{host-image-fallback-3TEMOQM5.js → host-image-fallback-NXY36VO2.js} +1 -1
- package/dist/chunks/{manager-cli-BXI4UFTJ.js → manager-cli-B6GIYTI7.js} +35 -13
- package/dist/chunks/{manager-upgrade-XPFXKO7A.js → manager-upgrade-WHER3WTJ.js} +284 -109
- package/dist/chunks/memory-git-C3S276QJ.js +19 -0
- package/dist/chunks/{model-registry-QKJ3YVDS.js → model-registry-QNEPISBJ.js} +11 -3
- package/dist/chunks/{read-file-understanding-N2ZZQLTZ.js → read-file-understanding-ZCBNCQHG.js} +3 -3
- package/dist/chunks/{src-F5N6O2HR.js → src-7CU7OTQS.js} +36 -36
- package/dist/chunks/{src-3PSR2AAX.js → src-7MZZJVOG.js} +1 -1
- package/dist/cli.js +750 -516
- package/package.json +2 -2
- package/dist/chunks/chunk-6WKBQZWM.js +0 -19
- package/dist/chunks/chunk-XMTRKMBG.js +0 -386
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
getSettingsPath
|
|
4
|
+
} from "./chunk-CBDQJMUI.js";
|
|
5
|
+
|
|
6
|
+
// src/commands/memory-distill.ts
|
|
7
|
+
import * as fs from "node:fs";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
var require2 = createRequire(import.meta.url);
|
|
12
|
+
function distillWorkerLogPath(memoryRoot) {
|
|
13
|
+
return path.join(memoryRoot, "distill-worker.log");
|
|
14
|
+
}
|
|
15
|
+
function distillLockPath(memoryRoot) {
|
|
16
|
+
return path.join(memoryRoot, "distill.lock");
|
|
17
|
+
}
|
|
18
|
+
function readDistillWorkerLog(memoryRoot, limit = 20) {
|
|
19
|
+
try {
|
|
20
|
+
const raw = fs.readFileSync(distillWorkerLogPath(memoryRoot), "utf8");
|
|
21
|
+
const lines = raw.split("\n").filter((line) => line.trim().length > 0);
|
|
22
|
+
return lines.slice(-limit);
|
|
23
|
+
} catch {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
var MEMORY_DISTILL_RETRYABLE_EXIT_CODE = 75;
|
|
28
|
+
function distillExitCode(result) {
|
|
29
|
+
return result.ok ? 0 : result.retryable ? MEMORY_DISTILL_RETRYABLE_EXIT_CODE : 1;
|
|
30
|
+
}
|
|
31
|
+
function spawnDistillWorker(memoryRoot, date, sessionsDir) {
|
|
32
|
+
return spawnDistillCli(memoryRoot, ["--date", date, ...sessionsDir ? ["--sessions-dir", sessionsDir] : []]);
|
|
33
|
+
}
|
|
34
|
+
function spawnDistillAutoWorker(memoryRoot, sessionsDir) {
|
|
35
|
+
return spawnDistillCli(memoryRoot, ["--auto", ...sessionsDir ? ["--sessions-dir", sessionsDir] : []]);
|
|
36
|
+
}
|
|
37
|
+
function spawnDistillCli(memoryRoot, modeArgs) {
|
|
38
|
+
const logPath = distillWorkerLogPath(memoryRoot);
|
|
39
|
+
const entry = process.argv[1] ? path.resolve(process.argv[1]) : null;
|
|
40
|
+
if (!entry) return false;
|
|
41
|
+
try {
|
|
42
|
+
fs.mkdirSync(memoryRoot, { recursive: true });
|
|
43
|
+
} catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
const args = [entry, "memory", "distill", ...modeArgs, "--worker", "--memory-root", memoryRoot];
|
|
47
|
+
let out;
|
|
48
|
+
try {
|
|
49
|
+
out = fs.openSync(logPath, "a");
|
|
50
|
+
const child = spawn(process.execPath, args, {
|
|
51
|
+
detached: true,
|
|
52
|
+
windowsHide: true,
|
|
53
|
+
stdio: ["ignore", out, out],
|
|
54
|
+
env: { ...process.env, PIE_MEMORY_WORKER: "1" }
|
|
55
|
+
});
|
|
56
|
+
child.on("error", (error) => {
|
|
57
|
+
try {
|
|
58
|
+
fs.appendFileSync(logPath, `[${(/* @__PURE__ */ new Date()).toISOString()}] spawn failed: ${String(error)}
|
|
59
|
+
`);
|
|
60
|
+
} catch {
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
child.unref();
|
|
64
|
+
try {
|
|
65
|
+
fs.appendFileSync(logPath, `[${(/* @__PURE__ */ new Date()).toISOString()}] spawned worker (${modeArgs.join(" ")}) (pid ${child.pid})
|
|
66
|
+
`);
|
|
67
|
+
} catch {
|
|
68
|
+
}
|
|
69
|
+
return true;
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
} finally {
|
|
73
|
+
if (out !== void 0) {
|
|
74
|
+
try {
|
|
75
|
+
fs.closeSync(out);
|
|
76
|
+
} catch {
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
var advisoryLockBackend = /* @__PURE__ */ (() => {
|
|
82
|
+
let impl;
|
|
83
|
+
return () => {
|
|
84
|
+
if (impl) return impl;
|
|
85
|
+
const koffi = require2("koffi");
|
|
86
|
+
const { createMemoryLockBackend } = require2("@pie/shared-headless-capabilities");
|
|
87
|
+
impl = createMemoryLockBackend(koffi);
|
|
88
|
+
return impl;
|
|
89
|
+
};
|
|
90
|
+
})();
|
|
91
|
+
function acquireAdvisoryLock(lockPath) {
|
|
92
|
+
const backend = advisoryLockBackend();
|
|
93
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
94
|
+
let handle;
|
|
95
|
+
try {
|
|
96
|
+
handle = backend.open(lockPath);
|
|
97
|
+
} catch (error) {
|
|
98
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const result = backend.lock(handle);
|
|
102
|
+
if (result !== "acquired") {
|
|
103
|
+
backend.unlock(handle);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
} catch (error) {
|
|
107
|
+
backend.unlock(handle);
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
let released = false;
|
|
111
|
+
return {
|
|
112
|
+
release() {
|
|
113
|
+
if (released) return;
|
|
114
|
+
released = true;
|
|
115
|
+
backend.unlock(handle);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function acquireDistillLock(memoryRoot) {
|
|
120
|
+
const lock = acquireAdvisoryLock(distillLockPath(memoryRoot));
|
|
121
|
+
return lock ? () => lock.release() : null;
|
|
122
|
+
}
|
|
123
|
+
function resolveDefaultModelSpecFromSettings() {
|
|
124
|
+
try {
|
|
125
|
+
const raw = JSON.parse(fs.readFileSync(getSettingsPath(), "utf8"));
|
|
126
|
+
if (typeof raw.defaultProvider === "string" && typeof raw.defaultModel === "string" && raw.defaultProvider && raw.defaultModel) {
|
|
127
|
+
return `${raw.defaultProvider}/${raw.defaultModel}`;
|
|
128
|
+
}
|
|
129
|
+
} catch {
|
|
130
|
+
}
|
|
131
|
+
return void 0;
|
|
132
|
+
}
|
|
133
|
+
function createWikiModelCall(registry, modelClass, explicitModelSpec, timeoutMs = 18e4, hooks) {
|
|
134
|
+
const resolveTarget = () => {
|
|
135
|
+
const trySpec = (spec) => {
|
|
136
|
+
const slash = spec.indexOf("/");
|
|
137
|
+
if (slash <= 0 || slash === spec.length - 1) return void 0;
|
|
138
|
+
const provider = spec.slice(0, slash);
|
|
139
|
+
const modelId = spec.slice(slash + 1);
|
|
140
|
+
const model = registry.find(provider, modelId);
|
|
141
|
+
if (!model) return void 0;
|
|
142
|
+
const apiKey = registry.getApiKey(model);
|
|
143
|
+
if (!apiKey) return void 0;
|
|
144
|
+
return { model, apiKey };
|
|
145
|
+
};
|
|
146
|
+
if (explicitModelSpec) {
|
|
147
|
+
const exact = trySpec(explicitModelSpec);
|
|
148
|
+
if (!exact) {
|
|
149
|
+
throw new Error(`model "${explicitModelSpec}" is not configured or has no API key`);
|
|
150
|
+
}
|
|
151
|
+
return exact;
|
|
152
|
+
}
|
|
153
|
+
const byClass = registry.resolveModelClass(modelClass);
|
|
154
|
+
if (byClass.model && byClass.apiKey) {
|
|
155
|
+
return { model: byClass.model, apiKey: byClass.apiKey };
|
|
156
|
+
}
|
|
157
|
+
const fallbackSpec = resolveDefaultModelSpecFromSettings();
|
|
158
|
+
if (fallbackSpec) {
|
|
159
|
+
const fallback = trySpec(fallbackSpec);
|
|
160
|
+
if (fallback) return fallback;
|
|
161
|
+
}
|
|
162
|
+
throw new Error(`no complete model/key pair for class ${modelClass}${byClass.fallbackReason ? `: ${byClass.fallbackReason}` : ""}`);
|
|
163
|
+
};
|
|
164
|
+
return async (prompt, options) => {
|
|
165
|
+
const { model, apiKey } = resolveTarget();
|
|
166
|
+
const complete = hooks?.completeFn ?? (await import("./src-TIDKYA5F.js")).completeSimple;
|
|
167
|
+
const invokeOnce = async () => {
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
let timedOut = false;
|
|
170
|
+
const timer = setTimeout(() => {
|
|
171
|
+
timedOut = true;
|
|
172
|
+
controller.abort();
|
|
173
|
+
}, timeoutMs);
|
|
174
|
+
try {
|
|
175
|
+
const message = await complete(
|
|
176
|
+
model,
|
|
177
|
+
{
|
|
178
|
+
systemPrompt: options?.system ?? "You are a disciplined memory curator. Output JSON only.",
|
|
179
|
+
messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }]
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
apiKey,
|
|
183
|
+
...model.reasoning ? { reasoning: "low" } : {},
|
|
184
|
+
maxTokens: Math.min(model.maxTokens ?? 32768, 32768),
|
|
185
|
+
signal: controller.signal
|
|
186
|
+
}
|
|
187
|
+
);
|
|
188
|
+
if (timedOut) {
|
|
189
|
+
const err = new Error(`wiki model call (${model.provider}/${model.id}) timed out after ${timeoutMs}ms`);
|
|
190
|
+
err.noImmediateReplay = true;
|
|
191
|
+
throw err;
|
|
192
|
+
}
|
|
193
|
+
if (message.stopReason && message.stopReason !== "stop") {
|
|
194
|
+
const detail = typeof message.errorMessage === "string" && message.errorMessage.trim() ? `: ${message.errorMessage.trim()}` : "";
|
|
195
|
+
const err = new Error(`wiki model call (${model.provider}/${model.id}) ended with stopReason=${message.stopReason}${detail}`);
|
|
196
|
+
if (message.retryable === false || message.stopReason === "length") {
|
|
197
|
+
err.noImmediateReplay = true;
|
|
198
|
+
}
|
|
199
|
+
throw err;
|
|
200
|
+
}
|
|
201
|
+
return message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
202
|
+
} catch (rawError) {
|
|
203
|
+
if (timedOut && !(rawError instanceof Error && rawError.message.includes("timed out after"))) {
|
|
204
|
+
const err = new Error(`wiki model call (${model.provider}/${model.id}) timed out after ${timeoutMs}ms`);
|
|
205
|
+
err.noImmediateReplay = true;
|
|
206
|
+
throw err;
|
|
207
|
+
}
|
|
208
|
+
throw rawError;
|
|
209
|
+
} finally {
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
try {
|
|
214
|
+
return await invokeOnce();
|
|
215
|
+
} catch (firstError) {
|
|
216
|
+
const msg = firstError instanceof Error ? firstError.message : String(firstError);
|
|
217
|
+
const noReplay = Boolean(firstError?.noImmediateReplay);
|
|
218
|
+
if (noReplay || !isTransientDistillError(msg) || msg.toLowerCase().includes("stopreason=length")) {
|
|
219
|
+
throw firstError;
|
|
220
|
+
}
|
|
221
|
+
await new Promise((resolve2) => setTimeout(resolve2, hooks?.retryDelayMs ?? 1500));
|
|
222
|
+
return await invokeOnce();
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
function isWikiDreamResultRetryable(dreamRes) {
|
|
227
|
+
const err = dreamRes.error ?? "wiki dream failed";
|
|
228
|
+
const sessionsAllTransient = !dreamRes.failedSessions?.length || dreamRes.failedSessions.every((f) => isTransientDistillError(f.error));
|
|
229
|
+
const hasHarvestFail = Boolean(dreamRes.error?.includes("harvest failed"));
|
|
230
|
+
const isExtractionOnlyWrapper = Boolean(dreamRes.failedSessions?.length) && Boolean(dreamRes.error) && (dreamRes.error.startsWith("partial dream failure") || /^all \d+ session signal extractions failed/i.test(dreamRes.error));
|
|
231
|
+
const hasStageFailure = Boolean(dreamRes.violations?.length) || hasHarvestFail || Boolean(dreamRes.error) && !isExtractionOnlyWrapper;
|
|
232
|
+
const stageTransient = !hasStageFailure || !dreamRes.violations?.length && !hasHarvestFail && isTransientDistillError(err);
|
|
233
|
+
return sessionsAllTransient && stageTransient;
|
|
234
|
+
}
|
|
235
|
+
function normalizeCwdPath(value) {
|
|
236
|
+
if (value.length > 1 && value.endsWith(path.sep)) return value.slice(0, -1);
|
|
237
|
+
return value;
|
|
238
|
+
}
|
|
239
|
+
function pathContains(parent, child) {
|
|
240
|
+
if (parent === child) return true;
|
|
241
|
+
const parentWithSep = parent.endsWith(path.sep) ? parent : parent + path.sep;
|
|
242
|
+
return child.startsWith(parentWithSep);
|
|
243
|
+
}
|
|
244
|
+
async function readExcludeCwds() {
|
|
245
|
+
try {
|
|
246
|
+
const { getSettingsPath: getSettingsPath2 } = await import("./config-4EOI5NOU.js");
|
|
247
|
+
const raw = JSON.parse(fs.readFileSync(getSettingsPath2(), "utf8"));
|
|
248
|
+
const list = raw?.extensions?.memory?.excludeCwds;
|
|
249
|
+
if (!Array.isArray(list)) return [];
|
|
250
|
+
return list.filter((entry) => typeof entry === "string" && path.isAbsolute(entry)).map(normalizeCwdPath);
|
|
251
|
+
} catch {
|
|
252
|
+
return [];
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
async function createExcludeCwdFilter() {
|
|
256
|
+
const excludeCwds = await readExcludeCwds();
|
|
257
|
+
if (excludeCwds.length === 0) return void 0;
|
|
258
|
+
return (cwd) => {
|
|
259
|
+
if (!cwd) return true;
|
|
260
|
+
const normalized = normalizeCwdPath(cwd);
|
|
261
|
+
return !excludeCwds.some((excluded) => pathContains(excluded, normalized));
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function isTransientDistillError(message) {
|
|
265
|
+
const lower = message.toLowerCase();
|
|
266
|
+
if (/^(?:(?:harvest|evidence|apply):\s*)?memory store is contended \(write\.lock\)/i.test(message.trim())) {
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
if (/^(?:harvest|evidence|apply):/i.test(message)) {
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
272
|
+
if (/^(?:distill:[^:]+:\s*)?distill (?:response contains no json array|response contains invalid json|response is not an array|candidate is not an object|candidate has invalid shape|quote is implausibly long)/i.test(
|
|
273
|
+
message.trim()
|
|
274
|
+
) || /^(?:wiki (?:signal extractor returned (?:no json array|malformed json|non-array json)|dream response (?:contains no json object|contains invalid json|missing updates array)|dream update entry (?:is not an object|requires non-empty path and content)|dream batch overflow))/i.test(
|
|
275
|
+
message.trim()
|
|
276
|
+
)) {
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
if (lower.includes("no complete model/key pair") || lower.includes("invalid api key") || lower.includes("unauthorized") || lower.includes("forbidden") || lower.includes("eacces") || lower.includes("eperm") || lower.includes("erofs") || lower.includes("enospc")) {
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
282
|
+
if (lower.includes("syntaxerror") || lower.includes("invalid json") || lower.includes("in json at position")) {
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
return lower.includes("timed out") || lower.includes("timeout") || lower.includes("rate limit") || lower.includes("too many requests") || lower.includes("overloaded") || lower.includes("temporarily unavailable") || lower.includes("service unavailable") || lower.includes("bad gateway") || lower.includes("gateway timeout") || lower.includes("fetch failed") || lower.includes("connection error") || lower.includes("network error") || lower.includes("socket hang up") || lower.includes("premature close") || lower.includes("responses_protocol_error") || lower.includes("stream ended without a terminal event") || lower.includes("incomplete stream") || lower.includes("unexpected end of json") || lower.includes("econnreset") || lower.includes("econnrefused") || lower.includes("etimedout") || lower.includes("enotfound") || lower.includes("eai_again") || lower.includes("stopreason=length") || /(?:^|:\s*|http\s+|(?:api\s+)?error\s+(?:code\s*[:=]?\s*)?|status(?:\s*code)?\s*[:=]?\s*)(?:429|500|502|503|504|529)\b/.test(lower);
|
|
286
|
+
}
|
|
287
|
+
function hasLegacyMemorySeed(memoryRoot) {
|
|
288
|
+
for (const rel of ["MEMORY.md", "THREADS.md"]) {
|
|
289
|
+
try {
|
|
290
|
+
const stat = fs.statSync(path.join(memoryRoot, rel));
|
|
291
|
+
if (stat.isFile() && stat.size > 0) return true;
|
|
292
|
+
} catch {
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
try {
|
|
296
|
+
const projectsDir = path.join(memoryRoot, "projects");
|
|
297
|
+
if (fs.existsSync(projectsDir) && fs.readdirSync(projectsDir).length > 0) return true;
|
|
298
|
+
} catch {
|
|
299
|
+
}
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
async function runDistillWorkerMain(memoryRoot, date, noExit = false, sessionsDir) {
|
|
303
|
+
const log = (message) => {
|
|
304
|
+
try {
|
|
305
|
+
fs.appendFileSync(distillWorkerLogPath(memoryRoot), `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
|
|
306
|
+
`);
|
|
307
|
+
} catch {
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
const release = acquireDistillLock(memoryRoot);
|
|
311
|
+
if (!release) {
|
|
312
|
+
return { ok: false, error: "another distillation worker holds the lock", busy: true };
|
|
313
|
+
}
|
|
314
|
+
let result;
|
|
315
|
+
let wikiForError;
|
|
316
|
+
try {
|
|
317
|
+
const { ModelRegistry } = await import("./model-registry-QNEPISBJ.js");
|
|
318
|
+
const { AuthStorage } = await import("./auth-storage-IJEJ2TGE.js");
|
|
319
|
+
const { getSessionsDir } = await import("./config-4EOI5NOU.js");
|
|
320
|
+
const { FileSessionStore } = await import("./src-7MZZJVOG.js");
|
|
321
|
+
const { WikiStore, runWikiBootstrap, runWikiDream, runWikiGc } = await import("./src-7CU7OTQS.js");
|
|
322
|
+
const { commitCuratedMemoryBestEffort } = await import("./memory-git-C3S276QJ.js");
|
|
323
|
+
const wiki = new WikiStore(memoryRoot);
|
|
324
|
+
wikiForError = wiki;
|
|
325
|
+
if (wiki.hasDreamedDate(date)) {
|
|
326
|
+
result = { ok: true, status: "skipped-ran" };
|
|
327
|
+
} else {
|
|
328
|
+
const registry = new ModelRegistry(AuthStorage.create());
|
|
329
|
+
const cwdFilter = await createExcludeCwdFilter();
|
|
330
|
+
const lightCall = createWikiModelCall(registry, "light", void 0, 12e4);
|
|
331
|
+
const balancedCall = createWikiModelCall(registry, "balanced", void 0, 18e4);
|
|
332
|
+
if (!wiki.exists() && hasLegacyMemorySeed(memoryRoot)) {
|
|
333
|
+
const boot = await runWikiBootstrap({ memoryRoot, balancedCall });
|
|
334
|
+
log(`[wiki] auto-bootstrap ok=${boot.ok} written=${boot.written.length}${boot.error ? ` error=${boot.error}` : ""}`);
|
|
335
|
+
if (!boot.ok) {
|
|
336
|
+
const err = boot.error ?? "wiki bootstrap failed";
|
|
337
|
+
try {
|
|
338
|
+
wiki.recordDreamFailure(err, date);
|
|
339
|
+
} catch {
|
|
340
|
+
}
|
|
341
|
+
const retryable = !boot.violations?.length && isTransientDistillError(err);
|
|
342
|
+
result = { ok: false, status: "failed", error: err, retryable };
|
|
343
|
+
} else if (boot.written.length > 0) {
|
|
344
|
+
commitCuratedMemoryBestEffort(memoryRoot, `wiki(bootstrap): ${date} (${boot.written.length} pages)`);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (!result) {
|
|
348
|
+
const resolvedSessionsDir = sessionsDir ? path.resolve(sessionsDir) : getSessionsDir();
|
|
349
|
+
const dreamRes = await runWikiDream({
|
|
350
|
+
sessionStore: new FileSessionStore(resolvedSessionsDir),
|
|
351
|
+
memoryRoot,
|
|
352
|
+
dates: [date],
|
|
353
|
+
lightCall,
|
|
354
|
+
balancedCall,
|
|
355
|
+
cwdFilter,
|
|
356
|
+
log
|
|
357
|
+
});
|
|
358
|
+
log(`[wiki] dream ${date}: ok=${dreamRes.ok} sessions=${dreamRes.sessionsHarvested} signals=${dreamRes.signalsAuthenticated} written=${dreamRes.written.length}${dreamRes.error ? ` error=${dreamRes.error}` : ""}`);
|
|
359
|
+
let gcWrote = false;
|
|
360
|
+
if (dreamRes.ok) {
|
|
361
|
+
const meta = wiki.readMeta();
|
|
362
|
+
const sevenDaysMs = 7 * 24 * 60 * 60 * 1e3;
|
|
363
|
+
const needsGc = !meta.lastGcAt || Date.now() - meta.lastGcAt >= sevenDaysMs || wiki.listActivePages().length >= 18;
|
|
364
|
+
if (needsGc && wiki.exists()) {
|
|
365
|
+
const gcRes = await runWikiGc({ memoryRoot, balancedCall });
|
|
366
|
+
log(`[wiki] weekly gc: ok=${gcRes.ok} archived=${gcRes.archivedInactive.length} compressed=${gcRes.compressedPages.length}${gcRes.error ? ` error=${gcRes.error}` : ""}`);
|
|
367
|
+
gcWrote = gcRes.archivedInactive.length > 0 || gcRes.compressedPages.length > 0;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (dreamRes.written.length > 0 || dreamRes.archived.length > 0 || gcWrote) {
|
|
371
|
+
commitCuratedMemoryBestEffort(memoryRoot, `wiki(dream): ${date}`);
|
|
372
|
+
}
|
|
373
|
+
if (dreamRes.ok) {
|
|
374
|
+
const status = dreamRes.sessionsHarvested === 0 ? "skipped-empty" : "applied";
|
|
375
|
+
result = { ok: true, status };
|
|
376
|
+
} else {
|
|
377
|
+
const err = dreamRes.error ?? "wiki dream failed";
|
|
378
|
+
const retryable = isWikiDreamResultRetryable(dreamRes);
|
|
379
|
+
try {
|
|
380
|
+
wiki.recordDreamFailure(err, date);
|
|
381
|
+
} catch {
|
|
382
|
+
}
|
|
383
|
+
result = { ok: false, status: "failed", error: err, retryable };
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
} catch (error) {
|
|
388
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
389
|
+
log(`failed ${date}: ${message}`);
|
|
390
|
+
try {
|
|
391
|
+
wikiForError?.recordDreamFailure(message, date);
|
|
392
|
+
} catch {
|
|
393
|
+
}
|
|
394
|
+
const retryable = isTransientDistillError(message);
|
|
395
|
+
result = { ok: false, error: message, ...retryable ? { retryable: true } : {} };
|
|
396
|
+
} finally {
|
|
397
|
+
release();
|
|
398
|
+
}
|
|
399
|
+
if (!noExit) {
|
|
400
|
+
const exitCode = distillExitCode(result);
|
|
401
|
+
setTimeout(() => process.exit(exitCode), 50).unref?.();
|
|
402
|
+
}
|
|
403
|
+
return result;
|
|
404
|
+
}
|
|
405
|
+
async function runDistillAuto(memoryRoot, days = 7, runner, sessionsDir) {
|
|
406
|
+
const log = (message) => {
|
|
407
|
+
try {
|
|
408
|
+
fs.appendFileSync(distillWorkerLogPath(memoryRoot), `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
|
|
409
|
+
`);
|
|
410
|
+
} catch {
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
const { WikiStore, todayKey } = await import("./src-7CU7OTQS.js");
|
|
414
|
+
const wiki = new WikiStore(memoryRoot);
|
|
415
|
+
const today = todayKey(Date.now());
|
|
416
|
+
const dates = [];
|
|
417
|
+
for (let offset = days; offset >= 1; offset -= 1) {
|
|
418
|
+
const probe = /* @__PURE__ */ new Date();
|
|
419
|
+
probe.setDate(probe.getDate() - offset);
|
|
420
|
+
const date = todayKey(probe.getTime());
|
|
421
|
+
if (date === today) continue;
|
|
422
|
+
if (!wiki.hasDreamedDate(date)) {
|
|
423
|
+
dates.push(date);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (dates.length === 0) {
|
|
427
|
+
log("auto: no missing checkpoints in the window");
|
|
428
|
+
return { ok: true, lines: ["memory --auto: no missing checkpoints in the last " + days + " days."] };
|
|
429
|
+
}
|
|
430
|
+
log(`auto: ${dates.length} missing date(s): ${dates.join(", ")}`);
|
|
431
|
+
const lines = [];
|
|
432
|
+
let failures = 0;
|
|
433
|
+
let hasPermanentFailure = false;
|
|
434
|
+
for (const date of dates) {
|
|
435
|
+
const result = await (runner ?? runDistillWorkerMain)(memoryRoot, date, true, sessionsDir);
|
|
436
|
+
if (!result.ok && result.busy) {
|
|
437
|
+
lines.push(`${date}: busy \u2014 another distillation worker is running; next schedule retries`);
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
lines.push(`${date}: ${result.status ?? "failed"}${result.error ? ` \u2014 ${result.error}` : ""}`);
|
|
441
|
+
if (!result.ok) {
|
|
442
|
+
failures += 1;
|
|
443
|
+
const isRetryable = result.retryable ?? (result.error !== void 0 && isTransientDistillError(result.error));
|
|
444
|
+
if (!isRetryable) hasPermanentFailure = true;
|
|
445
|
+
log(`auto: ${date} failed (${isRetryable ? "transient/retryable" : "permanent"}); continuing the remaining dates`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (failures > 0) {
|
|
449
|
+
lines.push(
|
|
450
|
+
hasPermanentFailure ? `${failures} date(s) failed (includes permanent config/storage failure; inspect log)` : `${failures} date(s) failed (transient/retryable; next run retries them)`
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
const succeeded = failures === 0;
|
|
454
|
+
const retryable = failures > 0 && !hasPermanentFailure;
|
|
455
|
+
if (!process.env.NODE_TEST_CONTEXT) {
|
|
456
|
+
const code = distillExitCode({ ok: succeeded, retryable });
|
|
457
|
+
setTimeout(() => process.exit(code), 50).unref?.();
|
|
458
|
+
}
|
|
459
|
+
return { ok: succeeded, ...retryable ? { retryable: true } : {}, lines };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export {
|
|
463
|
+
distillWorkerLogPath,
|
|
464
|
+
readDistillWorkerLog,
|
|
465
|
+
MEMORY_DISTILL_RETRYABLE_EXIT_CODE,
|
|
466
|
+
distillExitCode,
|
|
467
|
+
spawnDistillWorker,
|
|
468
|
+
spawnDistillAutoWorker,
|
|
469
|
+
acquireDistillLock,
|
|
470
|
+
createWikiModelCall,
|
|
471
|
+
isWikiDreamResultRetryable,
|
|
472
|
+
createExcludeCwdFilter,
|
|
473
|
+
isTransientDistillError,
|
|
474
|
+
runDistillWorkerMain,
|
|
475
|
+
runDistillAuto
|
|
476
|
+
};
|
|
@@ -5,7 +5,7 @@ import "./chunk-LZQXQOPJ.js";
|
|
|
5
5
|
import * as os from "node:os";
|
|
6
6
|
async function describeImageViaUnderstandingChain(options) {
|
|
7
7
|
try {
|
|
8
|
-
const { understandReadFile } = await import("./read-file-understanding-
|
|
8
|
+
const { understandReadFile } = await import("./read-file-understanding-ZCBNCQHG.js");
|
|
9
9
|
const ext = options.filePath.toLowerCase().split(".").pop() ?? "";
|
|
10
10
|
const mimeType = ext === "png" ? "image/png" : ext === "gif" ? "image/gif" : ext === "webp" ? "image/webp" : "image/jpeg";
|
|
11
11
|
const result = await understandReadFile(
|
|
@@ -859,21 +859,39 @@ function withStartLock(dir, fn) {
|
|
|
859
859
|
});
|
|
860
860
|
}
|
|
861
861
|
async function runUpgradeCommand(args) {
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
862
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
863
|
+
console.log("Usage: pie manager upgrade [--target <latest|x.y.z>] [--force]");
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
const { upgradePaths, performUpgrade, cliEffects, parseTarget } = await import("./manager-upgrade-WHER3WTJ.js");
|
|
867
|
+
let targetRaw;
|
|
868
|
+
let force = false;
|
|
869
|
+
for (let i = 0; i < args.length; i++) {
|
|
870
|
+
const arg = args[i];
|
|
871
|
+
if (arg === "--force") {
|
|
872
|
+
force = true;
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
if (arg === "--target") {
|
|
876
|
+
if (typeof args[i + 1] !== "string") {
|
|
877
|
+
console.error('--target expects "latest" or an x.y.z version (no value given)');
|
|
878
|
+
process.exitCode = 2;
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
targetRaw = args[++i];
|
|
882
|
+
continue;
|
|
883
|
+
}
|
|
884
|
+
console.error(`Unknown option for 'manager upgrade': ${arg}`);
|
|
885
|
+
console.error("Usage: pie manager upgrade [--target <latest|x.y.z>] [--force]");
|
|
866
886
|
process.exitCode = 2;
|
|
867
887
|
return;
|
|
868
888
|
}
|
|
869
|
-
const target = parseTarget(
|
|
889
|
+
const target = parseTarget(targetRaw);
|
|
870
890
|
if (target === void 0) {
|
|
871
|
-
|
|
872
|
-
console.error(`--target expects "latest" or an x.y.z version (got ${JSON.stringify(given)})`);
|
|
891
|
+
console.error(`--target expects "latest" or an x.y.z version (got ${JSON.stringify(targetRaw)})`);
|
|
873
892
|
process.exitCode = 2;
|
|
874
893
|
return;
|
|
875
894
|
}
|
|
876
|
-
const force = args.includes("--force");
|
|
877
895
|
const paths = upgradePaths(process.argv[1] ?? "");
|
|
878
896
|
console.log(`Upgrading @cydm/pie \u2192 ${target} (this may take a minute)\u2026`);
|
|
879
897
|
const result = await performUpgrade(paths, cliEffects(paths, (m) => console.log(m)), { target, force });
|
|
@@ -888,6 +906,14 @@ async function runUpgradeCommand(args) {
|
|
|
888
906
|
}
|
|
889
907
|
async function runManagerCommand(args) {
|
|
890
908
|
const sub = args[0] ?? "";
|
|
909
|
+
if (sub === "--help" || sub === "-h" || sub === "help") {
|
|
910
|
+
console.log("Usage: pie manager [start|status|stop|tail|upgrade|--install-service|--uninstall-service]");
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
if (sub === "upgrade") {
|
|
914
|
+
await runUpgradeCommand(args.slice(1));
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
891
917
|
const dir = sub === "tail" ? tailWorkspaceDir() : workspaceDir();
|
|
892
918
|
if (sub === "status") {
|
|
893
919
|
const state = readState();
|
|
@@ -1082,10 +1108,6 @@ async function runManagerCommand(args) {
|
|
|
1082
1108
|
process.exitCode = 2;
|
|
1083
1109
|
return;
|
|
1084
1110
|
}
|
|
1085
|
-
if (sub === "upgrade") {
|
|
1086
|
-
await runUpgradeCommand(args.slice(1));
|
|
1087
|
-
return;
|
|
1088
|
-
}
|
|
1089
1111
|
if (sub === "allow") {
|
|
1090
1112
|
const { runManagerAllowCommand } = await import("./manager-allow-SF5ROGDM.js");
|
|
1091
1113
|
runManagerAllowCommand(args.slice(1));
|
|
@@ -1284,7 +1306,7 @@ async function runManagerCommand(args) {
|
|
|
1284
1306
|
if (sub && sub !== "start") {
|
|
1285
1307
|
console.error(`Unknown subcommand: ${sub}`);
|
|
1286
1308
|
console.error(
|
|
1287
|
-
"Usage: pie manager [start|status|stop|tail|--install-service|--uninstall-service]"
|
|
1309
|
+
"Usage: pie manager [start|status|stop|tail|upgrade|--install-service|--uninstall-service]"
|
|
1288
1310
|
);
|
|
1289
1311
|
process.exitCode = 2;
|
|
1290
1312
|
return;
|