@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.2-beta.1
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/agent/channel-runner.d.ts +9 -1
- package/dist/agent/channel-runner.js +51 -18
- package/dist/agent/command-extension.js +24 -27
- package/dist/agent/commands.d.ts +51 -7
- package/dist/agent/commands.js +199 -59
- package/dist/agent/effect-ledger.js +9 -2
- package/dist/agent/job-manager.d.ts +4 -0
- package/dist/agent/job-manager.js +17 -2
- package/dist/agent/prompt/manifest.d.ts +1 -1
- package/dist/agent/prompt/manifest.js +6 -7
- package/dist/agent/prompt/sections.js +9 -5
- package/dist/agent/reply-limits.d.ts +16 -0
- package/dist/agent/reply-limits.js +17 -0
- package/dist/agent/session-events.d.ts +2 -0
- package/dist/agent/session-events.js +29 -14
- package/dist/agent/status-render.js +12 -12
- package/dist/agent/turn-recovery.js +2 -2
- package/dist/agent/type-guards.js +5 -1
- package/dist/agent/workspace-resources.d.ts +2 -2
- package/dist/agent/workspace-resources.js +41 -3
- package/dist/executor.d.ts +28 -0
- package/dist/executor.js +120 -18
- package/dist/file-store.d.ts +96 -0
- package/dist/file-store.js +189 -0
- package/dist/main.js +3 -4
- package/dist/memory/commands.js +79 -38
- package/dist/memory/consolidation.d.ts +5 -1
- package/dist/memory/consolidation.js +35 -38
- package/dist/memory/extraction.d.ts +8 -1
- package/dist/memory/extraction.js +47 -4
- package/dist/memory/files.d.ts +0 -1
- package/dist/memory/files.js +31 -12
- package/dist/memory/lifecycle.js +9 -2
- package/dist/memory/maintenance-jobs.js +16 -38
- package/dist/memory/maintenance-state.js +2 -1
- package/dist/memory/metadata.d.ts +3 -0
- package/dist/memory/metadata.js +7 -0
- package/dist/memory/recall.d.ts +19 -0
- package/dist/memory/recall.js +116 -24
- package/dist/memory/review-log.d.ts +0 -2
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/session-corpus.js +5 -0
- package/dist/memory/session-search.js +15 -22
- package/dist/memory/sidecar-worker.js +4 -0
- package/dist/memory/source-window.d.ts +0 -1
- package/dist/memory/source-window.js +0 -5
- package/dist/memory/transcript.d.ts +10 -0
- package/dist/memory/transcript.js +39 -0
- package/dist/playbooks/agent-delegation.md +34 -25
- package/dist/playbooks/background-jobs.md +8 -16
- package/dist/playbooks/catalog.d.ts +1 -1
- package/dist/playbooks/catalog.js +1 -1
- package/dist/playbooks/event-scheduling.md +15 -15
- package/dist/playbooks/memory-and-learning.md +30 -23
- package/dist/playbooks/outbound-media.md +15 -8
- package/dist/playbooks/runtime-orientation.md +40 -37
- package/dist/playbooks/task-driving.md +36 -38
- package/dist/playbooks/task-planning.md +21 -21
- package/dist/runtime/app-home.d.ts +6 -0
- package/dist/runtime/app-home.js +16 -7
- package/dist/runtime/bootstrap.js +54 -13
- package/dist/runtime/channel-context.d.ts +2 -1
- package/dist/runtime/delivery.js +3 -3
- package/dist/runtime/dingtalk.d.ts +9 -1
- package/dist/runtime/dingtalk.js +30 -15
- package/dist/runtime/durable-dispatch.d.ts +26 -1
- package/dist/runtime/durable-dispatch.js +51 -5
- package/dist/runtime/event-commands.d.ts +15 -0
- package/dist/runtime/event-commands.js +55 -56
- package/dist/runtime/events.d.ts +4 -2
- package/dist/runtime/events.js +15 -20
- package/dist/runtime/project-commands.d.ts +16 -0
- package/dist/runtime/project-commands.js +13 -17
- package/dist/runtime/subagent-commands.d.ts +20 -0
- package/dist/runtime/subagent-commands.js +61 -58
- package/dist/runtime/task-commands.d.ts +37 -0
- package/dist/runtime/task-commands.js +108 -66
- package/dist/runtime/task-driver.js +2 -2
- package/dist/security/block-message.d.ts +11 -0
- package/dist/security/block-message.js +12 -0
- package/dist/security/path-guard-check.d.ts +13 -0
- package/dist/security/path-guard-check.js +39 -0
- package/dist/security/path-guard.js +61 -12
- package/dist/security/types.d.ts +9 -0
- package/dist/settings.js +3 -2
- package/dist/shared/atomic-file.d.ts +17 -1
- package/dist/shared/atomic-file.js +50 -3
- package/dist/shared/duration.d.ts +2 -0
- package/dist/shared/duration.js +7 -0
- package/dist/shared/safe-id.d.ts +19 -0
- package/dist/shared/safe-id.js +24 -0
- package/dist/shared/text-utils.d.ts +1 -1
- package/dist/shared/text-utils.js +3 -8
- package/dist/shared/type-guards.d.ts +2 -0
- package/dist/shared/type-guards.js +4 -0
- package/dist/subagents/discovery.d.ts +51 -19
- package/dist/subagents/discovery.js +93 -98
- package/dist/subagents/external/claude-code.js +40 -2
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/run.js +61 -8
- package/dist/subagents/format.d.ts +3 -2
- package/dist/subagents/format.js +3 -7
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/runs.js +10 -9
- package/dist/subagents/tool.d.ts +31 -18
- package/dist/subagents/tool.js +592 -562
- package/dist/subagents/workspace-lease.js +1 -1
- package/dist/tasks/control.js +7 -9
- package/dist/tasks/ledger.d.ts +2 -2
- package/dist/tasks/ledger.js +3 -7
- package/dist/tasks/transitions.d.ts +5 -1
- package/dist/tasks/transitions.js +2 -2
- package/dist/tasks/verification.d.ts +7 -5
- package/dist/tools/bash.d.ts +1 -2
- package/dist/tools/bash.js +99 -76
- package/dist/tools/config.d.ts +6 -1
- package/dist/tools/config.js +9 -0
- package/dist/tools/edit.d.ts +2 -3
- package/dist/tools/edit.js +276 -75
- package/dist/tools/event-manage.d.ts +13 -7
- package/dist/tools/event-manage.js +52 -14
- package/dist/tools/glob-match.d.ts +11 -0
- package/dist/tools/glob-match.js +75 -0
- package/dist/tools/glob.d.ts +15 -0
- package/dist/tools/glob.js +113 -0
- package/dist/tools/grep.d.ts +0 -1
- package/dist/tools/grep.js +60 -44
- package/dist/tools/ignore-dirs.d.ts +6 -0
- package/dist/tools/ignore-dirs.js +15 -0
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +54 -40
- package/dist/tools/job.d.ts +0 -1
- package/dist/tools/job.js +3 -9
- package/dist/tools/line-index.d.ts +16 -0
- package/dist/tools/line-index.js +76 -0
- package/dist/tools/memory-manage.d.ts +21 -8
- package/dist/tools/memory-manage.js +114 -103
- package/dist/tools/presentation.d.ts +2 -0
- package/dist/tools/presentation.js +109 -0
- package/dist/tools/read.d.ts +2 -2
- package/dist/tools/read.js +100 -120
- package/dist/tools/registry.d.ts +4 -1
- package/dist/tools/registry.js +89 -22
- package/dist/tools/send-media.d.ts +6 -6
- package/dist/tools/send-media.js +21 -43
- package/dist/tools/session-search.d.ts +0 -1
- package/dist/tools/session-search.js +0 -1
- package/dist/tools/skill-security.d.ts +0 -2
- package/dist/tools/skill-security.js +1 -25
- package/dist/tools/skill.d.ts +31 -0
- package/dist/tools/skill.js +153 -0
- package/dist/tools/subagent-manage.d.ts +6 -5
- package/dist/tools/subagent-manage.js +47 -47
- package/dist/tools/task-manage/create.d.ts +2 -2
- package/dist/tools/task-manage/create.js +1 -3
- package/dist/tools/task-manage/lifecycle.d.ts +9 -6
- package/dist/tools/task-manage/lifecycle.js +49 -56
- package/dist/tools/task-manage/schema.d.ts +27 -15
- package/dist/tools/task-manage/schema.js +58 -74
- package/dist/tools/task-manage/shared.d.ts +11 -6
- package/dist/tools/task-manage/shared.js +30 -21
- package/dist/tools/task-manage/types.d.ts +14 -15
- package/dist/tools/task-manage/verification.d.ts +4 -4
- package/dist/tools/task-manage/verification.js +6 -8
- package/dist/tools/task-manage.d.ts +8 -11
- package/dist/tools/task-manage.js +63 -50
- package/dist/tools/tool-details.d.ts +17 -1
- package/dist/tools/tool-details.js +24 -0
- package/dist/tools/truncate.d.ts +8 -0
- package/dist/tools/truncate.js +8 -0
- package/dist/tools/web-fetch.d.ts +0 -1
- package/dist/tools/web-fetch.js +9 -2
- package/dist/tools/web-search.d.ts +0 -1
- package/dist/tools/web-search.js +0 -1
- package/dist/tools/write-content.d.ts +3 -3
- package/dist/tools/write-content.js +12 -41
- package/dist/tools/write.d.ts +2 -3
- package/dist/tools/write.js +3 -4
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.d.ts +1 -1
- package/dist/tui/commands.js +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/tui/turn-controller.js +14 -4
- package/dist/usage/ledger.js +7 -4
- package/dist/usage/render.js +10 -8
- package/examples/sub-agents/README.md +2 -0
- package/package.json +3 -2
- package/dist/tools/skill-manage.d.ts +0 -41
- package/dist/tools/skill-manage.js +0 -231
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
2
|
+
import { stat as fsStat, mkdir, open, readdir, rename, unlink } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { Writable } from "node:stream";
|
|
5
|
+
import { createAtomicTempPath, writeFileAtomically } from "./shared/atomic-file.js";
|
|
6
|
+
export function fingerprintOf(stat) {
|
|
7
|
+
return { size: stat.size, mtimeMs: stat.mtimeMs, ino: stat.ino };
|
|
8
|
+
}
|
|
9
|
+
export function fingerprintsEqual(a, b) {
|
|
10
|
+
return a.size === b.size && a.mtimeMs === b.mtimeMs && a.ino === b.ino;
|
|
11
|
+
}
|
|
12
|
+
export function createFileStore() {
|
|
13
|
+
return new HostFileStore();
|
|
14
|
+
}
|
|
15
|
+
function toFileStat(raw) {
|
|
16
|
+
return {
|
|
17
|
+
size: raw.size,
|
|
18
|
+
mtimeMs: raw.mtimeMs,
|
|
19
|
+
ino: raw.ino,
|
|
20
|
+
mode: raw.mode,
|
|
21
|
+
isDirectory: raw.isDirectory(),
|
|
22
|
+
isFile: raw.isFile(),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function throwIfAborted(signal) {
|
|
26
|
+
if (signal?.aborted) {
|
|
27
|
+
throw new Error("Aborted");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Best-effort directory fsync after a rename; mirrors `shared/atomic-file.ts`'s own tolerance. */
|
|
31
|
+
async function fsyncDir(dir) {
|
|
32
|
+
await open(dir, "r")
|
|
33
|
+
.then(async (dirHandle) => {
|
|
34
|
+
try {
|
|
35
|
+
await dirHandle.sync();
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
await dirHandle.close();
|
|
39
|
+
}
|
|
40
|
+
})
|
|
41
|
+
.catch(() => undefined);
|
|
42
|
+
}
|
|
43
|
+
class HostFileStore {
|
|
44
|
+
async stat(path) {
|
|
45
|
+
try {
|
|
46
|
+
return toFileStat(await fsStat(path));
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error.code === "ENOENT") {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async readBytes(path, opts = {}) {
|
|
56
|
+
throwIfAborted(opts.signal);
|
|
57
|
+
const handle = await open(path, "r");
|
|
58
|
+
try {
|
|
59
|
+
const stat = toFileStat(await handle.stat());
|
|
60
|
+
const start = Math.max(0, opts.start ?? 0);
|
|
61
|
+
const maxBytes = opts.maxBytes ?? Number.POSITIVE_INFINITY;
|
|
62
|
+
const available = Math.max(0, stat.size - start);
|
|
63
|
+
const toRead = Math.min(available, maxBytes);
|
|
64
|
+
const buffer = Buffer.alloc(toRead);
|
|
65
|
+
let readTotal = 0;
|
|
66
|
+
while (readTotal < toRead) {
|
|
67
|
+
throwIfAborted(opts.signal);
|
|
68
|
+
const { bytesRead } = await handle.read(buffer, readTotal, toRead - readTotal, start + readTotal);
|
|
69
|
+
if (bytesRead === 0) {
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
readTotal += bytesRead;
|
|
73
|
+
}
|
|
74
|
+
const data = readTotal === buffer.length ? buffer : buffer.subarray(0, readTotal);
|
|
75
|
+
return { data, eof: start + readTotal >= stat.size, stat };
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await handle.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
openRead(path, opts = {}) {
|
|
82
|
+
return createReadStream(path, { start: opts.start, end: opts.end });
|
|
83
|
+
}
|
|
84
|
+
async writeAtomic(path, data, opts = {}) {
|
|
85
|
+
throwIfAborted(opts.signal);
|
|
86
|
+
if (opts.createParentDir) {
|
|
87
|
+
await mkdir(dirname(path), { recursive: true });
|
|
88
|
+
}
|
|
89
|
+
await writeFileAtomically(path, data, { preserveMode: opts.preserveMode });
|
|
90
|
+
}
|
|
91
|
+
async replaceViaTemp(path, produce, opts = {}) {
|
|
92
|
+
throwIfAborted(opts.signal);
|
|
93
|
+
const dir = dirname(path);
|
|
94
|
+
await mkdir(dir, { recursive: true });
|
|
95
|
+
const tempPath = createAtomicTempPath(path);
|
|
96
|
+
try {
|
|
97
|
+
const handle = await open(tempPath, "w");
|
|
98
|
+
try {
|
|
99
|
+
if (opts.preserveMode) {
|
|
100
|
+
const existing = await this.stat(path);
|
|
101
|
+
if (existing) {
|
|
102
|
+
await handle.chmod(existing.mode & 0o777);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// `handle.createWriteStream()` closes the underlying `FileHandle` itself once the stream
|
|
106
|
+
// ends, so a subsequent `handle.sync()`/`handle.close()` on the same handle would throw
|
|
107
|
+
// "file closed". Write through `handle.write()` directly instead, keeping the handle
|
|
108
|
+
// under our own control until the explicit `sync()` + `close()` below.
|
|
109
|
+
const out = new Writable({
|
|
110
|
+
write(chunk, _encoding, callback) {
|
|
111
|
+
handle.write(chunk).then(() => callback(), (error) => callback(error instanceof Error ? error : new Error(String(error))));
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
await produce(out);
|
|
115
|
+
await new Promise((resolve, reject) => {
|
|
116
|
+
out.once("error", reject);
|
|
117
|
+
out.end(() => resolve());
|
|
118
|
+
});
|
|
119
|
+
await handle.sync();
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
await handle.close();
|
|
123
|
+
}
|
|
124
|
+
await rename(tempPath, path);
|
|
125
|
+
await fsyncDir(dir);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
await unlink(tempPath).catch(() => undefined);
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async listDirectory(path, opts) {
|
|
133
|
+
const results = [];
|
|
134
|
+
const walk = async (currentDir, relPrefix, depth) => {
|
|
135
|
+
const entries = await readdir(currentDir, { withFileTypes: true });
|
|
136
|
+
for (const entry of entries) {
|
|
137
|
+
const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
|
|
138
|
+
const isDirectory = entry.isDirectory();
|
|
139
|
+
results.push({ name: entry.name, relativePath, isDirectory });
|
|
140
|
+
if (isDirectory && depth < opts.maxDepth) {
|
|
141
|
+
await walk(join(currentDir, entry.name), relativePath, depth + 1);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
await walk(path, "", 1);
|
|
146
|
+
return results;
|
|
147
|
+
}
|
|
148
|
+
async walkFiles(path, opts) {
|
|
149
|
+
const files = [];
|
|
150
|
+
let truncated = false;
|
|
151
|
+
const walk = async (currentDir, relPrefix) => {
|
|
152
|
+
if (truncated)
|
|
153
|
+
return;
|
|
154
|
+
throwIfAborted(opts.signal);
|
|
155
|
+
let entries;
|
|
156
|
+
try {
|
|
157
|
+
entries = await readdir(currentDir, { withFileTypes: true });
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// An unreadable directory (permission, or removed mid-walk) is skipped rather than
|
|
161
|
+
// failing the whole discovery -- one bad subtree must not blank out every other match.
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
for (const entry of entries) {
|
|
165
|
+
if (truncated)
|
|
166
|
+
return;
|
|
167
|
+
const relativePath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
|
|
168
|
+
if (entry.isDirectory()) {
|
|
169
|
+
if (opts.prune?.(entry.name))
|
|
170
|
+
continue;
|
|
171
|
+
await walk(join(currentDir, entry.name), relativePath);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
// Symlinks (to files or directories) report false from both checks and are skipped: a
|
|
175
|
+
// glob result must never resolve outside the guarded root through a link the walk never
|
|
176
|
+
// asked permission to follow.
|
|
177
|
+
if (!entry.isFile())
|
|
178
|
+
continue;
|
|
179
|
+
files.push(relativePath);
|
|
180
|
+
if (files.length >= opts.maxEntries) {
|
|
181
|
+
truncated = true;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
await walk(path, "");
|
|
187
|
+
return { files, truncated };
|
|
188
|
+
}
|
|
189
|
+
}
|
package/dist/main.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { runAuth } from "./models/auth-cli.js";
|
|
3
|
-
import { isBootstrapExitError } from "./runtime/app-home.js";
|
|
3
|
+
import { formatCliCommandsHelp, isBootstrapExitError } from "./runtime/app-home.js";
|
|
4
4
|
import { bootstrap } from "./runtime/bootstrap.js";
|
|
5
5
|
import { runTui } from "./tui/cli.js";
|
|
6
6
|
function handleError(error) {
|
|
@@ -31,9 +31,8 @@ else if (command === undefined || command === "run" || command.startsWith("-"))
|
|
|
31
31
|
}
|
|
32
32
|
else {
|
|
33
33
|
console.error(`Unknown command: ${command}`);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
console.error(" pipiclaw auth status|login|logout Manage provider credentials");
|
|
34
|
+
for (const line of formatCliCommandsHelp("pipiclaw"))
|
|
35
|
+
console.error(line);
|
|
37
36
|
console.error("Run `pipiclaw --help` for options.");
|
|
38
37
|
process.exit(1);
|
|
39
38
|
}
|
package/dist/memory/commands.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { renderSubcommandUsage } from "../agent/commands.js";
|
|
2
|
+
import { capReply } from "../agent/reply-limits.js";
|
|
2
3
|
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
3
|
-
import { localDayKey } from "../shared/local-time.js";
|
|
4
|
+
import { localDayKey, parseLocalTime } from "../shared/local-time.js";
|
|
4
5
|
import { clipText } from "../shared/text-utils.js";
|
|
5
6
|
import { getChannelMemoryPath, parseChannelMemoryEntries, readChannelMemory } from "./files.js";
|
|
6
7
|
import { syncMemoryMetadata } from "./metadata.js";
|
|
@@ -11,33 +12,41 @@ async function reconcile(options) {
|
|
|
11
12
|
const metadata = await syncMemoryMetadata(options.channelDir, entries);
|
|
12
13
|
return { entries, metadata };
|
|
13
14
|
}
|
|
14
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Flattens `memory-review.jsonl` action entries for `/memory recent` and the `status` summary —
|
|
17
|
+
* the only consumers of the review log's write history. `user-forget` actions carry `entryId`
|
|
18
|
+
* instead of `target`/`action`; both shapes are tolerated here.
|
|
19
|
+
*/
|
|
20
|
+
async function readRecentMemoryActions(channelDir, sinceMs) {
|
|
15
21
|
const raw = await readOptionalTextFile(getMemoryReviewLogPath(channelDir));
|
|
16
|
-
const
|
|
22
|
+
const actions = [];
|
|
17
23
|
for (const line of raw.split("\n")) {
|
|
18
24
|
if (!line.trim())
|
|
19
25
|
continue;
|
|
20
26
|
try {
|
|
21
27
|
const entry = JSON.parse(line);
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
const entryMs = entry.timestamp ? (parseLocalTime(entry.timestamp) ?? 0) : 0;
|
|
29
|
+
if (entryMs < sinceMs)
|
|
30
|
+
continue;
|
|
31
|
+
for (const value of entry.actions ?? []) {
|
|
32
|
+
if (value && typeof value === "object") {
|
|
33
|
+
actions.push({ timestamp: entry.timestamp, reason: entry.reason, ...value });
|
|
34
|
+
}
|
|
25
35
|
}
|
|
26
36
|
}
|
|
27
37
|
catch {
|
|
28
38
|
// A torn audit line should not break the management surface.
|
|
29
39
|
}
|
|
30
40
|
}
|
|
31
|
-
return
|
|
41
|
+
return actions;
|
|
32
42
|
}
|
|
33
43
|
function renderUsage() {
|
|
34
|
-
return "
|
|
44
|
+
return renderSubcommandUsage("memory");
|
|
35
45
|
}
|
|
36
46
|
export async function handleMemoryCommand(options) {
|
|
37
47
|
const [action = "status", argument] = options.args.trim().split(/\s+/, 2);
|
|
38
48
|
const { entries, metadata } = await reconcile(options);
|
|
39
49
|
if (action === "status") {
|
|
40
|
-
const pending = await readPendingSuggestions(options.channelDir);
|
|
41
50
|
const tombstones = await readMemoryTombstones(options.channelDir);
|
|
42
51
|
const records = Object.values(metadata.entries);
|
|
43
52
|
const active = records.filter((entry) => entry.status === "active");
|
|
@@ -49,70 +58,102 @@ export async function handleMemoryCommand(options) {
|
|
|
49
58
|
const sinceDay = localDayKey(since);
|
|
50
59
|
const recalls30d = active.reduce((sum, entry) => sum +
|
|
51
60
|
Object.entries(entry.recallByDay ?? {}).reduce((entrySum, [day, count]) => entrySum + (day >= sinceDay ? count : 0), 0), 0);
|
|
61
|
+
const last7d = new Date();
|
|
62
|
+
last7d.setDate(last7d.getDate() - 7);
|
|
63
|
+
const recent = await readRecentMemoryActions(options.channelDir, last7d.getTime());
|
|
64
|
+
const written = recent
|
|
65
|
+
.filter((item) => item.target === "MEMORY.md" && item.action === "append")
|
|
66
|
+
.reduce((sum, item) => sum + (item.entries ?? 0), 0);
|
|
67
|
+
const dropped = recent.reduce((sum, item) => {
|
|
68
|
+
if (item.entryId)
|
|
69
|
+
return sum + 1;
|
|
70
|
+
if (item.target === "MEMORY.md" && item.action === "rewrite")
|
|
71
|
+
return sum + (item.droppedEntryIds?.length ?? 0);
|
|
72
|
+
return sum;
|
|
73
|
+
}, 0);
|
|
74
|
+
const expired = recent
|
|
75
|
+
.filter((item) => item.target === "MEMORY.md" && item.action === "expire")
|
|
76
|
+
.reduce((sum, item) => sum + (item.entries ?? 0), 0);
|
|
52
77
|
const lastFailure = (await readOptionalTextFile(getMemoryReviewLogPath(options.channelDir)))
|
|
53
78
|
.split("\n")
|
|
54
79
|
.reverse()
|
|
55
80
|
.find((line) => line.includes('"error"'));
|
|
56
81
|
return [
|
|
57
|
-
"
|
|
82
|
+
"**记忆状态**",
|
|
58
83
|
"",
|
|
59
|
-
`-
|
|
60
|
-
`-
|
|
61
|
-
`-
|
|
62
|
-
`-
|
|
63
|
-
`-
|
|
64
|
-
`-
|
|
65
|
-
`-
|
|
66
|
-
`-
|
|
67
|
-
`-
|
|
84
|
+
`- 生效条目:\`${entries.length}\``,
|
|
85
|
+
`- 元数据记录:\`${records.length}\``,
|
|
86
|
+
`- 观察期:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].probationUntil}\`)` : ""}`,
|
|
87
|
+
`- 最近 7 天:+${written} 写入 / -${dropped} 丢弃 / -${expired} 过期`,
|
|
88
|
+
`- 墓碑:\`${tombstones.length}\``,
|
|
89
|
+
`- 累计召回:\`${active.reduce((sum, entry) => sum + entry.recallCount, 0)}\``,
|
|
90
|
+
`- 召回(30 天):\`${recalls30d}\``,
|
|
91
|
+
`- 查询多样性:\`${new Set(active.flatMap((entry) => entry.queryFingerprints)).size}\``,
|
|
92
|
+
`- 最近一次召回:\`${active
|
|
68
93
|
.map((entry) => entry.lastRecalledAt)
|
|
69
94
|
.filter(Boolean)
|
|
70
95
|
.sort()
|
|
71
|
-
.at(-1) ?? "
|
|
72
|
-
`-
|
|
73
|
-
`-
|
|
96
|
+
.at(-1) ?? "从未"}\``,
|
|
97
|
+
`- 近期失败:${lastFailure ? "有,查看 memory-review.jsonl" : "无"}`,
|
|
98
|
+
`- 生效文件:\`${getChannelMemoryPath(options.channelDir)}\``,
|
|
74
99
|
].join("\n");
|
|
75
100
|
}
|
|
76
101
|
if (action === "list") {
|
|
77
102
|
if (entries.length === 0)
|
|
78
|
-
return "
|
|
103
|
+
return "**记忆条目**\n\n暂无生效的频道记忆条目。";
|
|
79
104
|
const visible = entries.slice(0, 50);
|
|
80
105
|
const lines = visible.map((entry) => {
|
|
81
106
|
const record = metadata.entries[entry.id];
|
|
82
|
-
const probation = record?.probationUntil ?
|
|
107
|
+
const probation = record?.probationUntil ? `(观察期至 \`${record.probationUntil}\`)` : "";
|
|
83
108
|
return `- \`${entry.id}\` [${record?.kind ?? "fact"}]${probation} ${clipText(entry.content, 180, { headRatio: 1 })}`;
|
|
84
109
|
});
|
|
85
110
|
if (entries.length > visible.length) {
|
|
86
|
-
lines.push(`- ${entries.length - visible.length}
|
|
111
|
+
lines.push(`- 另有 ${entries.length - visible.length} 条已省略;缩小范围后用 \`/memory show <entry-id>\` 查看。`);
|
|
87
112
|
}
|
|
88
|
-
return
|
|
113
|
+
return capReply(`**记忆条目**\n\n${lines.join("\n")}`, {
|
|
114
|
+
nextStepHint: "用 `/memory show <entry-id>` 查看单条记忆",
|
|
115
|
+
}).text;
|
|
89
116
|
}
|
|
90
117
|
if (action === "show") {
|
|
91
118
|
if (!argument)
|
|
92
|
-
return
|
|
119
|
+
return `缺少 entry id。${renderUsage()}`;
|
|
93
120
|
const entry = entries.find((candidate) => candidate.id === argument);
|
|
94
121
|
const record = metadata.entries[argument];
|
|
95
122
|
if (!entry && !record)
|
|
96
|
-
return
|
|
123
|
+
return `未找到记忆条目 \`${argument}\`。用 \`/memory list\` 查看 id。`;
|
|
97
124
|
return [
|
|
98
|
-
|
|
125
|
+
`**记忆 ${argument}**`,
|
|
99
126
|
"",
|
|
100
|
-
entry?.content ?? "
|
|
127
|
+
entry?.content ?? "(未在 MEMORY.md 中生效)",
|
|
101
128
|
"",
|
|
102
129
|
"```json",
|
|
103
130
|
JSON.stringify(record ?? { id: argument, status: "unknown" }, null, 2),
|
|
104
131
|
"```",
|
|
105
132
|
].join("\n");
|
|
106
133
|
}
|
|
107
|
-
if (action === "
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
134
|
+
if (action === "recent") {
|
|
135
|
+
const last7d = new Date();
|
|
136
|
+
last7d.setDate(last7d.getDate() - 7);
|
|
137
|
+
const recent = (await readRecentMemoryActions(options.channelDir, last7d.getTime())).slice(-30).reverse();
|
|
138
|
+
if (recent.length === 0)
|
|
139
|
+
return "**近期记忆活动**\n\n最近 7 天没有记忆活动。";
|
|
111
140
|
return [
|
|
112
|
-
"
|
|
141
|
+
"**近期记忆活动**",
|
|
113
142
|
"",
|
|
114
|
-
...
|
|
143
|
+
...recent.map((item) => {
|
|
144
|
+
const when = item.timestamp ? `(${item.timestamp})` : "";
|
|
145
|
+
if (item.entryId)
|
|
146
|
+
return `- ${when}遗忘 \`${item.entryId}\`(${item.reason})`;
|
|
147
|
+
const detail = item.action === "append"
|
|
148
|
+
? `新增 ${item.entries ?? 0} 条`
|
|
149
|
+
: item.action === "rewrite"
|
|
150
|
+
? `重写${item.droppedEntryIds?.length ? `(丢弃 ${item.droppedEntryIds.join(", ")})` : ""}`
|
|
151
|
+
: item.action === "expire"
|
|
152
|
+
? `过期 ${item.entries ?? 0} 条`
|
|
153
|
+
: (item.action ?? "unknown");
|
|
154
|
+
return `- ${when}${item.target ?? "?"}:${detail}(${item.reason})`;
|
|
155
|
+
}),
|
|
115
156
|
].join("\n");
|
|
116
157
|
}
|
|
117
|
-
return
|
|
158
|
+
return `未知的 memory 命令 \`${action}\`。${renderUsage()}`;
|
|
118
159
|
}
|
|
@@ -46,5 +46,9 @@ export type MemoryCleanupShrinkGuard = Pick<PipiclawMemoryMaintenanceSettings, "
|
|
|
46
46
|
export declare class MemoryCleanupRejectedError extends Error {
|
|
47
47
|
constructor(reason: string);
|
|
48
48
|
}
|
|
49
|
-
export
|
|
49
|
+
export interface MemoryCleanupResult {
|
|
50
|
+
rewritten: boolean;
|
|
51
|
+
droppedEntryIds: string[];
|
|
52
|
+
}
|
|
53
|
+
export declare function cleanupChannelMemory(options: ConsolidationRunOptions, currentMemory: string, guard?: MemoryCleanupShrinkGuard): Promise<MemoryCleanupResult>;
|
|
50
54
|
export declare function foldChannelHistory(options: ConsolidationRunOptions, currentHistory: string): Promise<boolean>;
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { getLatestCompactionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
3
3
|
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
4
|
+
import { clipText } from "../shared/text-utils.js";
|
|
4
5
|
import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
|
|
5
6
|
import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
|
|
7
|
+
import { readMemoryMetadata } from "./metadata.js";
|
|
6
8
|
import { classifyMemoryWrite, DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, MAX_PROBATION_WRITES_PER_RUN, } from "./promotion.js";
|
|
7
9
|
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
8
10
|
import { runSidecarTask } from "./sidecar-worker.js";
|
|
9
|
-
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
11
|
+
import { hasMeaningfulExchange, sanitizeMessagesForMemory } from "./transcript.js";
|
|
10
12
|
const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
|
|
11
13
|
const MEMORY_CLEANUP_LENGTH_THRESHOLD = 5_000;
|
|
12
14
|
const MEMORY_UPDATE_BLOCK_THRESHOLD = 4;
|
|
@@ -15,6 +17,7 @@ const HISTORY_BLOCK_THRESHOLD = 5;
|
|
|
15
17
|
const HISTORY_RECENT_BLOCKS_TO_KEEP = 3;
|
|
16
18
|
const INLINE_CONSOLIDATION_TIMEOUT_MS = 20_000;
|
|
17
19
|
const MEMORY_CLEANUP_TIMEOUT_MS = 120_000;
|
|
20
|
+
const MEMORY_CLEANUP_INPUT_MAX_CHARS = 24_000;
|
|
18
21
|
const HISTORY_FOLDING_TIMEOUT_MS = 120_000;
|
|
19
22
|
const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMORY.md file.
|
|
20
23
|
|
|
@@ -70,30 +73,6 @@ function entriesAfterLatestCompactionBoundary(entries) {
|
|
|
70
73
|
function extractMessagesFromSessionEntries(entries) {
|
|
71
74
|
return entries.filter(isMessage).map((entry) => entry.message);
|
|
72
75
|
}
|
|
73
|
-
function hasMeaningfulMessages(messages) {
|
|
74
|
-
let meaningfulCount = 0;
|
|
75
|
-
for (const message of messages) {
|
|
76
|
-
if (message.role === "user") {
|
|
77
|
-
const text = typeof message.content === "string"
|
|
78
|
-
? message.content
|
|
79
|
-
: message.content.map((part) => (part.type === "text" ? part.text : "[image]")).join("\n");
|
|
80
|
-
if (text.trim())
|
|
81
|
-
meaningfulCount++;
|
|
82
|
-
}
|
|
83
|
-
else if (message.role === "assistant") {
|
|
84
|
-
const text = message.content
|
|
85
|
-
.filter((part) => part.type === "text")
|
|
86
|
-
.map((part) => part.text)
|
|
87
|
-
.join("\n");
|
|
88
|
-
if (text.trim())
|
|
89
|
-
meaningfulCount++;
|
|
90
|
-
}
|
|
91
|
-
if (meaningfulCount >= 2) {
|
|
92
|
-
return true;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
return false;
|
|
96
|
-
}
|
|
97
76
|
function countMatchingSectionHeadings(content, prefix) {
|
|
98
77
|
return splitH2Sections(content).filter((section) => section.heading.startsWith(prefix)).length;
|
|
99
78
|
}
|
|
@@ -132,7 +111,7 @@ export async function runInlineConsolidation(options) {
|
|
|
132
111
|
const sourceEntries = options.sourceWindow?.entries ?? entriesAfterLatestCompactionBoundary(options.sessionEntries ?? []);
|
|
133
112
|
const relevantMessages = options.sourceWindow?.messages ??
|
|
134
113
|
(sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages);
|
|
135
|
-
if (!
|
|
114
|
+
if (!hasMeaningfulExchange(sanitizeMessagesForMemory(relevantMessages))) {
|
|
136
115
|
return {
|
|
137
116
|
skipped: true,
|
|
138
117
|
appendedMemoryEntries: 0,
|
|
@@ -182,8 +161,7 @@ export async function runInlineConsolidation(options) {
|
|
|
182
161
|
const acceptedProbationary = probationaryCandidates.slice(0, MAX_PROBATION_WRITES_PER_RUN);
|
|
183
162
|
rejectedMemoryOps.push(...probationaryCandidates.slice(MAX_PROBATION_WRITES_PER_RUN));
|
|
184
163
|
let appliedMemoryOps = 0;
|
|
185
|
-
if (
|
|
186
|
-
!options.sourceWindow?.hasExternalToolContent) {
|
|
164
|
+
if (durableCandidates.length > 0 || acceptedProbationary.length > 0) {
|
|
187
165
|
const sourceEntryIds = options.sourceWindow?.entries.map((entry) => entry.id) ?? [];
|
|
188
166
|
const ops = [
|
|
189
167
|
...durableCandidates.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId }, "durable")),
|
|
@@ -223,14 +201,17 @@ function isCleanupResultTooSmall(currentMemory, nextMemory, guard) {
|
|
|
223
201
|
const afterEntries = parseChannelMemoryEntries(after).length;
|
|
224
202
|
if (beforeEntries > 0 && afterEntries === 0)
|
|
225
203
|
return true;
|
|
204
|
+
// Entry-count guard applies at every file size. The char threshold below exists so a tiny
|
|
205
|
+
// file is not judged on byte ratio, but "four short Update blocks" is exactly the shape
|
|
206
|
+
// cleanup fires on and it sits under that threshold — letting the char escape short-circuit
|
|
207
|
+
// the entry guard left the most common cleanup input completely unprotected.
|
|
208
|
+
if (beforeEntries >= 4 && afterEntries * 2 < beforeEntries)
|
|
209
|
+
return true;
|
|
226
210
|
if (before.length < Math.max(0, guard.cleanupShrinkGuardMinChars))
|
|
227
211
|
return false;
|
|
228
|
-
|
|
229
|
-
return true;
|
|
230
|
-
}
|
|
231
|
-
return beforeEntries > 0 && afterEntries * 2 < beforeEntries;
|
|
212
|
+
return after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio));
|
|
232
213
|
}
|
|
233
|
-
function validateCleanupSchema(currentMemory, nextMemory) {
|
|
214
|
+
function validateCleanupSchema(currentMemory, nextMemory, mustKeepIds) {
|
|
234
215
|
if (!/^# Channel Memory(?:\s|$)/.test(nextMemory.trimStart())) {
|
|
235
216
|
return 'cleanup output must start with "# Channel Memory"';
|
|
236
217
|
}
|
|
@@ -244,24 +225,40 @@ function validateCleanupSchema(currentMemory, nextMemory) {
|
|
|
244
225
|
return `cleanup output duplicated entry id ${entry.id}`;
|
|
245
226
|
ids.add(entry.id);
|
|
246
227
|
}
|
|
228
|
+
const missing = mustKeepIds.filter((id) => !ids.has(id));
|
|
229
|
+
if (missing.length > 0)
|
|
230
|
+
return `cleanup output dropped user-saved entries: ${missing.join(", ")}`;
|
|
247
231
|
return null;
|
|
248
232
|
}
|
|
249
233
|
export async function cleanupChannelMemory(options, currentMemory, guard) {
|
|
250
234
|
if (!shouldCleanupChannelMemory(currentMemory)) {
|
|
251
|
-
return false;
|
|
235
|
+
return { rewritten: false, droppedEntryIds: [] };
|
|
252
236
|
}
|
|
253
|
-
const
|
|
254
|
-
|
|
237
|
+
const metadata = await readMemoryMetadata(options.channelDir);
|
|
238
|
+
const beforeEntries = parseChannelMemoryEntries(currentMemory);
|
|
239
|
+
const mustKeepIds = beforeEntries
|
|
240
|
+
.map((entry) => entry.id)
|
|
241
|
+
.filter((id) => metadata.entries[id]?.sourceType === "user");
|
|
242
|
+
const prompt = [
|
|
243
|
+
mustKeepIds.length > 0
|
|
244
|
+
? `These entries were saved on the user's explicit instruction and MUST appear verbatim in the output: ${mustKeepIds.join(", ")}`
|
|
245
|
+
: "",
|
|
246
|
+
`Current MEMORY.md:\n${clipText(currentMemory, MEMORY_CLEANUP_INPUT_MAX_CHARS, { headRatio: 0.5 })}`,
|
|
247
|
+
]
|
|
248
|
+
.filter(Boolean)
|
|
249
|
+
.join("\n\n");
|
|
255
250
|
const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
|
|
256
|
-
const schemaError = validateCleanupSchema(currentMemory, nextMemory);
|
|
251
|
+
const schemaError = validateCleanupSchema(currentMemory, nextMemory, mustKeepIds);
|
|
257
252
|
if (schemaError) {
|
|
258
253
|
throw new MemoryCleanupRejectedError(`${schemaError}. Retry cleanup while preserving the MEMORY.md schema and ids.`);
|
|
259
254
|
}
|
|
260
255
|
if (guard && isCleanupResultTooSmall(currentMemory, nextMemory, guard)) {
|
|
261
256
|
throw new MemoryCleanupRejectedError("cleanup result shrank below the configured guard threshold");
|
|
262
257
|
}
|
|
258
|
+
const afterIds = new Set(parseChannelMemoryEntries(nextMemory).map((entry) => entry.id));
|
|
259
|
+
const droppedEntryIds = beforeEntries.map((entry) => entry.id).filter((id) => !afterIds.has(id));
|
|
263
260
|
await rewriteChannelMemory(options.channelDir, nextMemory);
|
|
264
|
-
return true;
|
|
261
|
+
return { rewritten: true, droppedEntryIds };
|
|
265
262
|
}
|
|
266
263
|
export async function foldChannelHistory(options, currentHistory) {
|
|
267
264
|
if (!shouldFoldChannelHistory(currentHistory)) {
|
|
@@ -1,7 +1,7 @@
|
|
|
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 MemoryOp } from "./files.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type MemoryEntryKind } from "./metadata.js";
|
|
5
5
|
import type { MemoryPromotionCandidate, MemoryWriteTier } from "./promotion.js";
|
|
6
6
|
export interface MemoryExtractionPromptOptions {
|
|
7
7
|
includeHistoryBlock: boolean;
|
|
@@ -44,4 +44,11 @@ export interface MemoryExtractionRequest extends MemoryExtractionPromptOptions {
|
|
|
44
44
|
correlationId?: string;
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Tool output never reaches this prompt: `sanitizeMessagesForMemory` drops every `toolResult`
|
|
49
|
+
* message before serialization (`transcript.ts`), an invariant pinned by
|
|
50
|
+
* `test/memory-transcript.test.ts` ("drops tool results ... before memory workers see them").
|
|
51
|
+
* That is why no additional untrusted-content filter is applied here — a window-level one used to
|
|
52
|
+
* exist and silently discarded every durable write from any tool-using conversation.
|
|
53
|
+
*/
|
|
47
54
|
export declare function runMemoryExtraction(request: MemoryExtractionRequest): Promise<MemoryExtractionResult>;
|