@oyasmi/pipiclaw 0.9.3-beta.6 → 0.9.4-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.js +137 -61
  4. package/dist/agent/command-extension.js +47 -34
  5. package/dist/agent/job-manager.js +31 -11
  6. package/dist/agent/model-fallback.js +1 -1
  7. package/dist/agent/prompt/manifest.d.ts +6 -1
  8. package/dist/agent/prompt/manifest.js +45 -64
  9. package/dist/agent/prompt/resources.js +4 -1
  10. package/dist/agent/run-queue.js +7 -2
  11. package/dist/agent/session-adapter.js +1 -1
  12. package/dist/agent/session-events.js +17 -6
  13. package/dist/agent/session-resource-gate.js +3 -1
  14. package/dist/agent/status-render.d.ts +0 -1
  15. package/dist/agent/status-render.js +4 -16
  16. package/dist/agent/turn-error.d.ts +31 -0
  17. package/dist/agent/turn-error.js +68 -0
  18. package/dist/app-services.js +7 -4
  19. package/dist/channel/channel-index.d.ts +9 -2
  20. package/dist/channel/channel-index.js +29 -7
  21. package/dist/channel/project-scope-store.js +1 -1
  22. package/dist/commands/catalog.d.ts +21 -4
  23. package/dist/commands/catalog.js +88 -41
  24. package/dist/commands/reply-limits.d.ts +6 -0
  25. package/dist/commands/reply-limits.js +24 -0
  26. package/dist/events/event-commands.js +94 -44
  27. package/dist/events/event-validation.d.ts +13 -2
  28. package/dist/events/event-validation.js +17 -9
  29. package/dist/events/events.js +77 -32
  30. package/dist/executor.js +2 -2
  31. package/dist/log.d.ts +12 -2
  32. package/dist/log.js +26 -34
  33. package/dist/main.js +1 -1
  34. package/dist/memory/commands.js +29 -23
  35. package/dist/memory/lifecycle.js +26 -5
  36. package/dist/memory/maintenance-state.js +4 -1
  37. package/dist/memory/scheduler.js +3 -1
  38. package/dist/models/auth-cli.js +3 -2
  39. package/dist/paths.d.ts +2 -0
  40. package/dist/paths.js +9 -0
  41. package/dist/playbooks/agent-delegation.md +2 -2
  42. package/dist/runtime/app-home.d.ts +6 -0
  43. package/dist/runtime/app-home.js +21 -3
  44. package/dist/runtime/bootstrap.js +192 -64
  45. package/dist/runtime/channel-queue.js +1 -1
  46. package/dist/runtime/delivery.js +29 -15
  47. package/dist/runtime/dingtalk.js +96 -42
  48. package/dist/runtime/durable-dispatch.d.ts +27 -1
  49. package/dist/runtime/durable-dispatch.js +111 -3
  50. package/dist/runtime/project-commands.js +16 -15
  51. package/dist/runtime/proxy.js +4 -2
  52. package/dist/runtime/report-commands.js +1 -1
  53. package/dist/runtime/skill-commands.d.ts +1 -1
  54. package/dist/runtime/skill-commands.js +17 -10
  55. package/dist/runtime/subagent-commands.d.ts +5 -4
  56. package/dist/runtime/subagent-commands.js +116 -77
  57. package/dist/runtime/task-commands.d.ts +1 -1
  58. package/dist/runtime/task-commands.js +110 -64
  59. package/dist/runtime/task-driver.d.ts +6 -3
  60. package/dist/runtime/task-driver.js +57 -22
  61. package/dist/runtime/task-migration.d.ts +7 -2
  62. package/dist/runtime/task-migration.js +247 -61
  63. package/dist/runtime/task-spawn.js +12 -5
  64. package/dist/runtime/wake-coalescing.d.ts +18 -0
  65. package/dist/runtime/wake-coalescing.js +29 -0
  66. package/dist/security/block-message.d.ts +22 -1
  67. package/dist/security/block-message.js +66 -1
  68. package/dist/security/network.d.ts +2 -1
  69. package/dist/security/network.js +3 -2
  70. package/dist/security/path-guard-check.js +2 -2
  71. package/dist/settings.d.ts +3 -2
  72. package/dist/settings.js +4 -1
  73. package/dist/shared/format.d.ts +12 -0
  74. package/dist/shared/format.js +37 -0
  75. package/dist/shared/host-process.js +15 -3
  76. package/dist/shared/with-timeout.d.ts +3 -2
  77. package/dist/shared/with-timeout.js +14 -3
  78. package/dist/subagents/external/claude-code.js +23 -1
  79. package/dist/subagents/external/progress-tail.d.ts +17 -0
  80. package/dist/subagents/external/progress-tail.js +64 -17
  81. package/dist/subagents/external/run.d.ts +3 -0
  82. package/dist/subagents/external/run.js +21 -7
  83. package/dist/subagents/external/settlement.d.ts +3 -0
  84. package/dist/subagents/external/settlement.js +1 -1
  85. package/dist/subagents/runs.d.ts +21 -1
  86. package/dist/subagents/runs.js +137 -32
  87. package/dist/subagents/tool.d.ts +22 -15
  88. package/dist/subagents/tool.js +226 -32
  89. package/dist/subagents/workspace-summary.d.ts +16 -4
  90. package/dist/subagents/workspace-summary.js +74 -18
  91. package/dist/tasks/board.d.ts +8 -1
  92. package/dist/tasks/board.js +37 -2
  93. package/dist/tasks/frontmatter.d.ts +5 -0
  94. package/dist/tasks/frontmatter.js +8 -0
  95. package/dist/tasks/log.d.ts +11 -1
  96. package/dist/tasks/log.js +58 -2
  97. package/dist/tasks/store.d.ts +18 -1
  98. package/dist/tasks/store.js +61 -9
  99. package/dist/tasks/ticket.d.ts +3 -1
  100. package/dist/tasks/ticket.js +19 -1
  101. package/dist/tools/bash.js +2 -2
  102. package/dist/tools/index.d.ts +2 -0
  103. package/dist/tools/index.js +1 -0
  104. package/dist/tools/memory-manage.js +4 -1
  105. package/dist/tools/subagent-manage.d.ts +1 -1
  106. package/dist/tools/subagent-manage.js +16 -11
  107. package/dist/tools/task-manage/step-end.js +4 -1
  108. package/dist/tools/tool-details.d.ts +10 -2
  109. package/dist/tools/tool-details.js +39 -2
  110. package/dist/tui/cli.js +2 -2
  111. package/dist/tui/commands.js +4 -4
  112. package/dist/tui/pitui-frontend.js +1 -1
  113. package/dist/tui/renderer.js +3 -2
  114. package/dist/tui/turn-controller.d.ts +2 -0
  115. package/dist/tui/turn-controller.js +36 -21
  116. package/dist/usage/ledger.js +3 -1
  117. package/dist/usage/render.js +3 -1
  118. package/package.json +1 -1
@@ -1,24 +1,43 @@
1
1
  import { basename } from "path";
2
- import { sessionCommandDescription } from "../commands/catalog.js";
2
+ import { formatNewSessionReply, sessionCommandDescription } from "../commands/catalog.js";
3
+ import { capReply } from "../commands/reply-limits.js";
3
4
  import { findModelReferenceMatch, formatModelList, formatModelReference } from "../models/utils.js";
5
+ import { estimateTokens } from "../shared/format.js";
6
+ import { truncate } from "../shared/text-utils.js";
4
7
  export const COMMAND_RESULT_CUSTOM_TYPE = "pipiclaw.command_result";
5
8
  function buildSessionText(stats, currentModel, thinkingLevel, lastResponseModel) {
6
9
  const configuredRef = currentModel ? formatModelReference(currentModel) : null;
7
- const modelText = configuredRef ? `\`${configuredRef}\`` : "(none)";
10
+ const modelText = configuredRef ? `\`${configuredRef}\`` : "(无)";
8
11
  const actualText = lastResponseModel && configuredRef && lastResponseModel !== configuredRef
9
- ? ` (actual: \`${lastResponseModel}\`)`
12
+ ? `(实际响应:\`${lastResponseModel}\`)`
10
13
  : "";
11
- const sessionFile = stats.sessionFile ? `\`${basename(stats.sessionFile)}\`` : "(none)";
14
+ const sessionFile = stats.sessionFile ? `\`${basename(stats.sessionFile)}\`` : "(无)";
15
+ const tokens = stats.tokens;
12
16
  return `**会话**
13
17
 
14
- - Session ID:\`${stats.sessionId}\`
15
- - Session file:${sessionFile}
18
+ - 会话 ID:\`${stats.sessionId}\`
19
+ - 会话文件:${sessionFile}
16
20
  - 模型:${modelText}${actualText}
17
- - Thinking level:\`${thinkingLevel}\`
21
+ - 思考档位(thinking):\`${thinkingLevel}\`
18
22
  - 消息:用户 \`${stats.userMessages}\` · 助手 \`${stats.assistantMessages}\` · 共 \`${stats.totalMessages}\`
19
23
  - 工具调用:\`${stats.toolCalls}\` · 工具结果:\`${stats.toolResults}\`
20
- - Tokens:\`${stats.tokens.total}\`(input \`${stats.tokens.input}\`,output \`${stats.tokens.output}\`,cache read \`${stats.tokens.cacheRead}\`,cache write \`${stats.tokens.cacheWrite}\`)
21
- - Cost:\`$${stats.cost.toFixed(4)}\``;
24
+ - token 用量:共 \`${tokens.total}\`(输入 \`${tokens.input}\`,输出 \`${tokens.output}\`,缓存读 \`${tokens.cacheRead}\`,缓存写 \`${tokens.cacheWrite}\`)
25
+ - 花费:\`$${stats.cost.toFixed(4)}\``;
26
+ }
27
+ /**
28
+ * The `/compact` confirmation: sizes and the summary's first line only — the summary itself is
29
+ * the model's working notes and can run to pages (spec 053, D9).
30
+ */
31
+ function buildCompactText(result) {
32
+ const after = result.estimatedTokensAfter ?? estimateTokens(result.summary);
33
+ const firstLine = result.summary
34
+ .split("\n")
35
+ .map((line) => line.replace(/^#+\s*/, "").trim())
36
+ .find(Boolean) ?? "";
37
+ const lines = [`已压缩当前会话上下文:压缩前 \`${result.tokensBefore}\` tokens,压缩后约 \`${after}\` tokens。`];
38
+ if (firstLine)
39
+ lines.push(`摘要开头:${truncate(firstLine, 120)}`);
40
+ return lines.join("\n");
22
41
  }
23
42
  async function runCompact(ctx, customInstructions) {
24
43
  return await new Promise((resolve, reject) => {
@@ -37,12 +56,12 @@ function sendCommandResult(sender, text) {
37
56
  });
38
57
  }
39
58
  function buildThinkingText(current, available) {
40
- return `**Thinking**
59
+ return `**思考档位**
41
60
 
42
61
  - 当前档位:\`${current}\`
43
- - 可用档位:${available.map((level) => `\`${level}\``).join(", ")}
62
+ - 可用档位:${available.map((level) => `\`${level}\``).join("、")}
44
63
 
45
- 用 \`/thinking <level>\` 设置档位,或 \`/thinking cycle\` 切到下一个支持的档位。`;
64
+ 用 \`/thinking <档位>\` 设置,或 \`/thinking cycle\` 切到下一个可用档位。`;
46
65
  }
47
66
  export function createCommandExtension(options) {
48
67
  return (pi) => {
@@ -70,21 +89,21 @@ export function createCommandExtension(options) {
70
89
  if (normalized === "cycle") {
71
90
  const next = options.cycleThinkingLevel();
72
91
  if (!next) {
73
- sendCommandResult(pi, "当前模型不支持 thinking/reasoning。");
92
+ sendCommandResult(pi, "当前模型不支持思考档位。用 `/model` 换一个支持推理的模型。");
74
93
  return;
75
94
  }
76
- sendCommandResult(pi, `Thinking level 已切换为 \`${next}\`。`);
95
+ sendCommandResult(pi, `思考档位已切换为 \`${next}\`。`);
77
96
  return;
78
97
  }
79
98
  if (!available.includes(normalized)) {
80
- sendCommandResult(pi, `不支持 thinking level \`${args.trim()}\`。当前模型可用值:${available
99
+ sendCommandResult(pi, `当前模型不支持思考档位 \`${args.trim()}\`。可用档位:${available
81
100
  .map((level) => `\`${level}\``)
82
- .join(", ")}`);
101
+ .join("、")}。`);
83
102
  return;
84
103
  }
85
104
  const level = normalized;
86
105
  options.setThinkingLevel(level);
87
- sendCommandResult(pi, `Thinking level 已设置为 \`${level}\`。`);
106
+ sendCommandResult(pi, `思考档位已设置为 \`${level}\`。`);
88
107
  },
89
108
  });
90
109
  pi.registerCommand("model", {
@@ -93,23 +112,24 @@ export function createCommandExtension(options) {
93
112
  const availableModels = await options.getAvailableModels();
94
113
  const currentModel = options.getCurrentModel();
95
114
  if (!args.trim()) {
96
- const current = currentModel ? `\`${formatModelReference(currentModel)}\`` : "(none)";
97
- const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel) : "- (none)";
98
- sendCommandResult(pi, `**模型**
115
+ const current = currentModel ? `\`${formatModelReference(currentModel)}\`` : "(无)";
116
+ const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel) : "- (无可用模型)";
117
+ const report = `**模型**
99
118
 
100
119
  当前模型:${current}
101
120
 
102
- 用 \`/model <provider/modelId>\`、\`/model <modelId>\` 或任意能唯一匹配的子串切换。
121
+ 用 \`/model <provider/modelId>\`、\`/model <modelId>\` 或任意能唯一匹配的片段切换。
103
122
 
104
123
  可用模型:
105
- ${available}`);
124
+ ${available}`;
125
+ sendCommandResult(pi, capReply(report, { nextStepHint: "用 `/model <片段>` 按名称直接切换" }).text);
106
126
  return;
107
127
  }
108
128
  const match = findModelReferenceMatch(args, availableModels);
109
- const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel, 10) : "- (none)";
129
+ const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel, 10) : "- (无可用模型)";
110
130
  if (match.match) {
111
131
  await options.switchModel(match.match);
112
- sendCommandResult(pi, `已切换模型到 \`${formatModelReference(match.match)}\``);
132
+ sendCommandResult(pi, `已切换模型到 \`${formatModelReference(match.match)}\`。`);
113
133
  return;
114
134
  }
115
135
  if (match.ambiguous) {
@@ -133,7 +153,7 @@ ${available}`);
133
153
  withSession: async (nextCtx) => {
134
154
  sentFromReplacement = true;
135
155
  await options.refreshSessionResources();
136
- await sendCommandResult(nextCtx, `已开启新会话。\n\nSession ID:\`${nextCtx.sessionManager.getSessionId()}\``);
156
+ await sendCommandResult(nextCtx, formatNewSessionReply(nextCtx.sessionManager.getSessionId()));
137
157
  },
138
158
  });
139
159
  if (result.cancelled) {
@@ -141,7 +161,7 @@ ${available}`);
141
161
  }
142
162
  else if (!sentFromReplacement) {
143
163
  await options.refreshSessionResources();
144
- sendCommandResult(pi, `已开启新会话。\n\nSession ID:\`${ctx.sessionManager.getSessionId()}\``);
164
+ sendCommandResult(pi, formatNewSessionReply(ctx.sessionManager.getSessionId()));
145
165
  }
146
166
  },
147
167
  });
@@ -150,14 +170,7 @@ ${available}`);
150
170
  handler: async (args, ctx) => {
151
171
  const customInstructions = args.trim() || undefined;
152
172
  const result = await runCompact(ctx, customInstructions);
153
- sendCommandResult(pi, `已压缩当前会话上下文。
154
-
155
- - 压缩前 tokens:\`${result.tokensBefore}\`
156
- - 摘要:
157
-
158
- \`\`\`text
159
- ${result.summary}
160
- \`\`\``);
173
+ sendCommandResult(pi, buildCompactText(result));
161
174
  },
162
175
  });
163
176
  };
@@ -235,7 +235,10 @@ export class ChannelJobManager {
235
235
  catch (error) {
236
236
  if (required)
237
237
  throw error;
238
- log.logWarning(`Failed to persist background job ${record.id}`, errorMessage(error));
238
+ log.logWarn("job.persist.failed", "Background job persist failed", {
239
+ reason: errorMessage(error),
240
+ fields: { jobId: record.id },
241
+ });
239
242
  }
240
243
  }
241
244
  async forget(record) {
@@ -416,7 +419,10 @@ export class ChannelJobManager {
416
419
  agent: "job",
417
420
  label,
418
421
  }).catch((error) => {
419
- log.logWarning(`Failed to log dispatch of job ${id} to task ${options.taskId}`, errorMessage(error));
422
+ log.logWarn("job.task_dispatch.log_failed", "Task dispatch record failed", {
423
+ reason: errorMessage(error),
424
+ fields: { jobId: id, taskId: options.taskId },
425
+ });
420
426
  });
421
427
  }
422
428
  this.ensureSweeper();
@@ -484,7 +490,7 @@ export class ChannelJobManager {
484
490
  // rejection here (a probe that cannot spawn — EAGAIN/EMFILE/ENOMEM) exits the
485
491
  // whole daemon, since nothing installs a process-level rejection handler.
486
492
  this.sweep().catch((error) => {
487
- log.logWarning("Background job sweep failed", errorMessage(error));
493
+ log.logWarn("job.sweep.failed", "Background job sweep failed", { reason: errorMessage(error) });
488
494
  });
489
495
  }, this.sweepIntervalMs);
490
496
  // Do not keep the process alive just for the sweeper.
@@ -524,7 +530,10 @@ export class ChannelJobManager {
524
530
  await this.applyProbe(record, probes.get(record.id) ?? "");
525
531
  })
526
532
  .catch((error) => {
527
- log.logWarning(`Background job sweep failed to refresh job ${record.id}`, errorMessage(error));
533
+ log.logWarn("job.sweep.refresh_failed", "Background job refresh failed", {
534
+ reason: errorMessage(error),
535
+ fields: { jobId: record.id },
536
+ });
528
537
  });
529
538
  }
530
539
  await this.collectGarbage();
@@ -713,7 +722,10 @@ export class ChannelJobManager {
713
722
  tail: output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim() || undefined,
714
723
  durationMs: record.durationMs,
715
724
  }).catch((error) => {
716
- log.logWarning(`Failed to log settlement of job ${record.id} to task ${taskId}`, errorMessage(error));
725
+ log.logWarn("job.task_settle.log_failed", "Task settlement record failed", {
726
+ reason: errorMessage(error),
727
+ fields: { jobId: record.id, taskId },
728
+ });
717
729
  });
718
730
  await this.persist(record);
719
731
  }
@@ -763,7 +775,10 @@ export class ChannelJobManager {
763
775
  await this.options.dispatch(event);
764
776
  }
765
777
  catch (error) {
766
- log.logWarning(`Failed to dispatch completion wake for job ${record.id}`, errorMessage(error));
778
+ log.logWarn("job.wake.dispatch_failed", "Completion wake dispatch failed", {
779
+ reason: errorMessage(error),
780
+ fields: { jobId: record.id },
781
+ });
767
782
  return;
768
783
  }
769
784
  record.notified = true;
@@ -972,7 +987,9 @@ export class ChannelJobManager {
972
987
  record = undefined;
973
988
  }
974
989
  if (!record) {
975
- log.logWarning(`Discarding unreadable background job record: ${filename}`);
990
+ log.logWarn("job.record.unreadable", "Unreadable background job record discarded", {
991
+ fields: { file: filename },
992
+ });
976
993
  await unlink(path).catch(() => undefined);
977
994
  continue;
978
995
  }
@@ -981,7 +998,10 @@ export class ChannelJobManager {
981
998
  // One probe decides between "still running", "finished while we were down", and "gone";
982
999
  // refresh already encodes all three, including the late completion wake.
983
1000
  await this.refresh(record, signal).catch((error) => {
984
- log.logWarning(`Failed to reconcile background job ${record?.id}`, errorMessage(error));
1001
+ log.logWarn("job.reconcile.failed", "Background job reconcile failed", {
1002
+ reason: errorMessage(error),
1003
+ fields: { jobId: record?.id },
1004
+ });
985
1005
  });
986
1006
  }
987
1007
  await this.collectGarbage();
@@ -1019,7 +1039,7 @@ export function createJobRuntime(executor, options = {}) {
1019
1039
  const manager = managers.get(channelId);
1020
1040
  if (!manager)
1021
1041
  return [];
1022
- return manager.listRunning().map((job) => `job \`${job.id}\`: ${job.command.slice(0, 80)}`);
1042
+ return manager.listRunning().map((job) => `后台作业 \`${job.id}\` 仍在运行:${job.command.slice(0, 80)}`);
1023
1043
  }
1024
1044
  function get(channelId) {
1025
1045
  let manager = managers.get(channelId);
@@ -1057,7 +1077,7 @@ export function createJobRuntime(executor, options = {}) {
1057
1077
  .map((entry) => entry.name);
1058
1078
  }
1059
1079
  catch (error) {
1060
- log.logWarning("Failed to scan persisted background jobs", errorMessage(error));
1080
+ log.logWarn("job.scan.failed", "Persisted background job scan failed", { reason: errorMessage(error) });
1061
1081
  return 0;
1062
1082
  }
1063
1083
  let restored = 0;
@@ -1065,7 +1085,7 @@ export function createJobRuntime(executor, options = {}) {
1065
1085
  restored += await get(channelId).restore();
1066
1086
  }
1067
1087
  if (restored > 0) {
1068
- log.logInfo(`Restored ${restored} background job record(s)`);
1088
+ log.logInfoEvent("job.restore.done", "Background job records restored", { fields: { count: restored } });
1069
1089
  }
1070
1090
  return restored;
1071
1091
  }
@@ -113,7 +113,7 @@ export async function runPromptWithFallback(promptText, deps) {
113
113
  if (deps.promptWasSubmitted()) {
114
114
  truncated = takeFailedTurn(deps.getMessages());
115
115
  if (!truncated) {
116
- log.logWarning("[fallback] transcript tail is not [user, assistant(error)]; skipping fallback to avoid corrupting context");
116
+ log.logWarn("agent.model.fallback_skipped", "Fallback skipped: transcript tail is not [user, assistant(error)]");
117
117
  return false;
118
118
  }
119
119
  }
@@ -32,7 +32,7 @@ export interface ToolSchemaMeasurement {
32
32
  chars: number;
33
33
  units: number;
34
34
  }
35
- /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
35
+ /** The operator wording for "the tool set is over budget", for the rebuild log (`/context` says it in Chinese). */
36
36
  export declare function toolSchemaBudgetWarning(measurement: ToolSchemaMeasurement): string;
37
37
  /**
38
38
  * What the tool set costs on top of the system prompt. Counts what the provider is actually sent
@@ -102,4 +102,9 @@ export declare function estimateSkillsPromptChars(skills: Array<{
102
102
  }>): number;
103
103
  /** Section metadata without any section body — safe to write next to a channel. */
104
104
  export declare function buildPromptManifest(build: PromptBuildResult, finalPrompt?: string): PromptManifest;
105
+ /**
106
+ * `/context` (spec 053, D9): the default view is a summary a user can read on a phone; `detail`
107
+ * adds the per-section sources and the tool/skill inventory, still under the reply budget.
108
+ * "单位" is the prompt-unit measure the budgets are written in (`countPromptUnits`).
109
+ */
105
110
  export declare function renderContextReport(input: PromptContextReportInput): string;
@@ -9,6 +9,7 @@
9
9
  * owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
10
10
  * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
11
  */
12
+ import { capReply } from "../../commands/reply-limits.js";
12
13
  import { estimateTokens } from "../../shared/format.js";
13
14
  import { countPromptUnits } from "../../shared/prompt-units.js";
14
15
  import { RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
@@ -30,7 +31,7 @@ export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
30
31
  * is exactly when someone should be looking.
31
32
  */
32
33
  export const TOOL_SCHEMA_TARGET_UNITS = 3_000;
33
- /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
34
+ /** The operator wording for "the tool set is over budget", for the rebuild log (`/context` says it in Chinese). */
34
35
  export function toolSchemaBudgetWarning(measurement) {
35
36
  return `tool JSON schemas are ${measurement.units} units (${measurement.chars} chars), over the ${TOOL_SCHEMA_TARGET_UNITS} unit target. Shorten a tool description, move detail into a playbook, or unregister a tool; \`/context detail\` lists the set.`;
36
37
  }
@@ -78,84 +79,64 @@ export function buildPromptManifest(build, finalPrompt) {
78
79
  function formatNumber(value) {
79
80
  return value.toLocaleString("en-US");
80
81
  }
81
- function renderWorkspaceResourceLine(label, resource) {
82
+ function renderWorkspaceResource(label, resource) {
82
83
  if (!resource || resource.isDefaultTemplate)
83
84
  return undefined;
84
- const state = resource.truncated ? "truncated" : "complete";
85
- return `- ${label}: ${formatNumber(resource.injectedUnits)} / ${formatNumber(resource.budgetUnits)} units, ${state}`;
85
+ const state = resource.truncated ? ",已截断" : "";
86
+ return `${label} ${formatNumber(resource.injectedUnits)} / ${formatNumber(resource.budgetUnits)} 单位${state}`;
86
87
  }
88
+ /**
89
+ * `/context` (spec 053, D9): the default view is a summary a user can read on a phone; `detail`
90
+ * adds the per-section sources and the tool/skill inventory, still under the reply budget.
91
+ * "单位" is the prompt-unit measure the budgets are written in (`countPromptUnits`).
92
+ */
87
93
  export function renderContextReport(input) {
88
94
  const { build, finalPrompt, detail } = input;
89
- const lines = ["# Context Report", ""];
90
- lines.push(`Pipiclaw runtime-authored: ${formatNumber(build.runtimeAuthoredUnits)} units (target ${formatNumber(RUNTIME_PROMPT_TARGET_UNITS)}) · Pipiclaw sections total: ${formatNumber(build.totalUnits)} units / ${formatNumber(build.totalChars)} chars, ~${formatNumber(build.estimatedTokens)} tokens`);
95
+ const lines = ["**上下文**", ""];
96
+ lines.push(`- 系统提示词(Pipiclaw 部分):${formatNumber(build.totalUnits)} 单位,约 ${formatNumber(build.estimatedTokens)} tokens;其中运行时自带 ${formatNumber(build.runtimeAuthoredUnits)} / 目标 ${formatNumber(RUNTIME_PROMPT_TARGET_UNITS)} 单位`);
91
97
  if (finalPrompt) {
92
98
  // The string the provider actually caches: our sections + pi's skills/date/cwd tail +
93
99
  // the boundary footer. It is the fingerprint that matters for cache hits — the build
94
- // fingerprint below only covers the part Pipiclaw owns, and stays stable across a
95
- // date rollover that does invalidate the provider's cached prefix.
96
- lines.push(`Sent to the model (incl. skills, date, cwd): ${formatNumber(finalPrompt.length)} chars, ~${formatNumber(estimateTokens(finalPrompt))} tokens, sha256:${sha256(finalPrompt).slice(0, 16)}`);
97
- }
98
- lines.push(`Fingerprint (Pipiclaw sections): sha256:${build.fingerprint.slice(0, 16)}`);
99
- lines.push("");
100
- // Space-padded column alignment relies on a monospace font: DingTalk's proportional rendering
101
- // collapses it back into unaligned runs, so each field is punctuation-delimited instead of
102
- // column-aligned (review 2026-08-24 §1.3a).
103
- for (const section of build.sections) {
104
- const flags = [section.cacheClass];
105
- if (section.truncated)
106
- flags.push(`truncated from ${formatNumber(section.rawUnits)} units`);
107
- lines.push(`- ${section.id}: ${formatNumber(section.injectedUnits)} units, ${formatNumber(section.injectedChars)} chars, ${flags.join(", ")}`);
100
+ // fingerprint only covers the part Pipiclaw owns, and stays stable across a date rollover
101
+ // that does invalidate the provider's cached prefix.
102
+ lines.push(`- 实际发送(含 skills、日期、工作目录):${formatNumber(finalPrompt.length)} 字,约 ${formatNumber(estimateTokens(finalPrompt))} tokens,指纹 \`${sha256(finalPrompt).slice(0, 16)}\``);
108
103
  }
109
- const soulLine = renderWorkspaceResourceLine("SOUL.md", input.soul);
110
- const agentsLine = renderWorkspaceResourceLine("AGENTS.md", input.agents);
111
- if (soulLine || agentsLine) {
112
- lines.push("");
113
- lines.push("Workspace resources (independent budgets, not competing with the runtime):");
114
- if (soulLine)
115
- lines.push(soulLine);
116
- if (agentsLine)
117
- lines.push(agentsLine);
118
- }
119
- lines.push("");
120
104
  const overToolBudget = input.toolSchemas.units > TOOL_SCHEMA_TARGET_UNITS;
121
- lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemas.units)} / ${formatNumber(TOOL_SCHEMA_TARGET_UNITS)} units, ${formatNumber(input.toolSchemas.chars)} chars${overToolBudget ? " — over target" : ""} (billed on top of the system prompt)`);
122
- lines.push(`Skills: ${input.skills.length} visible, ≈${formatNumber(estimateSkillsPromptChars(input.skills))} chars (rendered and managed by pi, not budgeted by Pipiclaw)`);
105
+ lines.push(`- 工具定义:${input.toolNames.length} 个,${formatNumber(input.toolSchemas.units)} / 目标 ${formatNumber(TOOL_SCHEMA_TARGET_UNITS)} 单位${overToolBudget ? "(超出目标)" : ""},在系统提示词之外另计`);
106
+ lines.push(`- Skills:${input.skills.length} 个可见,约 ${formatNumber(estimateSkillsPromptChars(input.skills))} 字(由 pi 渲染,不计入 Pipiclaw 预算)`);
107
+ const resources = [
108
+ renderWorkspaceResource("SOUL.md", input.soul),
109
+ renderWorkspaceResource("AGENTS.md", input.agents),
110
+ ]
111
+ .filter(Boolean)
112
+ .join(";");
113
+ if (resources)
114
+ lines.push(`- 工作区文件(独立预算):${resources}`);
123
115
  if (input.lastTurn) {
124
116
  const turn = input.lastTurn;
125
117
  const automaticUnits = turn.channelCapsuleUnits + turn.taskDigestUnits + turn.durableMemoryUnits;
126
- lines.push("");
127
- lines.push(`Last automatic turn context: ${formatNumber(automaticUnits)} / ${formatNumber(AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS)} units (per-turn, not cached):`);
128
- lines.push(`- channel capsule: ${formatNumber(turn.channelCapsuleUnits)} units`);
129
- lines.push(`- task agenda: ${formatNumber(turn.taskDigestUnits)} units / ${formatNumber(turn.taskDigestChars)} chars`);
130
- lines.push(`- memory bootstrap: ${formatNumber(turn.durableMemoryUnits)} units / ${formatNumber(turn.durableMemoryChars)} chars (first turn only)`);
131
- lines.push(`- user message: ${formatNumber(turn.userMessageChars)} chars (not automatic; not capped here)`);
118
+ lines.push(`- 上一回合自动附加:${formatNumber(automaticUnits)} / ${formatNumber(AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS)} 单位(频道信息 ${formatNumber(turn.channelCapsuleUnits)},任务清单 ${formatNumber(turn.taskDigestUnits)},记忆 ${formatNumber(turn.durableMemoryUnits)},记忆只在首个回合附加);用户消息 ${formatNumber(turn.userMessageChars)} 字`);
119
+ }
120
+ for (const diagnostic of build.diagnostics) {
121
+ lines.push(`- ⚠️ ${diagnostic.sectionId}:${diagnostic.message}`);
132
122
  }
133
- if (build.diagnostics.length > 0 || overToolBudget) {
134
- lines.push("");
135
- lines.push("Diagnostics:");
136
- for (const diagnostic of build.diagnostics) {
137
- lines.push(`- [${diagnostic.level}] ${diagnostic.sectionId}: ${diagnostic.message}`);
138
- }
139
- if (overToolBudget) {
140
- lines.push(`- [warning] tools: ${toolSchemaBudgetWarning(input.toolSchemas)}`);
141
- }
123
+ if (overToolBudget) {
124
+ lines.push("- ⚠️ 工具定义超出目标:缩短某个工具的说明、把细节移到 playbook,或停用一个工具;`/context detail` 列出全部工具");
142
125
  }
143
- if (detail) {
144
- lines.push("");
145
- lines.push("Detail:");
146
- for (const section of build.sections) {
147
- lines.push(`- ${section.id} (${section.authority}) ← ${section.source} · sha256:${section.sha256.slice(0, 12)}`);
148
- }
149
- if (input.toolNames.length > 0) {
150
- lines.push(`- tools: ${input.toolNames.join(", ")}`);
151
- }
152
- if (input.skills.length > 0) {
153
- lines.push(`- skills: ${input.skills.map((skill) => skill.name).join(", ")}`);
154
- }
126
+ if (!detail) {
127
+ lines.push("", "用 `/context detail` 查看各分段的来源与工具、skill 清单。");
128
+ return lines.join("\n");
155
129
  }
156
- else {
157
- lines.push("");
158
- lines.push("Run `/context detail` for per-section sources, hashes, and the tool/skill inventory.");
130
+ lines.push("", "**分段**");
131
+ for (const section of build.sections) {
132
+ const truncated = section.truncated ? `,已截断(原 ${formatNumber(section.rawUnits)} 单位)` : "";
133
+ lines.push(`- ${section.id}:${formatNumber(section.injectedUnits)} 单位,${formatNumber(section.injectedChars)} 字,${section.cacheClass}${truncated};来源 ${section.source}(${section.authority})`);
159
134
  }
160
- return lines.join("\n");
135
+ if (input.toolNames.length > 0)
136
+ lines.push("", `**工具**:${input.toolNames.join("、")}`);
137
+ if (input.skills.length > 0)
138
+ lines.push("", `**Skills**:${input.skills.map((skill) => skill.name).join("、")}`);
139
+ return capReply(lines.join("\n"), {
140
+ nextStepHint: "用 `/context` 只看汇总;完整提示词需部署者在服务器上设 `PIPICLAW_DEBUG=1`,之后查看频道目录的 `last_prompt.json`",
141
+ }).text;
161
142
  }
@@ -30,7 +30,10 @@ function readWorkspaceFile(path) {
30
30
  return readFileSync(path, "utf-8").replace(/\r/g, "").trim();
31
31
  }
32
32
  catch (error) {
33
- log.logWarning(`Failed to read ${path}`, String(error));
33
+ log.logWarn("agent.prompt.resource_read_failed", "Prompt resource read failed", {
34
+ reason: String(error),
35
+ fields: { path },
36
+ });
34
37
  return "";
35
38
  }
36
39
  }
@@ -20,7 +20,10 @@ export function createRunQueue() {
20
20
  }
21
21
  catch (err) {
22
22
  const errMsg = errorMessage(err);
23
- log.logWarning(`DingTalk API error (${errorContext})`, errMsg);
23
+ log.logWarn("delivery.api.failed", "DingTalk API call failed", {
24
+ reason: errMsg,
25
+ fields: { context: errorContext },
26
+ });
24
27
  }
25
28
  });
26
29
  },
@@ -34,7 +37,9 @@ export function createRunQueue() {
34
37
  });
35
38
  }
36
39
  catch (err) {
37
- log.logWarning("Run queue drain deadline exceeded; releasing the turn", errorMessage(err));
40
+ log.logWarn("delivery.queue.drain_timeout", "Run queue drain deadline exceeded; releasing the turn", {
41
+ reason: errorMessage(err),
42
+ });
38
43
  }
39
44
  },
40
45
  };
@@ -71,7 +71,7 @@ export function initializeThinkingLevelCompat(agent, model, sessionManager, conf
71
71
  export function setSessionBaseToolsOverride(session, tools, channelId) {
72
72
  const target = session;
73
73
  if (!("_baseToolsOverride" in target)) {
74
- log.logWarning(`[${channelId}] AgentSession no longer exposes _baseToolsOverride; tool reloads may use stale tools (SDK change?)`);
74
+ log.logWarn("agent.session.sdk_drift", "AgentSession no longer exposes _baseToolsOverride; tool reloads may use stale tools", { channelId: channelId });
75
75
  }
76
76
  target._baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));
77
77
  }
@@ -1,10 +1,12 @@
1
1
  import * as log from "../log.js";
2
+ import { renderGuardBlockForUser } from "../security/block-message.js";
2
3
  import { truncate } from "../shared/text-utils.js";
3
4
  import { isRecord } from "../shared/type-guards.js";
4
5
  import { addUsage } from "../shared/types.js";
5
6
  import { describeToolCall } from "../tools/presentation.js";
6
- import { isArgumentValidationFailure, isRecoverableRejection, toolResultDetails, } from "../tools/tool-details.js";
7
+ import { isArgumentValidationFailure, isRecoverableRejection, takeGuardBlock, toolResultDetails, } from "../tools/tool-details.js";
7
8
  import { extractToolResultText, formatProgressEntry } from "./progress-formatter.js";
9
+ import { renderCompactionFailure } from "./turn-error.js";
8
10
  import { extractCustomCommandResultText, isAssistantEventMessage, isAutoCompactionEndEvent, isAutoCompactionStartEvent, isAutoRetryStartEvent, isMessageEndEvent, isMessageStartEvent, isSubAgentToolDetails, isTextPart, isThinkingPart, isToolExecutionEndEvent, isToolExecutionStartEvent, isToolExecutionUpdateEvent, isTurnEndEvent, } from "./type-guards.js";
9
11
  /**
10
12
  * A `write`/`edit` result whose resolved target landed inside the workspace `skills/` tree. The
@@ -21,6 +23,9 @@ function isWorkspaceSkillWrite(toolName, details, skillsDir) {
21
23
  }
22
24
  return details.path === skillsDir || details.path.startsWith(`${skillsDir}/`);
23
25
  }
26
+ function firstLine(text) {
27
+ return text.trim().split("\n", 1)[0] ?? "";
28
+ }
24
29
  function mergeSubAgentUsage(totalUsage, details) {
25
30
  addUsage(totalUsage, details.usage);
26
31
  }
@@ -89,7 +94,7 @@ export async function handleSessionEvent(event, context) {
89
94
  context.refreshSessionResources &&
90
95
  isWorkspaceSkillWrite(event.toolName, details, context.skillsDir)) {
91
96
  queue.enqueue(() => context.refreshSessionResources?.() ?? Promise.resolve(), "refresh skills");
92
- queue.enqueue(() => ctx.respondInThread("已沉淀:workspace skill 已更新,下一轮生效。"), "skill notice");
97
+ queue.enqueue(() => ctx.respondInThread("已更新 workspace skill,下一条消息起生效。"), "skill notice");
93
98
  }
94
99
  // A recoverable rejection (bad arguments, unmet precondition the model can fix) is not a
95
100
  // fault: the model normally corrects it on the next call. It is logged so the retry is
@@ -116,8 +121,14 @@ export async function handleSessionEvent(event, context) {
116
121
  if (!treatAsError && !rejected && event.toolName !== "task_step_end") {
117
122
  runState.toolsUsed.push(event.toolName);
118
123
  }
124
+ // Claimed on every error, shown or not, so the parked refusal never outlives its call.
125
+ const blocked = event.isError ? takeGuardBlock(event.toolCallId, resultStr) : undefined;
119
126
  if (treatAsError && showProgress) {
120
- queue.enqueue(() => ctx.respond(formatProgressEntry("error", truncate(resultStr, 200)), false), "tool error");
127
+ // The tool's error text is written for the model (spec 053, D2): a guard refusal is shown
128
+ // from its structured form; anything else as its first line only — the full text is in
129
+ // the log (`agent.tool.failed`).
130
+ const line = blocked ? renderGuardBlockForUser(blocked) : truncate(firstLine(resultStr), 120);
131
+ queue.enqueue(() => ctx.respond(formatProgressEntry("error", line), false), "tool error");
121
132
  }
122
133
  return;
123
134
  }
@@ -236,7 +247,7 @@ export async function handleSessionEvent(event, context) {
236
247
  return;
237
248
  }
238
249
  if (isAutoCompactionStartEvent(event)) {
239
- const label = "Compacting context...";
250
+ const label = "正在压缩上下文…";
240
251
  log.logEvent("info", "agent.compaction.started", "Compaction started", {
241
252
  ctx: logCtx,
242
253
  fields: { reason: event.reason },
@@ -264,7 +275,7 @@ export async function handleSessionEvent(event, context) {
264
275
  fields: { error: event.errorMessage },
265
276
  });
266
277
  if (showProgress) {
267
- queue.enqueue(() => ctx.respond(formatProgressEntry("error", truncate(event.errorMessage ?? "Compaction failed", 200)), false), "compaction error");
278
+ queue.enqueue(() => ctx.respond(formatProgressEntry("error", renderCompactionFailure(event.errorMessage ?? "")), false), "compaction error");
268
279
  }
269
280
  }
270
281
  return;
@@ -275,7 +286,7 @@ export async function handleSessionEvent(event, context) {
275
286
  fields: { attempt: event.attempt, maxAttempts: event.maxAttempts, error: event.errorMessage },
276
287
  });
277
288
  if (showProgress) {
278
- queue.enqueue(() => ctx.respond(formatProgressEntry("assistant", `Retrying (${event.attempt}/${event.maxAttempts})...`), false), "retry");
289
+ queue.enqueue(() => ctx.respond(formatProgressEntry("assistant", `模型请求失败,正在重试(${event.attempt}/${event.maxAttempts})…`), false), "retry");
279
290
  }
280
291
  }
281
292
  }
@@ -63,7 +63,9 @@ export class SessionResourceGate {
63
63
  catch (error) {
64
64
  // The chain is awaited by the next prompt and by detached callers, so a
65
65
  // failed reload must never reject it: log and carry the previous resources.
66
- log.logWarning("Session resource reload failed", errorMessage(error));
66
+ log.logWarn("agent.session.resources_reload_failed", "Session resource reload failed", {
67
+ reason: errorMessage(error),
68
+ });
67
69
  }
68
70
  };
69
71
  this.reloadChain = this.reloadChain.then(runReload, runReload);
@@ -7,5 +7,4 @@ export interface RenderStatusOptions {
7
7
  uptimeMs: number;
8
8
  }
9
9
  export declare function formatTokenCount(count: number): string;
10
- export declare function formatUptime(ms: number): string;
11
10
  export declare function renderStatus(options: RenderStatusOptions): string;