@oyasmi/pipiclaw 0.7.0-beta.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/agent/channel-runner.d.ts +14 -0
  2. package/dist/agent/channel-runner.js +139 -6
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +6 -0
  5. package/dist/agent/model-fallback.d.ts +64 -0
  6. package/dist/agent/model-fallback.js +125 -0
  7. package/dist/agent/session-events.d.ts +2 -0
  8. package/dist/agent/session-events.js +31 -12
  9. package/dist/agent/types.d.ts +7 -0
  10. package/dist/agent/types.js +8 -0
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.js +2 -0
  13. package/dist/log.d.ts +25 -0
  14. package/dist/log.js +105 -1
  15. package/dist/memory/consolidation.d.ts +1 -0
  16. package/dist/memory/consolidation.js +8 -3
  17. package/dist/memory/lifecycle.js +2 -0
  18. package/dist/memory/maintenance-jobs.js +1 -0
  19. package/dist/memory/post-turn-review.js +1 -0
  20. package/dist/memory/recall.d.ts +1 -0
  21. package/dist/memory/recall.js +1 -0
  22. package/dist/memory/session-search.d.ts +1 -0
  23. package/dist/memory/session-search.js +1 -0
  24. package/dist/memory/session.d.ts +1 -0
  25. package/dist/memory/session.js +1 -0
  26. package/dist/memory/sidecar-worker.d.ts +4 -0
  27. package/dist/memory/sidecar-worker.js +29 -0
  28. package/dist/paths.d.ts +3 -0
  29. package/dist/paths.js +3 -0
  30. package/dist/runtime/bootstrap.js +19 -3
  31. package/dist/runtime/dingtalk.d.ts +1 -0
  32. package/dist/runtime/dingtalk.js +4 -0
  33. package/dist/sandbox.js +7 -77
  34. package/dist/security/command-guard.js +0 -4
  35. package/dist/security/path-guard.js +0 -4
  36. package/dist/settings.d.ts +19 -0
  37. package/dist/settings.js +32 -0
  38. package/dist/shared/jsonl-appender.d.ts +25 -0
  39. package/dist/shared/jsonl-appender.js +85 -0
  40. package/dist/shared/shell-escape.d.ts +0 -7
  41. package/dist/shared/shell-escape.js +0 -11
  42. package/dist/subagents/tool.js +1 -0
  43. package/dist/tools/bash.js +2 -2
  44. package/dist/tools/edit.js +2 -2
  45. package/dist/tools/read.js +6 -6
  46. package/dist/tools/registry.js +1 -0
  47. package/dist/tools/session-search.d.ts +1 -0
  48. package/dist/tools/session-search.js +1 -0
  49. package/dist/tools/write-content.js +3 -3
  50. package/dist/usage/ledger.d.ts +47 -0
  51. package/dist/usage/ledger.js +95 -0
  52. package/dist/usage/render.d.ts +11 -0
  53. package/dist/usage/render.js +67 -0
  54. package/package.json +1 -1
  55. package/dist/security/platform.d.ts +0 -1
  56. package/dist/security/platform.js +0 -3
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,19 @@ 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
+ });
219
+ }
220
+ // Model fallback (spec 017)
221
+ export function logModelFallback(ctx, from, to, error) {
222
+ console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} ⤳ Fallback ${from} → ${to}`));
223
+ emit("warn", "model_fallback", `Fallback ${from} → ${to}`, {
224
+ ctx,
225
+ details: error,
226
+ fields: { from, to, error },
227
+ });
136
228
  }
137
229
  // Usage summary
138
230
  export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
@@ -159,7 +251,7 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
159
251
  (usage.cacheRead > 0 || usage.cacheWrite > 0
160
252
  ? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`
161
253
  : ""));
162
- lines.push(`**Total: $${usage.cost.total.toFixed(4)}**`);
254
+ lines.push(`**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`);
163
255
  const summary = lines.join("\n");
164
256
  // Log to console
165
257
  console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} 💰 Usage`));
@@ -168,6 +260,18 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
168
260
  ? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`
169
261
  : "") +
170
262
  ` = $${usage.cost.total.toFixed(4)}`));
263
+ emit("info", "usage", `Total $${usage.cost.total.toFixed(4)} (incl. sub-agents)`, {
264
+ ctx,
265
+ fields: {
266
+ usage: {
267
+ input: usage.input,
268
+ output: usage.output,
269
+ cacheRead: usage.cacheRead,
270
+ cacheWrite: usage.cacheWrite,
271
+ cost: usage.cost,
272
+ },
273
+ },
274
+ });
171
275
  return summary;
172
276
  }
173
277
  // 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";
@@ -188,11 +190,10 @@ function writeJsonFileIfMissing(path, value, label, created, mode) {
188
190
  }
189
191
  // App-level config files that may hold secrets (DingTalk client secret, provider
190
192
  // API keys, Brave key). They are created owner-only, and any pre-existing file with
191
- // looser bits is tightened on startup. No-op on Windows, where POSIX mode bits do
192
- // not apply.
193
+ // looser bits is tightened on startup.
193
194
  const SECRET_FILE_MODE = 0o600;
194
195
  function hardenExistingSecretFile(path) {
195
- if (process.platform === "win32" || !existsSync(path)) {
196
+ if (!existsSync(path)) {
196
197
  return;
197
198
  }
198
199
  try {
@@ -431,6 +432,12 @@ function renderStatus(options) {
431
432
  try {
432
433
  const snapshot = state.runner.getStatusSnapshot();
433
434
  lines.push(`- Model: ${snapshot.model}`);
435
+ if (snapshot.fallback) {
436
+ const until = new Date(snapshot.fallback.cooldownUntilMs);
437
+ const hh = String(until.getHours()).padStart(2, "0");
438
+ const mm = String(until.getMinutes()).padStart(2, "0");
439
+ lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
440
+ }
434
441
  if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
435
442
  lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
436
443
  }
@@ -456,6 +463,7 @@ export function createRuntimeContext(options) {
456
463
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
457
464
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
458
465
  const runtimeSettingsManager = new PipiclawSettingsManager(options.paths.appHomeDir);
466
+ log.configureLogging(runtimeSettingsManager.getLoggingSettings());
459
467
  const startedAt = Date.now();
460
468
  const cliVersion = readCliVersion();
461
469
  const channelStates = new Map();
@@ -523,6 +531,10 @@ export function createRuntimeContext(options) {
523
531
  });
524
532
  await bot.sendPlain(event.channelId, response);
525
533
  },
534
+ async handleUsageCommand(event, bot, args) {
535
+ const response = renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
536
+ await bot.sendPlain(event.channelId, response);
537
+ },
526
538
  async handleBusyMessage(event, bot, mode, queueText) {
527
539
  if (shuttingDown) {
528
540
  return { kind: "handled" };
@@ -603,6 +615,10 @@ export function createRuntimeContext(options) {
603
615
  await handler.handleStatusCommand(event, bot);
604
616
  return;
605
617
  }
618
+ if (builtInCommand.name === "usage") {
619
+ await handler.handleUsageCommand(event, bot, builtInCommand.args);
620
+ return;
621
+ }
606
622
  await state.runner.handleBuiltinCommand(ctx, builtInCommand);
607
623
  return;
608
624
  }
@@ -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;
package/dist/sandbox.js CHANGED
@@ -1,4 +1,4 @@
1
- import { spawn, spawnSync } from "child_process";
1
+ import { spawn } from "child_process";
2
2
  import { shellEscape } from "./shared/shell-escape.js";
3
3
  /**
4
4
  * Error raised when sandbox configuration is invalid or the target sandbox is not
@@ -26,14 +26,6 @@ export function parseSandboxArg(value) {
26
26
  }
27
27
  export async function validateSandbox(config) {
28
28
  if (config.type === "host") {
29
- if (process.platform === "win32") {
30
- try {
31
- resolveWindowsHostShell();
32
- }
33
- catch (error) {
34
- throw new SandboxConfigError(error instanceof Error ? error.message : String(error));
35
- }
36
- }
37
29
  return;
38
30
  }
39
31
  // Check if Docker is available
@@ -60,7 +52,6 @@ function execSimple(cmd, args) {
60
52
  return new Promise((resolve, reject) => {
61
53
  const child = spawn(cmd, args, {
62
54
  stdio: ["ignore", "pipe", "pipe"],
63
- windowsHide: true,
64
55
  });
65
56
  let stdout = "";
66
57
  let stderr = "";
@@ -78,51 +69,6 @@ function execSimple(cmd, args) {
78
69
  });
79
70
  });
80
71
  }
81
- const WINDOWS_POSIX_SHELL_CANDIDATES = [
82
- "bash",
83
- "sh",
84
- "C:\\Program Files\\Git\\bin\\bash.exe",
85
- "C:\\Program Files\\Git\\usr\\bin\\bash.exe",
86
- "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
87
- "C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",
88
- ];
89
- let cachedWindowsHostShell;
90
- function looksLikeUnixShellPath(shell) {
91
- return shell.endsWith("/bash") || shell.endsWith("/sh");
92
- }
93
- function isUsablePosixShell(command) {
94
- const result = spawnSync(command, ["-lc", "printf pipiclaw"], {
95
- stdio: ["ignore", "pipe", "ignore"],
96
- encoding: "utf-8",
97
- windowsHide: true,
98
- });
99
- return !result.error && result.status === 0 && result.stdout === "pipiclaw";
100
- }
101
- function resolveWindowsHostShell() {
102
- if (cachedWindowsHostShell) {
103
- return cachedWindowsHostShell;
104
- }
105
- const configuredShell = process.env.PIPICLAW_SHELL?.trim();
106
- const inheritedShell = process.env.SHELL?.trim();
107
- const shellCandidates = [
108
- configuredShell,
109
- inheritedShell && looksLikeUnixShellPath(inheritedShell) ? inheritedShell.split("/").pop() : undefined,
110
- ...WINDOWS_POSIX_SHELL_CANDIDATES,
111
- ].filter((value) => Boolean(value));
112
- for (const command of shellCandidates) {
113
- if (isUsablePosixShell(command)) {
114
- cachedWindowsHostShell = { command, args: ["-lc"] };
115
- return cachedWindowsHostShell;
116
- }
117
- }
118
- throw new Error("Windows host sandbox requires a POSIX shell. Install Git Bash and ensure `bash` is on PATH, set `PIPICLAW_SHELL`, or use the Docker sandbox.");
119
- }
120
- function resolveHostShell() {
121
- if (process.platform === "win32") {
122
- return resolveWindowsHostShell();
123
- }
124
- return { command: "sh", args: ["-c"] };
125
- }
126
72
  /**
127
73
  * Create an executor that runs commands either on host or in Docker container
128
74
  */
@@ -135,13 +81,11 @@ export function createExecutor(config) {
135
81
  class HostExecutor {
136
82
  async exec(command, options) {
137
83
  return new Promise((resolve, reject) => {
138
- const shell = resolveHostShell();
139
84
  const child = (() => {
140
85
  try {
141
- return spawn(shell.command, [...shell.args, command], {
86
+ return spawn("sh", ["-c", command], {
142
87
  detached: true,
143
88
  stdio: ["pipe", "pipe", "pipe"],
144
- windowsHide: true,
145
89
  });
146
90
  }
147
91
  catch (err) {
@@ -255,29 +199,15 @@ class DockerExecutor {
255
199
  }
256
200
  }
257
201
  function killProcessTree(pid) {
258
- if (process.platform === "win32") {
259
- try {
260
- spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
261
- stdio: "ignore",
262
- detached: true,
263
- windowsHide: true,
264
- });
265
- }
266
- catch {
267
- // Ignore errors
268
- }
202
+ try {
203
+ process.kill(-pid, "SIGKILL");
269
204
  }
270
- else {
205
+ catch {
271
206
  try {
272
- process.kill(-pid, "SIGKILL");
207
+ process.kill(pid, "SIGKILL");
273
208
  }
274
209
  catch {
275
- try {
276
- process.kill(pid, "SIGKILL");
277
- }
278
- catch {
279
- // Process already dead
280
- }
210
+ // Process already dead
281
211
  }
282
212
  }
283
213
  }
@@ -1,5 +1,4 @@
1
1
  import { basename } from "node:path";
2
- import { isWindowsPlatform } from "./platform.js";
3
2
  const WHITESPACE = /\s+/;
4
3
  function stripNullAndNormalize(text) {
5
4
  return text.replace(/\0/g, "").normalize("NFKC");
@@ -549,9 +548,6 @@ export function guardCommand(command, config) {
549
548
  if (!config.enabled) {
550
549
  return { allowed: true };
551
550
  }
552
- if (isWindowsPlatform()) {
553
- return { allowed: true };
554
- }
555
551
  const match = evaluateCommand(command, config, 0);
556
552
  if (match) {
557
553
  return {