@oyasmi/pipiclaw 0.9.3 → 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 (113) hide show
  1. package/dist/agent/channel-runner.js +137 -61
  2. package/dist/agent/command-extension.js +47 -34
  3. package/dist/agent/job-manager.js +31 -11
  4. package/dist/agent/model-fallback.js +1 -1
  5. package/dist/agent/prompt/manifest.d.ts +6 -1
  6. package/dist/agent/prompt/manifest.js +45 -64
  7. package/dist/agent/prompt/resources.js +4 -1
  8. package/dist/agent/run-queue.js +7 -2
  9. package/dist/agent/session-adapter.js +1 -1
  10. package/dist/agent/session-events.js +17 -6
  11. package/dist/agent/session-resource-gate.js +3 -1
  12. package/dist/agent/status-render.d.ts +0 -1
  13. package/dist/agent/status-render.js +4 -16
  14. package/dist/agent/turn-error.d.ts +31 -0
  15. package/dist/agent/turn-error.js +68 -0
  16. package/dist/app-services.js +7 -4
  17. package/dist/channel/channel-index.js +4 -1
  18. package/dist/channel/project-scope-store.js +1 -1
  19. package/dist/commands/catalog.d.ts +21 -4
  20. package/dist/commands/catalog.js +88 -41
  21. package/dist/commands/reply-limits.d.ts +6 -0
  22. package/dist/commands/reply-limits.js +24 -0
  23. package/dist/events/event-commands.js +94 -44
  24. package/dist/events/event-validation.d.ts +13 -2
  25. package/dist/events/event-validation.js +17 -9
  26. package/dist/events/events.js +77 -32
  27. package/dist/executor.js +2 -2
  28. package/dist/log.d.ts +12 -2
  29. package/dist/log.js +26 -34
  30. package/dist/main.js +1 -1
  31. package/dist/memory/commands.js +29 -23
  32. package/dist/memory/lifecycle.js +26 -5
  33. package/dist/memory/maintenance-state.js +4 -1
  34. package/dist/memory/scheduler.js +3 -1
  35. package/dist/models/auth-cli.js +3 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +9 -0
  38. package/dist/playbooks/agent-delegation.md +2 -2
  39. package/dist/runtime/app-home.d.ts +6 -0
  40. package/dist/runtime/app-home.js +21 -3
  41. package/dist/runtime/bootstrap.js +189 -60
  42. package/dist/runtime/channel-queue.js +1 -1
  43. package/dist/runtime/delivery.js +29 -15
  44. package/dist/runtime/dingtalk.js +96 -42
  45. package/dist/runtime/durable-dispatch.d.ts +27 -1
  46. package/dist/runtime/durable-dispatch.js +111 -3
  47. package/dist/runtime/project-commands.js +16 -15
  48. package/dist/runtime/proxy.js +4 -2
  49. package/dist/runtime/report-commands.js +1 -1
  50. package/dist/runtime/skill-commands.d.ts +1 -1
  51. package/dist/runtime/skill-commands.js +17 -10
  52. package/dist/runtime/subagent-commands.d.ts +5 -4
  53. package/dist/runtime/subagent-commands.js +116 -77
  54. package/dist/runtime/task-commands.d.ts +1 -1
  55. package/dist/runtime/task-commands.js +110 -64
  56. package/dist/runtime/task-driver.d.ts +4 -2
  57. package/dist/runtime/task-driver.js +55 -20
  58. package/dist/runtime/task-migration.js +23 -6
  59. package/dist/runtime/task-spawn.js +12 -5
  60. package/dist/runtime/wake-coalescing.d.ts +18 -0
  61. package/dist/runtime/wake-coalescing.js +29 -0
  62. package/dist/security/block-message.d.ts +22 -1
  63. package/dist/security/block-message.js +66 -1
  64. package/dist/security/network.d.ts +2 -1
  65. package/dist/security/network.js +3 -2
  66. package/dist/security/path-guard-check.js +2 -2
  67. package/dist/settings.d.ts +3 -2
  68. package/dist/settings.js +4 -1
  69. package/dist/shared/format.d.ts +12 -0
  70. package/dist/shared/format.js +37 -0
  71. package/dist/shared/host-process.js +15 -3
  72. package/dist/shared/with-timeout.d.ts +3 -2
  73. package/dist/shared/with-timeout.js +14 -3
  74. package/dist/subagents/external/claude-code.js +23 -1
  75. package/dist/subagents/external/progress-tail.d.ts +17 -0
  76. package/dist/subagents/external/progress-tail.js +64 -17
  77. package/dist/subagents/external/run.d.ts +3 -0
  78. package/dist/subagents/external/run.js +21 -7
  79. package/dist/subagents/external/settlement.d.ts +3 -0
  80. package/dist/subagents/external/settlement.js +1 -1
  81. package/dist/subagents/runs.d.ts +21 -1
  82. package/dist/subagents/runs.js +137 -32
  83. package/dist/subagents/tool.d.ts +22 -15
  84. package/dist/subagents/tool.js +226 -32
  85. package/dist/subagents/workspace-summary.d.ts +16 -4
  86. package/dist/subagents/workspace-summary.js +74 -18
  87. package/dist/tasks/board.d.ts +8 -1
  88. package/dist/tasks/board.js +37 -2
  89. package/dist/tasks/frontmatter.d.ts +5 -0
  90. package/dist/tasks/frontmatter.js +8 -0
  91. package/dist/tasks/log.d.ts +11 -1
  92. package/dist/tasks/log.js +58 -2
  93. package/dist/tasks/store.js +4 -2
  94. package/dist/tasks/ticket.d.ts +3 -1
  95. package/dist/tasks/ticket.js +19 -1
  96. package/dist/tools/bash.js +2 -2
  97. package/dist/tools/index.d.ts +2 -0
  98. package/dist/tools/index.js +1 -0
  99. package/dist/tools/memory-manage.js +4 -1
  100. package/dist/tools/subagent-manage.d.ts +1 -1
  101. package/dist/tools/subagent-manage.js +16 -11
  102. package/dist/tools/task-manage/step-end.js +4 -1
  103. package/dist/tools/tool-details.d.ts +10 -2
  104. package/dist/tools/tool-details.js +39 -2
  105. package/dist/tui/cli.js +2 -2
  106. package/dist/tui/commands.js +4 -4
  107. package/dist/tui/pitui-frontend.js +1 -1
  108. package/dist/tui/renderer.js +3 -2
  109. package/dist/tui/turn-controller.d.ts +2 -0
  110. package/dist/tui/turn-controller.js +36 -21
  111. package/dist/usage/ledger.js +3 -1
  112. package/dist/usage/render.js +3 -1
  113. package/package.json +1 -1
@@ -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;
@@ -3,6 +3,7 @@
3
3
  * the DingTalk runtime and the terminal TUI can render the same status block
4
4
  * from an `AgentRunner` status snapshot. Pure functions, no side effects.
5
5
  */
6
+ import { formatElapsedZh } from "../shared/format.js";
6
7
  import { errorMessage } from "../shared/text-utils.js";
7
8
  export function formatTokenCount(count) {
8
9
  if (count < 1000)
@@ -11,19 +12,6 @@ export function formatTokenCount(count) {
11
12
  return `${Math.round(count / 1000)}k`;
12
13
  return `${(count / 1_000_000).toFixed(1)}M`;
13
14
  }
14
- export function formatUptime(ms) {
15
- const totalSeconds = Math.floor(ms / 1000);
16
- const days = Math.floor(totalSeconds / 86400);
17
- const hours = Math.floor((totalSeconds % 86400) / 3600);
18
- const minutes = Math.floor((totalSeconds % 3600) / 60);
19
- const parts = [];
20
- if (days > 0)
21
- parts.push(`${days}d`);
22
- if (hours > 0)
23
- parts.push(`${hours}h`);
24
- parts.push(`${minutes}m`);
25
- return parts.join(" ");
26
- }
27
15
  export function renderStatus(options) {
28
16
  const { runner, version, uptimeMs } = options;
29
17
  let runState;
@@ -39,12 +27,12 @@ export function renderStatus(options) {
39
27
  if (runner) {
40
28
  try {
41
29
  const snapshot = runner.getStatusSnapshot();
42
- let modelLine = `- 模型:\`${snapshot.model}\`(thinking \`${snapshot.thinkingLevel}\`)`;
30
+ let modelLine = `- 模型:\`${snapshot.model}\`(思考档位 \`${snapshot.thinkingLevel}\`)`;
43
31
  if (snapshot.fallback) {
44
32
  const until = new Date(snapshot.fallback.cooldownUntilMs);
45
33
  const hh = String(until.getHours()).padStart(2, "0");
46
34
  const mm = String(until.getMinutes()).padStart(2, "0");
47
- modelLine += ` · fallback 生效中(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`;
35
+ modelLine += ` · 正在使用备用模型(主模型 \`${snapshot.fallback.primary}\` 暂停到 ${hh}:${mm})`;
48
36
  }
49
37
  lines.push(modelLine);
50
38
  if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
@@ -59,6 +47,6 @@ export function renderStatus(options) {
59
47
  else {
60
48
  lines.push("- 模型:本频道尚未开始过会话");
61
49
  }
62
- lines.push(`- 已运行 ${formatUptime(uptimeMs)} · 版本 \`${version}\``);
50
+ lines.push(`- 已运行 ${formatElapsedZh(uptimeMs)} · 版本 \`${version}\``);
63
51
  return lines.join("\n");
64
52
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Turn-failure classification for the user's error bubble (spec 053, D5.1).
3
+ *
4
+ * A raw provider error ("401 invalid x-api-key", "429 rate_limit_error", "prompt is too long")
5
+ * tells the user nothing they can act on. The bubble now leads with a class and the one or two
6
+ * things the user (or the deployer, on the server) can actually do about it; the raw text is kept
7
+ * as a short quoted line for whoever has to debug it.
8
+ *
9
+ * Only stable features are matched — HTTP status codes and the phrases providers have used for
10
+ * years. Anything unrecognised is `other`, which still carries a next step.
11
+ */
12
+ export type TurnErrorKind = "auth" | "rate_limit" | "context_overflow" | "network" | "other";
13
+ export declare function classifyTurnError(message: string): TurnErrorKind;
14
+ /** What the user is told for each class: a reason (absent for `other`) and what to do next. */
15
+ export declare function describeTurnError(kind: TurnErrorKind): {
16
+ reason?: string;
17
+ nextStep: string;
18
+ };
19
+ export interface TurnErrorReplyInput {
20
+ errorMessage: string;
21
+ /** A failed recovery compaction whose error differs from the turn's own. */
22
+ compactionError?: string;
23
+ /** The fallback model already tried, when the runner switched to one. */
24
+ fallbackRef?: string;
25
+ }
26
+ /** The error bubble: class + next step first, the raw provider text last (spec 053, D5.1). */
27
+ export declare function renderTurnErrorReply(input: TurnErrorReplyInput): string;
28
+ /** The progress line for a failed automatic compaction. */
29
+ export declare function renderCompactionFailure(errorMessage: string): string;
30
+ /** The line shown when the runner switches to the fallback model mid-turn; the raw error goes to the log. */
31
+ export declare function renderFallbackSwitch(from: string, to: string, errorMessage: string): string;
@@ -0,0 +1,68 @@
1
+ const PATTERNS = [
2
+ [
3
+ "auth",
4
+ /\b40[13]\b|unauthori[sz]ed|forbidden|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|authentication[ _-]?(?:error|failed)|(?:token|credential)s? (?:has |have )?expired/i,
5
+ ],
6
+ [
7
+ "context_overflow",
8
+ /context[ _-]?length|context window|too many tokens|prompt is too long|input is too long|maximum context|exceeds? the (?:model's )?(?:maximum|context)/i,
9
+ ],
10
+ [
11
+ "rate_limit",
12
+ /\b429\b|\b529\b|rate[ _-]?limit|too many requests|quota|insufficient[ _-]?(?:quota|balance|credit|funds)|overloaded/i,
13
+ ],
14
+ [
15
+ "network",
16
+ /ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|socket hang up|fetch failed|network error|timed out|\b50[0234]\b|internal server error|bad gateway|service unavailable|gateway timeout/i,
17
+ ],
18
+ ];
19
+ export function classifyTurnError(message) {
20
+ for (const [kind, pattern] of PATTERNS) {
21
+ if (pattern.test(message))
22
+ return kind;
23
+ }
24
+ return "other";
25
+ }
26
+ /** What the user is told for each class: a reason (absent for `other`) and what to do next. */
27
+ export function describeTurnError(kind) {
28
+ switch (kind) {
29
+ case "auth":
30
+ return {
31
+ reason: "模型凭据无效或已过期。",
32
+ nextStep: "请部署者在服务器上执行 `pipiclaw auth login`,或用 `/model` 换一个模型。",
33
+ };
34
+ case "rate_limit":
35
+ return { reason: "模型暂时限流或额度不足。", nextStep: "稍后重发,或用 `/model` 换一个模型。" };
36
+ case "context_overflow":
37
+ return { reason: "会话上下文已满。", nextStep: "用 `/compact` 压缩,或用 `/new` 开新会话。" };
38
+ case "network":
39
+ return { reason: "连不上模型服务。", nextStep: "稍后重发;持续出现请检查服务器网络或代理。" };
40
+ case "other":
41
+ return { nextStep: "可以重发一次;持续出现请用 `/status` 查看模型状态。" };
42
+ }
43
+ }
44
+ function quoteRaw(text) {
45
+ const flat = text.replace(/`/g, "'").replace(/\s+/g, " ").trim();
46
+ return `\`${flat.length > 240 ? `${flat.slice(0, 239)}…` : flat}\``;
47
+ }
48
+ /** The error bubble: class + next step first, the raw provider text last (spec 053, D5.1). */
49
+ export function renderTurnErrorReply(input) {
50
+ const { reason, nextStep } = describeTurnError(classifyTurnError(input.errorMessage));
51
+ const lines = [reason ? `处理失败:${reason}` : "处理失败。", nextStep];
52
+ if (input.fallbackRef)
53
+ lines.push(`已切换备用模型 \`${input.fallbackRef}\` 重试,仍失败。`);
54
+ lines.push(`原始错误:${quoteRaw(input.errorMessage)}`);
55
+ if (input.compactionError)
56
+ lines.push(`压缩重试的错误:${quoteRaw(input.compactionError)}`);
57
+ return lines.join("\n");
58
+ }
59
+ /** The progress line for a failed automatic compaction. */
60
+ export function renderCompactionFailure(errorMessage) {
61
+ const { reason } = describeTurnError(classifyTurnError(errorMessage));
62
+ return reason ? `上下文压缩失败:${reason}` : "上下文压缩失败。";
63
+ }
64
+ /** The line shown when the runner switches to the fallback model mid-turn; the raw error goes to the log. */
65
+ export function renderFallbackSwitch(from, to, errorMessage) {
66
+ const { reason } = describeTurnError(classifyTurnError(errorMessage));
67
+ return `模型 \`${from}\` 请求失败${reason ? `:${reason}` : "。"}改用 \`${to}\` 重试…`;
68
+ }
@@ -24,20 +24,23 @@ export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
24
24
  installLlmProxy();
25
25
  const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
26
26
  for (const { scope, error } of settingsManager.drainErrors()) {
27
- log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
27
+ log.logWarn("config.settings.load_failed", "Settings load failed", {
28
+ reason: error.message,
29
+ fields: { scope, path: paths.settingsConfigPath },
30
+ });
28
31
  }
29
32
  // Errors already went out above with a richer message; this pass exists for the
30
33
  // warnings, chiefly retired settings keys (spec 035 D3).
31
34
  for (const diagnostic of settingsManager.getDiagnostics()) {
32
35
  if (diagnostic.severity === "error")
33
36
  continue;
34
- log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
37
+ log.logWarn("config.diagnostic", formatConfigDiagnostic(diagnostic), { fields: { path: diagnostic.path } });
35
38
  }
36
39
  for (const diagnostic of loadToolsConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
37
- log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
40
+ log.logWarn("config.diagnostic", formatConfigDiagnostic(diagnostic), { fields: { path: diagnostic.path } });
38
41
  }
39
42
  for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
40
- log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
43
+ log.logWarn("config.diagnostic", formatConfigDiagnostic(diagnostic), { fields: { path: diagnostic.path } });
41
44
  }
42
45
  return { settingsManager };
43
46
  }
@@ -282,7 +282,10 @@ export function createChannelIndex(options) {
282
282
  })
283
283
  .catch((error) => {
284
284
  dirty = true;
285
- log.logWarning(`Failed to update ${CHANNELS_INDEX_FILENAME}`, errorMessage(error));
285
+ log.logWarn("channel.index.write_failed", "Channel index update failed", {
286
+ reason: errorMessage(error),
287
+ fields: { file: CHANNELS_INDEX_FILENAME },
288
+ });
286
289
  });
287
290
  return pending;
288
291
  };