@oyasmi/pipiclaw 0.8.5 → 0.8.7-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.
Files changed (74) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +27 -10
  3. package/dist/agent/command-extension.d.ts +1 -0
  4. package/dist/agent/command-extension.js +6 -0
  5. package/dist/agent/commands.js +6 -0
  6. package/dist/agent/session-events.js +17 -5
  7. package/dist/agent/types.d.ts +1 -0
  8. package/dist/log.d.ts +12 -20
  9. package/dist/log.js +195 -198
  10. package/dist/memory/bootstrap.d.ts +5 -0
  11. package/dist/memory/bootstrap.js +14 -4
  12. package/dist/memory/candidates.d.ts +2 -0
  13. package/dist/memory/candidates.js +13 -3
  14. package/dist/memory/commands.d.ts +6 -0
  15. package/dist/memory/commands.js +112 -0
  16. package/dist/memory/consolidation.d.ts +3 -0
  17. package/dist/memory/consolidation.js +68 -26
  18. package/dist/memory/files.d.ts +13 -0
  19. package/dist/memory/files.js +65 -8
  20. package/dist/memory/lifecycle.d.ts +2 -1
  21. package/dist/memory/lifecycle.js +38 -7
  22. package/dist/memory/maintenance-jobs.js +48 -23
  23. package/dist/memory/metadata.d.ts +60 -0
  24. package/dist/memory/metadata.js +135 -0
  25. package/dist/memory/policy.d.ts +3 -0
  26. package/dist/memory/policy.js +19 -0
  27. package/dist/memory/post-turn-review.d.ts +11 -1
  28. package/dist/memory/post-turn-review.js +78 -19
  29. package/dist/memory/promotion.d.ts +5 -2
  30. package/dist/memory/promotion.js +3 -1
  31. package/dist/memory/recall.d.ts +3 -0
  32. package/dist/memory/recall.js +27 -5
  33. package/dist/memory/review-log.d.ts +2 -0
  34. package/dist/memory/review-log.js +15 -0
  35. package/dist/memory/session-corpus.js +11 -3
  36. package/dist/memory/session-search.js +8 -4
  37. package/dist/memory/session.d.ts +1 -0
  38. package/dist/memory/session.js +3 -1
  39. package/dist/memory/sidecar-worker.d.ts +1 -0
  40. package/dist/memory/sidecar-worker.js +1 -0
  41. package/dist/memory/source-window.d.ts +25 -0
  42. package/dist/memory/source-window.js +64 -0
  43. package/dist/memory/tombstones.d.ts +12 -0
  44. package/dist/memory/tombstones.js +44 -0
  45. package/dist/memory/transcript.js +26 -3
  46. package/dist/runtime/bootstrap.d.ts +1 -0
  47. package/dist/runtime/bootstrap.js +42 -11
  48. package/dist/runtime/dingtalk.js +19 -6
  49. package/dist/runtime/events.d.ts +2 -0
  50. package/dist/runtime/events.js +14 -7
  51. package/dist/runtime/store.d.ts +4 -6
  52. package/dist/runtime/store.js +44 -40
  53. package/dist/runtime/task-commands.js +1 -1
  54. package/dist/security/logger.d.ts +3 -1
  55. package/dist/security/logger.js +33 -10
  56. package/dist/settings.js +1 -1
  57. package/dist/shared/jsonl-appender.d.ts +27 -8
  58. package/dist/shared/jsonl-appender.js +128 -41
  59. package/dist/tasks/control.js +9 -3
  60. package/dist/tasks/store.d.ts +1 -0
  61. package/dist/tasks/store.js +11 -1
  62. package/dist/tools/bash.js +1 -1
  63. package/dist/tools/edit.js +1 -1
  64. package/dist/tools/grep.js +1 -1
  65. package/dist/tools/memory-manage.d.ts +1 -1
  66. package/dist/tools/memory-manage.js +27 -6
  67. package/dist/tools/read.js +1 -1
  68. package/dist/tools/task-manage.js +2 -2
  69. package/dist/tools/write-content.js +1 -1
  70. package/dist/tui/app.js +17 -0
  71. package/dist/usage/ledger.d.ts +4 -0
  72. package/dist/usage/ledger.js +3 -1
  73. package/dist/web/client.js +3 -3
  74. package/package.json +1 -1
@@ -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;
@@ -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 (matchedTokens.size === 0 && exactBoost === 0) {
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 candidates;
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
- if (filteredCandidates.length === 0) {
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 = filteredCandidates
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, filteredCandidates, scored, queryIntents, queryTokens)
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
- if (docs.length > maxDocuments) {
241
- return docs.slice(-maxDocuments);
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 docs;
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)).filter((document) => roleFilter.size === 0 || roleFilter.has(document.role));
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, Math.min(limit, maxChunks))
141
+ .slice(0, limit)
138
142
  : documents
139
143
  .sort(sortRecentDocuments)
140
- .slice(0, Math.min(limit, maxChunks))
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) {
@@ -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>;
@@ -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 ? { channelId: options.channelId } : undefined,
261
+ usageContext: options.channelId
262
+ ? { channelId: options.channelId, correlationId: options.usageCorrelationId }
263
+ : undefined,
262
264
  });
263
265
  update = result.output;
264
266
  }
@@ -11,6 +11,7 @@ export interface SidecarTask<T> {
11
11
  /** Attributes this task's LLM spend to a channel in the usage ledger. */
12
12
  usageContext?: {
13
13
  channelId: string;
14
+ correlationId?: string;
14
15
  };
15
16
  }
16
17
  export interface SidecarResult<T> {
@@ -66,6 +66,7 @@ function recordSidecarUsage(task, message) {
66
66
  kind: "sidecar",
67
67
  model: formatModelReference(task.model),
68
68
  label: task.name,
69
+ correlationId: task.usageContext?.correlationId,
69
70
  usage: {
70
71
  input: usage.input ?? 0,
71
72
  output: usage.output ?? 0,
@@ -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,4 +1,5 @@
1
1
  import { buildStandardMessages } from "../shared/type-guards.js";
2
+ import { redactSecrets } from "./policy.js";
2
3
  // The channel runner prepends the channel capsule, recalled memory, the task agenda
3
4
  // and the durable bootstrap to the raw user input, then wraps the input itself in
4
5
  // <user_message>. If that combined text flows back into consolidation / session
@@ -14,11 +15,25 @@ export function stripInjectedMemoryContext(text) {
14
15
  }
15
16
  function sanitizeUserMessage(message) {
16
17
  if (typeof message.content === "string") {
17
- return { ...message, content: stripInjectedMemoryContext(message.content) };
18
+ return { ...message, content: redactSecrets(stripInjectedMemoryContext(message.content)) };
18
19
  }
19
20
  return {
20
21
  ...message,
21
- 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
+ }),
22
37
  };
23
38
  }
24
39
  /**
@@ -27,5 +42,13 @@ function sanitizeUserMessage(message) {
27
42
  * transcript, so recalled memory is never folded back into durable memory.
28
43
  */
29
44
  export function sanitizeMessagesForMemory(messages) {
30
- return buildStandardMessages(messages).map((message) => message.role === "user" ? sanitizeUserMessage(message) : message);
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
+ });
31
54
  }
@@ -57,6 +57,7 @@ interface RuntimeContextOptions {
57
57
  createEventsWatcher?: (workspaceDir: string, bot: DingTalkBot, executor: Executor, eventHistoryPath: string) => {
58
58
  start(): void;
59
59
  stop(): void;
60
+ flush?(): Promise<void>;
60
61
  };
61
62
  createMemoryMaintenanceScheduler?: () => {
62
63
  start(): void;
@@ -11,6 +11,7 @@ import { ensureChannelMemoryFilesSync } from "../memory/files.js";
11
11
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
12
12
  import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, EVENT_HISTORY_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
13
13
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
14
+ import { flushSecurityLogs } from "../security/logger.js";
14
15
  import { PipiclawSettingsManager } from "../settings.js";
15
16
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
16
17
  import { readActiveTasks } from "../shared/task-ledger.js";
@@ -122,6 +123,7 @@ const SECURITY_CONFIG_TEMPLATE = {
122
123
  const SHUTDOWN_WAIT_MS = 15000;
123
124
  const SHUTDOWN_FLUSH_WAIT_MS = 45000;
124
125
  const SHUTDOWN_ABORT_WAIT_MS = 5000;
126
+ const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
125
127
  export const DEFAULT_BOOTSTRAP_PATHS = {
126
128
  appName: APP_NAME,
127
129
  appHomeDir: APP_HOME_DIR,
@@ -342,12 +344,14 @@ function waitForTasks(tasks, timeoutMs) {
342
344
  if (tasks.length === 0) {
343
345
  return Promise.resolve(true);
344
346
  }
345
- return Promise.race([
346
- Promise.allSettled(tasks).then(() => true),
347
- new Promise((resolve) => {
348
- setTimeout(() => resolve(false), timeoutMs);
349
- }),
350
- ]);
347
+ return new Promise((resolve) => {
348
+ const timer = setTimeout(() => resolve(false), timeoutMs);
349
+ timer.unref?.();
350
+ void Promise.allSettled(tasks).then(() => {
351
+ clearTimeout(timer);
352
+ resolve(true);
353
+ });
354
+ });
351
355
  }
352
356
  function flushInactiveChannelMemory(channelRunners) {
353
357
  const flushes = [];
@@ -487,7 +491,10 @@ export function createRuntimeContext(options) {
487
491
  return { kind: "handled" };
488
492
  }
489
493
  if (mode === "followUp") {
490
- log.logInfo(`[${event.channelId}] Queued followUp as next task: ${trimmedQueueText.substring(0, 80)}`);
494
+ log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
495
+ ctx: { channelId: event.channelId, userName: event.userName },
496
+ fields: { messageLength: trimmedQueueText.length },
497
+ });
491
498
  return { kind: "requeue", text: trimmedQueueText };
492
499
  }
493
500
  try {
@@ -506,7 +513,10 @@ export function createRuntimeContext(options) {
506
513
  ? "Queued as steer. I’ll apply it after the current tool step finishes."
507
514
  : "Queued as steer. I’ll apply this after the current tool step finishes. Use `/followup <message>` to queue it after completion.";
508
515
  await bot.sendPlain(event.channelId, confirmation);
509
- log.logInfo(`[${event.channelId}] Queued ${mode}: ${trimmedQueueText.substring(0, 80)}`);
516
+ log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
517
+ ctx: { channelId: event.channelId, userName: event.userName },
518
+ fields: { messageLength: trimmedQueueText.length },
519
+ });
510
520
  return { kind: "handled" };
511
521
  }
512
522
  catch (err) {
@@ -546,7 +556,10 @@ export function createRuntimeContext(options) {
546
556
  const ctx = createDingTalkContext(event, bot, store);
547
557
  const builtInCommand = parseBuiltInCommand(event.text);
548
558
  if (builtInCommand) {
549
- log.logInfo(`[${event.channelId}] Executing command: ${builtInCommand.rawText}`);
559
+ log.logEvent("info", "runtime.command.started", "Executing command", {
560
+ ctx: { channelId: event.channelId, userName: event.userName },
561
+ fields: { command: builtInCommand.name },
562
+ });
550
563
  if (builtInCommand.name === "events") {
551
564
  await handler.handleEventsCommand(event, bot, builtInCommand.args);
552
565
  return;
@@ -576,7 +589,10 @@ export function createRuntimeContext(options) {
576
589
  await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
577
590
  return;
578
591
  }
579
- log.logInfo(`[${event.channelId}] Starting run: ${event.text.substring(0, 50)}`);
592
+ log.logEvent("info", "agent.turn.started", "Starting turn", {
593
+ ctx: { channelId: event.channelId, userName: event.userName },
594
+ fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
595
+ });
580
596
  if (!_isEvent) {
581
597
  ctx.primeCard(350);
582
598
  }
@@ -588,6 +604,7 @@ export function createRuntimeContext(options) {
588
604
  costUsd: result.usage.cost.total,
589
605
  wallTimeMinutes: result.durationMs / 60_000,
590
606
  failed: result.stopReason === "error" || result.stopReason === "aborted",
607
+ silent: result.silent,
591
608
  finishedAt: new Date(),
592
609
  });
593
610
  }
@@ -596,7 +613,10 @@ export function createRuntimeContext(options) {
596
613
  }
597
614
  }
598
615
  catch (err) {
599
- log.logWarning(`[${event.channelId}] Run error`, errorMessage(err));
616
+ log.logEvent("error", "agent.turn.failed", "Turn failed", {
617
+ ctx: { channelId: event.channelId, userName: event.userName },
618
+ fields: { error: errorMessage(err) },
619
+ });
600
620
  }
601
621
  finally {
602
622
  await durableDispatch?.markCompleted(event.dispatchId);
@@ -727,6 +747,17 @@ export function createRuntimeContext(options) {
727
747
  modelsConfigPath: options.paths.modelsConfigPath,
728
748
  }, channelDir);
729
749
  }
750
+ const storageFlushes = [
751
+ store.close(),
752
+ getUsageLedger().flush?.() ?? Promise.resolve(),
753
+ flushSecurityLogs(),
754
+ ...(eventsWatcher.flush ? [eventsWatcher.flush()] : []),
755
+ ];
756
+ const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
757
+ if (!storageFlushed) {
758
+ log.logWarning(`Shutdown log flush exceeded ${SHUTDOWN_LOG_FLUSH_WAIT_MS}ms`);
759
+ }
760
+ await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
730
761
  })();
731
762
  return shutdownPromise;
732
763
  };
@@ -335,7 +335,9 @@ export class DingTalkBot {
335
335
  if (!this.config.cardTemplateId) {
336
336
  log.logWarning("DingTalk: cardTemplateId not configured — AI Card streaming will not work");
337
337
  }
338
- log.logInfo(`DingTalk: initializing stream (clientId=${this.config.clientId.substring(0, 8)}…)`);
338
+ log.logEvent("info", "runtime.dingtalk.connecting", "Initializing stream client", {
339
+ fields: { clientIdPrefix: this.config.clientId.substring(0, 8) },
340
+ });
339
341
  this.clearAllTimers();
340
342
  const clientOptions = {
341
343
  clientId: this.config.clientId,
@@ -390,7 +392,9 @@ export class DingTalkBot {
390
392
  this.clearKeepAliveTimer();
391
393
  if (!immediate && this.reconnectAttempts > 0) {
392
394
  const delay = Math.min(1000 * 2 ** this.reconnectAttempts + Math.random() * 1000, 30000);
393
- log.logInfo(`DingTalk: waiting ${Math.round(delay / 1000)}s before reconnecting...`);
395
+ log.logEvent("info", "runtime.dingtalk.reconnect_scheduled", "Reconnect scheduled", {
396
+ fields: { delayMs: delay },
397
+ });
394
398
  await this.waitForDelay(delay);
395
399
  if (this.isStopped || !this.client) {
396
400
  this.isReconnecting = false;
@@ -409,7 +413,7 @@ export class DingTalkBot {
409
413
  await this.connectWithTimeout();
410
414
  this.lastSocketAvailableTime = Date.now();
411
415
  this.reconnectAttempts = 0; // Success, reset backoff
412
- log.logInfo("DingTalk: connected to stream.");
416
+ log.logEvent("info", "runtime.dingtalk.stream_connected", "Connected to stream");
413
417
  if (!this.hasReportedReady) {
414
418
  log.logConnected();
415
419
  this.hasReportedReady = true;
@@ -510,10 +514,16 @@ export class DingTalkBot {
510
514
  }
511
515
  const queue = this.getQueue(event.channelId);
512
516
  if (queue.size() >= 5) {
513
- log.logWarning(`Event queue full for ${event.channelId}, discarding: ${event.text.substring(0, 50)}`);
517
+ log.logEvent("warn", "runtime.channel_queue.full", "Discarding incoming event", {
518
+ ctx: { channelId: event.channelId, userName: event.userName },
519
+ fields: { messageLength: event.text.length },
520
+ });
514
521
  return false;
515
522
  }
516
- log.logInfo(`Enqueueing event for ${event.channelId}: ${event.text.substring(0, 50)}`);
523
+ log.logEvent("debug", "runtime.channel_queue.enqueued", "Incoming event queued", {
524
+ ctx: { channelId: event.channelId, userName: event.userName },
525
+ fields: { messageLength: event.text.length },
526
+ });
517
527
  queue.enqueue(async () => {
518
528
  this.activeMessageProcessing = true;
519
529
  try {
@@ -915,7 +925,10 @@ export class DingTalkBot {
915
925
  }
916
926
  // Determine channel ID
917
927
  const channelId = conversationType === "2" ? `group_${conversationId}` : `dm_${senderId}`;
918
- log.logInfo(`DingTalk ← ${senderName} (${senderId}) [${channelId}]: ${content.substring(0, 80)}`);
928
+ log.logEvent("info", "runtime.dingtalk.message_received", "Accepted incoming message", {
929
+ ctx: { channelId, userName: senderName },
930
+ fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
931
+ });
919
932
  // Cache conversation metadata for card creation
920
933
  this.setConversationMeta(channelId, {
921
934
  conversationId,
@@ -74,9 +74,11 @@ export declare class EventsWatcher {
74
74
  private startTime;
75
75
  private watcher;
76
76
  private knownFiles;
77
+ private readonly historyAppender?;
77
78
  constructor(eventsDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"] | undefined, options?: EventsWatcherOptions);
78
79
  start(): void;
79
80
  stop(): void;
81
+ flush(): Promise<void>;
80
82
  private ensureHistoryFile;
81
83
  private appendHistory;
82
84
  private appendEventHistory;