@oyasmi/pipiclaw 0.6.10 → 0.7.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/README.md +1 -1
- package/dist/agent/channel-runner.d.ts +12 -1
- package/dist/agent/channel-runner.js +58 -3
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +10 -0
- package/dist/agent/prompt-builder.d.ts +17 -0
- package/dist/agent/prompt-builder.js +42 -23
- package/dist/agent/session-events.d.ts +2 -0
- package/dist/agent/session-events.js +31 -12
- package/dist/agent/types.d.ts +9 -0
- package/dist/agent/types.js +8 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/log.d.ts +24 -0
- package/dist/log.js +96 -1
- package/dist/memory/bootstrap.js +35 -1
- package/dist/memory/candidates.js +21 -3
- package/dist/memory/consolidation.d.ts +7 -1
- package/dist/memory/consolidation.js +107 -36
- package/dist/memory/files.d.ts +40 -0
- package/dist/memory/files.js +0 -0
- package/dist/memory/lifecycle.js +2 -0
- package/dist/memory/maintenance-jobs.js +10 -4
- package/dist/memory/post-turn-review.js +4 -2
- package/dist/memory/promotion-signals.js +0 -1
- package/dist/memory/recall.d.ts +1 -0
- package/dist/memory/recall.js +11 -2
- package/dist/memory/session-search.d.ts +1 -0
- package/dist/memory/session-search.js +1 -0
- package/dist/memory/session.d.ts +1 -0
- package/dist/memory/session.js +44 -13
- package/dist/memory/sidecar-worker.d.ts +4 -0
- package/dist/memory/sidecar-worker.js +29 -0
- package/dist/memory/transcript.d.ts +9 -0
- package/dist/memory/transcript.js +30 -0
- package/dist/paths.d.ts +3 -0
- package/dist/paths.js +3 -0
- package/dist/runtime/bootstrap.js +151 -15
- package/dist/runtime/delivery.js +17 -0
- package/dist/runtime/dingtalk.d.ts +2 -0
- package/dist/runtime/dingtalk.js +19 -4
- package/dist/sandbox.d.ts +8 -0
- package/dist/sandbox.js +21 -17
- package/dist/settings.d.ts +16 -0
- package/dist/settings.js +22 -0
- package/dist/shared/jsonl-appender.d.ts +25 -0
- package/dist/shared/jsonl-appender.js +85 -0
- package/dist/subagents/tool.d.ts +2 -2
- package/dist/subagents/tool.js +25 -56
- package/dist/tools/bash.d.ts +8 -1
- package/dist/tools/bash.js +46 -21
- package/dist/tools/config.d.ts +3 -0
- package/dist/tools/config.js +9 -0
- package/dist/tools/edit.d.ts +1 -0
- package/dist/tools/edit.js +18 -11
- package/dist/tools/index.js +18 -53
- package/dist/tools/memory-save.d.ts +17 -0
- package/dist/tools/memory-save.js +43 -0
- package/dist/tools/read.d.ts +2 -2
- package/dist/tools/read.js +2 -2
- package/dist/tools/registry.d.ts +63 -0
- package/dist/tools/registry.js +154 -0
- package/dist/tools/session-search.d.ts +3 -2
- package/dist/tools/session-search.js +10 -5
- package/dist/tools/skill-list.js +1 -1
- package/dist/tools/skill-manage.d.ts +1 -1
- package/dist/tools/skill-manage.js +3 -1
- package/dist/tools/skill-view.js +12 -11
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools/web-search.js +1 -1
- package/dist/usage/ledger.d.ts +47 -0
- package/dist/usage/ledger.js +95 -0
- package/dist/usage/render.d.ts +11 -0
- package/dist/usage/render.js +67 -0
- package/package.json +5 -5
- package/dist/tools/attach.d.ts +0 -20
- package/dist/tools/attach.js +0 -69
package/dist/log.js
CHANGED
|
@@ -1,4 +1,62 @@
|
|
|
1
1
|
import { styleText } from "node:util";
|
|
2
|
+
import { RUNTIME_LOG_PATH } from "./paths.js";
|
|
3
|
+
import { createJsonlAppender } from "./shared/jsonl-appender.js";
|
|
4
|
+
const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
5
|
+
function readEnvLevel() {
|
|
6
|
+
const raw = process.env.PIPICLAW_LOG_LEVEL?.trim().toLowerCase();
|
|
7
|
+
if (raw && raw in LEVEL_ORDER) {
|
|
8
|
+
return raw;
|
|
9
|
+
}
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
function readEnvFileEnabled() {
|
|
13
|
+
const raw = process.env.PIPICLAW_LOG_FILE?.trim();
|
|
14
|
+
if (raw === "1" || raw === "true")
|
|
15
|
+
return true;
|
|
16
|
+
if (raw === "0" || raw === "false")
|
|
17
|
+
return false;
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
const envLevel = readEnvLevel();
|
|
21
|
+
const envFileEnabled = readEnvFileEnabled();
|
|
22
|
+
let thresholdLevel = envLevel ?? "info";
|
|
23
|
+
let fileSink =
|
|
24
|
+
// Honor an explicit env opt-in even before settings are loaded, so the
|
|
25
|
+
// earliest startup logs are captured. Defaults match DEFAULT_LOGGING.
|
|
26
|
+
envFileEnabled === true
|
|
27
|
+
? createJsonlAppender({ path: RUNTIME_LOG_PATH, maxSizeBytes: 5_000_000, maxRotations: 3 })
|
|
28
|
+
: null;
|
|
29
|
+
/**
|
|
30
|
+
* Configure the file sink from loaded settings. Env vars take precedence and
|
|
31
|
+
* have already applied at module load; this reconciles the two.
|
|
32
|
+
*/
|
|
33
|
+
export function configureLogging(config) {
|
|
34
|
+
thresholdLevel = envLevel ?? config.level;
|
|
35
|
+
const enabled = envFileEnabled ?? config.file.enabled;
|
|
36
|
+
fileSink = enabled
|
|
37
|
+
? createJsonlAppender({
|
|
38
|
+
path: RUNTIME_LOG_PATH,
|
|
39
|
+
maxSizeBytes: config.file.maxSizeBytes,
|
|
40
|
+
maxRotations: config.file.maxFiles,
|
|
41
|
+
})
|
|
42
|
+
: null;
|
|
43
|
+
}
|
|
44
|
+
function emit(level, event, message, extra) {
|
|
45
|
+
if (!fileSink)
|
|
46
|
+
return;
|
|
47
|
+
if (LEVEL_ORDER[level] < LEVEL_ORDER[thresholdLevel])
|
|
48
|
+
return;
|
|
49
|
+
const record = {
|
|
50
|
+
ts: new Date().toISOString(),
|
|
51
|
+
level,
|
|
52
|
+
event,
|
|
53
|
+
message,
|
|
54
|
+
...(extra?.ctx ? { channelId: extra.ctx.channelId, userName: extra.ctx.userName } : {}),
|
|
55
|
+
...(extra?.details ? { details: extra.details } : {}),
|
|
56
|
+
...(extra?.fields ? { fields: extra.fields } : {}),
|
|
57
|
+
};
|
|
58
|
+
void fileSink.append(record);
|
|
59
|
+
}
|
|
2
60
|
function color(style, text) {
|
|
3
61
|
return styleText(style, text);
|
|
4
62
|
}
|
|
@@ -54,6 +112,7 @@ function formatToolArgs(args) {
|
|
|
54
112
|
// User messages
|
|
55
113
|
export function logUserMessage(ctx, text) {
|
|
56
114
|
console.log(color("green", `${timestamp()} ${formatContext(ctx)} ${text}`));
|
|
115
|
+
emit("info", "user_message", text, { ctx });
|
|
57
116
|
}
|
|
58
117
|
// Tool execution
|
|
59
118
|
export function logToolStart(ctx, toolName, label, args) {
|
|
@@ -66,6 +125,11 @@ export function logToolStart(ctx, toolName, label, args) {
|
|
|
66
125
|
.join("\n");
|
|
67
126
|
console.log(color("dim", indented));
|
|
68
127
|
}
|
|
128
|
+
emit("debug", "tool_start", `${toolName}: ${label}`, {
|
|
129
|
+
ctx,
|
|
130
|
+
details: formattedArgs || undefined,
|
|
131
|
+
fields: { toolName, label },
|
|
132
|
+
});
|
|
69
133
|
}
|
|
70
134
|
export function logToolSuccess(ctx, toolName, durationMs, result) {
|
|
71
135
|
const duration = (durationMs / 1000).toFixed(1);
|
|
@@ -78,6 +142,11 @@ export function logToolSuccess(ctx, toolName, durationMs, result) {
|
|
|
78
142
|
.join("\n");
|
|
79
143
|
console.log(color("dim", indented));
|
|
80
144
|
}
|
|
145
|
+
emit("info", "tool_end", toolName, {
|
|
146
|
+
ctx,
|
|
147
|
+
details: truncated || undefined,
|
|
148
|
+
fields: { toolName, durationMs, isError: false },
|
|
149
|
+
});
|
|
81
150
|
}
|
|
82
151
|
export function logToolError(ctx, toolName, durationMs, error) {
|
|
83
152
|
const duration = (durationMs / 1000).toFixed(1);
|
|
@@ -88,10 +157,16 @@ export function logToolError(ctx, toolName, durationMs, error) {
|
|
|
88
157
|
.map((line) => ` ${line}`)
|
|
89
158
|
.join("\n");
|
|
90
159
|
console.log(color("dim", indented));
|
|
160
|
+
emit("error", "tool_end", toolName, {
|
|
161
|
+
ctx,
|
|
162
|
+
details: truncated,
|
|
163
|
+
fields: { toolName, durationMs, isError: true },
|
|
164
|
+
});
|
|
91
165
|
}
|
|
92
166
|
// Response streaming
|
|
93
167
|
export function logResponseStart(ctx) {
|
|
94
168
|
console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} → Streaming response...`));
|
|
169
|
+
emit("debug", "response_start", "Streaming response...", { ctx });
|
|
95
170
|
}
|
|
96
171
|
export function logThinking(ctx, thinking) {
|
|
97
172
|
console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💭 Thinking`));
|
|
@@ -101,6 +176,7 @@ export function logThinking(ctx, thinking) {
|
|
|
101
176
|
.map((line) => ` ${line}`)
|
|
102
177
|
.join("\n");
|
|
103
178
|
console.log(color("dim", indented));
|
|
179
|
+
emit("debug", "thinking", "Thinking", { ctx, details: truncated });
|
|
104
180
|
}
|
|
105
181
|
export function logResponse(ctx, text) {
|
|
106
182
|
console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💬 Response`));
|
|
@@ -110,10 +186,12 @@ export function logResponse(ctx, text) {
|
|
|
110
186
|
.map((line) => ` ${line}`)
|
|
111
187
|
.join("\n");
|
|
112
188
|
console.log(color("dim", indented));
|
|
189
|
+
emit("info", "response", "Response", { ctx, details: truncated });
|
|
113
190
|
}
|
|
114
191
|
// System
|
|
115
192
|
export function logInfo(message) {
|
|
116
193
|
console.log(color("blue", `${timestamp()} [system] ${message}`));
|
|
194
|
+
emit("info", "system", message);
|
|
117
195
|
}
|
|
118
196
|
export function logWarning(message, details) {
|
|
119
197
|
console.log(color("yellow", `${timestamp()} [system] ⚠ ${message}`));
|
|
@@ -124,6 +202,7 @@ export function logWarning(message, details) {
|
|
|
124
202
|
.join("\n");
|
|
125
203
|
console.log(color("dim", indented));
|
|
126
204
|
}
|
|
205
|
+
emit("warn", "system", message, { details });
|
|
127
206
|
}
|
|
128
207
|
export function logAgentError(ctx, error) {
|
|
129
208
|
const context = ctx === "system" ? "[system]" : formatContext(ctx);
|
|
@@ -133,6 +212,10 @@ export function logAgentError(ctx, error) {
|
|
|
133
212
|
.map((line) => ` ${line}`)
|
|
134
213
|
.join("\n");
|
|
135
214
|
console.log(color("dim", indented));
|
|
215
|
+
emit("error", "agent_error", "Agent error", {
|
|
216
|
+
ctx: ctx === "system" ? undefined : ctx,
|
|
217
|
+
details: error,
|
|
218
|
+
});
|
|
136
219
|
}
|
|
137
220
|
// Usage summary
|
|
138
221
|
export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
@@ -159,7 +242,7 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
|
159
242
|
(usage.cacheRead > 0 || usage.cacheWrite > 0
|
|
160
243
|
? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`
|
|
161
244
|
: ""));
|
|
162
|
-
lines.push(`**Total: $${usage.cost.total.toFixed(4)}
|
|
245
|
+
lines.push(`**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`);
|
|
163
246
|
const summary = lines.join("\n");
|
|
164
247
|
// Log to console
|
|
165
248
|
console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💰 Usage`));
|
|
@@ -168,6 +251,18 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
|
168
251
|
? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`
|
|
169
252
|
: "") +
|
|
170
253
|
` = $${usage.cost.total.toFixed(4)}`));
|
|
254
|
+
emit("info", "usage", `Total $${usage.cost.total.toFixed(4)} (incl. sub-agents)`, {
|
|
255
|
+
ctx,
|
|
256
|
+
fields: {
|
|
257
|
+
usage: {
|
|
258
|
+
input: usage.input,
|
|
259
|
+
output: usage.output,
|
|
260
|
+
cacheRead: usage.cacheRead,
|
|
261
|
+
cacheWrite: usage.cacheWrite,
|
|
262
|
+
cost: usage.cost,
|
|
263
|
+
},
|
|
264
|
+
},
|
|
265
|
+
});
|
|
171
266
|
return summary;
|
|
172
267
|
}
|
|
173
268
|
// Startup
|
package/dist/memory/bootstrap.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
1
2
|
import { clipText } from "../shared/text-utils.js";
|
|
2
3
|
const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
|
|
3
4
|
const MIN_SECTION_BUDGET = 600;
|
|
@@ -5,6 +6,39 @@ const CHANNEL_MEMORY_WEIGHT = 0.6;
|
|
|
5
6
|
function normalizeContent(content) {
|
|
6
7
|
return content.replace(/\r/g, "").trim();
|
|
7
8
|
}
|
|
9
|
+
function hasVisibleContent(content) {
|
|
10
|
+
return content.replace(/<!--[\s\S]*?-->/g, "").trim().length > 0;
|
|
11
|
+
}
|
|
12
|
+
// Channel MEMORY.md is "structured sections up top, `## Update <ts>` blocks appended
|
|
13
|
+
// at the tail". A plain head clip would drop the newest facts, so pick sections by
|
|
14
|
+
// priority (structured first, then newest Update blocks) but render in document order
|
|
15
|
+
// for readability.
|
|
16
|
+
function selectChannelMemoryForBootstrap(content, budget) {
|
|
17
|
+
const sections = splitH2Sections(content).filter((section) => hasVisibleContent(section.content));
|
|
18
|
+
if (sections.length === 0) {
|
|
19
|
+
return clipText(content, budget, { headRatio: 1 });
|
|
20
|
+
}
|
|
21
|
+
const renderSection = (section) => `## ${section.heading}\n\n${section.content}`;
|
|
22
|
+
const structured = sections.filter((section) => !section.heading.startsWith("Update "));
|
|
23
|
+
const updatesNewestFirst = sections.filter((section) => section.heading.startsWith("Update ")).reverse();
|
|
24
|
+
const byPriority = [...structured, ...updatesNewestFirst];
|
|
25
|
+
const chosen = new Set();
|
|
26
|
+
let used = 0;
|
|
27
|
+
for (const section of byPriority) {
|
|
28
|
+
const cost = (chosen.size > 0 ? 2 : 0) + renderSection(section).length;
|
|
29
|
+
if (used + cost <= budget) {
|
|
30
|
+
chosen.add(section);
|
|
31
|
+
used += cost;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (chosen.size === 0) {
|
|
35
|
+
return clipText(renderSection(byPriority[0]), budget, { headRatio: 0.5 });
|
|
36
|
+
}
|
|
37
|
+
return sections
|
|
38
|
+
.filter((section) => chosen.has(section))
|
|
39
|
+
.map(renderSection)
|
|
40
|
+
.join("\n\n");
|
|
41
|
+
}
|
|
8
42
|
function allocateBudgets(channelMemory, workspaceMemory, maxChars) {
|
|
9
43
|
if (!channelMemory && !workspaceMemory) {
|
|
10
44
|
return [0, 0];
|
|
@@ -35,7 +69,7 @@ export function buildFirstTurnMemoryBootstrap(options) {
|
|
|
35
69
|
];
|
|
36
70
|
if (channelMemory) {
|
|
37
71
|
sections.push("", "[Channel MEMORY.md]");
|
|
38
|
-
sections.push(channelBudget > 0 ?
|
|
72
|
+
sections.push(channelBudget > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory);
|
|
39
73
|
}
|
|
40
74
|
if (workspaceMemory) {
|
|
41
75
|
sections.push("", "[Workspace MEMORY.md]");
|
|
@@ -61,19 +61,32 @@ function inferPriority(source, title) {
|
|
|
61
61
|
}
|
|
62
62
|
return 4;
|
|
63
63
|
}
|
|
64
|
+
const ENTRY_ID_COMMENT_GLOBAL = /\s*<!--\s*id:m-[a-z0-9]+\s*-->/gi;
|
|
65
|
+
function stripEntryIdComments(text) {
|
|
66
|
+
return text.replace(ENTRY_ID_COMMENT_GLOBAL, "");
|
|
67
|
+
}
|
|
64
68
|
function buildCandidate(source, path, title, content, timestamp, searchText) {
|
|
69
|
+
const cleanContent = stripEntryIdComments(content);
|
|
65
70
|
return {
|
|
66
71
|
id: `${source}:${slugify(title)}:${timestamp ?? ""}`,
|
|
67
72
|
source,
|
|
68
73
|
path,
|
|
69
74
|
title,
|
|
70
|
-
content,
|
|
71
|
-
searchText,
|
|
75
|
+
content: cleanContent,
|
|
76
|
+
searchText: searchText === undefined ? undefined : stripEntryIdComments(searchText),
|
|
72
77
|
timestamp,
|
|
73
78
|
sectionKind: title.trim().toLowerCase(),
|
|
74
79
|
priority: inferPriority(source, title),
|
|
75
80
|
};
|
|
76
81
|
}
|
|
82
|
+
function parseUpdateBlockTimestamp(heading) {
|
|
83
|
+
const match = heading.match(/^Update\s+(.+)$/);
|
|
84
|
+
if (!match) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
const timestamp = match[1].trim();
|
|
88
|
+
return Number.isFinite(Date.parse(timestamp)) ? timestamp : undefined;
|
|
89
|
+
}
|
|
77
90
|
function buildWorkspaceOrChannelMemoryCandidates(source, path, content) {
|
|
78
91
|
const sections = splitH2Sections(content);
|
|
79
92
|
if (sections.length === 0 && content) {
|
|
@@ -83,7 +96,12 @@ function buildWorkspaceOrChannelMemoryCandidates(source, path, content) {
|
|
|
83
96
|
}
|
|
84
97
|
return sections
|
|
85
98
|
.filter((section) => section.content.trim())
|
|
86
|
-
.map((section) =>
|
|
99
|
+
.map((section) => {
|
|
100
|
+
// `## Update <ISO>` blocks carry their write time in the heading; surfacing it
|
|
101
|
+
// lets recall apply a recency boost and keeps appended-block ids distinct.
|
|
102
|
+
const timestamp = source === "channel-memory" ? parseUpdateBlockTimestamp(section.heading) : undefined;
|
|
103
|
+
return buildCandidate(source, path, section.heading, section.content, timestamp);
|
|
104
|
+
});
|
|
87
105
|
}
|
|
88
106
|
function buildSessionCandidates(path, content) {
|
|
89
107
|
const sections = splitH1Sections(content).filter((section) => section.content.trim());
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
3
|
import { type SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
|
|
4
5
|
export type ConsolidationMode = "idle" | "boundary";
|
|
5
6
|
export interface ConsolidationRunOptions {
|
|
7
|
+
channelId?: string;
|
|
6
8
|
channelDir: string;
|
|
7
9
|
model: Model<Api>;
|
|
8
10
|
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
@@ -25,5 +27,9 @@ export declare function shouldCleanupChannelMemory(currentMemory: string): boole
|
|
|
25
27
|
export declare function shouldFoldChannelHistory(currentHistory: string): boolean;
|
|
26
28
|
export declare function getStructuralMaintenanceStats(currentMemory: string, currentHistory: string): StructuralMaintenanceStats;
|
|
27
29
|
export declare function runInlineConsolidation(options: ConsolidationRunOptions): Promise<InlineConsolidationResult>;
|
|
28
|
-
export
|
|
30
|
+
export type MemoryCleanupShrinkGuard = Pick<PipiclawMemoryMaintenanceSettings, "cleanupShrinkGuardMinRatio" | "cleanupShrinkGuardMinChars">;
|
|
31
|
+
export declare class MemoryCleanupRejectedError extends Error {
|
|
32
|
+
constructor(reason: string);
|
|
33
|
+
}
|
|
34
|
+
export declare function cleanupChannelMemory(options: ConsolidationRunOptions, currentMemory: string, guard?: MemoryCleanupShrinkGuard): Promise<boolean>;
|
|
29
35
|
export declare function foldChannelHistory(options: ConsolidationRunOptions, currentHistory: string): Promise<boolean>;
|
|
@@ -2,9 +2,9 @@ import { getLatestCompactionEntry, serializeConversation, } from "@earendil-work
|
|
|
2
2
|
import { parseJsonObject } from "../shared/llm-json.js";
|
|
3
3
|
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
4
4
|
import { clipText } from "../shared/text-utils.js";
|
|
5
|
-
import {
|
|
6
|
-
import { appendChannelHistoryBlock, appendChannelMemoryUpdate, readChannelHistory, readChannelMemory, readChannelSession, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
|
|
5
|
+
import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
|
|
7
6
|
import { runRetriedSidecarTask, runSidecarTask } from "./sidecar-worker.js";
|
|
7
|
+
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
8
8
|
const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
|
|
9
9
|
const MEMORY_CLEANUP_LENGTH_THRESHOLD = 5_000;
|
|
10
10
|
const MEMORY_UPDATE_BLOCK_THRESHOLD = 4;
|
|
@@ -14,30 +14,35 @@ const HISTORY_RECENT_BLOCKS_TO_KEEP = 3;
|
|
|
14
14
|
const INLINE_CONSOLIDATION_TIMEOUT_MS = 20_000;
|
|
15
15
|
const MEMORY_CLEANUP_TIMEOUT_MS = 120_000;
|
|
16
16
|
const HISTORY_FOLDING_TIMEOUT_MS = 120_000;
|
|
17
|
+
const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEMORY.md:
|
|
18
|
+
- {"op":"add","content":"..."} for a genuinely new durable fact.
|
|
19
|
+
- {"op":"supersede","targetId":"m-xxxx","content":"..."} when new information updates or contradicts an existing entry (use its id).
|
|
20
|
+
- {"op":"invalidate","targetId":"m-xxxx","reason":"..."} when an existing entry is now obsolete or resolved.
|
|
21
|
+
- Only reference targetId values that appear in the current MEMORY.md entries shown below.
|
|
22
|
+
- Durable = stable facts, decisions, preferences, constraints, or medium-horizon open loops.
|
|
23
|
+
- Each content string must be a standalone, keyword-rich sentence fragment suitable for a Markdown bullet (no leading "-"). Write it so future keyword search can find it.
|
|
24
|
+
- Do not add content already present in SESSION.md or MEMORY.md; prefer supersede/invalidate over piling on near-duplicates.
|
|
25
|
+
- Do not promote active execution state, temporary debugging observations, completed worklog, raw transcript quotes, acknowledgements, or formatting instructions.`;
|
|
17
26
|
const BOUNDARY_INLINE_CONSOLIDATION_SYSTEM_PROMPT = `You are a runtime memory consolidation worker for Pipiclaw.
|
|
18
27
|
|
|
19
28
|
Return strict JSON only. Do not wrap in Markdown fences.
|
|
20
29
|
|
|
21
30
|
Output schema:
|
|
22
31
|
{
|
|
23
|
-
"
|
|
32
|
+
"memoryOps": [{"op": "add|supersede|invalidate", "targetId": "m-xxxx", "content": "string", "reason": "string"}],
|
|
24
33
|
"historyBlock": "string"
|
|
25
34
|
}
|
|
26
35
|
|
|
27
36
|
Rules:
|
|
28
|
-
|
|
29
|
-
- Each memoryEntries item must be a standalone sentence fragment suitable for a Markdown bullet without the bullet prefix.
|
|
30
|
-
- Do not include raw transcript quotes unless essential.
|
|
31
|
-
- Do not include ephemeral chatter, obvious one-shot acknowledgements, or formatting instructions.
|
|
32
|
-
- Leave active execution state, current step-by-step work, temporary debugging observations, and completed worklog in SESSION.md instead of promoting it into durable memory.
|
|
37
|
+
${MEMORY_OPS_RULES}
|
|
33
38
|
- historyBlock: concise Markdown summarizing the conversation chunk for later recovery.
|
|
34
39
|
- For any conversation that contains at least one meaningful user request and one meaningful assistant reply, return a non-empty historyBlock with at least one bullet.
|
|
35
40
|
- Prefer short bullets and short paragraphs.
|
|
36
|
-
- If there is nothing worth storing, return empty
|
|
41
|
+
- If there is nothing worth storing, return an empty memoryOps array and empty historyBlock.
|
|
37
42
|
|
|
38
43
|
Example output for a short useful exchange:
|
|
39
44
|
{
|
|
40
|
-
"
|
|
45
|
+
"memoryOps": [{"op": "add", "content": "User prefers dark mode in the dashboard"}],
|
|
41
46
|
"historyBlock": "- User asked how to toggle dashboard theme; confirmed dark mode preference."
|
|
42
47
|
}`;
|
|
43
48
|
const IDLE_INLINE_CONSOLIDATION_SYSTEM_PROMPT = `You are a runtime memory consolidation worker for Pipiclaw.
|
|
@@ -46,21 +51,18 @@ Return strict JSON only. Do not wrap in Markdown fences.
|
|
|
46
51
|
|
|
47
52
|
Output schema:
|
|
48
53
|
{
|
|
49
|
-
"
|
|
54
|
+
"memoryOps": [{"op": "add|supersede|invalidate", "targetId": "m-xxxx", "content": "string", "reason": "string"}]
|
|
50
55
|
}
|
|
51
56
|
|
|
52
57
|
Rules:
|
|
53
58
|
- This is an idle maintenance pass after a normal assistant turn.
|
|
54
|
-
|
|
59
|
+
${MEMORY_OPS_RULES}
|
|
55
60
|
- Do not summarize the exchange for HISTORY.md. Idle consolidation never writes HISTORY.md.
|
|
56
|
-
-
|
|
57
|
-
- Do not include active execution state, temporary debugging observations, completed worklog, raw transcript quotes, acknowledgements, or formatting instructions.
|
|
58
|
-
- Each memoryEntries item must be a standalone sentence fragment suitable for a Markdown bullet without the bullet prefix.
|
|
59
|
-
- If there is nothing durable enough to store, return an empty memoryEntries array.
|
|
61
|
+
- If there is nothing durable enough to store, return an empty memoryOps array.
|
|
60
62
|
|
|
61
63
|
Example output:
|
|
62
64
|
{
|
|
63
|
-
"
|
|
65
|
+
"memoryOps": [{"op": "add", "content": "User prefers dark mode in the dashboard"}]
|
|
64
66
|
}`;
|
|
65
67
|
const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMORY.md file.
|
|
66
68
|
|
|
@@ -92,17 +94,45 @@ Goals:
|
|
|
92
94
|
- Keep important decisions, milestones, and unresolved outcomes.
|
|
93
95
|
- Remove redundancy and transcript-like detail.
|
|
94
96
|
- Preserve a chronological narrative at a high level.`;
|
|
97
|
+
function usageContextFor(channelId) {
|
|
98
|
+
return channelId ? { channelId } : undefined;
|
|
99
|
+
}
|
|
95
100
|
function normalizeText(text) {
|
|
96
101
|
return text.replace(/\r/g, "").trim();
|
|
97
102
|
}
|
|
103
|
+
function normalizeMemoryOp(value) {
|
|
104
|
+
if (typeof value !== "object" || value === null) {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
const record = value;
|
|
108
|
+
const content = typeof record.content === "string" ? record.content.trim() : "";
|
|
109
|
+
const targetId = typeof record.targetId === "string" ? record.targetId.trim() : "";
|
|
110
|
+
if (record.op === "supersede" && targetId && content) {
|
|
111
|
+
return { op: "supersede", targetId, content };
|
|
112
|
+
}
|
|
113
|
+
if (record.op === "invalidate" && targetId) {
|
|
114
|
+
return {
|
|
115
|
+
op: "invalidate",
|
|
116
|
+
targetId,
|
|
117
|
+
reason: typeof record.reason === "string" ? record.reason.trim() : undefined,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
// Default to add for "add" or any unrecognized op that still carries content.
|
|
121
|
+
if (content) {
|
|
122
|
+
return { op: "add", content };
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
98
126
|
function parseConsolidationResponse(text) {
|
|
99
127
|
const parsed = parseJsonObject(text);
|
|
128
|
+
const rawOps = Array.isArray(parsed.memoryOps)
|
|
129
|
+
? parsed.memoryOps
|
|
130
|
+
: // Back-compat: tolerate the old memoryEntries: string[] shape.
|
|
131
|
+
Array.isArray(parsed.memoryEntries)
|
|
132
|
+
? parsed.memoryEntries.map((entry) => ({ op: "add", content: entry }))
|
|
133
|
+
: [];
|
|
100
134
|
return {
|
|
101
|
-
|
|
102
|
-
? parsed.memoryEntries
|
|
103
|
-
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
|
|
104
|
-
.filter((entry) => entry.length > 0)
|
|
105
|
-
: [],
|
|
135
|
+
memoryOps: rawOps.map(normalizeMemoryOp).filter((op) => op !== null),
|
|
106
136
|
historyBlock: typeof parsed.historyBlock === "string" ? parsed.historyBlock.trim() : "",
|
|
107
137
|
};
|
|
108
138
|
}
|
|
@@ -164,7 +194,7 @@ export function getStructuralMaintenanceStats(currentMemory, currentHistory) {
|
|
|
164
194
|
hasHistoryContent: currentHistory.replace(/^# Channel History\s*/i, "").trim().length > 0,
|
|
165
195
|
};
|
|
166
196
|
}
|
|
167
|
-
async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt, timeoutMs) {
|
|
197
|
+
async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt, timeoutMs, usageContext) {
|
|
168
198
|
const result = await runSidecarTask({
|
|
169
199
|
name,
|
|
170
200
|
model,
|
|
@@ -172,20 +202,29 @@ async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt,
|
|
|
172
202
|
systemPrompt,
|
|
173
203
|
prompt,
|
|
174
204
|
timeoutMs,
|
|
205
|
+
usageContext,
|
|
175
206
|
parse: (text) => text.trim(),
|
|
176
207
|
});
|
|
177
208
|
return result.output;
|
|
178
209
|
}
|
|
210
|
+
function renderMemoryEntriesForPrompt(rawMemory) {
|
|
211
|
+
const entries = parseChannelMemoryEntries(rawMemory);
|
|
212
|
+
if (entries.length === 0) {
|
|
213
|
+
return "";
|
|
214
|
+
}
|
|
215
|
+
return entries.map((entry) => `${entry.id} — ${entry.content}`).join("\n");
|
|
216
|
+
}
|
|
179
217
|
async function buildInlineConsolidationResponse(options, messages) {
|
|
180
218
|
const mode = options.mode ?? "boundary";
|
|
181
219
|
const transcript = clipText(serializeConversation(messages), INLINE_TRANSCRIPT_MAX_CHARS, { headRatio: 0.35 });
|
|
182
|
-
const
|
|
220
|
+
const rawMemory = await readChannelMemory(options.channelDir);
|
|
221
|
+
const currentMemory = clipText(renderMemoryEntriesForPrompt(rawMemory), 8_000, { headRatio: 0.35 });
|
|
183
222
|
const currentSession = clipText(await readChannelSession(options.channelDir), 8_000, { headRatio: 0.35 });
|
|
184
223
|
const currentHistory = clipText(await readChannelHistory(options.channelDir), 8_000, { headRatio: 0.35 });
|
|
185
224
|
const prompt = `Current SESSION.md:
|
|
186
225
|
${currentSession || "(empty)"}
|
|
187
226
|
|
|
188
|
-
|
|
227
|
+
Current MEMORY.md entries (id — content; reference ids in supersede/invalidate):
|
|
189
228
|
${currentMemory || "(empty)"}
|
|
190
229
|
|
|
191
230
|
Channel history file:
|
|
@@ -200,6 +239,7 @@ ${transcript || "(empty)"}`;
|
|
|
200
239
|
systemPrompt: mode === "idle" ? IDLE_INLINE_CONSOLIDATION_SYSTEM_PROMPT : BOUNDARY_INLINE_CONSOLIDATION_SYSTEM_PROMPT,
|
|
201
240
|
prompt,
|
|
202
241
|
timeoutMs: INLINE_CONSOLIDATION_TIMEOUT_MS,
|
|
242
|
+
usageContext: usageContextFor(options.channelId),
|
|
203
243
|
parse: (text) => text.trim(),
|
|
204
244
|
});
|
|
205
245
|
const rawResponse = result.output;
|
|
@@ -209,17 +249,16 @@ export async function runInlineConsolidation(options) {
|
|
|
209
249
|
const mode = options.mode ?? "boundary";
|
|
210
250
|
const sourceEntries = options.sessionEntries ?? [];
|
|
211
251
|
const relevantEntries = sourceEntries.length > 0 ? sourceEntries.slice(getLatestCompactionBoundary(sourceEntries)) : sourceEntries;
|
|
212
|
-
const relevantMessages =
|
|
252
|
+
const relevantMessages = sanitizeMessagesForMemory(relevantEntries.length > 0 ? extractMessagesFromSessionEntries(relevantEntries) : options.messages);
|
|
213
253
|
if (!hasMeaningfulMessages(relevantMessages)) {
|
|
214
254
|
return { skipped: true, appendedMemoryEntries: 0, appendedHistoryBlock: false };
|
|
215
255
|
}
|
|
216
256
|
const response = await buildInlineConsolidationResponse(options, relevantMessages);
|
|
217
257
|
const timestamp = new Date().toISOString();
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
});
|
|
258
|
+
let appliedMemoryOps = 0;
|
|
259
|
+
if (response.memoryOps.length > 0) {
|
|
260
|
+
const applied = await applyChannelMemoryOps(options.channelDir, response.memoryOps, timestamp);
|
|
261
|
+
appliedMemoryOps = applied.added + applied.superseded + applied.invalidated + applied.downgradedToAdd;
|
|
223
262
|
}
|
|
224
263
|
if (mode === "boundary" && response.historyBlock.trim()) {
|
|
225
264
|
await appendChannelHistoryBlock(options.channelDir, {
|
|
@@ -229,17 +268,42 @@ export async function runInlineConsolidation(options) {
|
|
|
229
268
|
}
|
|
230
269
|
return {
|
|
231
270
|
skipped: false,
|
|
232
|
-
appendedMemoryEntries:
|
|
271
|
+
appendedMemoryEntries: appliedMemoryOps,
|
|
233
272
|
appendedHistoryBlock: mode === "boundary" && response.historyBlock.trim().length > 0,
|
|
234
273
|
};
|
|
235
274
|
}
|
|
236
|
-
export
|
|
275
|
+
export class MemoryCleanupRejectedError extends Error {
|
|
276
|
+
constructor(reason) {
|
|
277
|
+
super(reason);
|
|
278
|
+
this.name = "MemoryCleanupRejectedError";
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// Guard against a cleanup pass that catastrophically drops content (e.g. a truncated
|
|
282
|
+
// or malformed LLM response). Backups exist too, but refusing the write avoids
|
|
283
|
+
// clobbering good memory in the first place.
|
|
284
|
+
function isCleanupResultTooSmall(currentMemory, nextMemory, guard) {
|
|
285
|
+
const before = normalizeText(currentMemory);
|
|
286
|
+
const after = normalizeText(nextMemory);
|
|
287
|
+
if (before.length < Math.max(0, guard.cleanupShrinkGuardMinChars)) {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
if (after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio))) {
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
const beforeEntries = parseChannelMemoryEntries(before).length;
|
|
294
|
+
const afterEntries = parseChannelMemoryEntries(after).length;
|
|
295
|
+
return beforeEntries > 0 && afterEntries * 2 < beforeEntries;
|
|
296
|
+
}
|
|
297
|
+
export async function cleanupChannelMemory(options, currentMemory, guard) {
|
|
237
298
|
if (!shouldCleanupChannelMemory(currentMemory)) {
|
|
238
299
|
return false;
|
|
239
300
|
}
|
|
240
301
|
const prompt = `Current MEMORY.md:
|
|
241
302
|
${currentMemory}`;
|
|
242
|
-
const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS);
|
|
303
|
+
const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId));
|
|
304
|
+
if (guard && isCleanupResultTooSmall(currentMemory, nextMemory, guard)) {
|
|
305
|
+
throw new MemoryCleanupRejectedError("cleanup result shrank below the configured guard threshold");
|
|
306
|
+
}
|
|
243
307
|
await rewriteChannelMemory(options.channelDir, nextMemory);
|
|
244
308
|
return true;
|
|
245
309
|
}
|
|
@@ -250,9 +314,16 @@ export async function foldChannelHistory(options, currentHistory) {
|
|
|
250
314
|
const sections = splitH2Sections(currentHistory);
|
|
251
315
|
const olderSections = sections.slice(0, -HISTORY_RECENT_BLOCKS_TO_KEEP);
|
|
252
316
|
const recentSections = sections.slice(-HISTORY_RECENT_BLOCKS_TO_KEEP);
|
|
317
|
+
const renderedOlder = olderSections.map((section) => `## ${section.heading}\n\n${section.content}`).join("\n\n");
|
|
318
|
+
// Preserve the raw blocks before folding turns them lossy, so nothing is
|
|
319
|
+
// permanently blurred by repeated folds.
|
|
320
|
+
await appendChannelHistoryArchive(options.channelDir, {
|
|
321
|
+
timestamp: new Date().toISOString(),
|
|
322
|
+
content: renderedOlder,
|
|
323
|
+
});
|
|
253
324
|
const prompt = `Older history blocks to fold:
|
|
254
|
-
${
|
|
255
|
-
const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS);
|
|
325
|
+
${renderedOlder}`;
|
|
326
|
+
const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS, usageContextFor(options.channelId));
|
|
256
327
|
const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? new Date().toISOString()}`;
|
|
257
328
|
const rebuiltHistory = [
|
|
258
329
|
"# Channel History",
|
package/dist/memory/files.d.ts
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
+
export declare function generateMemoryEntryId(): string;
|
|
2
|
+
export declare function stripMemoryEntryIdComment(text: string): string;
|
|
3
|
+
export interface ParsedMemoryEntry {
|
|
4
|
+
id: string;
|
|
5
|
+
content: string;
|
|
6
|
+
sectionHeading: string;
|
|
7
|
+
timestamp?: string;
|
|
8
|
+
lineIndex: number;
|
|
9
|
+
hasExplicitId: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** Parse durable MEMORY.md bullet entries with stable ids for op-based edits. */
|
|
12
|
+
export declare function parseChannelMemoryEntries(content: string): ParsedMemoryEntry[];
|
|
13
|
+
export type MemoryOp = {
|
|
14
|
+
op: "add";
|
|
15
|
+
content: string;
|
|
16
|
+
} | {
|
|
17
|
+
op: "supersede";
|
|
18
|
+
targetId: string;
|
|
19
|
+
content: string;
|
|
20
|
+
} | {
|
|
21
|
+
op: "invalidate";
|
|
22
|
+
targetId: string;
|
|
23
|
+
reason?: string;
|
|
24
|
+
};
|
|
25
|
+
export interface ApplyMemoryOpsResult {
|
|
26
|
+
added: number;
|
|
27
|
+
superseded: number;
|
|
28
|
+
invalidated: number;
|
|
29
|
+
downgradedToAdd: number;
|
|
30
|
+
missingTarget: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Apply add/supersede/invalidate ops to a channel MEMORY.md with line-level edits,
|
|
34
|
+
* preserving any surrounding markdown. Missing supersede targets downgrade to add;
|
|
35
|
+
* missing invalidate targets are skipped. Mutating edits are backed up first.
|
|
36
|
+
*/
|
|
37
|
+
export declare function applyChannelMemoryOps(channelDir: string, ops: MemoryOp[], timestamp?: string): Promise<ApplyMemoryOpsResult>;
|
|
1
38
|
export interface MemoryUpdateBlock {
|
|
2
39
|
timestamp: string;
|
|
3
40
|
entries: string[];
|
|
@@ -18,4 +55,7 @@ export declare function rewriteChannelMemory(channelDir: string, content: string
|
|
|
18
55
|
export declare function rewriteChannelHistory(channelDir: string, content: string): Promise<void>;
|
|
19
56
|
export declare function rewriteChannelSession(channelDir: string, content: string): Promise<void>;
|
|
20
57
|
export declare function appendChannelMemoryUpdate(channelDir: string, block: MemoryUpdateBlock): Promise<void>;
|
|
58
|
+
export declare function getChannelHistoryArchivePath(channelDir: string): string;
|
|
59
|
+
/** Append raw history blocks to a never-rewritten archive before lossy folding. */
|
|
60
|
+
export declare function appendChannelHistoryArchive(channelDir: string, block: HistoryBlock): Promise<void>;
|
|
21
61
|
export declare function appendChannelHistoryBlock(channelDir: string, block: HistoryBlock): Promise<void>;
|
package/dist/memory/files.js
CHANGED
|
Binary file
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -16,6 +16,7 @@ export class MemoryLifecycle {
|
|
|
16
16
|
}
|
|
17
17
|
buildRunOptions(messages, sessionEntries) {
|
|
18
18
|
return {
|
|
19
|
+
channelId: this.options.channelId,
|
|
19
20
|
channelDir: this.options.channelDir,
|
|
20
21
|
model: this.options.getModel(),
|
|
21
22
|
resolveApiKey: this.options.resolveApiKey,
|
|
@@ -91,6 +92,7 @@ export class MemoryLifecycle {
|
|
|
91
92
|
const { reason } = request;
|
|
92
93
|
try {
|
|
93
94
|
await updateChannelSessionMemory({
|
|
95
|
+
channelId: this.options.channelId,
|
|
94
96
|
channelDir: this.options.channelDir,
|
|
95
97
|
messages: request.messages ?? this.options.getMessages(),
|
|
96
98
|
model: this.options.getModel(),
|