@oyasmi/pipiclaw 0.8.6 → 0.8.7-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/channel-runner.d.ts +2 -0
- package/dist/agent/channel-runner.js +26 -6
- package/dist/agent/prompt/builder.d.ts +11 -20
- package/dist/agent/prompt/builder.js +40 -87
- package/dist/agent/prompt/manifest.d.ts +28 -2
- package/dist/agent/prompt/manifest.js +50 -11
- package/dist/agent/prompt/resources.d.ts +11 -2
- package/dist/agent/prompt/resources.js +51 -12
- package/dist/agent/prompt/sections.d.ts +9 -10
- package/dist/agent/prompt/sections.js +46 -99
- package/dist/agent/prompt/types.d.ts +14 -0
- package/dist/agent/session-events.js +17 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/log.d.ts +12 -20
- package/dist/log.js +195 -198
- package/dist/memory/bootstrap.d.ts +6 -0
- package/dist/memory/bootstrap.js +53 -21
- package/dist/memory/lifecycle.js +4 -1
- package/dist/memory/recall.d.ts +8 -0
- package/dist/memory/recall.js +19 -13
- package/dist/memory/task-digest.d.ts +4 -0
- package/dist/memory/task-digest.js +9 -3
- package/dist/playbooks/catalog.d.ts +7 -2
- package/dist/playbooks/catalog.js +10 -6
- package/dist/playbooks/event-scheduling.md +1 -1
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/runtime-orientation.md +1 -1
- package/dist/playbooks/task-closeout.md +1 -1
- package/dist/playbooks/task-delegation.md +1 -1
- package/dist/playbooks/task-driving.md +1 -1
- package/dist/playbooks/task-planning.md +1 -1
- package/dist/playbooks/task-recurring.md +1 -1
- package/dist/playbooks/task-repair.md +1 -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 +20 -8
- 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/shared/prompt-units.d.ts +46 -0
- package/dist/shared/prompt-units.js +153 -0
- 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
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
|
}
|
|
@@ -1,7 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Automatic-context share for the first-turn durable snapshot (spec 026 §5.3).
|
|
3
|
+
* It is a fallback, not a full memory dump: turn-specific recall carries the rest.
|
|
4
|
+
*/
|
|
5
|
+
export declare const FIRST_TURN_BOOTSTRAP_MAX_UNITS = 400;
|
|
1
6
|
export interface FirstTurnMemoryBootstrapOptions {
|
|
2
7
|
channelMemory: string;
|
|
3
8
|
workspaceMemory: string;
|
|
4
9
|
maxChars?: number;
|
|
10
|
+
maxUnits?: number;
|
|
5
11
|
}
|
|
6
12
|
export interface FirstTurnMemoryBootstrapResult {
|
|
7
13
|
renderedText: string;
|
package/dist/memory/bootstrap.js
CHANGED
|
@@ -1,72 +1,104 @@
|
|
|
1
1
|
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
2
|
-
import {
|
|
2
|
+
import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
|
|
3
3
|
import { buildMemoryCandidateId } from "./candidates.js";
|
|
4
4
|
import { parseChannelMemoryEntries } from "./files.js";
|
|
5
5
|
const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* Automatic-context share for the first-turn durable snapshot (spec 026 §5.3).
|
|
8
|
+
* It is a fallback, not a full memory dump: turn-specific recall carries the rest.
|
|
9
|
+
*/
|
|
10
|
+
export const FIRST_TURN_BOOTSTRAP_MAX_UNITS = 400;
|
|
11
|
+
const MIN_SECTION_CHARS = 600;
|
|
12
|
+
const MIN_SECTION_UNITS = 100;
|
|
7
13
|
const CHANNEL_MEMORY_WEIGHT = 0.6;
|
|
14
|
+
const ZERO_BUDGET = { chars: 0, units: 0 };
|
|
8
15
|
function normalizeContent(content) {
|
|
9
16
|
return content.replace(/\r/g, "").trim();
|
|
10
17
|
}
|
|
11
18
|
function hasVisibleContent(content) {
|
|
12
19
|
return content.replace(/<!--[\s\S]*?-->/g, "").trim().length > 0;
|
|
13
20
|
}
|
|
21
|
+
/** Keep `text` within both the char and unit ceilings, head/tail (or head-only when headRatio ≥ 1). */
|
|
22
|
+
function clipToBudget(text, budget, headRatio) {
|
|
23
|
+
return clipTextByPromptUnits(text, budget.units, {
|
|
24
|
+
headRatio,
|
|
25
|
+
maxChars: budget.chars,
|
|
26
|
+
marker: "\n\n[... omitted for length ...]\n\n",
|
|
27
|
+
}).text;
|
|
28
|
+
}
|
|
14
29
|
// Channel MEMORY.md is "structured sections up top, `## Update <ts>` blocks appended
|
|
15
30
|
// at the tail". A plain head clip would drop the newest facts, so pick sections by
|
|
16
31
|
// priority (structured first, then newest Update blocks) but render in document order
|
|
17
|
-
// for readability.
|
|
32
|
+
// for readability. A section is kept only if it fits both the char and unit budget.
|
|
18
33
|
function selectChannelMemoryForBootstrap(content, budget) {
|
|
19
34
|
const sections = splitH2Sections(content).filter((section) => hasVisibleContent(section.content));
|
|
20
35
|
if (sections.length === 0) {
|
|
21
|
-
return
|
|
36
|
+
return clipToBudget(content, budget, 1);
|
|
22
37
|
}
|
|
23
38
|
const renderSection = (section) => `## ${section.heading}\n\n${section.content}`;
|
|
24
39
|
const structured = sections.filter((section) => !section.heading.startsWith("Update "));
|
|
25
40
|
const updatesNewestFirst = sections.filter((section) => section.heading.startsWith("Update ")).reverse();
|
|
26
41
|
const byPriority = [...structured, ...updatesNewestFirst];
|
|
27
42
|
const chosen = new Set();
|
|
28
|
-
let
|
|
43
|
+
let usedChars = 0;
|
|
44
|
+
let usedUnits = 0;
|
|
29
45
|
for (const section of byPriority) {
|
|
30
|
-
const
|
|
31
|
-
|
|
46
|
+
const text = renderSection(section);
|
|
47
|
+
const separatorChars = chosen.size > 0 ? 2 : 0;
|
|
48
|
+
const costChars = separatorChars + text.length;
|
|
49
|
+
const costUnits = countPromptUnits(text); // section separators are whitespace → 0 units
|
|
50
|
+
if (usedChars + costChars <= budget.chars && usedUnits + costUnits <= budget.units) {
|
|
32
51
|
chosen.add(section);
|
|
33
|
-
|
|
52
|
+
usedChars += costChars;
|
|
53
|
+
usedUnits += costUnits;
|
|
34
54
|
}
|
|
35
55
|
}
|
|
36
56
|
if (chosen.size === 0) {
|
|
37
|
-
return
|
|
57
|
+
return clipToBudget(renderSection(byPriority[0]), budget, 0.5);
|
|
38
58
|
}
|
|
39
59
|
return sections
|
|
40
60
|
.filter((section) => chosen.has(section))
|
|
41
61
|
.map(renderSection)
|
|
42
62
|
.join("\n\n");
|
|
43
63
|
}
|
|
44
|
-
|
|
64
|
+
/** Split the total budget across channel (60%) and workspace memory in both dimensions. */
|
|
65
|
+
function splitBudget(max) {
|
|
66
|
+
const channelChars = Math.max(MIN_SECTION_CHARS, Math.floor(max.chars * CHANNEL_MEMORY_WEIGHT));
|
|
67
|
+
const workspaceChars = Math.max(MIN_SECTION_CHARS, max.chars - channelChars);
|
|
68
|
+
const channelUnits = Math.max(MIN_SECTION_UNITS, Math.floor(max.units * CHANNEL_MEMORY_WEIGHT));
|
|
69
|
+
const workspaceUnits = Math.max(MIN_SECTION_UNITS, max.units - channelUnits);
|
|
70
|
+
const channel = {
|
|
71
|
+
chars: channelChars + Math.max(0, max.chars - channelChars - workspaceChars),
|
|
72
|
+
units: channelUnits + Math.max(0, max.units - channelUnits - workspaceUnits),
|
|
73
|
+
};
|
|
74
|
+
return [channel, { chars: workspaceChars, units: workspaceUnits }];
|
|
75
|
+
}
|
|
76
|
+
function allocateBudgets(channelMemory, workspaceMemory, max) {
|
|
45
77
|
if (!channelMemory && !workspaceMemory) {
|
|
46
|
-
return [
|
|
78
|
+
return [ZERO_BUDGET, ZERO_BUDGET];
|
|
47
79
|
}
|
|
48
80
|
if (!channelMemory) {
|
|
49
|
-
return [
|
|
81
|
+
return [ZERO_BUDGET, max];
|
|
50
82
|
}
|
|
51
83
|
if (!workspaceMemory) {
|
|
52
|
-
return [
|
|
84
|
+
return [max, ZERO_BUDGET];
|
|
53
85
|
}
|
|
54
|
-
|
|
55
|
-
const workspaceBudget = Math.max(MIN_SECTION_BUDGET, maxChars - channelBudget);
|
|
56
|
-
const remainder = maxChars - channelBudget - workspaceBudget;
|
|
57
|
-
return [channelBudget + Math.max(0, remainder), workspaceBudget];
|
|
86
|
+
return splitBudget(max);
|
|
58
87
|
}
|
|
59
88
|
export function buildFirstTurnMemoryBootstrap(options) {
|
|
60
89
|
return buildFirstTurnMemoryBootstrapResult(options).renderedText;
|
|
61
90
|
}
|
|
62
91
|
export function buildFirstTurnMemoryBootstrapResult(options) {
|
|
63
|
-
const
|
|
92
|
+
const max = {
|
|
93
|
+
chars: options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS,
|
|
94
|
+
units: options.maxUnits ?? FIRST_TURN_BOOTSTRAP_MAX_UNITS,
|
|
95
|
+
};
|
|
64
96
|
const channelMemory = normalizeContent(options.channelMemory);
|
|
65
97
|
const workspaceMemory = normalizeContent(options.workspaceMemory);
|
|
66
98
|
if (!channelMemory && !workspaceMemory) {
|
|
67
99
|
return { renderedText: "", includedCandidateIds: [] };
|
|
68
100
|
}
|
|
69
|
-
const [channelBudget, workspaceBudget] = allocateBudgets(channelMemory, workspaceMemory,
|
|
101
|
+
const [channelBudget, workspaceBudget] = allocateBudgets(channelMemory, workspaceMemory, max);
|
|
70
102
|
const sections = [
|
|
71
103
|
"<durable_memory_snapshot>",
|
|
72
104
|
"Durable memory bootstrap for the first user turn in this session.",
|
|
@@ -74,13 +106,13 @@ export function buildFirstTurnMemoryBootstrapResult(options) {
|
|
|
74
106
|
];
|
|
75
107
|
const includedCandidateIds = [];
|
|
76
108
|
if (channelMemory) {
|
|
77
|
-
const selectedChannelMemory = channelBudget > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory;
|
|
109
|
+
const selectedChannelMemory = channelBudget.chars > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory;
|
|
78
110
|
sections.push("", "[Channel MEMORY.md]");
|
|
79
111
|
sections.push(selectedChannelMemory);
|
|
80
112
|
includedCandidateIds.push(...parseChannelMemoryEntries(selectedChannelMemory).map((entry) => entry.id));
|
|
81
113
|
}
|
|
82
114
|
if (workspaceMemory) {
|
|
83
|
-
const selectedWorkspaceMemory = workspaceBudget > 0 ?
|
|
115
|
+
const selectedWorkspaceMemory = workspaceBudget.chars > 0 ? clipToBudget(workspaceMemory, workspaceBudget, 1) : workspaceMemory;
|
|
84
116
|
sections.push("", "[Workspace MEMORY.md]");
|
|
85
117
|
sections.push(selectedWorkspaceMemory);
|
|
86
118
|
includedCandidateIds.push(...splitH2Sections(selectedWorkspaceMemory).map((section) => buildMemoryCandidateId("workspace-memory", section.heading)));
|
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"}`);
|
package/dist/memory/recall.d.ts
CHANGED
|
@@ -10,6 +10,12 @@ export interface RecallRequest {
|
|
|
10
10
|
maxCandidates: number;
|
|
11
11
|
maxInjected: number;
|
|
12
12
|
maxChars: number;
|
|
13
|
+
/**
|
|
14
|
+
* Runtime hard cap in prompt units for the automatic turn context (spec 026 §5.3);
|
|
15
|
+
* whichever of chars/units binds first clips. Omitted for explicit searches, which
|
|
16
|
+
* budget in characters only.
|
|
17
|
+
*/
|
|
18
|
+
maxUnits?: number;
|
|
13
19
|
rerankWithModel: boolean | "auto";
|
|
14
20
|
autoRerank?: boolean;
|
|
15
21
|
model: Model<Api>;
|
|
@@ -29,5 +35,7 @@ export interface RecallResult {
|
|
|
29
35
|
items: RecalledMemory[];
|
|
30
36
|
renderedText: string;
|
|
31
37
|
}
|
|
38
|
+
/** Automatic-context share for relevant memory recall (spec 026 §5.3). */
|
|
39
|
+
export declare const MEMORY_RECALL_MAX_UNITS = 1800;
|
|
32
40
|
export declare function tokenizeRecallText(text: string): string[];
|
|
33
41
|
export declare function recallRelevantMemory(request: RecallRequest): Promise<RecallResult>;
|