@oyasmi/pipiclaw 0.8.6 → 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.
- package/dist/agent/channel-runner.js +8 -2
- package/dist/agent/session-events.js +17 -5
- package/dist/log.d.ts +12 -20
- package/dist/log.js +195 -198
- package/dist/memory/lifecycle.js +4 -1
- package/dist/runtime/bootstrap.d.ts +1 -0
- package/dist/runtime/bootstrap.js +41 -11
- package/dist/runtime/dingtalk.js +19 -6
- package/dist/runtime/events.d.ts +2 -0
- package/dist/runtime/events.js +14 -7
- package/dist/runtime/store.d.ts +4 -6
- package/dist/runtime/store.js +44 -40
- package/dist/security/logger.d.ts +3 -1
- package/dist/security/logger.js +33 -10
- package/dist/shared/jsonl-appender.d.ts +27 -8
- package/dist/shared/jsonl-appender.js +128 -41
- package/dist/tools/bash.js +1 -1
- package/dist/tools/edit.js +1 -1
- package/dist/tools/grep.js +1 -1
- package/dist/tools/read.js +1 -1
- package/dist/tools/write-content.js +1 -1
- package/dist/tui/app.js +17 -0
- package/dist/usage/ledger.d.ts +2 -0
- package/dist/usage/ledger.js +3 -1
- package/dist/web/client.js +3 -3
- package/package.json +1 -1
|
@@ -281,7 +281,10 @@ export class ChannelRunner {
|
|
|
281
281
|
catch (err) {
|
|
282
282
|
this.runState.stopReason = "error";
|
|
283
283
|
this.runState.errorMessage = errorMessage(err);
|
|
284
|
-
log.
|
|
284
|
+
log.logEvent("error", "agent.turn.failed", "Runner failed", {
|
|
285
|
+
ctx: this.runState.logCtx ?? { channelId: this.channelId },
|
|
286
|
+
fields: { error: this.runState.errorMessage },
|
|
287
|
+
});
|
|
285
288
|
}
|
|
286
289
|
},
|
|
287
290
|
getRunError: () => ({
|
|
@@ -326,7 +329,10 @@ export class ChannelRunner {
|
|
|
326
329
|
catch (err) {
|
|
327
330
|
this.runState.stopReason = "error";
|
|
328
331
|
this.runState.errorMessage = errorMessage(err);
|
|
329
|
-
log.
|
|
332
|
+
log.logEvent("error", "agent.turn.failed", "Runner failed", {
|
|
333
|
+
ctx: this.runState.logCtx ?? { channelId: this.channelId },
|
|
334
|
+
fields: { error: this.runState.errorMessage },
|
|
335
|
+
});
|
|
330
336
|
}
|
|
331
337
|
finally {
|
|
332
338
|
this.turn.phase = "finishing";
|
|
@@ -251,7 +251,10 @@ export async function handleSessionEvent(event, context) {
|
|
|
251
251
|
}
|
|
252
252
|
if (isAutoCompactionStartEvent(event)) {
|
|
253
253
|
const label = "Compacting context...";
|
|
254
|
-
log.
|
|
254
|
+
log.logEvent("info", "agent.compaction.started", "Compaction started", {
|
|
255
|
+
ctx: logCtx,
|
|
256
|
+
fields: { reason: event.reason },
|
|
257
|
+
});
|
|
255
258
|
if (showProgress) {
|
|
256
259
|
queue.enqueue(() => ctx.respond(formatProgressEntry("assistant", label), false), "compaction start");
|
|
257
260
|
}
|
|
@@ -260,14 +263,20 @@ export async function handleSessionEvent(event, context) {
|
|
|
260
263
|
if (isAutoCompactionEndEvent(event)) {
|
|
261
264
|
if (event.result) {
|
|
262
265
|
runState.lastCompactionError = undefined;
|
|
263
|
-
log.
|
|
266
|
+
log.logEvent("info", "agent.compaction.finished", "Compaction completed", {
|
|
267
|
+
ctx: logCtx,
|
|
268
|
+
fields: { tokensBefore: event.result.tokensBefore },
|
|
269
|
+
});
|
|
264
270
|
}
|
|
265
271
|
else if (event.aborted) {
|
|
266
|
-
log.
|
|
272
|
+
log.logEvent("info", "agent.compaction.aborted", "Compaction aborted", { ctx: logCtx });
|
|
267
273
|
}
|
|
268
274
|
else if (event.errorMessage) {
|
|
269
275
|
runState.lastCompactionError = event.errorMessage;
|
|
270
|
-
log.
|
|
276
|
+
log.logEvent("warn", "agent.compaction.failed", "Compaction failed", {
|
|
277
|
+
ctx: logCtx,
|
|
278
|
+
fields: { error: event.errorMessage },
|
|
279
|
+
});
|
|
271
280
|
if (showProgress) {
|
|
272
281
|
queue.enqueue(() => ctx.respond(formatProgressEntry("error", truncate(event.errorMessage ?? "Compaction failed", 200)), false), "compaction error");
|
|
273
282
|
}
|
|
@@ -275,7 +284,10 @@ export async function handleSessionEvent(event, context) {
|
|
|
275
284
|
return;
|
|
276
285
|
}
|
|
277
286
|
if (isAutoRetryStartEvent(event)) {
|
|
278
|
-
log.
|
|
287
|
+
log.logEvent("warn", "agent.retrying", "Retrying model request", {
|
|
288
|
+
ctx: logCtx,
|
|
289
|
+
fields: { attempt: event.attempt, maxAttempts: event.maxAttempts, error: event.errorMessage },
|
|
290
|
+
});
|
|
279
291
|
if (showProgress) {
|
|
280
292
|
queue.enqueue(() => ctx.respond(formatProgressEntry("assistant", `Retrying (${event.attempt}/${event.maxAttempts})...`), false), "retry");
|
|
281
293
|
}
|
package/dist/log.d.ts
CHANGED
|
@@ -4,16 +4,6 @@ export interface LogContext {
|
|
|
4
4
|
channelName?: string;
|
|
5
5
|
}
|
|
6
6
|
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
7
|
-
export interface LogRecord {
|
|
8
|
-
ts: string;
|
|
9
|
-
level: LogLevel;
|
|
10
|
-
event: string;
|
|
11
|
-
channelId?: string;
|
|
12
|
-
userName?: string;
|
|
13
|
-
message: string;
|
|
14
|
-
details?: string;
|
|
15
|
-
fields?: Record<string, unknown>;
|
|
16
|
-
}
|
|
17
7
|
export interface LoggingConfig {
|
|
18
8
|
level: LogLevel;
|
|
19
9
|
file: {
|
|
@@ -22,24 +12,26 @@ export interface LoggingConfig {
|
|
|
22
12
|
maxFiles: number;
|
|
23
13
|
};
|
|
24
14
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
15
|
+
export interface LogOptions {
|
|
16
|
+
ctx?: LogContext;
|
|
17
|
+
details?: string;
|
|
18
|
+
fields?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
/** Configure both console filtering and the optional structured file sink. */
|
|
29
21
|
export declare function configureLogging(config: LoggingConfig): void;
|
|
30
|
-
/**
|
|
31
|
-
* Toggle the human-readable console sink. The TUI disables it so structured
|
|
32
|
-
* logging does not corrupt the pi-tui frame (which owns stdout); the file sink
|
|
33
|
-
* is unaffected, so logs are still captured when file logging is enabled.
|
|
34
|
-
*/
|
|
22
|
+
/** The TUI owns stdout, so its runtime logs are file-only. */
|
|
35
23
|
export declare function setConsoleLoggingEnabled(enabled: boolean): void;
|
|
24
|
+
/** Wait for structured logs accepted so far to reach disk. */
|
|
25
|
+
export declare function flushLogging(): Promise<void>;
|
|
26
|
+
/** Emit one consistently formatted runtime event to stdout and the JSONL sink. */
|
|
27
|
+
export declare function logEvent(level: LogLevel, event: string, message: string, options?: LogOptions): void;
|
|
36
28
|
export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
|
|
37
29
|
export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;
|
|
38
30
|
export declare function logToolError(ctx: LogContext, toolName: string, durationMs: number, error: string): void;
|
|
39
31
|
export declare function logResponseStart(ctx: LogContext): void;
|
|
40
32
|
export declare function logThinking(ctx: LogContext, thinking: string): void;
|
|
41
33
|
export declare function logResponse(ctx: LogContext, text: string): void;
|
|
42
|
-
export declare function logInfo(message: string): void;
|
|
34
|
+
export declare function logInfo(message: string, details?: string): void;
|
|
43
35
|
export declare function logWarning(message: string, details?: string): void;
|
|
44
36
|
export declare function logModelFallback(ctx: LogContext, from: string, to: string, error: string): void;
|
|
45
37
|
export declare function logUsageSummary(ctx: LogContext, usage: {
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
70
|
-
|
|
71
|
-
console.log(...args);
|
|
44
|
+
function isEnabled(level) {
|
|
45
|
+
return LEVEL_ORDER[level] >= LEVEL_ORDER[thresholdLevel];
|
|
72
46
|
}
|
|
73
|
-
function
|
|
74
|
-
|
|
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
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
|
|
90
|
-
const user = ctx.userName || "unknown";
|
|
91
|
-
return `[${channel}:${user}]`;
|
|
97
|
+
return result;
|
|
92
98
|
}
|
|
93
|
-
function
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
156
|
-
fields: { toolName, durationMs,
|
|
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
|
-
|
|
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:
|
|
171
|
-
fields: { toolName, durationMs,
|
|
193
|
+
details: error,
|
|
194
|
+
fields: { tool: toolName, durationMs, error },
|
|
172
195
|
});
|
|
173
196
|
}
|
|
174
|
-
// Response streaming
|
|
175
197
|
export function logResponseStart(ctx) {
|
|
176
|
-
|
|
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
|
-
|
|
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
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
.
|
|
194
|
-
|
|
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
|
-
//
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
-
|
|
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
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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
|
|
270
|
+
return lines.join("\n");
|
|
271
271
|
}
|
|
272
|
-
// Startup
|
|
273
272
|
export function logStartup(workingDir) {
|
|
274
|
-
|
|
275
|
-
con(` Working directory: ${workingDir}`);
|
|
273
|
+
logEvent("info", "runtime.started", "Starting pipiclaw", { fields: { workingDir } });
|
|
276
274
|
}
|
|
277
275
|
export function logConnected() {
|
|
278
|
-
|
|
279
|
-
con("");
|
|
276
|
+
logEvent("info", "runtime.dingtalk.connected", "Connected and listening");
|
|
280
277
|
}
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -132,7 +132,10 @@ export class MemoryLifecycle {
|
|
|
132
132
|
}
|
|
133
133
|
logConsolidationResult(reason, result) {
|
|
134
134
|
if (result.skipped) {
|
|
135
|
-
log.
|
|
135
|
+
log.logEvent("debug", "memory.consolidation.skipped", "No meaningful snapshot", {
|
|
136
|
+
ctx: { channelId: this.options.channelId },
|
|
137
|
+
fields: { reason },
|
|
138
|
+
});
|
|
136
139
|
return;
|
|
137
140
|
}
|
|
138
141
|
log.logInfo(`[${this.options.channelId}] Memory consolidation finished (${reason}): memory entries=${result.appendedMemoryEntries}, history=${result.appendedHistoryBlock ? "yes" : "no"}`);
|
|
@@ -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;
|