@oyasmi/pipiclaw 0.8.4 → 0.8.6
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 +2 -1
- package/dist/agent/channel-runner.d.ts +29 -0
- package/dist/agent/channel-runner.js +156 -53
- package/dist/agent/command-extension.d.ts +1 -0
- package/dist/agent/command-extension.js +6 -0
- package/dist/agent/commands.d.ts +2 -2
- package/dist/agent/commands.js +16 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/builder.d.ts +32 -0
- package/dist/agent/prompt/builder.js +252 -0
- package/dist/agent/prompt/extension.d.ts +22 -0
- package/dist/agent/prompt/extension.js +24 -0
- package/dist/agent/prompt/manifest.d.ts +51 -0
- package/dist/agent/prompt/manifest.js +84 -0
- package/dist/agent/prompt/resources.d.ts +18 -0
- package/dist/agent/prompt/resources.js +61 -0
- package/dist/agent/prompt/sections.d.ts +39 -0
- package/dist/agent/prompt/sections.js +267 -0
- package/dist/agent/prompt/types.d.ts +110 -0
- package/dist/agent/prompt/types.js +11 -0
- package/dist/agent/types.d.ts +3 -0
- package/dist/agent/workspace-resources.d.ts +25 -13
- package/dist/agent/workspace-resources.js +28 -41
- package/dist/index.d.ts +7 -2
- package/dist/index.js +6 -2
- package/dist/memory/bootstrap.d.ts +5 -0
- package/dist/memory/bootstrap.js +14 -4
- package/dist/memory/candidates.d.ts +2 -0
- package/dist/memory/candidates.js +13 -3
- package/dist/memory/commands.d.ts +6 -0
- package/dist/memory/commands.js +112 -0
- package/dist/memory/consolidation.d.ts +3 -0
- package/dist/memory/consolidation.js +68 -26
- package/dist/memory/files.d.ts +13 -0
- package/dist/memory/files.js +65 -8
- package/dist/memory/lifecycle.d.ts +2 -1
- package/dist/memory/lifecycle.js +34 -6
- package/dist/memory/maintenance-jobs.js +48 -23
- package/dist/memory/metadata.d.ts +60 -0
- package/dist/memory/metadata.js +135 -0
- package/dist/memory/policy.d.ts +3 -0
- package/dist/memory/policy.js +19 -0
- package/dist/memory/post-turn-review.d.ts +11 -1
- package/dist/memory/post-turn-review.js +78 -19
- package/dist/memory/promotion.d.ts +5 -2
- package/dist/memory/promotion.js +3 -1
- package/dist/memory/recall.d.ts +3 -0
- package/dist/memory/recall.js +27 -5
- package/dist/memory/review-log.d.ts +2 -0
- package/dist/memory/review-log.js +15 -0
- package/dist/memory/session-corpus.js +11 -3
- package/dist/memory/session-search.js +8 -4
- package/dist/memory/session.d.ts +1 -0
- package/dist/memory/session.js +3 -1
- package/dist/memory/sidecar-worker.d.ts +1 -0
- package/dist/memory/sidecar-worker.js +1 -0
- package/dist/memory/source-window.d.ts +25 -0
- package/dist/memory/source-window.js +64 -0
- package/dist/memory/tombstones.d.ts +12 -0
- package/dist/memory/tombstones.js +44 -0
- package/dist/memory/transcript.js +33 -9
- package/dist/playbooks/catalog.d.ts +22 -1
- package/dist/playbooks/catalog.js +57 -4
- package/dist/playbooks/event-scheduling.md +2 -0
- package/dist/playbooks/memory-and-learning.md +2 -0
- package/dist/playbooks/runtime-orientation.md +1 -0
- package/dist/playbooks/task-closeout.md +3 -1
- package/dist/playbooks/task-delegation.md +3 -1
- package/dist/playbooks/task-driving.md +2 -0
- package/dist/playbooks/task-planning.md +2 -0
- package/dist/playbooks/task-recurring.md +2 -0
- package/dist/playbooks/task-repair.md +3 -1
- package/dist/runtime/bootstrap.js +8 -38
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +3 -0
- package/dist/runtime/task-commands.js +1 -1
- package/dist/runtime/workspace-templates.d.ts +11 -0
- package/dist/runtime/workspace-templates.js +51 -0
- package/dist/settings.js +1 -1
- package/dist/tasks/control.js +9 -3
- package/dist/tasks/store.d.ts +1 -0
- package/dist/tasks/store.js +11 -1
- package/dist/tools/memory-manage.d.ts +1 -1
- package/dist/tools/memory-manage.js +27 -6
- package/dist/tools/task-manage.js +2 -2
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/turn-controller.js +1 -0
- package/dist/usage/ledger.d.ts +2 -0
- package/package.json +1 -1
- package/dist/agent/prompt-builder.d.ts +0 -12
- package/dist/agent/prompt-builder.js +0 -71
package/dist/memory/recall.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export interface RecallRequest {
|
|
|
6
6
|
workspaceDir: string;
|
|
7
7
|
channelDir: string;
|
|
8
8
|
allowedSources?: MemoryCandidate["source"][];
|
|
9
|
+
excludedCandidateIds?: string[];
|
|
9
10
|
maxCandidates: number;
|
|
10
11
|
maxInjected: number;
|
|
11
12
|
maxChars: number;
|
|
@@ -16,6 +17,8 @@ export interface RecallRequest {
|
|
|
16
17
|
candidateStore?: MemoryCandidateStore;
|
|
17
18
|
}
|
|
18
19
|
export interface RecalledMemory {
|
|
20
|
+
id: string;
|
|
21
|
+
entryId?: string;
|
|
19
22
|
source: MemoryCandidate["source"];
|
|
20
23
|
path: string;
|
|
21
24
|
title: string;
|
package/dist/memory/recall.js
CHANGED
|
@@ -2,6 +2,7 @@ import { parseJsonObject } from "../shared/llm-json.js";
|
|
|
2
2
|
import { HAN_REGEX } from "../shared/text-utils.js";
|
|
3
3
|
import { buildMemoryCandidates, createMemoryCandidateStore, } from "./candidates.js";
|
|
4
4
|
import { COMMON_CHINESE_WORDS } from "./chinese-words.js";
|
|
5
|
+
import { recordMemoryRecall, syncMemoryMetadata } from "./metadata.js";
|
|
5
6
|
import { runSidecarTask } from "./sidecar-worker.js";
|
|
6
7
|
const RERANK_SYSTEM_PROMPT = `You are selecting which memory snippets are most relevant to the current user turn.
|
|
7
8
|
|
|
@@ -21,6 +22,8 @@ const MEMORY_RECALL_RERANK_TIMEOUT_MS = 8_000;
|
|
|
21
22
|
const RERANK_CONTENT_CLIP = 800;
|
|
22
23
|
const HIGH_CONFIDENCE_SCORE = 36;
|
|
23
24
|
const CLOSE_SCORE_DELTA = 8;
|
|
25
|
+
const MIN_LOCAL_SCORE = 12;
|
|
26
|
+
const MIN_QUERY_COVERAGE = 0.25;
|
|
24
27
|
const MAX_HAN_WORD_LENGTH = Array.from(COMMON_CHINESE_WORDS).reduce((max, word) => Math.max(max, word.length), 2);
|
|
25
28
|
const LATIN_STOP_WORDS = new Set([
|
|
26
29
|
"a",
|
|
@@ -327,6 +330,7 @@ function scoreCandidate(query, queryTokens, intents, candidate) {
|
|
|
327
330
|
const contentStats = computeTokenMatchStats(queryTokens, searchText);
|
|
328
331
|
const pathStats = computeTokenMatchStats(queryTokens, candidate.path);
|
|
329
332
|
const matchedTokens = collectMatchingQueryTokens(queryTokens, [candidate.title, searchText, candidate.path]);
|
|
333
|
+
const semanticFieldMatches = collectMatchingQueryTokens(queryTokens, [candidate.title, searchText]);
|
|
330
334
|
const exactBoost = computeExactMatchBoost(query, candidate);
|
|
331
335
|
const intentBoost = computeSectionIntentBoost(intents, candidate);
|
|
332
336
|
const overallCoverage = queryTokens.length > 0 ? matchedTokens.size / queryTokens.length : 0;
|
|
@@ -336,7 +340,7 @@ function scoreCandidate(query, queryTokens, intents, candidate) {
|
|
|
336
340
|
pathStats.coverage * 8 +
|
|
337
341
|
exactBoost;
|
|
338
342
|
const structuralScore = candidate.priority + intentBoost + computeRecencyBoost(candidate.timestamp);
|
|
339
|
-
if (
|
|
343
|
+
if (semanticFieldMatches.size === 0 || (overallCoverage < MIN_QUERY_COVERAGE && exactBoost === 0)) {
|
|
340
344
|
return null;
|
|
341
345
|
}
|
|
342
346
|
return {
|
|
@@ -423,7 +427,7 @@ async function rerankCandidates(request, candidates) {
|
|
|
423
427
|
});
|
|
424
428
|
const selectedIds = new Set(result.output);
|
|
425
429
|
if (selectedIds.size === 0) {
|
|
426
|
-
return
|
|
430
|
+
return [];
|
|
427
431
|
}
|
|
428
432
|
const selected = candidates.filter(({ candidate }) => selectedIds.has(candidate.id));
|
|
429
433
|
return selected.length > 0 ? selected : candidates;
|
|
@@ -517,16 +521,19 @@ export async function recallRelevantMemory(request) {
|
|
|
517
521
|
const filteredCandidates = request.allowedSources?.length
|
|
518
522
|
? candidates.filter((candidate) => request.allowedSources?.includes(candidate.source))
|
|
519
523
|
: candidates;
|
|
520
|
-
|
|
524
|
+
const excludedIds = new Set(request.excludedCandidateIds ?? []);
|
|
525
|
+
const eligibleCandidates = filteredCandidates.filter((candidate) => !excludedIds.has(candidate.id));
|
|
526
|
+
if (eligibleCandidates.length === 0) {
|
|
521
527
|
return { items: [], renderedText: "" };
|
|
522
528
|
}
|
|
523
529
|
const queryTokens = tokenize(query);
|
|
524
530
|
const queryIntents = detectQueryIntents(query);
|
|
525
|
-
const scored =
|
|
531
|
+
const scored = eligibleCandidates
|
|
526
532
|
.map((candidate) => scoreCandidate(query, queryTokens, queryIntents, candidate))
|
|
527
533
|
.filter((candidate) => candidate !== null)
|
|
534
|
+
.filter((candidate) => candidate.score >= MIN_LOCAL_SCORE)
|
|
528
535
|
.sort(compareScoredCandidates);
|
|
529
|
-
const shortlist = seedIntentCandidates(request,
|
|
536
|
+
const shortlist = seedIntentCandidates(request, eligibleCandidates, scored, queryIntents, queryTokens)
|
|
530
537
|
.sort(compareScoredCandidates)
|
|
531
538
|
.slice(0, Math.max(request.maxCandidates, request.maxInjected));
|
|
532
539
|
if (shortlist.length === 0) {
|
|
@@ -534,12 +541,27 @@ export async function recallRelevantMemory(request) {
|
|
|
534
541
|
}
|
|
535
542
|
const reranked = await rerankCandidates(request, shortlist);
|
|
536
543
|
const items = reranked.slice(0, request.maxInjected).map(({ candidate, score }) => ({
|
|
544
|
+
id: candidate.id,
|
|
545
|
+
entryId: candidate.entryId,
|
|
537
546
|
source: candidate.source,
|
|
538
547
|
path: candidate.path,
|
|
539
548
|
title: candidate.title,
|
|
540
549
|
content: candidate.content,
|
|
541
550
|
score,
|
|
542
551
|
}));
|
|
552
|
+
const recalledEntryIds = items.flatMap((item) => (item.entryId ? [item.entryId] : []));
|
|
553
|
+
if (recalledEntryIds.length > 0) {
|
|
554
|
+
const metadataEntries = candidates
|
|
555
|
+
.filter((candidate) => candidate.source === "channel-memory" && candidate.entryId)
|
|
556
|
+
.map((candidate) => ({
|
|
557
|
+
id: candidate.entryId,
|
|
558
|
+
content: candidate.content,
|
|
559
|
+
sectionHeading: candidate.title,
|
|
560
|
+
timestamp: candidate.timestamp,
|
|
561
|
+
}));
|
|
562
|
+
await syncMemoryMetadata(request.channelDir, metadataEntries);
|
|
563
|
+
await recordMemoryRecall(request.channelDir, recalledEntryIds, query);
|
|
564
|
+
}
|
|
543
565
|
return {
|
|
544
566
|
items,
|
|
545
567
|
renderedText: renderRecallResult(items, request.maxChars),
|
|
@@ -3,6 +3,8 @@ export interface MemoryReviewLogEntry {
|
|
|
3
3
|
timestamp: string;
|
|
4
4
|
channelId: string;
|
|
5
5
|
reason: MemoryReviewReason;
|
|
6
|
+
/** Joins this outcome to the corresponding sidecar usage-ledger entry. */
|
|
7
|
+
correlationId?: string;
|
|
6
8
|
candidates?: unknown[];
|
|
7
9
|
actions?: unknown[];
|
|
8
10
|
suggestions?: unknown[];
|
|
@@ -4,6 +4,7 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
|
4
4
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
5
5
|
const REVIEW_LOG_MAX_BYTES = 1_024 * 1_024; // 1 MB
|
|
6
6
|
const writeQueue = createSerialQueue();
|
|
7
|
+
const lastGateSkipByPath = new Map();
|
|
7
8
|
export function getMemoryReviewLogPath(channelDir) {
|
|
8
9
|
return join(channelDir, "memory-review.jsonl");
|
|
9
10
|
}
|
|
@@ -29,6 +30,20 @@ async function rotateIfNeeded(path, incomingBytes) {
|
|
|
29
30
|
}
|
|
30
31
|
export async function appendMemoryReviewLog(channelDir, entry) {
|
|
31
32
|
const path = getMemoryReviewLogPath(channelDir);
|
|
33
|
+
const gateSkipOnly = (entry.skipped?.length ?? 0) > 0 &&
|
|
34
|
+
(entry.actions?.length ?? 0) === 0 &&
|
|
35
|
+
(entry.candidates?.length ?? 0) === 0 &&
|
|
36
|
+
(entry.suggestions?.length ?? 0) === 0 &&
|
|
37
|
+
!entry.error;
|
|
38
|
+
if (gateSkipOnly) {
|
|
39
|
+
const fingerprint = JSON.stringify({ reason: entry.reason, skipped: entry.skipped });
|
|
40
|
+
if (lastGateSkipByPath.get(path) === fingerprint)
|
|
41
|
+
return;
|
|
42
|
+
lastGateSkipByPath.set(path, fingerprint);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
lastGateSkipByPath.delete(path);
|
|
46
|
+
}
|
|
32
47
|
const line = `${JSON.stringify(entry)}\n`;
|
|
33
48
|
await writeQueue.run(path, async () => {
|
|
34
49
|
await mkdir(dirname(path), { recursive: true });
|
|
@@ -237,8 +237,16 @@ export async function buildSessionCorpus(options) {
|
|
|
237
237
|
break;
|
|
238
238
|
}
|
|
239
239
|
}
|
|
240
|
-
|
|
241
|
-
|
|
240
|
+
const deduplicated = [];
|
|
241
|
+
const seen = new Set();
|
|
242
|
+
for (const document of docs) {
|
|
243
|
+
const identity = document.timestamp
|
|
244
|
+
? `${document.timestamp}\0${document.role}\0${document.text}`
|
|
245
|
+
: `${document.source}\0${document.id}`;
|
|
246
|
+
if (seen.has(identity))
|
|
247
|
+
continue;
|
|
248
|
+
seen.add(identity);
|
|
249
|
+
deduplicated.push(document);
|
|
242
250
|
}
|
|
243
|
-
return
|
|
251
|
+
return deduplicated.length > maxDocuments ? deduplicated.slice(-maxDocuments) : deduplicated;
|
|
244
252
|
}
|
|
@@ -112,6 +112,7 @@ async function getCachedCorpus(channelDir, maxFiles, maxCharsPerChunk) {
|
|
|
112
112
|
if (corpusCache &&
|
|
113
113
|
corpusCache.channelDir === channelDir &&
|
|
114
114
|
corpusCache.maxFiles === maxFiles &&
|
|
115
|
+
corpusCache.maxCharsPerChunk === maxCharsPerChunk &&
|
|
115
116
|
Date.now() - corpusCache.timestamp < CORPUS_CACHE_TTL_MS) {
|
|
116
117
|
return corpusCache.documents;
|
|
117
118
|
}
|
|
@@ -120,7 +121,7 @@ async function getCachedCorpus(channelDir, maxFiles, maxCharsPerChunk) {
|
|
|
120
121
|
maxFiles,
|
|
121
122
|
maxCharsPerDocument: maxCharsPerChunk,
|
|
122
123
|
});
|
|
123
|
-
corpusCache = { channelDir, maxFiles, documents, timestamp: Date.now() };
|
|
124
|
+
corpusCache = { channelDir, maxFiles, maxCharsPerChunk, documents, timestamp: Date.now() };
|
|
124
125
|
return documents;
|
|
125
126
|
}
|
|
126
127
|
export async function searchChannelSessions(request) {
|
|
@@ -128,16 +129,19 @@ export async function searchChannelSessions(request) {
|
|
|
128
129
|
const maxChunks = clampInteger(request.maxChunks, 1, 500);
|
|
129
130
|
const query = request.query.trim();
|
|
130
131
|
const roleFilter = normalizeRoleFilter(request.roleFilter);
|
|
131
|
-
const documents = (await getCachedCorpus(request.channelDir, request.maxFiles, request.maxCharsPerChunk))
|
|
132
|
+
const documents = (await getCachedCorpus(request.channelDir, request.maxFiles, request.maxCharsPerChunk))
|
|
133
|
+
.filter((document) => roleFilter.size === 0 || roleFilter.has(document.role))
|
|
134
|
+
.sort(sortRecentDocuments)
|
|
135
|
+
.slice(0, maxChunks);
|
|
132
136
|
const selected = query
|
|
133
137
|
? documents
|
|
134
138
|
.map((document) => scoreDocument(document, query, tokenizeRecallText(query)))
|
|
135
139
|
.filter((entry) => entry.score > 0)
|
|
136
140
|
.sort((a, b) => b.score - a.score)
|
|
137
|
-
.slice(0,
|
|
141
|
+
.slice(0, limit)
|
|
138
142
|
: documents
|
|
139
143
|
.sort(sortRecentDocuments)
|
|
140
|
-
.slice(0,
|
|
144
|
+
.slice(0, limit)
|
|
141
145
|
.map((document) => ({ document, score: computeRecencyBoost(document.timestamp), matches: [] }));
|
|
142
146
|
const results = [];
|
|
143
147
|
for (const hit of selected) {
|
package/dist/memory/session.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export interface SessionMemoryUpdateOptions {
|
|
|
18
18
|
model: Model<Api>;
|
|
19
19
|
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
20
20
|
timeoutMs?: number;
|
|
21
|
+
usageCorrelationId?: string;
|
|
21
22
|
}
|
|
22
23
|
export declare function renderSessionMemory(state: SessionMemoryState): string;
|
|
23
24
|
export declare function updateChannelSessionMemory(options: SessionMemoryUpdateOptions): Promise<SessionMemoryState>;
|
package/dist/memory/session.js
CHANGED
|
@@ -258,7 +258,9 @@ export async function updateChannelSessionMemory(options) {
|
|
|
258
258
|
prompt: buildSessionPrompt(currentSession, currentMemory, messages),
|
|
259
259
|
parse: parseStateUpdate,
|
|
260
260
|
timeoutMs: options.timeoutMs ?? DEFAULT_SESSION_MEMORY_TIMEOUT_MS,
|
|
261
|
-
usageContext: options.channelId
|
|
261
|
+
usageContext: options.channelId
|
|
262
|
+
? { channelId: options.channelId, correlationId: options.usageCorrelationId }
|
|
263
|
+
: undefined,
|
|
262
264
|
});
|
|
263
265
|
update = result.output;
|
|
264
266
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
export type MemorySourceKind = "idle" | "compaction" | "new-session" | "shutdown" | "growth-review";
|
|
4
|
+
export interface MemorySourceWindow {
|
|
5
|
+
sourceKind: MemorySourceKind;
|
|
6
|
+
fromEntryId?: string;
|
|
7
|
+
throughEntryId?: string;
|
|
8
|
+
entries: SessionEntry[];
|
|
9
|
+
messages: AgentMessage[];
|
|
10
|
+
windowId: string;
|
|
11
|
+
hasExternalToolContent: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare function entriesSince(entries: SessionEntry[], lastEntryId: string | undefined): SessionEntry[];
|
|
14
|
+
export declare function buildIncrementalMemorySourceWindow(options: {
|
|
15
|
+
entries: SessionEntry[];
|
|
16
|
+
lastEntryId?: string;
|
|
17
|
+
sourceKind: Extract<MemorySourceKind, "idle" | "new-session" | "shutdown" | "growth-review">;
|
|
18
|
+
fallbackMessages?: AgentMessage[];
|
|
19
|
+
}): MemorySourceWindow;
|
|
20
|
+
export declare function buildCompactionMemorySourceWindow(options: {
|
|
21
|
+
entries: SessionEntry[];
|
|
22
|
+
messagesToSummarize: AgentMessage[];
|
|
23
|
+
firstKeptEntryId?: string;
|
|
24
|
+
lastEntryId?: string;
|
|
25
|
+
}): MemorySourceWindow;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
function isMessageEntry(entry) {
|
|
3
|
+
return entry.type === "message";
|
|
4
|
+
}
|
|
5
|
+
function messagesFromEntries(entries) {
|
|
6
|
+
return entries.filter(isMessageEntry).map((entry) => entry.message);
|
|
7
|
+
}
|
|
8
|
+
function hasToolResult(messages) {
|
|
9
|
+
return messages.some((message) => typeof message === "object" && message !== null && "role" in message && message.role === "toolResult");
|
|
10
|
+
}
|
|
11
|
+
function createWindowId(sourceKind, fromEntryId, throughEntryId, messages) {
|
|
12
|
+
const fallbackFingerprint = throughEntryId === undefined
|
|
13
|
+
? createHash("sha256").update(JSON.stringify(messages)).digest("hex").slice(0, 16)
|
|
14
|
+
: "";
|
|
15
|
+
return createHash("sha256")
|
|
16
|
+
.update([sourceKind, fromEntryId ?? "start", throughEntryId ?? fallbackFingerprint].join("\0"))
|
|
17
|
+
.digest("hex")
|
|
18
|
+
.slice(0, 20);
|
|
19
|
+
}
|
|
20
|
+
export function entriesSince(entries, lastEntryId) {
|
|
21
|
+
if (!lastEntryId) {
|
|
22
|
+
return [...entries];
|
|
23
|
+
}
|
|
24
|
+
const index = entries.findIndex((entry) => entry.id === lastEntryId);
|
|
25
|
+
return index >= 0 ? entries.slice(index + 1) : [...entries];
|
|
26
|
+
}
|
|
27
|
+
export function buildIncrementalMemorySourceWindow(options) {
|
|
28
|
+
const entries = entriesSince(options.entries, options.lastEntryId);
|
|
29
|
+
const entryMessages = messagesFromEntries(entries);
|
|
30
|
+
const messages = entryMessages.length > 0 || entries.length > 0 || options.lastEntryId !== undefined
|
|
31
|
+
? entryMessages
|
|
32
|
+
: [...(options.fallbackMessages ?? [])];
|
|
33
|
+
const throughEntryId = entries.at(-1)?.id;
|
|
34
|
+
return {
|
|
35
|
+
sourceKind: options.sourceKind,
|
|
36
|
+
fromEntryId: options.lastEntryId,
|
|
37
|
+
throughEntryId,
|
|
38
|
+
entries,
|
|
39
|
+
messages,
|
|
40
|
+
windowId: createWindowId(options.sourceKind, options.lastEntryId, throughEntryId, messages),
|
|
41
|
+
hasExternalToolContent: hasToolResult(messages),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function buildCompactionMemorySourceWindow(options) {
|
|
45
|
+
const boundaryIndex = options.firstKeptEntryId
|
|
46
|
+
? options.entries.findIndex((entry) => entry.id === options.firstKeptEntryId)
|
|
47
|
+
: -1;
|
|
48
|
+
const coveredEntries = boundaryIndex >= 0 ? options.entries.slice(0, boundaryIndex) : [];
|
|
49
|
+
const incrementalEntries = entriesSince(coveredEntries, options.lastEntryId);
|
|
50
|
+
const throughEntryId = incrementalEntries.at(-1)?.id ?? coveredEntries.at(-1)?.id;
|
|
51
|
+
const incrementalMessages = messagesFromEntries(incrementalEntries);
|
|
52
|
+
const messages = incrementalMessages.length > 0 || options.lastEntryId !== undefined
|
|
53
|
+
? incrementalMessages
|
|
54
|
+
: [...options.messagesToSummarize];
|
|
55
|
+
return {
|
|
56
|
+
sourceKind: "compaction",
|
|
57
|
+
fromEntryId: options.lastEntryId,
|
|
58
|
+
throughEntryId,
|
|
59
|
+
entries: incrementalEntries,
|
|
60
|
+
messages,
|
|
61
|
+
windowId: createWindowId("compaction", options.lastEntryId, throughEntryId, messages),
|
|
62
|
+
hasExternalToolContent: hasToolResult(messages),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface MemoryTombstone {
|
|
2
|
+
entryId: string;
|
|
3
|
+
contentHash: string;
|
|
4
|
+
deletedAt: string;
|
|
5
|
+
scope: "channel";
|
|
6
|
+
reason: string;
|
|
7
|
+
sourceEntryIds?: string[];
|
|
8
|
+
}
|
|
9
|
+
export declare function hashMemoryContent(content: string): string;
|
|
10
|
+
export declare function getMemoryTombstonesPath(channelDir: string): string;
|
|
11
|
+
export declare function appendMemoryTombstone(channelDir: string, tombstone: MemoryTombstone): Promise<void>;
|
|
12
|
+
export declare function readMemoryTombstones(channelDir: string): Promise<MemoryTombstone[]>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
5
|
+
const appendQueue = createSerialQueue();
|
|
6
|
+
function normalizeMemoryContent(content) {
|
|
7
|
+
return content.normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
|
|
8
|
+
}
|
|
9
|
+
export function hashMemoryContent(content) {
|
|
10
|
+
return createHash("sha256").update(normalizeMemoryContent(content)).digest("hex");
|
|
11
|
+
}
|
|
12
|
+
export function getMemoryTombstonesPath(channelDir) {
|
|
13
|
+
return join(channelDir, ".memory", "tombstones.jsonl");
|
|
14
|
+
}
|
|
15
|
+
export async function appendMemoryTombstone(channelDir, tombstone) {
|
|
16
|
+
const path = getMemoryTombstonesPath(channelDir);
|
|
17
|
+
await appendQueue.run(path, async () => {
|
|
18
|
+
await mkdir(dirname(path), { recursive: true });
|
|
19
|
+
await appendFile(path, `${JSON.stringify(tombstone)}\n`, "utf-8");
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export async function readMemoryTombstones(channelDir) {
|
|
23
|
+
try {
|
|
24
|
+
const raw = await readFile(getMemoryTombstonesPath(channelDir), "utf-8");
|
|
25
|
+
return raw
|
|
26
|
+
.split("\n")
|
|
27
|
+
.filter(Boolean)
|
|
28
|
+
.flatMap((line) => {
|
|
29
|
+
try {
|
|
30
|
+
const value = JSON.parse(line);
|
|
31
|
+
return value.entryId && value.contentHash ? [value] : [];
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { buildStandardMessages } from "../shared/type-guards.js";
|
|
2
|
-
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
|
|
2
|
+
import { redactSecrets } from "./policy.js";
|
|
3
|
+
// The channel runner prepends the channel capsule, recalled memory, the task agenda
|
|
4
|
+
// and the durable bootstrap to the raw user input, then wraps the input itself in
|
|
5
|
+
// <user_message>. If that combined text flows back into consolidation / session
|
|
6
|
+
// refresh / signal scans, previously recalled memory gets re-summarized into
|
|
7
|
+
// MEMORY.md — a self-reinforcing echo. Strip the injected wrappers before any memory
|
|
8
|
+
// job reads the transcript.
|
|
9
|
+
const INJECTED_CONTEXT_BLOCK = /<(runtime_context|runtime_turn_context|durable_memory_snapshot|task_agenda)>[\s\S]*?<\/\1>\s*/gi;
|
|
8
10
|
const USER_MESSAGE_WRAPPER = /^<user_message>\s*([\s\S]*?)\s*<\/user_message>$/i;
|
|
9
11
|
export function stripInjectedMemoryContext(text) {
|
|
10
12
|
const withoutBlocks = text.replace(INJECTED_CONTEXT_BLOCK, "").trim();
|
|
@@ -13,11 +15,25 @@ export function stripInjectedMemoryContext(text) {
|
|
|
13
15
|
}
|
|
14
16
|
function sanitizeUserMessage(message) {
|
|
15
17
|
if (typeof message.content === "string") {
|
|
16
|
-
return { ...message, content: stripInjectedMemoryContext(message.content) };
|
|
18
|
+
return { ...message, content: redactSecrets(stripInjectedMemoryContext(message.content)) };
|
|
17
19
|
}
|
|
18
20
|
return {
|
|
19
21
|
...message,
|
|
20
|
-
content: message.content.map((part) => part.type === "text" ? { ...part, text: stripInjectedMemoryContext(part.text) } : part),
|
|
22
|
+
content: message.content.map((part) => part.type === "text" ? { ...part, text: redactSecrets(stripInjectedMemoryContext(part.text)) } : part),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function sanitizeAssistantMessage(message) {
|
|
26
|
+
return {
|
|
27
|
+
...message,
|
|
28
|
+
content: message.content.map((part) => {
|
|
29
|
+
if (part.type === "text") {
|
|
30
|
+
return { ...part, text: redactSecrets(part.text) };
|
|
31
|
+
}
|
|
32
|
+
if (part.type === "thinking") {
|
|
33
|
+
return { ...part, thinking: redactSecrets(part.thinking) };
|
|
34
|
+
}
|
|
35
|
+
return part;
|
|
36
|
+
}),
|
|
21
37
|
};
|
|
22
38
|
}
|
|
23
39
|
/**
|
|
@@ -26,5 +42,13 @@ function sanitizeUserMessage(message) {
|
|
|
26
42
|
* transcript, so recalled memory is never folded back into durable memory.
|
|
27
43
|
*/
|
|
28
44
|
export function sanitizeMessagesForMemory(messages) {
|
|
29
|
-
return buildStandardMessages(messages)
|
|
45
|
+
return buildStandardMessages(messages)
|
|
46
|
+
.filter((message) => message.role !== "toolResult")
|
|
47
|
+
.map((message) => {
|
|
48
|
+
if (message.role === "user")
|
|
49
|
+
return sanitizeUserMessage(message);
|
|
50
|
+
if (message.role === "assistant")
|
|
51
|
+
return sanitizeAssistantMessage(message);
|
|
52
|
+
return message;
|
|
53
|
+
});
|
|
30
54
|
}
|
|
@@ -1,9 +1,30 @@
|
|
|
1
|
+
/** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
|
|
2
|
+
declare const PLAYBOOK_MODES: readonly ["normal", "task-driver", "event", "subagent", "maintenance"];
|
|
3
|
+
export type PlaybookMode = (typeof PLAYBOOK_MODES)[number];
|
|
4
|
+
/** A catalog entry is a trigger, not a summary; longer descriptions are clipped in the prompt. */
|
|
5
|
+
export declare const MAX_PLAYBOOK_DESCRIPTION_CHARS = 180;
|
|
1
6
|
export interface RuntimePlaybookMetadata {
|
|
2
7
|
name: string;
|
|
3
8
|
description: string;
|
|
4
9
|
filename: string;
|
|
5
10
|
path: string;
|
|
11
|
+
/**
|
|
12
|
+
* Listed only when at least one of these tools is registered — any-of, not all-of:
|
|
13
|
+
* task-delegation matters to a runtime with tasks *or* with sub-agents. Empty = always
|
|
14
|
+
* listed. (Prompt sections gate the other way: see `requiresAllTools` in agent/prompt/types.ts.)
|
|
15
|
+
*/
|
|
16
|
+
requiresAnyTool: string[];
|
|
17
|
+
/** Modes this playbook is offered in. Empty = all modes. */
|
|
18
|
+
modes: PlaybookMode[];
|
|
19
|
+
/** Ascending; ties break on filename. */
|
|
20
|
+
priority: number;
|
|
6
21
|
}
|
|
7
22
|
/** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
|
|
8
23
|
export declare function loadRuntimePlaybookCatalog(directory?: string): RuntimePlaybookMetadata[];
|
|
9
|
-
|
|
24
|
+
/**
|
|
25
|
+
* Drop playbooks whose mechanism is unreachable with the current tool set: the task
|
|
26
|
+
* playbooks are pure noise for a runtime with `task_manage` switched off.
|
|
27
|
+
*/
|
|
28
|
+
export declare function selectRuntimePlaybooks(catalog: RuntimePlaybookMetadata[], toolNames: readonly string[], mode?: PlaybookMode): RuntimePlaybookMetadata[];
|
|
29
|
+
export declare function renderPlaybookCatalog(playbooks: RuntimePlaybookMetadata[]): string;
|
|
30
|
+
export {};
|
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { readdirSync, readFileSync } from "node:fs";
|
|
2
2
|
import { basename, join } from "node:path";
|
|
3
3
|
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
4
|
+
import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
|
|
5
|
+
/** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
|
|
6
|
+
const PLAYBOOK_MODES = ["normal", "task-driver", "event", "subagent", "maintenance"];
|
|
7
|
+
const DEFAULT_PRIORITY = 100;
|
|
8
|
+
/** A catalog entry is a trigger, not a summary; longer descriptions are clipped in the prompt. */
|
|
9
|
+
export const MAX_PLAYBOOK_DESCRIPTION_CHARS = 180;
|
|
10
|
+
function parseList(value) {
|
|
11
|
+
if (!value)
|
|
12
|
+
return [];
|
|
13
|
+
return value
|
|
14
|
+
.split(",")
|
|
15
|
+
.map((item) => item.trim())
|
|
16
|
+
.filter(Boolean);
|
|
17
|
+
}
|
|
4
18
|
function parseFrontmatter(content, filename) {
|
|
5
19
|
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
|
|
6
20
|
if (!match)
|
|
@@ -25,7 +39,26 @@ function parseFrontmatter(content, filename) {
|
|
|
25
39
|
if (`${name}.md` !== filename) {
|
|
26
40
|
throw new Error(`Runtime playbook ${filename} metadata name must be "${basename(filename, ".md")}".`);
|
|
27
41
|
}
|
|
28
|
-
|
|
42
|
+
// Authored metadata is validated, never silently ignored: a typo in a tool name would
|
|
43
|
+
// otherwise drop the playbook from the catalog with no signal anywhere.
|
|
44
|
+
const requiresAnyTool = parseList(fields.get("requires-tools"));
|
|
45
|
+
for (const tool of requiresAnyTool) {
|
|
46
|
+
if (!(tool in TOOL_PROMPT_HINTS)) {
|
|
47
|
+
throw new Error(`Runtime playbook ${filename} requires unknown tool "${tool}".`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const modes = parseList(fields.get("modes"));
|
|
51
|
+
for (const mode of modes) {
|
|
52
|
+
if (!PLAYBOOK_MODES.includes(mode)) {
|
|
53
|
+
throw new Error(`Runtime playbook ${filename} declares unknown mode "${mode}".`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const priorityField = fields.get("priority");
|
|
57
|
+
const priority = priorityField ? Number(priorityField) : DEFAULT_PRIORITY;
|
|
58
|
+
if (!Number.isFinite(priority)) {
|
|
59
|
+
throw new Error(`Runtime playbook ${filename} has a non-numeric priority "${priorityField}".`);
|
|
60
|
+
}
|
|
61
|
+
return { name, description, requiresAnyTool, modes: modes, priority };
|
|
29
62
|
}
|
|
30
63
|
/** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
|
|
31
64
|
export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
|
|
@@ -35,10 +68,30 @@ export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
|
|
|
35
68
|
.map((filename) => {
|
|
36
69
|
const path = join(directory, filename);
|
|
37
70
|
return { ...parseFrontmatter(readFileSync(path, "utf-8"), filename), filename, path };
|
|
71
|
+
})
|
|
72
|
+
.sort((a, b) => a.priority - b.priority || a.filename.localeCompare(b.filename));
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Drop playbooks whose mechanism is unreachable with the current tool set: the task
|
|
76
|
+
* playbooks are pure noise for a runtime with `task_manage` switched off.
|
|
77
|
+
*/
|
|
78
|
+
export function selectRuntimePlaybooks(catalog, toolNames, mode = "normal") {
|
|
79
|
+
const tools = new Set(toolNames);
|
|
80
|
+
return catalog.filter((playbook) => {
|
|
81
|
+
if (playbook.modes.length > 0 && !playbook.modes.includes(mode))
|
|
82
|
+
return false;
|
|
83
|
+
if (playbook.requiresAnyTool.length === 0)
|
|
84
|
+
return true;
|
|
85
|
+
return playbook.requiresAnyTool.some((tool) => tools.has(tool));
|
|
38
86
|
});
|
|
39
87
|
}
|
|
40
|
-
export function
|
|
41
|
-
return
|
|
42
|
-
.map((playbook) =>
|
|
88
|
+
export function renderPlaybookCatalog(playbooks) {
|
|
89
|
+
return playbooks
|
|
90
|
+
.map((playbook) => {
|
|
91
|
+
const description = playbook.description.length > MAX_PLAYBOOK_DESCRIPTION_CHARS
|
|
92
|
+
? `${playbook.description.slice(0, MAX_PLAYBOOK_DESCRIPTION_CHARS - 1)}…`
|
|
93
|
+
: playbook.description;
|
|
94
|
+
return `- ${playbook.filename} — ${description}`;
|
|
95
|
+
})
|
|
43
96
|
.join("\n");
|
|
44
97
|
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: memory-and-learning
|
|
3
3
|
description: Read when remembering or forgetting facts, choosing SESSION/MEMORY/HISTORY/ENVIRONMENT/tasks/skills, or turning repeated experience into a workspace skill.
|
|
4
|
+
requires-tools: memory_manage, skill_manage
|
|
5
|
+
priority: 20
|
|
4
6
|
---
|
|
5
7
|
|
|
6
8
|
# 记忆、状态与程序性学习
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: task-closeout
|
|
3
|
-
description: Read before candidate verification, importing a verifier verdict, requesting external approval,
|
|
3
|
+
description: Read before candidate verification, importing a verifier verdict, requesting external approval, or completing/cancelling a task.
|
|
4
|
+
requires-tools: task_manage
|
|
5
|
+
priority: 42
|
|
4
6
|
---
|
|
5
7
|
|
|
6
8
|
# 验收、外部审批与闭环
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: task-delegation
|
|
3
|
-
description: Read before splitting parent/child tasks, using predefined or inline subagents, creating task-owned worktrees, or delegating
|
|
3
|
+
description: Read before splitting parent/child tasks, using predefined or inline subagents, creating task-owned worktrees, or delegating work you must revisit later.
|
|
4
|
+
requires-tools: task_manage, subagent
|
|
5
|
+
priority: 45
|
|
4
6
|
---
|
|
5
7
|
|
|
6
8
|
# 任务分解与委派
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: task-driving
|
|
3
3
|
description: Read whenever TASK_DRIVER or a task-owned event resumes work, and when checkpointing progress, waiting with wake, handling idempotent recovery, or deciding the next task action.
|
|
4
|
+
requires-tools: task_manage
|
|
5
|
+
priority: 41
|
|
4
6
|
---
|
|
5
7
|
|
|
6
8
|
# Task driver 推进与断点恢复
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: task-planning
|
|
3
3
|
description: Read before creating or restructuring a persistent task, choosing task versus event, writing Goal/DoD/Manual/Verification, or setting control metadata and budgets.
|
|
4
|
+
requires-tools: task_manage
|
|
5
|
+
priority: 40
|
|
4
6
|
---
|
|
5
7
|
|
|
6
8
|
# 长程任务规划与建档
|