@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
@@ -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;
@@ -29,6 +30,8 @@ export declare class ChannelRunner implements AgentRunner {
29
30
  private firstTurnMemoryBootstrapPending;
30
31
  private acceptingBusyMessages;
31
32
  private agentLoopStarted;
33
+ /** When the primary model last failed and we switched to the backup. null = on primary. */
34
+ private primaryFailedAt;
32
35
  private runState;
33
36
  constructor(sandboxConfig: SandboxConfig, channelId: string, channelDir: string);
34
37
  run(ctx: DingTalkContext, store: ChannelStore): Promise<{
@@ -49,6 +52,17 @@ export declare class ChannelRunner implements AgentRunner {
49
52
  private queueBusyMessage;
50
53
  private resetRunState;
51
54
  private refreshSessionResources;
55
+ /**
56
+ * At turn start, if a fallback is active and the primary's cooldown has elapsed,
57
+ * switch back to the preferred model. Silent — no user notice on recovery.
58
+ */
59
+ private maybeRestorePrimaryModel;
60
+ /**
61
+ * Resolve the configured backup model reference against available models.
62
+ * Returns null when unset, unresolvable/ambiguous, or missing an API key —
63
+ * each case logs a warning and disables fallback for this turn.
64
+ */
65
+ private resolveFallbackModel;
52
66
  private initializeSession;
53
67
  private reloadSessionResources;
54
68
  private bindSessionExtensions;
@@ -10,7 +10,7 @@ import { MemoryLifecycle } from "../memory/lifecycle.js";
10
10
  import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../memory/maintenance-state.js";
11
11
  import { recallRelevantMemory } from "../memory/recall.js";
12
12
  import { getApiKeyForModel } from "../models/api-keys.js";
13
- import { formatModelReference, resolveInitialModel } from "../models/utils.js";
13
+ import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
14
14
  import { APP_HOME_DIR, AUTH_CONFIG_PATH, MODELS_CONFIG_PATH } from "../paths.js";
15
15
  import { createExecutor } from "../sandbox.js";
16
16
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
@@ -22,10 +22,12 @@ 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";
28
- import { clipUserInput } from "./progress-formatter.js";
29
+ import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
30
+ import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
29
31
  import { buildAppendSystemPrompt } from "./prompt-builder.js";
30
32
  import { createRunQueue } from "./run-queue.js";
31
33
  import { handleSessionEvent } from "./session-events.js";
@@ -53,10 +55,13 @@ function asSdkSettingsManager(manager) {
53
55
  }
54
56
  export class ChannelRunner {
55
57
  constructor(sandboxConfig, channelId, channelDir) {
58
+ this.ledger = getUsageLedger();
56
59
  this.currentTools = [];
57
60
  this.firstTurnMemoryBootstrapPending = true;
58
61
  this.acceptingBusyMessages = false;
59
62
  this.agentLoopStarted = false;
63
+ /** When the primary model last failed and we switched to the backup. null = on primary. */
64
+ this.primaryFailedAt = null;
60
65
  // --- Per run ---
61
66
  this.runState = createEmptyRunState();
62
67
  this.sandboxConfig = sandboxConfig;
@@ -148,8 +153,11 @@ export class ChannelRunner {
148
153
  const runQueue = createRunQueue(ctx);
149
154
  this.runState.queue = runQueue.queue;
150
155
  let promptSubmitted = false;
156
+ let fallbackAttempted = false;
157
+ let fallbackTargetRef;
151
158
  try {
152
159
  await this.ensureSessionReady();
160
+ await this.maybeRestorePrimaryModel();
153
161
  this.memoryLifecycle.noteUserTurnStarted();
154
162
  const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
155
163
  if (normalizedInputLength > MAX_USER_MESSAGE_CHARS) {
@@ -169,6 +177,7 @@ export class ChannelRunner {
169
177
  if (recallSettings.enabled) {
170
178
  const recall = await recallRelevantMemory({
171
179
  query: clippedInput,
180
+ channelId: this.channelId,
172
181
  workspaceDir: this.workspaceDir,
173
182
  channelDir: this.channelDir,
174
183
  maxCandidates: recallSettings.maxCandidates,
@@ -204,10 +213,58 @@ export class ChannelRunner {
204
213
  };
205
214
  await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2));
206
215
  }
207
- await this.sessionResourceGate.runPrompt(async () => {
208
- await this.session.prompt(promptText);
209
- promptSubmitted = true;
210
- });
216
+ const fallbackDeps = {
217
+ prompt: async (text) => {
218
+ try {
219
+ await this.sessionResourceGate.runPrompt(async () => {
220
+ await this.session.prompt(text);
221
+ promptSubmitted = true;
222
+ });
223
+ }
224
+ catch (err) {
225
+ this.runState.stopReason = "error";
226
+ this.runState.errorMessage = err instanceof Error ? err.message : String(err);
227
+ log.logWarning(`[${this.channelId}] Runner failed`, this.runState.errorMessage);
228
+ }
229
+ },
230
+ getRunError: () => ({
231
+ stopReason: this.runState.stopReason,
232
+ errorMessage: this.runState.errorMessage,
233
+ }),
234
+ resetRunError: () => {
235
+ this.runState.stopReason = "stop";
236
+ this.runState.errorMessage = undefined;
237
+ this.runState.finalOutcome = { kind: "none" };
238
+ this.runState.lastCompactionError = undefined;
239
+ },
240
+ getMessages: () => this.agent.state.messages,
241
+ setMessages: (messages) => {
242
+ this.agent.state.messages = messages;
243
+ },
244
+ promptWasSubmitted: () => promptSubmitted,
245
+ getCurrentModelRef: () => formatModelReference(this.session.model ?? this.activeModel),
246
+ resolveFallbackModel: () => this.resolveFallbackModel(),
247
+ setModel: async (model) => {
248
+ await this.session.setModel(model);
249
+ },
250
+ notifySwitch: (from, to, errorSummary) => {
251
+ fallbackTargetRef = to;
252
+ if (this.runState.logCtx) {
253
+ log.logModelFallback(this.runState.logCtx, from, to, errorSummary);
254
+ }
255
+ const text = `⚠️ 模型 ${from} 出错(${errorSummary}),切换到 ${to} 重试…`;
256
+ if (ctx.progressStyle !== "none") {
257
+ runQueue.queue.enqueue(() => ctx.respond(formatProgressEntry("error", text), false), "fallback switch");
258
+ }
259
+ else {
260
+ runQueue.queue.enqueue(() => ctx.respondInThread(text), "fallback switch");
261
+ }
262
+ },
263
+ markPrimaryFailed: () => {
264
+ this.primaryFailedAt = Date.now();
265
+ },
266
+ };
267
+ fallbackAttempted = await runPromptWithFallback(promptText, fallbackDeps);
211
268
  }
212
269
  catch (err) {
213
270
  this.runState.stopReason = "error";
@@ -245,6 +302,9 @@ export class ChannelRunner {
245
302
  if (compactionSummary) {
246
303
  detailLines.push(`Recovery: \`${compactionSummary}\``);
247
304
  }
305
+ if (fallbackAttempted && fallbackTargetRef) {
306
+ detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
307
+ }
248
308
  await ctx.replaceMessage(`_Sorry, something went wrong._\n\n${detailLines.join("\n\n")}`);
249
309
  }
250
310
  catch (err) {
@@ -299,6 +359,21 @@ export class ChannelRunner {
299
359
  const contextWindow = currentRunModel.contextWindow || 200000;
300
360
  log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
301
361
  const responseModel = lastAssistantMessage?.responseModel;
362
+ // Ledger turn entry: assistant-only usage (sub-agents recorded separately),
363
+ // keeping Σ(entries) == real spend with no double counting.
364
+ this.ledger.record({
365
+ channelId: this.channelId,
366
+ kind: "turn",
367
+ model: responseModel ?? formatModelReference(currentRunModel),
368
+ usage: {
369
+ input: this.runState.assistantUsage.input,
370
+ output: this.runState.assistantUsage.output,
371
+ cacheRead: this.runState.assistantUsage.cacheRead,
372
+ cacheWrite: this.runState.assistantUsage.cacheWrite,
373
+ total: this.runState.assistantUsage.total,
374
+ },
375
+ cost: { ...this.runState.assistantUsage.cost },
376
+ });
302
377
  if (responseModel &&
303
378
  responseModel !== formatModelReference(currentRunModel) &&
304
379
  responseModel !== currentRunModel.id) {
@@ -372,11 +447,18 @@ export class ChannelRunner {
372
447
  getStatusSnapshot() {
373
448
  const model = this.session.model ?? this.activeModel;
374
449
  const contextTokens = this.session.getContextUsage()?.tokens;
450
+ const fallbackActive = formatModelReference(model) !== formatModelReference(this.activeModel);
375
451
  return {
376
452
  model: formatModelReference(model),
377
453
  contextTokens: typeof contextTokens === "number" ? contextTokens : undefined,
378
454
  contextWindow: model.contextWindow || 200000,
379
455
  thinkingLevel: this.session.thinkingLevel,
456
+ fallback: fallbackActive
457
+ ? {
458
+ primary: formatModelReference(this.activeModel),
459
+ cooldownUntilMs: (this.primaryFailedAt ?? Date.now()) + PRIMARY_COOLDOWN_MS,
460
+ }
461
+ : undefined,
380
462
  };
381
463
  }
382
464
  async abort() {
@@ -468,6 +550,54 @@ export class ChannelRunner {
468
550
  await this.ensureSessionReady();
469
551
  await this.sessionResourceGate.requestRefresh();
470
552
  }
553
+ /**
554
+ * At turn start, if a fallback is active and the primary's cooldown has elapsed,
555
+ * switch back to the preferred model. Silent — no user notice on recovery.
556
+ */
557
+ async maybeRestorePrimaryModel() {
558
+ const current = this.session.model;
559
+ if (!current || formatModelReference(current) === formatModelReference(this.activeModel)) {
560
+ this.primaryFailedAt = null;
561
+ return;
562
+ }
563
+ if (!shouldRestorePrimary(this.primaryFailedAt, Date.now())) {
564
+ return;
565
+ }
566
+ try {
567
+ await this.session.setModel(this.activeModel);
568
+ this.primaryFailedAt = null;
569
+ log.logInfo(`[${this.channelId}] Restored primary model ${formatModelReference(this.activeModel)}`);
570
+ }
571
+ catch (err) {
572
+ log.logWarning(`[${this.channelId}] Failed to restore primary model`, err instanceof Error ? err.message : String(err));
573
+ }
574
+ }
575
+ /**
576
+ * Resolve the configured backup model reference against available models.
577
+ * Returns null when unset, unresolvable/ambiguous, or missing an API key —
578
+ * each case logs a warning and disables fallback for this turn.
579
+ */
580
+ async resolveFallbackModel() {
581
+ const reference = this.settingsManager.getFallbackModelReference();
582
+ if (!reference) {
583
+ return null;
584
+ }
585
+ this.modelRegistry.refresh();
586
+ const available = await this.modelRegistry.getAvailable();
587
+ const { match, ambiguous } = findExactModelReferenceMatch(reference, available);
588
+ if (!match) {
589
+ log.logWarning(`[${this.channelId}] fallbackModel "${reference}" ${ambiguous ? "is ambiguous" : "not found"}; skipping fallback`);
590
+ return null;
591
+ }
592
+ try {
593
+ await getApiKeyForModel(this.modelRegistry, match);
594
+ }
595
+ catch {
596
+ log.logWarning(`[${this.channelId}] fallbackModel "${reference}" has no API key; skipping fallback`);
597
+ return null;
598
+ }
599
+ return match;
600
+ }
471
601
  async initializeSession() {
472
602
  await this.reloadSessionResources();
473
603
  await this.bindSessionExtensions();
@@ -566,6 +696,8 @@ export class ChannelRunner {
566
696
  switchModel: async (model) => {
567
697
  await this.session.setModel(model);
568
698
  this.activeModel = model;
699
+ // Manual /model switch redefines the preferred model and clears fallback state.
700
+ this.primaryFailedAt = null;
569
701
  },
570
702
  refreshSessionResources: async () => {
571
703
  await this.refreshSessionResources();
@@ -707,6 +839,7 @@ export class ChannelRunner {
707
839
  store: this.runState.store,
708
840
  runState: this.runState,
709
841
  memoryLifecycle: this.memoryLifecycle,
842
+ ledger: this.ledger,
710
843
  refreshSessionResources: async () => {
711
844
  await this.refreshSessionResources();
712
845
  },
@@ -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;
@@ -0,0 +1,64 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ /**
3
+ * Backup-model fallback (spec 017).
4
+ *
5
+ * When the primary model's turn ends in error, switch to a single configured
6
+ * backup model and re-run the turn once. Pure decision helpers live here so the
7
+ * orchestration is fully testable without a real SDK session.
8
+ */
9
+ /** How long the primary model stays "cooling down" after a fallback before we retry it. */
10
+ export declare const PRIMARY_COOLDOWN_MS: number;
11
+ /**
12
+ * A turn ended with `stopReason: "error"`. Decide whether switching to the backup
13
+ * model is worth trying. Blacklist, not classifier: everything is worth a retry on a
14
+ * different provider EXCEPT context overflow (that is compaction's job — a bigger
15
+ * transcript fails the same way on any model). 429 / 5xx / quota / auth / even 400 all
16
+ * return true; the cost of a wasted extra attempt buys a one-sentence rule.
17
+ */
18
+ export declare function shouldFallback(errorMessage: string | undefined): boolean;
19
+ /**
20
+ * State surgery. The failed single-shot turn leaves the transcript tail as
21
+ * `[user, assistant(stopReason "error")]` — the shape of the common 429 / quota / auth
22
+ * case where the very first API call fails before any tool runs. Return the transcript
23
+ * with those two messages removed, ready to be re-prompted on the backup model.
24
+ *
25
+ * Returns `null` if the tail is any other shape (multi-step failure, unexpected state).
26
+ * The caller MUST then skip fallback — better to surface the error than corrupt context.
27
+ * This is the single coupling point to the SDK's `agent.state.messages` layout.
28
+ */
29
+ export declare function takeFailedTurn(messages: readonly unknown[]): unknown[] | null;
30
+ /** At turn start, may we leave the backup model and try the primary again? */
31
+ export declare function shouldRestorePrimary(primaryFailedAt: number | null, now: number): boolean;
32
+ /** Short one-line error summary for the user-facing switch notice. */
33
+ export declare function summarizeFallbackError(errorMessage: string | undefined): string;
34
+ export interface FallbackRunDeps {
35
+ /** Submit a prompt. Must catch transport/prompt errors and record them into run error state. */
36
+ prompt(text: string): Promise<void>;
37
+ /** Read the current turn's terminal error state (populated by prompt + session events). */
38
+ getRunError(): {
39
+ stopReason: string;
40
+ errorMessage?: string;
41
+ };
42
+ /** Clear stopReason/errorMessage/finalOutcome so the re-run starts clean. */
43
+ resetRunError(): void;
44
+ /** Live `agent.state.messages` reference for surgery. */
45
+ getMessages(): readonly unknown[];
46
+ /** Assign the truncated transcript back (SDK setter copies the array). */
47
+ setMessages(messages: unknown[]): void;
48
+ /** Whether the first prompt actually enqueued its user message (false = pre-flight throw, e.g. no API key). */
49
+ promptWasSubmitted(): boolean;
50
+ getCurrentModelRef(): string;
51
+ /** Resolve the configured backup model, or null (unset / unresolvable / no API key). */
52
+ resolveFallbackModel(): Promise<Model<Api> | null>;
53
+ setModel(model: Model<Api>): Promise<void>;
54
+ /** Notify the user a switch happened. */
55
+ notifySwitch(from: string, to: string, errorSummary: string): void;
56
+ /** Record `primaryFailedAt = now` so cooldown/restore logic engages. */
57
+ markPrimaryFailed(): void;
58
+ }
59
+ /**
60
+ * Run the prompt with at most one backup-model retry. Returns whether a fallback
61
+ * re-run was attempted (for error-message wording / logging). When no backup is
62
+ * configured, this is a single `prompt()` — behaviorally identical to the status quo.
63
+ */
64
+ export declare function runPromptWithFallback(promptText: string, deps: FallbackRunDeps): Promise<boolean>;
@@ -0,0 +1,125 @@
1
+ import { isContextOverflow } from "@earendil-works/pi-ai";
2
+ import * as log from "../log.js";
3
+ import { formatModelReference } from "../models/utils.js";
4
+ import { isRecord } from "../shared/type-guards.js";
5
+ /**
6
+ * Backup-model fallback (spec 017).
7
+ *
8
+ * When the primary model's turn ends in error, switch to a single configured
9
+ * backup model and re-run the turn once. Pure decision helpers live here so the
10
+ * orchestration is fully testable without a real SDK session.
11
+ */
12
+ /** How long the primary model stays "cooling down" after a fallback before we retry it. */
13
+ export const PRIMARY_COOLDOWN_MS = 5 * 60_000;
14
+ /**
15
+ * A turn ended with `stopReason: "error"`. Decide whether switching to the backup
16
+ * model is worth trying. Blacklist, not classifier: everything is worth a retry on a
17
+ * different provider EXCEPT context overflow (that is compaction's job — a bigger
18
+ * transcript fails the same way on any model). 429 / 5xx / quota / auth / even 400 all
19
+ * return true; the cost of a wasted extra attempt buys a one-sentence rule.
20
+ */
21
+ export function shouldFallback(errorMessage) {
22
+ if (!errorMessage) {
23
+ return true;
24
+ }
25
+ // Only the error-message branch of isContextOverflow matters here (we already know
26
+ // stopReason === "error"); usage/contextWindow paths are irrelevant, so a minimal
27
+ // message is enough. NON_OVERFLOW_PATTERNS inside keeps rate-limit (429) → fallback.
28
+ const overflow = isContextOverflow({
29
+ role: "assistant",
30
+ stopReason: "error",
31
+ errorMessage,
32
+ content: [],
33
+ usage: {
34
+ input: 0,
35
+ output: 0,
36
+ cacheRead: 0,
37
+ cacheWrite: 0,
38
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
39
+ },
40
+ });
41
+ return !overflow;
42
+ }
43
+ function isAssistantErrorMessage(value) {
44
+ return isRecord(value) && value.role === "assistant" && value.stopReason === "error";
45
+ }
46
+ function isUserMessage(value) {
47
+ return isRecord(value) && value.role === "user";
48
+ }
49
+ /**
50
+ * State surgery. The failed single-shot turn leaves the transcript tail as
51
+ * `[user, assistant(stopReason "error")]` — the shape of the common 429 / quota / auth
52
+ * case where the very first API call fails before any tool runs. Return the transcript
53
+ * with those two messages removed, ready to be re-prompted on the backup model.
54
+ *
55
+ * Returns `null` if the tail is any other shape (multi-step failure, unexpected state).
56
+ * The caller MUST then skip fallback — better to surface the error than corrupt context.
57
+ * This is the single coupling point to the SDK's `agent.state.messages` layout.
58
+ */
59
+ export function takeFailedTurn(messages) {
60
+ if (messages.length < 2) {
61
+ return null;
62
+ }
63
+ const last = messages[messages.length - 1];
64
+ const prev = messages[messages.length - 2];
65
+ if (!isAssistantErrorMessage(last) || !isUserMessage(prev)) {
66
+ return null;
67
+ }
68
+ return messages.slice(0, -2);
69
+ }
70
+ /** At turn start, may we leave the backup model and try the primary again? */
71
+ export function shouldRestorePrimary(primaryFailedAt, now) {
72
+ if (primaryFailedAt === null) {
73
+ return true;
74
+ }
75
+ return now - primaryFailedAt > PRIMARY_COOLDOWN_MS;
76
+ }
77
+ /** Short one-line error summary for the user-facing switch notice. */
78
+ export function summarizeFallbackError(errorMessage) {
79
+ if (!errorMessage) {
80
+ return "未知错误";
81
+ }
82
+ const firstLine = errorMessage.split("\n")[0]?.trim() ?? "";
83
+ if (!firstLine) {
84
+ return "未知错误";
85
+ }
86
+ return firstLine.length > 120 ? `${firstLine.slice(0, 117)}...` : firstLine;
87
+ }
88
+ /**
89
+ * Run the prompt with at most one backup-model retry. Returns whether a fallback
90
+ * re-run was attempted (for error-message wording / logging). When no backup is
91
+ * configured, this is a single `prompt()` — behaviorally identical to the status quo.
92
+ */
93
+ export async function runPromptWithFallback(promptText, deps) {
94
+ await deps.prompt(promptText);
95
+ const firstError = deps.getRunError();
96
+ if (firstError.stopReason !== "error" || !shouldFallback(firstError.errorMessage)) {
97
+ return false;
98
+ }
99
+ const candidate = await deps.resolveFallbackModel();
100
+ if (!candidate) {
101
+ return false;
102
+ }
103
+ const fromRef = deps.getCurrentModelRef();
104
+ const toRef = formatModelReference(candidate);
105
+ if (fromRef === toRef) {
106
+ return false;
107
+ }
108
+ // Surgery only when the failed turn was actually enqueued. A pre-flight throw
109
+ // (no API key on the primary) submits nothing, so there is nothing to remove —
110
+ // switch straight to the backup, which covers a mis-configured primary key.
111
+ if (deps.promptWasSubmitted()) {
112
+ const truncated = takeFailedTurn(deps.getMessages());
113
+ if (!truncated) {
114
+ log.logWarning("[fallback] transcript tail is not [user, assistant(error)]; skipping fallback to avoid corrupting context");
115
+ return false;
116
+ }
117
+ deps.setMessages(truncated);
118
+ }
119
+ deps.markPrimaryFailed();
120
+ await deps.setModel(candidate);
121
+ deps.notifySwitch(fromRef, toRef, summarizeFallbackError(firstError.errorMessage));
122
+ deps.resetRunError();
123
+ await deps.prompt(promptText);
124
+ return true;
125
+ }
@@ -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,
@@ -8,6 +8,11 @@ export interface RunnerStatusSnapshot {
8
8
  contextTokens?: number;
9
9
  contextWindow: number;
10
10
  thinkingLevel: string;
11
+ /** Present only while running on the backup model (spec 017). */
12
+ fallback?: {
13
+ primary: string;
14
+ cooldownUntilMs: number;
15
+ };
11
16
  }
12
17
  export interface AgentRunner {
13
18
  run(ctx: DingTalkContext, store: ChannelStore): Promise<{
@@ -50,6 +55,8 @@ export interface RunState {
50
55
  queue: RunQueue | null;
51
56
  pendingTools: Map<string, PendingTool>;
52
57
  totalUsage: UsageTotals;
58
+ /** Main-loop assistant usage only (excludes sub-agents). Feeds the turn ledger entry. */
59
+ assistantUsage: UsageTotals;
53
60
  stopReason: string;
54
61
  errorMessage: string | undefined;
55
62
  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;
@@ -13,6 +37,7 @@ export declare function logResponse(ctx: LogContext, text: string): void;
13
37
  export declare function logInfo(message: string): void;
14
38
  export declare function logWarning(message: string, details?: string): void;
15
39
  export declare function logAgentError(ctx: LogContext | "system", error: string): void;
40
+ export declare function logModelFallback(ctx: LogContext, from: string, to: string, error: string): void;
16
41
  export declare function logUsageSummary(ctx: LogContext, usage: {
17
42
  input: number;
18
43
  output: number;