@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
package/dist/log.js CHANGED
@@ -2,12 +2,13 @@ import { styleText } from "node:util";
2
2
  import { RUNTIME_LOG_PATH } from "./paths.js";
3
3
  import { createJsonlAppender } from "./shared/jsonl-appender.js";
4
4
  const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
5
+ const MAX_VALUE_LENGTH = 240;
6
+ const MAX_COLLECTION_ITEMS = 10;
7
+ const SENSITIVE_KEY = /(?:api[_-]?key|authorization|cookie|credential|password|secret|private[_-]?key|(?:^|[_-])token(?:$|[_-])|token$|^env(?:ironment)?$)/i;
8
+ const SENSITIVE_TEXT = /\b(?:authorization|cookie|token|api[_-]?key|secret|password)\s*[:=]\s*[^\s,;]+|\bbearer\s+[^\s,;]+/gi;
5
9
  function readEnvLevel() {
6
10
  const raw = process.env.PIPICLAW_LOG_LEVEL?.trim().toLowerCase();
7
- if (raw && raw in LEVEL_ORDER) {
8
- return raw;
9
- }
10
- return undefined;
11
+ return raw && raw in LEVEL_ORDER ? raw : undefined;
11
12
  }
12
13
  function readEnvFileEnabled() {
13
14
  const raw = process.env.PIPICLAW_LOG_FILE?.trim();
@@ -20,16 +21,11 @@ function readEnvFileEnabled() {
20
21
  const envLevel = readEnvLevel();
21
22
  const envFileEnabled = readEnvFileEnabled();
22
23
  let thresholdLevel = envLevel ?? "info";
23
- let fileSink =
24
- // Honor an explicit env opt-in even before settings are loaded, so the
25
- // earliest startup logs are captured. Defaults match DEFAULT_LOGGING.
26
- envFileEnabled === true
24
+ let fileSink = envFileEnabled === true
27
25
  ? createJsonlAppender({ path: RUNTIME_LOG_PATH, maxSizeBytes: 5_000_000, maxRotations: 3 })
28
26
  : null;
29
- /**
30
- * Configure the file sink from loaded settings. Env vars take precedence and
31
- * have already applied at module load; this reconciles the two.
32
- */
27
+ let consoleEnabled = true;
28
+ /** Configure both console filtering and the optional structured file sink. */
33
29
  export function configureLogging(config) {
34
30
  thresholdLevel = envLevel ?? config.level;
35
31
  const enabled = envFileEnabled ?? config.file.enabled;
@@ -41,187 +37,199 @@ export function configureLogging(config) {
41
37
  })
42
38
  : null;
43
39
  }
44
- function emit(level, event, message, extra) {
45
- if (!fileSink)
46
- return;
47
- if (LEVEL_ORDER[level] < LEVEL_ORDER[thresholdLevel])
48
- return;
49
- const record = {
50
- ts: new Date().toISOString(),
51
- level,
52
- event,
53
- message,
54
- ...(extra?.ctx ? { channelId: extra.ctx.channelId, userName: extra.ctx.userName } : {}),
55
- ...(extra?.details ? { details: extra.details } : {}),
56
- ...(extra?.fields ? { fields: extra.fields } : {}),
57
- };
58
- void fileSink.append(record);
59
- }
60
- let consoleEnabled = true;
61
- /**
62
- * Toggle the human-readable console sink. The TUI disables it so structured
63
- * logging does not corrupt the pi-tui frame (which owns stdout); the file sink
64
- * is unaffected, so logs are still captured when file logging is enabled.
65
- */
40
+ /** The TUI owns stdout, so its runtime logs are file-only. */
66
41
  export function setConsoleLoggingEnabled(enabled) {
67
42
  consoleEnabled = enabled;
68
43
  }
69
- function con(...args) {
70
- if (consoleEnabled)
71
- console.log(...args);
44
+ function isEnabled(level) {
45
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[thresholdLevel];
72
46
  }
73
- function color(style, text) {
74
- return styleText(style, text);
47
+ function summarizeString(value) {
48
+ const redacted = value.replace(SENSITIVE_TEXT, (match) => {
49
+ const separator = match.includes(":") ? ":" : match.includes("=") ? "=" : " ";
50
+ return `${match.split(separator, 1)[0]}${separator}[REDACTED]`;
51
+ });
52
+ const normalized = redacted.replace(/\s+/g, " ").trim();
53
+ return normalized.length > MAX_VALUE_LENGTH
54
+ ? `${normalized.slice(0, MAX_VALUE_LENGTH)}… (length=${normalized.length})`
55
+ : normalized;
75
56
  }
76
- function timestamp() {
77
- const now = new Date();
78
- const hh = String(now.getHours()).padStart(2, "0");
79
- const mm = String(now.getMinutes()).padStart(2, "0");
80
- const ss = String(now.getSeconds()).padStart(2, "0");
81
- return `[${hh}:${mm}:${ss}]`;
57
+ /**
58
+ * Keep logging safe and cheap: redact values by conventional sensitive keys,
59
+ * flatten multiline strings, and bound nested diagnostic values.
60
+ */
61
+ function sanitizeValue(value, key, depth = 0) {
62
+ if (key && SENSITIVE_KEY.test(key))
63
+ return "[REDACTED]";
64
+ if (typeof value === "string")
65
+ return summarizeString(value);
66
+ if (typeof value === "number" || typeof value === "boolean" || value === null)
67
+ return value;
68
+ if (value === undefined)
69
+ return undefined;
70
+ if (value instanceof Error)
71
+ return summarizeString(value.message);
72
+ if (depth >= 2)
73
+ return "[summary omitted]";
74
+ if (Array.isArray(value)) {
75
+ return value.slice(0, MAX_COLLECTION_ITEMS).map((item) => sanitizeValue(item, undefined, depth + 1));
76
+ }
77
+ if (typeof value === "object") {
78
+ const result = {};
79
+ for (const [childKey, childValue] of Object.entries(value).slice(0, MAX_COLLECTION_ITEMS)) {
80
+ const sanitized = sanitizeValue(childValue, childKey, depth + 1);
81
+ if (sanitized !== undefined)
82
+ result[childKey] = sanitized;
83
+ }
84
+ return result;
85
+ }
86
+ return summarizeString(String(value));
82
87
  }
83
- function formatContext(ctx) {
84
- // DMs: [DM:username]
85
- // Groups: [group:channelId:username]
86
- if (ctx.channelId.startsWith("dm_")) {
87
- return `[DM:${ctx.userName || ctx.channelId}]`;
88
+ function sanitizeFields(fields) {
89
+ if (!fields)
90
+ return undefined;
91
+ const result = {};
92
+ for (const [key, value] of Object.entries(fields)) {
93
+ const sanitized = sanitizeValue(value, key);
94
+ if (sanitized !== undefined)
95
+ result[key] = sanitized;
88
96
  }
89
- const channel = ctx.channelName || ctx.channelId;
90
- const user = ctx.userName || "unknown";
91
- return `[${channel}:${user}]`;
97
+ return result;
92
98
  }
93
- function truncate(text, maxLen) {
94
- if (text.length <= maxLen)
95
- return text;
96
- return `${text.substring(0, maxLen)}\n(truncated at ${maxLen} chars)`;
99
+ function formatTimestamp(date = new Date()) {
100
+ const offsetMinutes = -date.getTimezoneOffset();
101
+ const sign = offsetMinutes >= 0 ? "+" : "-";
102
+ const offsetHours = String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0");
103
+ const offsetRemainder = String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
104
+ const year = date.getFullYear();
105
+ const month = String(date.getMonth() + 1).padStart(2, "0");
106
+ const day = String(date.getDate()).padStart(2, "0");
107
+ const hours = String(date.getHours()).padStart(2, "0");
108
+ const minutes = String(date.getMinutes()).padStart(2, "0");
109
+ const seconds = String(date.getSeconds()).padStart(2, "0");
110
+ const milliseconds = String(date.getMilliseconds()).padStart(3, "0");
111
+ return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${sign}${offsetHours}:${offsetRemainder}`;
97
112
  }
98
- function formatToolArgs(args) {
99
- const lines = [];
100
- for (const [key, value] of Object.entries(args)) {
101
- if (key === "label")
102
- continue;
103
- if (key === "path" && typeof value === "string") {
104
- const offset = args.offset;
105
- const limit = args.limit;
106
- if (offset !== undefined && limit !== undefined) {
107
- lines.push(`${value}:${offset}-${offset + limit}`);
108
- }
109
- else {
110
- lines.push(value);
111
- }
112
- continue;
113
- }
114
- if (key === "offset" || key === "limit")
115
- continue;
116
- if (typeof value === "string") {
117
- lines.push(value);
118
- }
119
- else {
120
- lines.push(JSON.stringify(value));
121
- }
113
+ function renderField(value) {
114
+ if (typeof value === "string")
115
+ return JSON.stringify(value);
116
+ try {
117
+ return JSON.stringify(value);
122
118
  }
123
- return lines.join("\n");
119
+ catch {
120
+ return JSON.stringify("[unserializable]");
121
+ }
122
+ }
123
+ function formatConsoleLine(level, event, message, options) {
124
+ const fields = {
125
+ ...(options.ctx
126
+ ? { channel: options.ctx.channelId, ...(options.ctx.userName ? { user: options.ctx.userName } : {}) }
127
+ : {}),
128
+ ...sanitizeFields(options.fields),
129
+ };
130
+ const suffix = Object.entries(fields)
131
+ .sort(([left], [right]) => left.localeCompare(right))
132
+ .map(([key, value]) => `${key}=${renderField(value)}`)
133
+ .join(" ");
134
+ return `${formatTimestamp()} ${level.toUpperCase().padEnd(5)} ${event} ${summarizeString(message)}${suffix ? ` ${suffix}` : ""}`;
124
135
  }
125
- // Tool execution
136
+ function colorFor(level) {
137
+ if (level === "debug")
138
+ return "dim";
139
+ if (level === "warn")
140
+ return "yellow";
141
+ if (level === "error")
142
+ return "red";
143
+ return "blue";
144
+ }
145
+ function writeConsole(level, event, message, options) {
146
+ if (!consoleEnabled || !isEnabled(level))
147
+ return;
148
+ console.log(styleText(colorFor(level), formatConsoleLine(level, event, message, options)));
149
+ }
150
+ function emit(level, event, message, options) {
151
+ if (!fileSink || !isEnabled(level))
152
+ return;
153
+ const fields = sanitizeFields(options.fields);
154
+ const details = options.details ? summarizeString(options.details) : undefined;
155
+ fileSink.tryAppend({
156
+ ts: new Date().toISOString(),
157
+ level,
158
+ event,
159
+ message: summarizeString(message),
160
+ ...(options.ctx ? { channelId: options.ctx.channelId, userName: options.ctx.userName } : {}),
161
+ ...(details ? { details } : {}),
162
+ ...(fields ? { fields } : {}),
163
+ }, level === "warn" || level === "error" ? "critical" : "normal");
164
+ }
165
+ /** Wait for structured logs accepted so far to reach disk. */
166
+ export async function flushLogging() {
167
+ await fileSink?.flush();
168
+ }
169
+ /** Emit one consistently formatted runtime event to stdout and the JSONL sink. */
170
+ export function logEvent(level, event, message, options = {}) {
171
+ writeConsole(level, event, message, options);
172
+ emit(level, event, message, options);
173
+ }
174
+ function formatToolArgs(args) {
175
+ const { label: _label, ...rest } = args;
176
+ return rest;
177
+ }
178
+ // Tool execution is diagnostic by default. Failures remain visible because they
179
+ // are useful even when an agent can recover in the same turn.
126
180
  export function logToolStart(ctx, toolName, label, args) {
127
- const formattedArgs = formatToolArgs(args);
128
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));
129
- if (formattedArgs) {
130
- const indented = formattedArgs
131
- .split("\n")
132
- .map((line) => ` ${line}`)
133
- .join("\n");
134
- con(color("dim", indented));
135
- }
136
- emit("debug", "tool_start", `${toolName}: ${label}`, {
137
- ctx,
138
- details: formattedArgs || undefined,
139
- fields: { toolName, label },
140
- });
181
+ logEvent("debug", "agent.tool.started", label, { ctx, fields: { tool: toolName, args: formatToolArgs(args) } });
141
182
  }
142
183
  export function logToolSuccess(ctx, toolName, durationMs, result) {
143
- const duration = (durationMs / 1000).toFixed(1);
144
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));
145
- const truncated = truncate(result, 1000);
146
- if (truncated) {
147
- const indented = truncated
148
- .split("\n")
149
- .map((line) => ` ${line}`)
150
- .join("\n");
151
- con(color("dim", indented));
152
- }
153
- emit("info", "tool_end", toolName, {
184
+ logEvent("debug", "agent.tool.finished", "Tool completed", {
154
185
  ctx,
155
- details: truncated || undefined,
156
- fields: { toolName, durationMs, isError: false },
186
+ details: result,
187
+ fields: { tool: toolName, durationMs, resultLength: result.length },
157
188
  });
158
189
  }
159
190
  export function logToolError(ctx, toolName, durationMs, error) {
160
- const duration = (durationMs / 1000).toFixed(1);
161
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));
162
- const truncated = truncate(error, 1000);
163
- const indented = truncated
164
- .split("\n")
165
- .map((line) => ` ${line}`)
166
- .join("\n");
167
- con(color("dim", indented));
168
- emit("error", "tool_end", toolName, {
191
+ logEvent("warn", "agent.tool.failed", "Tool failed", {
169
192
  ctx,
170
- details: truncated,
171
- fields: { toolName, durationMs, isError: true },
193
+ details: error,
194
+ fields: { tool: toolName, durationMs, error },
172
195
  });
173
196
  }
174
- // Response streaming
175
197
  export function logResponseStart(ctx) {
176
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} → Streaming response...`));
177
- emit("debug", "response_start", "Streaming response...", { ctx });
198
+ logEvent("debug", "agent.response.started", "Streaming response", { ctx });
178
199
  }
179
200
  export function logThinking(ctx, thinking) {
180
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💭 Thinking`));
181
- const truncated = truncate(thinking, 1000);
182
- const indented = truncated
183
- .split("\n")
184
- .map((line) => ` ${line}`)
185
- .join("\n");
186
- con(color("dim", indented));
187
- emit("debug", "thinking", "Thinking", { ctx, details: truncated });
201
+ logEvent("debug", "agent.thinking", "Thinking", { ctx, details: thinking, fields: { length: thinking.length } });
188
202
  }
189
203
  export function logResponse(ctx, text) {
190
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💬 Response`));
191
- const truncated = truncate(text, 1000);
192
- const indented = truncated
193
- .split("\n")
194
- .map((line) => ` ${line}`)
195
- .join("\n");
196
- con(color("dim", indented));
197
- emit("info", "response", "Response", { ctx, details: truncated });
204
+ logEvent("debug", "agent.response.finished", "Response ready", {
205
+ ctx,
206
+ details: text,
207
+ fields: { length: text.length },
208
+ });
198
209
  }
199
- // System
200
- export function logInfo(message) {
201
- con(color("blue", `${timestamp()} [system] ${message}`));
202
- emit("info", "system", message);
210
+ // Compatibility helpers keep lower-risk call sites centralized while they use
211
+ // the same output contract as structured events.
212
+ function legacyContext(message) {
213
+ const match = /^\[([A-Za-z0-9._-]+)\]\s*/.exec(message);
214
+ return match ? { message: message.slice(match[0].length), ctx: { channelId: match[1] } } : { message };
215
+ }
216
+ export function logInfo(message, details) {
217
+ const legacy = legacyContext(message);
218
+ logEvent("info", "system.info", legacy.message, {
219
+ ctx: legacy.ctx,
220
+ ...(details ? { details, fields: { reason: details } } : {}),
221
+ });
203
222
  }
204
223
  export function logWarning(message, details) {
205
- con(color("yellow", `${timestamp()} [system] ⚠ ${message}`));
206
- if (details) {
207
- const indented = details
208
- .split("\n")
209
- .map((line) => ` ${line}`)
210
- .join("\n");
211
- con(color("dim", indented));
212
- }
213
- emit("warn", "system", message, { details });
224
+ const legacy = legacyContext(message);
225
+ logEvent("warn", "system.warning", legacy.message, {
226
+ ctx: legacy.ctx,
227
+ ...(details ? { details, fields: { reason: details } } : {}),
228
+ });
214
229
  }
215
- // Model fallback (spec 017)
216
230
  export function logModelFallback(ctx, from, to, error) {
217
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} ⤳ Fallback ${from} → ${to}`));
218
- emit("warn", "model_fallback", `Fallback ${from} → ${to}`, {
219
- ctx,
220
- details: error,
221
- fields: { from, to, error },
222
- });
231
+ logEvent("warn", "agent.model.fallback", "Using fallback model", { ctx, fields: { from, to, error } });
223
232
  }
224
- // Usage summary
225
233
  export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
226
234
  const formatTokens = (count) => {
227
235
  if (count < 1000)
@@ -232,49 +240,38 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
232
240
  return `${Math.round(count / 1000)}k`;
233
241
  return `${(count / 1000000).toFixed(1)}M`;
234
242
  };
235
- const lines = [];
236
- lines.push("**Usage Summary**");
237
- lines.push(`Tokens: ${usage.input.toLocaleString()} in, ${usage.output.toLocaleString()} out`);
238
- if (usage.cacheRead > 0 || usage.cacheWrite > 0) {
239
- lines.push(`Cache: ${usage.cacheRead.toLocaleString()} read, ${usage.cacheWrite.toLocaleString()} write`);
240
- }
241
- if (contextTokens && contextWindow) {
242
- const contextPercent = ((contextTokens / contextWindow) * 100).toFixed(1);
243
- lines.push(`Context: ${formatTokens(contextTokens)} / ${formatTokens(contextWindow)} (${contextPercent}%)`);
244
- }
245
- lines.push(`Cost: $${usage.cost.input.toFixed(4)} in, $${usage.cost.output.toFixed(4)} out` +
246
- (usage.cacheRead > 0 || usage.cacheWrite > 0
247
- ? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`
248
- : ""));
249
- lines.push(`**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`);
250
- const summary = lines.join("\n");
251
- // Log to console
252
- con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💰 Usage`));
253
- con(color("dim", ` ${usage.input.toLocaleString()} in + ${usage.output.toLocaleString()} out` +
254
- (usage.cacheRead > 0 || usage.cacheWrite > 0
255
- ? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`
256
- : "") +
257
- ` = $${usage.cost.total.toFixed(4)}`));
258
- emit("info", "usage", `Total $${usage.cost.total.toFixed(4)} (incl. sub-agents)`, {
243
+ const lines = [
244
+ "**Usage Summary**",
245
+ `Tokens: ${usage.input.toLocaleString()} in, ${usage.output.toLocaleString()} out`,
246
+ ...(usage.cacheRead > 0 || usage.cacheWrite > 0
247
+ ? [`Cache: ${usage.cacheRead.toLocaleString()} read, ${usage.cacheWrite.toLocaleString()} write`]
248
+ : []),
249
+ ...(contextTokens && contextWindow
250
+ ? [
251
+ `Context: ${formatTokens(contextTokens)} / ${formatTokens(contextWindow)} (${((contextTokens / contextWindow) * 100).toFixed(1)}%)`,
252
+ ]
253
+ : []),
254
+ `Cost: $${usage.cost.input.toFixed(4)} in, $${usage.cost.output.toFixed(4)} out` +
255
+ (usage.cacheRead > 0 || usage.cacheWrite > 0
256
+ ? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`
257
+ : ""),
258
+ `**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`,
259
+ ];
260
+ logEvent("info", "agent.usage", "Usage recorded", {
259
261
  ctx,
260
262
  fields: {
261
- usage: {
262
- input: usage.input,
263
- output: usage.output,
264
- cacheRead: usage.cacheRead,
265
- cacheWrite: usage.cacheWrite,
266
- cost: usage.cost,
267
- },
263
+ input: usage.input,
264
+ output: usage.output,
265
+ cacheRead: usage.cacheRead,
266
+ cacheWrite: usage.cacheWrite,
267
+ cost: usage.cost,
268
268
  },
269
269
  });
270
- return summary;
270
+ return lines.join("\n");
271
271
  }
272
- // Startup
273
272
  export function logStartup(workingDir) {
274
- con("Starting pipiclaw...");
275
- con(` Working directory: ${workingDir}`);
273
+ logEvent("info", "runtime.started", "Starting pipiclaw", { fields: { workingDir } });
276
274
  }
277
275
  export function logConnected() {
278
- con("⚡️ pipiclaw connected and listening!");
279
- con("");
276
+ logEvent("info", "runtime.dingtalk.connected", "Connected and listening");
280
277
  }
@@ -3,4 +3,9 @@ export interface FirstTurnMemoryBootstrapOptions {
3
3
  workspaceMemory: string;
4
4
  maxChars?: number;
5
5
  }
6
+ export interface FirstTurnMemoryBootstrapResult {
7
+ renderedText: string;
8
+ includedCandidateIds: string[];
9
+ }
6
10
  export declare function buildFirstTurnMemoryBootstrap(options: FirstTurnMemoryBootstrapOptions): string;
11
+ export declare function buildFirstTurnMemoryBootstrapResult(options: FirstTurnMemoryBootstrapOptions): FirstTurnMemoryBootstrapResult;
@@ -1,5 +1,7 @@
1
1
  import { splitH2Sections } from "../shared/markdown-sections.js";
2
2
  import { clipText } from "../shared/text-utils.js";
3
+ import { buildMemoryCandidateId } from "./candidates.js";
4
+ import { parseChannelMemoryEntries } from "./files.js";
3
5
  const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
4
6
  const MIN_SECTION_BUDGET = 600;
5
7
  const CHANNEL_MEMORY_WEIGHT = 0.6;
@@ -55,11 +57,14 @@ function allocateBudgets(channelMemory, workspaceMemory, maxChars) {
55
57
  return [channelBudget + Math.max(0, remainder), workspaceBudget];
56
58
  }
57
59
  export function buildFirstTurnMemoryBootstrap(options) {
60
+ return buildFirstTurnMemoryBootstrapResult(options).renderedText;
61
+ }
62
+ export function buildFirstTurnMemoryBootstrapResult(options) {
58
63
  const maxChars = options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS;
59
64
  const channelMemory = normalizeContent(options.channelMemory);
60
65
  const workspaceMemory = normalizeContent(options.workspaceMemory);
61
66
  if (!channelMemory && !workspaceMemory) {
62
- return "";
67
+ return { renderedText: "", includedCandidateIds: [] };
63
68
  }
64
69
  const [channelBudget, workspaceBudget] = allocateBudgets(channelMemory, workspaceMemory, maxChars);
65
70
  const sections = [
@@ -67,14 +72,19 @@ export function buildFirstTurnMemoryBootstrap(options) {
67
72
  "Durable memory bootstrap for the first user turn in this session.",
68
73
  "Use it as background context together with any turn-specific recalled snippets.",
69
74
  ];
75
+ const includedCandidateIds = [];
70
76
  if (channelMemory) {
77
+ const selectedChannelMemory = channelBudget > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory;
71
78
  sections.push("", "[Channel MEMORY.md]");
72
- sections.push(channelBudget > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory);
79
+ sections.push(selectedChannelMemory);
80
+ includedCandidateIds.push(...parseChannelMemoryEntries(selectedChannelMemory).map((entry) => entry.id));
73
81
  }
74
82
  if (workspaceMemory) {
83
+ const selectedWorkspaceMemory = workspaceBudget > 0 ? clipText(workspaceMemory, workspaceBudget, { headRatio: 1 }) : workspaceMemory;
75
84
  sections.push("", "[Workspace MEMORY.md]");
76
- sections.push(workspaceBudget > 0 ? clipText(workspaceMemory, workspaceBudget, { headRatio: 1 }) : workspaceMemory);
85
+ sections.push(selectedWorkspaceMemory);
86
+ includedCandidateIds.push(...splitH2Sections(selectedWorkspaceMemory).map((section) => buildMemoryCandidateId("workspace-memory", section.heading)));
77
87
  }
78
88
  sections.push("</durable_memory_snapshot>");
79
- return sections.join("\n");
89
+ return { renderedText: sections.join("\n"), includedCandidateIds };
80
90
  }
@@ -8,11 +8,13 @@ export interface MemoryCandidate {
8
8
  timestamp?: string;
9
9
  sectionKind?: string;
10
10
  priority: number;
11
+ entryId?: string;
11
12
  }
12
13
  export interface BuildMemoryCandidatesOptions {
13
14
  workspaceDir: string;
14
15
  channelDir: string;
15
16
  }
17
+ export declare function buildMemoryCandidateId(source: MemoryCandidate["source"], title: string, timestamp?: string): string;
16
18
  export declare class MemoryCandidateStore {
17
19
  private files;
18
20
  private inflight;
@@ -2,7 +2,7 @@ import { stat } from "fs/promises";
2
2
  import { join } from "path";
3
3
  import { readOptionalTextFile } from "../shared/fs-utils.js";
4
4
  import { splitH1Sections, splitH2Sections } from "../shared/markdown-sections.js";
5
- import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, parseUpdateHeadingTimestamp, } from "./files.js";
5
+ import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, parseChannelMemoryEntries, parseUpdateHeadingTimestamp, } from "./files.js";
6
6
  function normalizeContent(content) {
7
7
  return content.replace(/\r/g, "").trim();
8
8
  }
@@ -61,10 +61,13 @@ const ENTRY_ID_COMMENT_GLOBAL = /\s*<!--\s*id:m-[a-z0-9]+\s*-->/gi;
61
61
  function stripEntryIdComments(text) {
62
62
  return text.replace(ENTRY_ID_COMMENT_GLOBAL, "");
63
63
  }
64
- function buildCandidate(source, path, title, content, timestamp, searchText) {
64
+ export function buildMemoryCandidateId(source, title, timestamp) {
65
+ return `${source}:${slugify(title)}:${timestamp ?? ""}`;
66
+ }
67
+ function buildCandidate(source, path, title, content, timestamp, searchText, id, entryId) {
65
68
  const cleanContent = stripEntryIdComments(content);
66
69
  return {
67
- id: `${source}:${slugify(title)}:${timestamp ?? ""}`,
70
+ id: id ?? buildMemoryCandidateId(source, title, timestamp),
68
71
  source,
69
72
  path,
70
73
  title,
@@ -73,9 +76,16 @@ function buildCandidate(source, path, title, content, timestamp, searchText) {
73
76
  timestamp,
74
77
  sectionKind: title.trim().toLowerCase(),
75
78
  priority: inferPriority(source, title),
79
+ entryId,
76
80
  };
77
81
  }
78
82
  function buildWorkspaceOrChannelMemoryCandidates(source, path, content) {
83
+ if (source === "channel-memory") {
84
+ const entries = parseChannelMemoryEntries(content);
85
+ if (entries.length > 0) {
86
+ return entries.map((entry) => buildCandidate(source, path, entry.sectionHeading, entry.content, entry.timestamp, entry.content, entry.id, entry.id));
87
+ }
88
+ }
79
89
  const sections = splitH2Sections(content);
80
90
  if (sections.length === 0 && content) {
81
91
  return [
@@ -0,0 +1,6 @@
1
+ interface MemoryCommandOptions {
2
+ channelDir: string;
3
+ args: string;
4
+ }
5
+ export declare function handleMemoryCommand(options: MemoryCommandOptions): Promise<string>;
6
+ export {};