@oyasmi/pipiclaw 0.7.0-beta.1 → 0.7.0

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 (43) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +19 -0
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +6 -0
  5. package/dist/agent/session-events.d.ts +2 -0
  6. package/dist/agent/session-events.js +31 -12
  7. package/dist/agent/types.d.ts +2 -0
  8. package/dist/agent/types.js +8 -0
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/log.d.ts +24 -0
  12. package/dist/log.js +96 -1
  13. package/dist/memory/consolidation.d.ts +1 -0
  14. package/dist/memory/consolidation.js +8 -3
  15. package/dist/memory/lifecycle.js +2 -0
  16. package/dist/memory/maintenance-jobs.js +1 -0
  17. package/dist/memory/post-turn-review.js +1 -0
  18. package/dist/memory/recall.d.ts +1 -0
  19. package/dist/memory/recall.js +1 -0
  20. package/dist/memory/session-search.d.ts +1 -0
  21. package/dist/memory/session-search.js +1 -0
  22. package/dist/memory/session.d.ts +1 -0
  23. package/dist/memory/session.js +1 -0
  24. package/dist/memory/sidecar-worker.d.ts +4 -0
  25. package/dist/memory/sidecar-worker.js +29 -0
  26. package/dist/paths.d.ts +3 -0
  27. package/dist/paths.js +3 -0
  28. package/dist/runtime/bootstrap.js +11 -0
  29. package/dist/runtime/dingtalk.d.ts +1 -0
  30. package/dist/runtime/dingtalk.js +4 -0
  31. package/dist/settings.d.ts +12 -0
  32. package/dist/settings.js +20 -0
  33. package/dist/shared/jsonl-appender.d.ts +25 -0
  34. package/dist/shared/jsonl-appender.js +85 -0
  35. package/dist/subagents/tool.js +1 -0
  36. package/dist/tools/registry.js +1 -0
  37. package/dist/tools/session-search.d.ts +1 -0
  38. package/dist/tools/session-search.js +1 -0
  39. package/dist/usage/ledger.d.ts +47 -0
  40. package/dist/usage/ledger.js +95 -0
  41. package/dist/usage/render.d.ts +11 -0
  42. package/dist/usage/render.js +67 -0
  43. package/package.json +1 -1
@@ -17,6 +17,7 @@ export declare class ChannelRunner implements AgentRunner {
17
17
  private readonly settingsManager;
18
18
  private readonly modelRegistry;
19
19
  private readonly memoryLifecycle;
20
+ private readonly ledger;
20
21
  private readonly memoryCandidateStore;
21
22
  private readonly sessionResourceGate;
22
23
  private readonly sessionReady;
@@ -22,6 +22,7 @@ import { discoverSubAgents, formatSubAgentList } from "../subagents/discovery.js
22
22
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
23
23
  import { createPipiclawTools } from "../tools/index.js";
24
24
  import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
25
+ import { getUsageLedger } from "../usage/ledger.js";
25
26
  import { createCommandExtension } from "./command-extension.js";
26
27
  import { renderBuiltInHelp } from "./commands.js";
27
28
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
@@ -53,6 +54,7 @@ function asSdkSettingsManager(manager) {
53
54
  }
54
55
  export class ChannelRunner {
55
56
  constructor(sandboxConfig, channelId, channelDir) {
57
+ this.ledger = getUsageLedger();
56
58
  this.currentTools = [];
57
59
  this.firstTurnMemoryBootstrapPending = true;
58
60
  this.acceptingBusyMessages = false;
@@ -169,6 +171,7 @@ export class ChannelRunner {
169
171
  if (recallSettings.enabled) {
170
172
  const recall = await recallRelevantMemory({
171
173
  query: clippedInput,
174
+ channelId: this.channelId,
172
175
  workspaceDir: this.workspaceDir,
173
176
  channelDir: this.channelDir,
174
177
  maxCandidates: recallSettings.maxCandidates,
@@ -299,6 +302,21 @@ export class ChannelRunner {
299
302
  const contextWindow = currentRunModel.contextWindow || 200000;
300
303
  log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
301
304
  const responseModel = lastAssistantMessage?.responseModel;
305
+ // Ledger turn entry: assistant-only usage (sub-agents recorded separately),
306
+ // keeping Σ(entries) == real spend with no double counting.
307
+ this.ledger.record({
308
+ channelId: this.channelId,
309
+ kind: "turn",
310
+ model: responseModel ?? formatModelReference(currentRunModel),
311
+ usage: {
312
+ input: this.runState.assistantUsage.input,
313
+ output: this.runState.assistantUsage.output,
314
+ cacheRead: this.runState.assistantUsage.cacheRead,
315
+ cacheWrite: this.runState.assistantUsage.cacheWrite,
316
+ total: this.runState.assistantUsage.total,
317
+ },
318
+ cost: { ...this.runState.assistantUsage.cost },
319
+ });
302
320
  if (responseModel &&
303
321
  responseModel !== formatModelReference(currentRunModel) &&
304
322
  responseModel !== currentRunModel.id) {
@@ -707,6 +725,7 @@ export class ChannelRunner {
707
725
  store: this.runState.store,
708
726
  runState: this.runState,
709
727
  memoryLifecycle: this.memoryLifecycle,
728
+ ledger: this.ledger,
710
729
  refreshSessionResources: async () => {
711
730
  await this.refreshSessionResources();
712
731
  },
@@ -1,4 +1,4 @@
1
- export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "status";
1
+ export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "status" | "usage";
2
2
  export interface BuiltInCommand {
3
3
  name: BuiltInCommandName;
4
4
  args: string;
@@ -27,6 +27,11 @@ These are handled directly by the DingTalk transport/runtime layer.
27
27
  - \`/status\`
28
28
  Show runtime status: run state, current model, context usage, uptime, version
29
29
  Example: \`/status\`
30
+ - \`/usage [7d|month]\`
31
+ Show LLM cost for this channel and globally, broken down by kind and top models
32
+ Example: \`/usage\`
33
+ Example: \`/usage 7d\`
34
+ Example: \`/usage month\`
30
35
 
31
36
  While a task is running, plain messages use the configured busy-message default. The default is \`steer\`; set \`busyMessageDefault\` in channel.json to \`followUp\` or \`followup\` to queue plain messages after the current task.
32
37
 
@@ -66,6 +71,7 @@ export function parseBuiltInCommand(text) {
66
71
  case "stop":
67
72
  case "events":
68
73
  case "status":
74
+ case "usage":
69
75
  return { name: rawName, args, rawText };
70
76
  default:
71
77
  return null;
@@ -1,6 +1,7 @@
1
1
  import type { MemoryLifecycle } from "../memory/lifecycle.js";
2
2
  import type { DingTalkContext } from "../runtime/dingtalk.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
+ import type { UsageLedger } from "../usage/ledger.js";
4
5
  import type { PendingTool, RunLogContext, RunQueue, RunState } from "./types.js";
5
6
  export interface SessionEventHandlerContext {
6
7
  ctx: DingTalkContext;
@@ -10,6 +11,7 @@ export interface SessionEventHandlerContext {
10
11
  store: ChannelStore | null;
11
12
  runState: RunState;
12
13
  memoryLifecycle: MemoryLifecycle;
14
+ ledger: UsageLedger;
13
15
  refreshSessionResources?: () => Promise<void>;
14
16
  }
15
17
  export declare function handleSessionEvent(event: unknown, context: SessionEventHandlerContext): Promise<void>;
@@ -18,21 +18,26 @@ function mergeSubAgentUsage(totalUsage, details) {
18
18
  totalUsage.cost.cacheWrite += details.usage.cost.cacheWrite;
19
19
  totalUsage.cost.total += details.usage.cost.total;
20
20
  }
21
+ function addUsage(target, usage) {
22
+ target.input += usage.input;
23
+ target.output += usage.output;
24
+ target.cacheRead += usage.cacheRead;
25
+ target.cacheWrite += usage.cacheWrite;
26
+ target.total += usage.total ?? usage.totalTokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
27
+ target.cost.input += usage.cost.input;
28
+ target.cost.output += usage.cost.output;
29
+ target.cost.cacheRead += usage.cost.cacheRead;
30
+ target.cost.cacheWrite += usage.cost.cacheWrite;
31
+ target.cost.total += usage.cost.total;
32
+ }
21
33
  function mergeAssistantUsage(runState, usage) {
22
- runState.totalUsage.input += usage.input;
23
- runState.totalUsage.output += usage.output;
24
- runState.totalUsage.cacheRead += usage.cacheRead;
25
- runState.totalUsage.cacheWrite += usage.cacheWrite;
26
- runState.totalUsage.total +=
27
- usage.total ?? usage.totalTokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
28
- runState.totalUsage.cost.input += usage.cost.input;
29
- runState.totalUsage.cost.output += usage.cost.output;
30
- runState.totalUsage.cost.cacheRead += usage.cost.cacheRead;
31
- runState.totalUsage.cost.cacheWrite += usage.cost.cacheWrite;
32
- runState.totalUsage.cost.total += usage.cost.total;
34
+ // totalUsage stays the console-summary tally (assistant + sub-agents).
35
+ // assistantUsage is the ledger's assistant-only "turn" tally.
36
+ addUsage(runState.totalUsage, usage);
37
+ addUsage(runState.assistantUsage, usage);
33
38
  }
34
39
  export async function handleSessionEvent(event, context) {
35
- const { ctx, logCtx, queue, pendingTools, store, runState, memoryLifecycle } = context;
40
+ const { ctx, logCtx, queue, pendingTools, store, runState, memoryLifecycle, ledger } = context;
36
41
  const showProgress = ctx.progressStyle !== "none";
37
42
  const finalToCard = ctx.finalDelivery === "card";
38
43
  if (isToolExecutionStartEvent(event)) {
@@ -81,6 +86,20 @@ export async function handleSessionEvent(event, context) {
81
86
  typeof pending.args.label === "string"
82
87
  ? (pending.args.label ?? "subagent").trim()
83
88
  : "subagent";
89
+ ledger.record({
90
+ channelId: logCtx.channelId,
91
+ kind: "subagent",
92
+ model: subAgentDetails.model,
93
+ label,
94
+ usage: {
95
+ input: subAgentDetails.usage.input,
96
+ output: subAgentDetails.usage.output,
97
+ cacheRead: subAgentDetails.usage.cacheRead,
98
+ cacheWrite: subAgentDetails.usage.cacheWrite,
99
+ total: subAgentDetails.usage.total,
100
+ },
101
+ cost: { ...subAgentDetails.usage.cost },
102
+ });
84
103
  queue.enqueue(() => store?.logSubAgentRun(logCtx.channelId, {
85
104
  date: new Date().toISOString(),
86
105
  toolCallId: event.toolCallId,
@@ -50,6 +50,8 @@ export interface RunState {
50
50
  queue: RunQueue | null;
51
51
  pendingTools: Map<string, PendingTool>;
52
52
  totalUsage: UsageTotals;
53
+ /** Main-loop assistant usage only (excludes sub-agents). Feeds the turn ledger entry. */
54
+ assistantUsage: UsageTotals;
53
55
  stopReason: string;
54
56
  errorMessage: string | undefined;
55
57
  lastCompactionError: string | undefined;
@@ -13,6 +13,14 @@ export function createEmptyRunState() {
13
13
  total: 0,
14
14
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
15
15
  },
16
+ assistantUsage: {
17
+ input: 0,
18
+ output: 0,
19
+ cacheRead: 0,
20
+ cacheWrite: 0,
21
+ total: 0,
22
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
23
+ },
16
24
  stopReason: "stop",
17
25
  errorMessage: undefined,
18
26
  lastCompactionError: undefined,
package/dist/index.d.ts CHANGED
@@ -24,3 +24,5 @@ export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSu
24
24
  export { createSubAgentTool, type SubAgentToolDetails, type SubAgentToolOptions, } from "./subagents/tool.js";
25
25
  export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, type PipiclawToolsConfig, type PipiclawWebFetchConfig, type PipiclawWebSearchConfig, type PipiclawWebToolsConfig, } from "./tools/config.js";
26
26
  export { type CreatePipiclawToolsOptions, createPipiclawBaseTools, createPipiclawTools, } from "./tools/index.js";
27
+ export { createUsageLedger, getUsageLedger, type UsageKind, type UsageLedger, type UsageLedgerEntry, type UsageSummary, } from "./usage/ledger.js";
28
+ export { parseUsageMode, renderUsageReport, type UsageQueryMode, usageWindows } from "./usage/render.js";
package/dist/index.js CHANGED
@@ -24,3 +24,5 @@ export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, resolveSubAgent
24
24
  export { createSubAgentTool, } from "./subagents/tool.js";
25
25
  export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, } from "./tools/config.js";
26
26
  export { createPipiclawBaseTools, createPipiclawTools, } from "./tools/index.js";
27
+ export { createUsageLedger, getUsageLedger, } from "./usage/ledger.js";
28
+ export { parseUsageMode, renderUsageReport, usageWindows } from "./usage/render.js";
package/dist/log.d.ts CHANGED
@@ -3,6 +3,30 @@ export interface LogContext {
3
3
  userName?: string;
4
4
  channelName?: string;
5
5
  }
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
+ export interface LoggingConfig {
18
+ level: LogLevel;
19
+ file: {
20
+ enabled: boolean;
21
+ maxSizeBytes: number;
22
+ maxFiles: number;
23
+ };
24
+ }
25
+ /**
26
+ * Configure the file sink from loaded settings. Env vars take precedence and
27
+ * have already applied at module load; this reconciles the two.
28
+ */
29
+ export declare function configureLogging(config: LoggingConfig): void;
6
30
  export declare function logUserMessage(ctx: LogContext, text: string): void;
7
31
  export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
8
32
  export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;
package/dist/log.js CHANGED
@@ -1,4 +1,62 @@
1
1
  import { styleText } from "node:util";
2
+ import { RUNTIME_LOG_PATH } from "./paths.js";
3
+ import { createJsonlAppender } from "./shared/jsonl-appender.js";
4
+ const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
5
+ function readEnvLevel() {
6
+ const raw = process.env.PIPICLAW_LOG_LEVEL?.trim().toLowerCase();
7
+ if (raw && raw in LEVEL_ORDER) {
8
+ return raw;
9
+ }
10
+ return undefined;
11
+ }
12
+ function readEnvFileEnabled() {
13
+ const raw = process.env.PIPICLAW_LOG_FILE?.trim();
14
+ if (raw === "1" || raw === "true")
15
+ return true;
16
+ if (raw === "0" || raw === "false")
17
+ return false;
18
+ return undefined;
19
+ }
20
+ const envLevel = readEnvLevel();
21
+ const envFileEnabled = readEnvFileEnabled();
22
+ 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
27
+ ? createJsonlAppender({ path: RUNTIME_LOG_PATH, maxSizeBytes: 5_000_000, maxRotations: 3 })
28
+ : 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
+ */
33
+ export function configureLogging(config) {
34
+ thresholdLevel = envLevel ?? config.level;
35
+ const enabled = envFileEnabled ?? config.file.enabled;
36
+ fileSink = enabled
37
+ ? createJsonlAppender({
38
+ path: RUNTIME_LOG_PATH,
39
+ maxSizeBytes: config.file.maxSizeBytes,
40
+ maxRotations: config.file.maxFiles,
41
+ })
42
+ : null;
43
+ }
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
+ }
2
60
  function color(style, text) {
3
61
  return styleText(style, text);
4
62
  }
@@ -54,6 +112,7 @@ function formatToolArgs(args) {
54
112
  // User messages
55
113
  export function logUserMessage(ctx, text) {
56
114
  console.log(color("green", `${timestamp()} ${formatContext(ctx)} ${text}`));
115
+ emit("info", "user_message", text, { ctx });
57
116
  }
58
117
  // Tool execution
59
118
  export function logToolStart(ctx, toolName, label, args) {
@@ -66,6 +125,11 @@ export function logToolStart(ctx, toolName, label, args) {
66
125
  .join("\n");
67
126
  console.log(color("dim", indented));
68
127
  }
128
+ emit("debug", "tool_start", `${toolName}: ${label}`, {
129
+ ctx,
130
+ details: formattedArgs || undefined,
131
+ fields: { toolName, label },
132
+ });
69
133
  }
70
134
  export function logToolSuccess(ctx, toolName, durationMs, result) {
71
135
  const duration = (durationMs / 1000).toFixed(1);
@@ -78,6 +142,11 @@ export function logToolSuccess(ctx, toolName, durationMs, result) {
78
142
  .join("\n");
79
143
  console.log(color("dim", indented));
80
144
  }
145
+ emit("info", "tool_end", toolName, {
146
+ ctx,
147
+ details: truncated || undefined,
148
+ fields: { toolName, durationMs, isError: false },
149
+ });
81
150
  }
82
151
  export function logToolError(ctx, toolName, durationMs, error) {
83
152
  const duration = (durationMs / 1000).toFixed(1);
@@ -88,10 +157,16 @@ export function logToolError(ctx, toolName, durationMs, error) {
88
157
  .map((line) => ` ${line}`)
89
158
  .join("\n");
90
159
  console.log(color("dim", indented));
160
+ emit("error", "tool_end", toolName, {
161
+ ctx,
162
+ details: truncated,
163
+ fields: { toolName, durationMs, isError: true },
164
+ });
91
165
  }
92
166
  // Response streaming
93
167
  export function logResponseStart(ctx) {
94
168
  console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} → Streaming response...`));
169
+ emit("debug", "response_start", "Streaming response...", { ctx });
95
170
  }
96
171
  export function logThinking(ctx, thinking) {
97
172
  console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💭 Thinking`));
@@ -101,6 +176,7 @@ export function logThinking(ctx, thinking) {
101
176
  .map((line) => ` ${line}`)
102
177
  .join("\n");
103
178
  console.log(color("dim", indented));
179
+ emit("debug", "thinking", "Thinking", { ctx, details: truncated });
104
180
  }
105
181
  export function logResponse(ctx, text) {
106
182
  console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💬 Response`));
@@ -110,10 +186,12 @@ export function logResponse(ctx, text) {
110
186
  .map((line) => ` ${line}`)
111
187
  .join("\n");
112
188
  console.log(color("dim", indented));
189
+ emit("info", "response", "Response", { ctx, details: truncated });
113
190
  }
114
191
  // System
115
192
  export function logInfo(message) {
116
193
  console.log(color("blue", `${timestamp()} [system] ${message}`));
194
+ emit("info", "system", message);
117
195
  }
118
196
  export function logWarning(message, details) {
119
197
  console.log(color("yellow", `${timestamp()} [system] ⚠ ${message}`));
@@ -124,6 +202,7 @@ export function logWarning(message, details) {
124
202
  .join("\n");
125
203
  console.log(color("dim", indented));
126
204
  }
205
+ emit("warn", "system", message, { details });
127
206
  }
128
207
  export function logAgentError(ctx, error) {
129
208
  const context = ctx === "system" ? "[system]" : formatContext(ctx);
@@ -133,6 +212,10 @@ export function logAgentError(ctx, error) {
133
212
  .map((line) => ` ${line}`)
134
213
  .join("\n");
135
214
  console.log(color("dim", indented));
215
+ emit("error", "agent_error", "Agent error", {
216
+ ctx: ctx === "system" ? undefined : ctx,
217
+ details: error,
218
+ });
136
219
  }
137
220
  // Usage summary
138
221
  export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
@@ -159,7 +242,7 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
159
242
  (usage.cacheRead > 0 || usage.cacheWrite > 0
160
243
  ? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`
161
244
  : ""));
162
- lines.push(`**Total: $${usage.cost.total.toFixed(4)}**`);
245
+ lines.push(`**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`);
163
246
  const summary = lines.join("\n");
164
247
  // Log to console
165
248
  console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💰 Usage`));
@@ -168,6 +251,18 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
168
251
  ? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`
169
252
  : "") +
170
253
  ` = $${usage.cost.total.toFixed(4)}`));
254
+ emit("info", "usage", `Total $${usage.cost.total.toFixed(4)} (incl. sub-agents)`, {
255
+ ctx,
256
+ fields: {
257
+ usage: {
258
+ input: usage.input,
259
+ output: usage.output,
260
+ cacheRead: usage.cacheRead,
261
+ cacheWrite: usage.cacheWrite,
262
+ cost: usage.cost,
263
+ },
264
+ },
265
+ });
171
266
  return summary;
172
267
  }
173
268
  // Startup
@@ -4,6 +4,7 @@ import { type SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
5
5
  export type ConsolidationMode = "idle" | "boundary";
6
6
  export interface ConsolidationRunOptions {
7
+ channelId?: string;
7
8
  channelDir: string;
8
9
  model: Model<Api>;
9
10
  resolveApiKey: (model: Model<Api>) => Promise<string>;
@@ -94,6 +94,9 @@ Goals:
94
94
  - Keep important decisions, milestones, and unresolved outcomes.
95
95
  - Remove redundancy and transcript-like detail.
96
96
  - Preserve a chronological narrative at a high level.`;
97
+ function usageContextFor(channelId) {
98
+ return channelId ? { channelId } : undefined;
99
+ }
97
100
  function normalizeText(text) {
98
101
  return text.replace(/\r/g, "").trim();
99
102
  }
@@ -191,7 +194,7 @@ export function getStructuralMaintenanceStats(currentMemory, currentHistory) {
191
194
  hasHistoryContent: currentHistory.replace(/^# Channel History\s*/i, "").trim().length > 0,
192
195
  };
193
196
  }
194
- async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt, timeoutMs) {
197
+ async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt, timeoutMs, usageContext) {
195
198
  const result = await runSidecarTask({
196
199
  name,
197
200
  model,
@@ -199,6 +202,7 @@ async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt,
199
202
  systemPrompt,
200
203
  prompt,
201
204
  timeoutMs,
205
+ usageContext,
202
206
  parse: (text) => text.trim(),
203
207
  });
204
208
  return result.output;
@@ -235,6 +239,7 @@ ${transcript || "(empty)"}`;
235
239
  systemPrompt: mode === "idle" ? IDLE_INLINE_CONSOLIDATION_SYSTEM_PROMPT : BOUNDARY_INLINE_CONSOLIDATION_SYSTEM_PROMPT,
236
240
  prompt,
237
241
  timeoutMs: INLINE_CONSOLIDATION_TIMEOUT_MS,
242
+ usageContext: usageContextFor(options.channelId),
238
243
  parse: (text) => text.trim(),
239
244
  });
240
245
  const rawResponse = result.output;
@@ -295,7 +300,7 @@ export async function cleanupChannelMemory(options, currentMemory, guard) {
295
300
  }
296
301
  const prompt = `Current MEMORY.md:
297
302
  ${currentMemory}`;
298
- const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS);
303
+ const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId));
299
304
  if (guard && isCleanupResultTooSmall(currentMemory, nextMemory, guard)) {
300
305
  throw new MemoryCleanupRejectedError("cleanup result shrank below the configured guard threshold");
301
306
  }
@@ -318,7 +323,7 @@ export async function foldChannelHistory(options, currentHistory) {
318
323
  });
319
324
  const prompt = `Older history blocks to fold:
320
325
  ${renderedOlder}`;
321
- const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS);
326
+ const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS, usageContextFor(options.channelId));
322
327
  const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? new Date().toISOString()}`;
323
328
  const rebuiltHistory = [
324
329
  "# Channel History",
@@ -16,6 +16,7 @@ export class MemoryLifecycle {
16
16
  }
17
17
  buildRunOptions(messages, sessionEntries) {
18
18
  return {
19
+ channelId: this.options.channelId,
19
20
  channelDir: this.options.channelDir,
20
21
  model: this.options.getModel(),
21
22
  resolveApiKey: this.options.resolveApiKey,
@@ -91,6 +92,7 @@ export class MemoryLifecycle {
91
92
  const { reason } = request;
92
93
  try {
93
94
  await updateChannelSessionMemory({
95
+ channelId: this.options.channelId,
94
96
  channelDir: this.options.channelDir,
95
97
  messages: request.messages ?? this.options.getMessages(),
96
98
  model: this.options.getModel(),
@@ -58,6 +58,7 @@ function renderMessagesForSignalScan(messages) {
58
58
  }
59
59
  function makeRunOptions(input) {
60
60
  return {
61
+ channelId: input.channelId,
61
62
  channelDir: input.channelDir,
62
63
  model: input.model,
63
64
  resolveApiKey: input.resolveApiKey,
@@ -147,6 +147,7 @@ ${transcript || "(empty)"}`;
147
147
  systemPrompt: POST_TURN_REVIEW_SYSTEM_PROMPT,
148
148
  prompt,
149
149
  timeoutMs: options.timeoutMs,
150
+ usageContext: { channelId: options.channelId },
150
151
  parse: (text) => parsePostTurnReviewResult(parseJsonObject(text)),
151
152
  });
152
153
  return result.output;
@@ -2,6 +2,7 @@ import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import { type MemoryCandidate, type MemoryCandidateStore } from "./candidates.js";
3
3
  export interface RecallRequest {
4
4
  query: string;
5
+ channelId?: string;
5
6
  workspaceDir: string;
6
7
  channelDir: string;
7
8
  allowedSources?: MemoryCandidate["source"][];
@@ -413,6 +413,7 @@ async function rerankCandidates(request, candidates) {
413
413
  systemPrompt: RERANK_SYSTEM_PROMPT,
414
414
  prompt: `User turn:\n${request.query.trim()}\n\nCandidates:\n${renderedCandidates}`,
415
415
  timeoutMs: MEMORY_RECALL_RERANK_TIMEOUT_MS,
416
+ usageContext: request.channelId ? { channelId: request.channelId } : undefined,
416
417
  parse: (text) => {
417
418
  const parsed = parseJsonObject(text);
418
419
  return Array.isArray(parsed.selectedIds)
@@ -1,6 +1,7 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import { type SessionSearchRole } from "./session-corpus.js";
3
3
  export interface SearchChannelSessionsRequest {
4
+ channelId?: string;
4
5
  channelDir: string;
5
6
  query: string;
6
7
  roleFilter?: string[];
@@ -86,6 +86,7 @@ ${query}
86
86
  Transcript hit:
87
87
  ${fallback}`,
88
88
  timeoutMs: request.timeoutMs,
89
+ usageContext: request.channelId ? { channelId: request.channelId } : undefined,
89
90
  parse: (text) => text.trim(),
90
91
  });
91
92
  return result.output || fallback;
@@ -12,6 +12,7 @@ export interface SessionMemoryState {
12
12
  worklog: string[];
13
13
  }
14
14
  export interface SessionMemoryUpdateOptions {
15
+ channelId?: string;
15
16
  channelDir: string;
16
17
  messages: AgentMessage[];
17
18
  model: Model<Api>;
@@ -258,6 +258,7 @@ 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
262
  });
262
263
  update = result.output;
263
264
  }
@@ -8,6 +8,10 @@ export interface SidecarTask<T> {
8
8
  parse: (text: string) => T;
9
9
  timeoutMs?: number;
10
10
  signal?: AbortSignal;
11
+ /** Attributes this task's LLM spend to a channel in the usage ledger. */
12
+ usageContext?: {
13
+ channelId: string;
14
+ };
11
15
  }
12
16
  export interface SidecarResult<T> {
13
17
  output: T;
@@ -1,6 +1,8 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
2
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
3
+ import { formatModelReference } from "../models/utils.js";
3
4
  import { extractAssistantText } from "../shared/text-utils.js";
5
+ import { getUsageLedger } from "../usage/ledger.js";
4
6
  const SIDE_CAR_RETRY_DELAY_MS = 2_000;
5
7
  const SIDE_CAR_MAX_ATTEMPTS = 2;
6
8
  export class SidecarTimeoutError extends Error {
@@ -54,6 +56,32 @@ function delay(ms, task) {
54
56
  signal.addEventListener("abort", abort, { once: true });
55
57
  });
56
58
  }
59
+ /** Attribute a completed sidecar task's LLM spend to the usage ledger. */
60
+ function recordSidecarUsage(task, message) {
61
+ const usage = message.usage;
62
+ if (!usage || !usage.cost)
63
+ return;
64
+ getUsageLedger().record({
65
+ channelId: task.usageContext?.channelId ?? "",
66
+ kind: "sidecar",
67
+ model: formatModelReference(task.model),
68
+ label: task.name,
69
+ usage: {
70
+ input: usage.input ?? 0,
71
+ output: usage.output ?? 0,
72
+ cacheRead: usage.cacheRead ?? 0,
73
+ cacheWrite: usage.cacheWrite ?? 0,
74
+ total: usage.total ?? 0,
75
+ },
76
+ cost: {
77
+ input: usage.cost.input ?? 0,
78
+ output: usage.cost.output ?? 0,
79
+ cacheRead: usage.cost.cacheRead ?? 0,
80
+ cacheWrite: usage.cost.cacheWrite ?? 0,
81
+ total: usage.cost.total ?? 0,
82
+ },
83
+ });
84
+ }
57
85
  export async function runSidecarTask(task) {
58
86
  const apiKey = await task.resolveApiKey(task.model);
59
87
  const worker = new Agent({
@@ -86,6 +114,7 @@ export async function runSidecarTask(task) {
86
114
  if (lastMessage.stopReason === "error" || lastMessage.stopReason === "aborted") {
87
115
  throw new Error(lastMessage.errorMessage || `Sidecar task "${task.name}" failed`);
88
116
  }
117
+ recordSidecarUsage(task, lastMessage);
89
118
  const rawText = extractAssistantText(lastMessage);
90
119
  try {
91
120
  return {
package/dist/paths.d.ts CHANGED
@@ -4,6 +4,9 @@ export declare const WORKSPACE_DIR: string;
4
4
  export declare const STATE_DIR: string;
5
5
  export declare const EVENT_STATE_DIR: string;
6
6
  export declare const EVENT_HISTORY_PATH: string;
7
+ export declare const LOG_STATE_DIR: string;
8
+ export declare const RUNTIME_LOG_PATH: string;
9
+ export declare const USAGE_STATE_DIR: string;
7
10
  export declare const SUB_AGENTS_DIR_NAME = "sub-agents";
8
11
  export declare const SUB_AGENTS_DIR: string;
9
12
  export declare const CHANNEL_CONFIG_PATH: string;
package/dist/paths.js CHANGED
@@ -6,6 +6,9 @@ export const WORKSPACE_DIR = join(APP_HOME_DIR, "workspace");
6
6
  export const STATE_DIR = join(APP_HOME_DIR, "state");
7
7
  export const EVENT_STATE_DIR = join(STATE_DIR, "events");
8
8
  export const EVENT_HISTORY_PATH = join(EVENT_STATE_DIR, "history.jsonl");
9
+ export const LOG_STATE_DIR = join(STATE_DIR, "logs");
10
+ export const RUNTIME_LOG_PATH = join(LOG_STATE_DIR, "runtime.jsonl");
11
+ export const USAGE_STATE_DIR = join(STATE_DIR, "usage");
9
12
  export const SUB_AGENTS_DIR_NAME = "sub-agents";
10
13
  export const SUB_AGENTS_DIR = join(WORKSPACE_DIR, SUB_AGENTS_DIR_NAME);
11
14
  export const CHANNEL_CONFIG_PATH = join(APP_HOME_DIR, "channel.json");
@@ -12,6 +12,8 @@ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
12
12
  import { PipiclawSettingsManager } from "../settings.js";
13
13
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
14
14
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
15
+ import { getUsageLedger } from "../usage/ledger.js";
16
+ import { parseUsageMode, renderUsageReport } from "../usage/render.js";
15
17
  import { ensureChannelDir } from "./channel-paths.js";
16
18
  import { createDingTalkContext } from "./delivery.js";
17
19
  import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
@@ -456,6 +458,7 @@ export function createRuntimeContext(options) {
456
458
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
457
459
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
458
460
  const runtimeSettingsManager = new PipiclawSettingsManager(options.paths.appHomeDir);
461
+ log.configureLogging(runtimeSettingsManager.getLoggingSettings());
459
462
  const startedAt = Date.now();
460
463
  const cliVersion = readCliVersion();
461
464
  const channelStates = new Map();
@@ -523,6 +526,10 @@ export function createRuntimeContext(options) {
523
526
  });
524
527
  await bot.sendPlain(event.channelId, response);
525
528
  },
529
+ async handleUsageCommand(event, bot, args) {
530
+ const response = renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
531
+ await bot.sendPlain(event.channelId, response);
532
+ },
526
533
  async handleBusyMessage(event, bot, mode, queueText) {
527
534
  if (shuttingDown) {
528
535
  return { kind: "handled" };
@@ -603,6 +610,10 @@ export function createRuntimeContext(options) {
603
610
  await handler.handleStatusCommand(event, bot);
604
611
  return;
605
612
  }
613
+ if (builtInCommand.name === "usage") {
614
+ await handler.handleUsageCommand(event, bot, builtInCommand.args);
615
+ return;
616
+ }
606
617
  await state.runner.handleBuiltinCommand(ctx, builtInCommand);
607
618
  return;
608
619
  }
@@ -66,6 +66,7 @@ export interface DingTalkHandler {
66
66
  handleStop(channelId: string, bot: DingTalkBot): Promise<void>;
67
67
  handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
68
68
  handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
69
+ handleUsageCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
69
70
  handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
70
71
  }
71
72
  export declare class DingTalkBot {
@@ -994,6 +994,10 @@ export class DingTalkBot {
994
994
  await this.handler.handleStatusCommand(event, this);
995
995
  return;
996
996
  }
997
+ if (builtInCommand?.name === "usage") {
998
+ await this.handler.handleUsageCommand(event, this, builtInCommand.args);
999
+ return;
1000
+ }
997
1001
  if (builtInCommand) {
998
1002
  await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, or \`/events <action>\`. Plain messages default to ${this.busyMessageDefault}.`);
999
1003
  return;
@@ -92,6 +92,14 @@ export interface PipiclawMemoryMaintenanceSettings {
92
92
  /** Only apply the shrink guard when the original exceeds this length (chars). */
93
93
  cleanupShrinkGuardMinChars: number;
94
94
  }
95
+ export interface PipiclawLoggingSettings {
96
+ level: "debug" | "info" | "warn" | "error";
97
+ file: {
98
+ enabled: boolean;
99
+ maxSizeBytes: number;
100
+ maxFiles: number;
101
+ };
102
+ }
95
103
  export interface PipiclawSessionSearchSettings {
96
104
  enabled: boolean;
97
105
  maxFiles: number;
@@ -111,6 +119,9 @@ export interface PipiclawSettings {
111
119
  memoryGrowth?: Partial<PipiclawMemoryGrowthSettings>;
112
120
  memoryMaintenance?: Partial<PipiclawMemoryMaintenanceSettings>;
113
121
  sessionSearch?: Partial<PipiclawSessionSearchSettings>;
122
+ logging?: Partial<Omit<PipiclawLoggingSettings, "file">> & {
123
+ file?: Partial<PipiclawLoggingSettings["file"]>;
124
+ };
114
125
  }
115
126
  /**
116
127
  * Settings manager for pipiclaw.
@@ -135,6 +146,7 @@ export declare class PipiclawSettingsManager {
135
146
  getMemoryGrowthSettings(): PipiclawMemoryGrowthSettings;
136
147
  getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
137
148
  getSessionSearchSettings(): PipiclawSessionSearchSettings;
149
+ getLoggingSettings(): PipiclawLoggingSettings;
138
150
  getRetryEnabled(): boolean;
139
151
  setRetryEnabled(enabled: boolean): void;
140
152
  getDefaultModel(): string | undefined;
package/dist/settings.js CHANGED
@@ -66,6 +66,16 @@ const DEFAULT_MEMORY_MAINTENANCE = {
66
66
  cleanupShrinkGuardMinRatio: 0.4,
67
67
  cleanupShrinkGuardMinChars: 2_000,
68
68
  };
69
+ // `file.enabled` defaults to true: for a long-lived daemon, persisting logs is
70
+ // worth more than the surprise of a new file under state/logs/. See docs.
71
+ const DEFAULT_LOGGING = {
72
+ level: "info",
73
+ file: {
74
+ enabled: true,
75
+ maxSizeBytes: 5_000_000,
76
+ maxFiles: 3,
77
+ },
78
+ };
69
79
  /**
70
80
  * Settings manager for pipiclaw.
71
81
  * Stores global settings in the pipiclaw root directory.
@@ -185,6 +195,16 @@ export class PipiclawSettingsManager {
185
195
  ...this.settings.sessionSearch,
186
196
  };
187
197
  }
198
+ getLoggingSettings() {
199
+ return {
200
+ ...DEFAULT_LOGGING,
201
+ ...this.settings.logging,
202
+ file: {
203
+ ...DEFAULT_LOGGING.file,
204
+ ...this.settings.logging?.file,
205
+ },
206
+ };
207
+ }
188
208
  getRetryEnabled() {
189
209
  return this.settings.retry?.enabled ?? DEFAULT_RETRY.enabled;
190
210
  }
@@ -0,0 +1,25 @@
1
+ export interface JsonlAppenderOptions {
2
+ /** Fixed target file. Mutually exclusive with `pathFor`. */
3
+ path?: string;
4
+ /** Resolve the target file per append (e.g. monthly ledger files). */
5
+ pathFor?: (now: Date) => string;
6
+ /** Rotate when the file would exceed this size (bytes). Omit to disable. */
7
+ maxSizeBytes?: number;
8
+ /** Number of rotated backups to keep (`.1`..`.N`). Default 3. */
9
+ maxRotations?: number;
10
+ /** File mode for created files. Default 0o600. */
11
+ mode?: number;
12
+ }
13
+ export interface JsonlAppender {
14
+ /** Serialize `record` as one JSON line. Never throws. */
15
+ append(record: unknown): Promise<void>;
16
+ }
17
+ /**
18
+ * Append-only JSONL writer shared by the runtime log and the usage ledger.
19
+ *
20
+ * Writes are serialized per resolved file path, size-tracked in memory (one
21
+ * initial stat), and rotated via rename. Observability infrastructure must not
22
+ * reach back into the business path, so a failed append only warns once (until
23
+ * the next success) and never rejects.
24
+ */
25
+ export declare function createJsonlAppender(options: JsonlAppenderOptions): JsonlAppender;
@@ -0,0 +1,85 @@
1
+ import { existsSync, mkdirSync, renameSync, statSync } from "node:fs";
2
+ import { appendFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { createSerialQueue } from "./serial-queue.js";
5
+ /**
6
+ * Append-only JSONL writer shared by the runtime log and the usage ledger.
7
+ *
8
+ * Writes are serialized per resolved file path, size-tracked in memory (one
9
+ * initial stat), and rotated via rename. Observability infrastructure must not
10
+ * reach back into the business path, so a failed append only warns once (until
11
+ * the next success) and never rejects.
12
+ */
13
+ export function createJsonlAppender(options) {
14
+ if (!options.path && !options.pathFor) {
15
+ throw new Error("createJsonlAppender requires either `path` or `pathFor`");
16
+ }
17
+ const maxRotations = options.maxRotations ?? 3;
18
+ const mode = options.mode ?? 0o600;
19
+ const queue = createSerialQueue();
20
+ const sizes = new Map();
21
+ const ensuredDirs = new Set();
22
+ let warned = false;
23
+ const resolvePath = (now) => (options.pathFor ? options.pathFor(now) : options.path);
24
+ const ensureDir = (filePath) => {
25
+ const dir = dirname(filePath);
26
+ if (ensuredDirs.has(dir))
27
+ return;
28
+ mkdirSync(dir, { recursive: true });
29
+ ensuredDirs.add(dir);
30
+ };
31
+ const currentSize = (filePath) => {
32
+ const cached = sizes.get(filePath);
33
+ if (cached !== undefined)
34
+ return cached;
35
+ let size = 0;
36
+ try {
37
+ if (existsSync(filePath))
38
+ size = statSync(filePath).size;
39
+ }
40
+ catch {
41
+ size = 0;
42
+ }
43
+ sizes.set(filePath, size);
44
+ return size;
45
+ };
46
+ const rotate = (filePath) => {
47
+ for (let i = maxRotations - 1; i >= 1; i--) {
48
+ const from = `${filePath}.${i}`;
49
+ if (existsSync(from)) {
50
+ renameSync(from, `${filePath}.${i + 1}`);
51
+ }
52
+ }
53
+ if (existsSync(filePath)) {
54
+ renameSync(filePath, `${filePath}.1`);
55
+ }
56
+ sizes.set(filePath, 0);
57
+ };
58
+ const write = async (filePath, line) => {
59
+ ensureDir(filePath);
60
+ const lineBytes = Buffer.byteLength(line);
61
+ if (options.maxSizeBytes && options.maxSizeBytes > 0) {
62
+ if (currentSize(filePath) + lineBytes > options.maxSizeBytes && currentSize(filePath) > 0) {
63
+ rotate(filePath);
64
+ }
65
+ }
66
+ await appendFile(filePath, line, { encoding: "utf-8", mode });
67
+ sizes.set(filePath, currentSize(filePath) + lineBytes);
68
+ };
69
+ return {
70
+ async append(record) {
71
+ const filePath = resolvePath(new Date());
72
+ const line = `${JSON.stringify(record)}\n`;
73
+ try {
74
+ await queue.run(filePath, () => write(filePath, line));
75
+ warned = false;
76
+ }
77
+ catch (error) {
78
+ if (!warned) {
79
+ warned = true;
80
+ console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
81
+ }
82
+ }
83
+ },
84
+ };
85
+ }
@@ -183,6 +183,7 @@ async function buildContextualBlocks(task, config, options, currentModel) {
183
183
  const recallQuery = [task.trim(), config.description.trim(), ...config.paths].filter(Boolean).join("\n");
184
184
  const recalled = await recallRelevantMemory({
185
185
  query: recallQuery,
186
+ channelId: options.runtimeContext.channelId,
186
187
  workspaceDir: options.workspaceDir,
187
188
  channelDir: options.channelDir,
188
189
  maxCandidates: recallSettings.maxCandidates,
@@ -91,6 +91,7 @@ export const TOOL_REGISTRY = [
91
91
  availableToSubagents: false,
92
92
  enabledBy: (ctx) => ctx.toolsConfig?.tools.memory.sessionSearch.enabled !== false,
93
93
  create: (ctx) => createSessionSearchTool({
94
+ channelId: ctx.channelId,
94
95
  channelDir: ctx.channelDir,
95
96
  getCurrentModel: req(ctx.getCurrentModel, "getCurrentModel"),
96
97
  resolveApiKey: req(ctx.resolveApiKey, "resolveApiKey"),
@@ -9,6 +9,7 @@ declare const sessionSearchSchema: Type.TObject<{
9
9
  roleFilter: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"system">, Type.TLiteral<"unknown">]>>>;
10
10
  }>;
11
11
  export interface SessionSearchToolOptions {
12
+ channelId?: string;
12
13
  channelDir: string;
13
14
  getCurrentModel: () => Model<Api>;
14
15
  resolveApiKey: (model: Model<Api>) => Promise<string>;
@@ -30,6 +30,7 @@ export function createSessionSearchTool(options) {
30
30
  const settings = options.getSessionSearchSettings();
31
31
  const model = options.getCurrentModel();
32
32
  const response = await searchChannelSessions({
33
+ channelId: options.channelId,
33
34
  channelDir: options.channelDir,
34
35
  query: query ?? "",
35
36
  roleFilter,
@@ -0,0 +1,47 @@
1
+ export type UsageKind = "turn" | "subagent" | "sidecar";
2
+ export interface UsageTokens {
3
+ input: number;
4
+ output: number;
5
+ cacheRead: number;
6
+ cacheWrite: number;
7
+ total: number;
8
+ }
9
+ export interface UsageCost {
10
+ input: number;
11
+ output: number;
12
+ cacheRead: number;
13
+ cacheWrite: number;
14
+ total: number;
15
+ }
16
+ export interface UsageLedgerEntry {
17
+ ts: string;
18
+ channelId: string;
19
+ kind: UsageKind;
20
+ model: string;
21
+ label?: string;
22
+ usage: UsageTokens;
23
+ cost: UsageCost;
24
+ }
25
+ export interface UsageSummary {
26
+ totalCost: number;
27
+ entryCount: number;
28
+ byKind: Record<string, number>;
29
+ byModel: Record<string, number>;
30
+ byChannel: Record<string, number>;
31
+ }
32
+ export interface UsageSummaryQuery {
33
+ since: Date;
34
+ until?: Date;
35
+ channelId?: string;
36
+ }
37
+ export declare const UNTRACKED_CHANNEL_ID = "(untracked)";
38
+ export interface UsageLedger {
39
+ record(entry: Omit<UsageLedgerEntry, "ts">): void;
40
+ summarize(query: UsageSummaryQuery): UsageSummary;
41
+ }
42
+ export interface CreateUsageLedgerOptions {
43
+ baseDir?: string;
44
+ }
45
+ export declare function createUsageLedger(options?: CreateUsageLedgerOptions): UsageLedger;
46
+ /** Process-wide ledger (single-process runtime). Tests use createUsageLedger. */
47
+ export declare function getUsageLedger(): UsageLedger;
@@ -0,0 +1,95 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import * as log from "../log.js";
4
+ import { USAGE_STATE_DIR } from "../paths.js";
5
+ import { createJsonlAppender } from "../shared/jsonl-appender.js";
6
+ export const UNTRACKED_CHANNEL_ID = "(untracked)";
7
+ function monthKey(date) {
8
+ return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
9
+ }
10
+ function monthKeysBetween(since, until) {
11
+ const keys = [];
12
+ const cursor = new Date(Date.UTC(since.getUTCFullYear(), since.getUTCMonth(), 1));
13
+ const end = new Date(Date.UTC(until.getUTCFullYear(), until.getUTCMonth(), 1));
14
+ while (cursor <= end) {
15
+ keys.push(monthKey(cursor));
16
+ cursor.setUTCMonth(cursor.getUTCMonth() + 1);
17
+ }
18
+ return keys;
19
+ }
20
+ export function createUsageLedger(options = {}) {
21
+ const baseDir = options.baseDir ?? USAGE_STATE_DIR;
22
+ const fileFor = (date) => join(baseDir, `usage-${monthKey(date)}.jsonl`);
23
+ const appender = createJsonlAppender({ pathFor: fileFor });
24
+ return {
25
+ record(entry) {
26
+ // No API billing (local models) → no ledger noise.
27
+ if (!(entry.cost.total > 0))
28
+ return;
29
+ if (!entry.channelId) {
30
+ log.logWarning("Usage ledger entry missing channelId; recording as untracked", `kind=${entry.kind}`);
31
+ }
32
+ const full = {
33
+ ts: new Date().toISOString(),
34
+ ...entry,
35
+ channelId: entry.channelId || UNTRACKED_CHANNEL_ID,
36
+ };
37
+ void appender.append(full);
38
+ },
39
+ summarize(query) {
40
+ const until = query.until ?? new Date();
41
+ const sinceMs = query.since.getTime();
42
+ const untilMs = until.getTime();
43
+ const summary = {
44
+ totalCost: 0,
45
+ entryCount: 0,
46
+ byKind: {},
47
+ byModel: {},
48
+ byChannel: {},
49
+ };
50
+ for (const key of monthKeysBetween(query.since, until)) {
51
+ const path = join(baseDir, `usage-${key}.jsonl`);
52
+ if (!existsSync(path))
53
+ continue;
54
+ let content;
55
+ try {
56
+ content = readFileSync(path, "utf-8");
57
+ }
58
+ catch {
59
+ continue;
60
+ }
61
+ for (const line of content.split("\n")) {
62
+ if (!line)
63
+ continue;
64
+ let entry;
65
+ try {
66
+ entry = JSON.parse(line);
67
+ }
68
+ catch {
69
+ continue; // tolerate a torn trailing line
70
+ }
71
+ const tsMs = Date.parse(entry.ts);
72
+ if (Number.isNaN(tsMs) || tsMs < sinceMs || tsMs > untilMs)
73
+ continue;
74
+ if (query.channelId && entry.channelId !== query.channelId)
75
+ continue;
76
+ const cost = entry.cost?.total ?? 0;
77
+ summary.totalCost += cost;
78
+ summary.entryCount += 1;
79
+ summary.byKind[entry.kind] = (summary.byKind[entry.kind] ?? 0) + cost;
80
+ summary.byModel[entry.model] = (summary.byModel[entry.model] ?? 0) + cost;
81
+ summary.byChannel[entry.channelId] = (summary.byChannel[entry.channelId] ?? 0) + cost;
82
+ }
83
+ }
84
+ return summary;
85
+ },
86
+ };
87
+ }
88
+ let singleton = null;
89
+ /** Process-wide ledger (single-process runtime). Tests use createUsageLedger. */
90
+ export function getUsageLedger() {
91
+ if (!singleton) {
92
+ singleton = createUsageLedger();
93
+ }
94
+ return singleton;
95
+ }
@@ -0,0 +1,11 @@
1
+ import type { UsageLedger } from "./ledger.js";
2
+ export type UsageQueryMode = "default" | "7d" | "month";
3
+ export declare function parseUsageMode(args: string): UsageQueryMode;
4
+ interface UsageWindow {
5
+ title: string;
6
+ since: Date;
7
+ until: Date;
8
+ }
9
+ export declare function usageWindows(mode: UsageQueryMode, now: Date): UsageWindow[];
10
+ export declare function renderUsageReport(ledger: UsageLedger, channelId: string, mode: UsageQueryMode, now: Date): string;
11
+ export {};
@@ -0,0 +1,67 @@
1
+ export function parseUsageMode(args) {
2
+ const normalized = args.trim().toLowerCase();
3
+ if (normalized === "7d" || normalized === "7")
4
+ return "7d";
5
+ if (normalized === "month" || normalized === "monthly")
6
+ return "month";
7
+ return "default";
8
+ }
9
+ function startOfUtcDay(now) {
10
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
11
+ }
12
+ function startOfUtcMonth(now) {
13
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
14
+ }
15
+ export function usageWindows(mode, now) {
16
+ const monthTitle = `This month (${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")})`;
17
+ switch (mode) {
18
+ case "7d":
19
+ return [{ title: "Last 7 days", since: new Date(now.getTime() - 7 * 86_400_000), until: now }];
20
+ case "month":
21
+ return [{ title: monthTitle, since: startOfUtcMonth(now), until: now }];
22
+ default:
23
+ return [
24
+ { title: "Today (UTC)", since: startOfUtcDay(now), until: now },
25
+ { title: monthTitle, since: startOfUtcMonth(now), until: now },
26
+ ];
27
+ }
28
+ }
29
+ function money(n) {
30
+ return `$${n.toFixed(4)}`;
31
+ }
32
+ function topEntries(map, limit) {
33
+ return Object.entries(map)
34
+ .filter(([, cost]) => cost > 0)
35
+ .sort((a, b) => b[1] - a[1])
36
+ .slice(0, limit);
37
+ }
38
+ function renderKindBreakdown(summary) {
39
+ const parts = topEntries(summary.byKind, 3).map(([kind, cost]) => `${kind} ${money(cost)}`);
40
+ return parts.length > 0 ? parts.join(" · ") : null;
41
+ }
42
+ function renderWindow(window, ledger, channelId) {
43
+ const global = ledger.summarize({ since: window.since, until: window.until });
44
+ const channel = ledger.summarize({ since: window.since, until: window.until, channelId });
45
+ const lines = [`## ${window.title}`];
46
+ if (global.entryCount === 0) {
47
+ lines.push("No recorded usage.");
48
+ return lines.join("\n");
49
+ }
50
+ lines.push(`This channel: ${money(channel.totalCost)}`);
51
+ const channelKinds = renderKindBreakdown(channel);
52
+ if (channelKinds) {
53
+ lines.push(` ${channelKinds}`);
54
+ }
55
+ const channelCount = Object.keys(global.byChannel).length;
56
+ lines.push(`Global: ${money(global.totalCost)} across ${channelCount} channel${channelCount === 1 ? "" : "s"}`);
57
+ const topModels = topEntries(global.byModel, 3);
58
+ if (topModels.length > 0) {
59
+ lines.push(` Top models: ${topModels.map(([model, cost]) => `${model} ${money(cost)}`).join(", ")}`);
60
+ }
61
+ return lines.join("\n");
62
+ }
63
+ export function renderUsageReport(ledger, channelId, mode, now) {
64
+ const windows = usageWindows(mode, now);
65
+ const body = windows.map((window) => renderWindow(window, ledger, channelId)).join("\n\n");
66
+ return `# Usage\n\n${body}`;
67
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.7.0-beta.1",
3
+ "version": "0.7.0",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {