@oyasmi/pipiclaw 0.8.4 → 0.8.6

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 (92) hide show
  1. package/README.md +2 -1
  2. package/dist/agent/channel-runner.d.ts +29 -0
  3. package/dist/agent/channel-runner.js +156 -53
  4. package/dist/agent/command-extension.d.ts +1 -0
  5. package/dist/agent/command-extension.js +6 -0
  6. package/dist/agent/commands.d.ts +2 -2
  7. package/dist/agent/commands.js +16 -1
  8. package/dist/agent/maintenance-context.js +1 -1
  9. package/dist/agent/prompt/builder.d.ts +32 -0
  10. package/dist/agent/prompt/builder.js +252 -0
  11. package/dist/agent/prompt/extension.d.ts +22 -0
  12. package/dist/agent/prompt/extension.js +24 -0
  13. package/dist/agent/prompt/manifest.d.ts +51 -0
  14. package/dist/agent/prompt/manifest.js +84 -0
  15. package/dist/agent/prompt/resources.d.ts +18 -0
  16. package/dist/agent/prompt/resources.js +61 -0
  17. package/dist/agent/prompt/sections.d.ts +39 -0
  18. package/dist/agent/prompt/sections.js +267 -0
  19. package/dist/agent/prompt/types.d.ts +110 -0
  20. package/dist/agent/prompt/types.js +11 -0
  21. package/dist/agent/types.d.ts +3 -0
  22. package/dist/agent/workspace-resources.d.ts +25 -13
  23. package/dist/agent/workspace-resources.js +28 -41
  24. package/dist/index.d.ts +7 -2
  25. package/dist/index.js +6 -2
  26. package/dist/memory/bootstrap.d.ts +5 -0
  27. package/dist/memory/bootstrap.js +14 -4
  28. package/dist/memory/candidates.d.ts +2 -0
  29. package/dist/memory/candidates.js +13 -3
  30. package/dist/memory/commands.d.ts +6 -0
  31. package/dist/memory/commands.js +112 -0
  32. package/dist/memory/consolidation.d.ts +3 -0
  33. package/dist/memory/consolidation.js +68 -26
  34. package/dist/memory/files.d.ts +13 -0
  35. package/dist/memory/files.js +65 -8
  36. package/dist/memory/lifecycle.d.ts +2 -1
  37. package/dist/memory/lifecycle.js +34 -6
  38. package/dist/memory/maintenance-jobs.js +48 -23
  39. package/dist/memory/metadata.d.ts +60 -0
  40. package/dist/memory/metadata.js +135 -0
  41. package/dist/memory/policy.d.ts +3 -0
  42. package/dist/memory/policy.js +19 -0
  43. package/dist/memory/post-turn-review.d.ts +11 -1
  44. package/dist/memory/post-turn-review.js +78 -19
  45. package/dist/memory/promotion.d.ts +5 -2
  46. package/dist/memory/promotion.js +3 -1
  47. package/dist/memory/recall.d.ts +3 -0
  48. package/dist/memory/recall.js +27 -5
  49. package/dist/memory/review-log.d.ts +2 -0
  50. package/dist/memory/review-log.js +15 -0
  51. package/dist/memory/session-corpus.js +11 -3
  52. package/dist/memory/session-search.js +8 -4
  53. package/dist/memory/session.d.ts +1 -0
  54. package/dist/memory/session.js +3 -1
  55. package/dist/memory/sidecar-worker.d.ts +1 -0
  56. package/dist/memory/sidecar-worker.js +1 -0
  57. package/dist/memory/source-window.d.ts +25 -0
  58. package/dist/memory/source-window.js +64 -0
  59. package/dist/memory/tombstones.d.ts +12 -0
  60. package/dist/memory/tombstones.js +44 -0
  61. package/dist/memory/transcript.js +33 -9
  62. package/dist/playbooks/catalog.d.ts +22 -1
  63. package/dist/playbooks/catalog.js +57 -4
  64. package/dist/playbooks/event-scheduling.md +2 -0
  65. package/dist/playbooks/memory-and-learning.md +2 -0
  66. package/dist/playbooks/runtime-orientation.md +1 -0
  67. package/dist/playbooks/task-closeout.md +3 -1
  68. package/dist/playbooks/task-delegation.md +3 -1
  69. package/dist/playbooks/task-driving.md +2 -0
  70. package/dist/playbooks/task-planning.md +2 -0
  71. package/dist/playbooks/task-recurring.md +2 -0
  72. package/dist/playbooks/task-repair.md +3 -1
  73. package/dist/runtime/bootstrap.js +8 -38
  74. package/dist/runtime/dingtalk.d.ts +1 -0
  75. package/dist/runtime/dingtalk.js +3 -0
  76. package/dist/runtime/task-commands.js +1 -1
  77. package/dist/runtime/workspace-templates.d.ts +11 -0
  78. package/dist/runtime/workspace-templates.js +51 -0
  79. package/dist/settings.js +1 -1
  80. package/dist/tasks/control.js +9 -3
  81. package/dist/tasks/store.d.ts +1 -0
  82. package/dist/tasks/store.js +11 -1
  83. package/dist/tools/memory-manage.d.ts +1 -1
  84. package/dist/tools/memory-manage.js +27 -6
  85. package/dist/tools/task-manage.js +2 -2
  86. package/dist/tui/commands.d.ts +1 -0
  87. package/dist/tui/commands.js +2 -0
  88. package/dist/tui/turn-controller.js +1 -0
  89. package/dist/usage/ledger.d.ts +2 -0
  90. package/package.json +1 -1
  91. package/dist/agent/prompt-builder.d.ts +0 -12
  92. package/dist/agent/prompt-builder.js +0 -71
package/README.md CHANGED
@@ -217,6 +217,7 @@ pipiclaw
217
217
  | `/tasks [show\|archive\|approve\|pause\|resume\|run\|stats\|doctor]` | 查看与治理任务台账,`approve` 是外部副作用的唯一授权入口 |
218
218
  | `/status` | 运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
219
219
  | `/usage [7d\|month]` | 本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
220
+ | `/context [detail]` | 当前发给模型的上下文构成:system prompt 各 section 体量与 fingerprint、工具 schema 开销、上一轮动态上下文 |
220
221
  | `/new` | 开启新会话 |
221
222
  | `/compact [instructions]` | 手动压缩当前会话上下文 |
222
223
  | `/session` | 当前会话状态、消息统计、token 使用量 |
@@ -224,7 +225,7 @@ pipiclaw
224
225
 
225
226
  说明:
226
227
 
227
- - 前八条由传输层直接处理,**忙碌时也可用**;后四条是会话命令,仅空闲时可用(忙碌时会收到提示)。
228
+ - 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM 成本);后四条会话命令仅空闲时可用(忙碌时会收到提示)。
228
229
  - 忙碌时的普通消息默认等价于 `/steer`,可通过 `channel.json` 的 `busyMessageDefault` 改为排队(`followUp`)。
229
230
  - 未知的斜杠命令会被直接拒绝并提示 `/help`,不会作为普通消息发给模型(避免 `/modle` 这类笔误变成一整轮 LLM 调用)。workspace skill 也可作为命令调用(`/skill:<名称>`)。
230
231
  - `/model` 依次尝试精确 `provider/modelId`、精确 `modelId`、对完整引用的子串匹配,只有唯一命中时才切换,例如 `/model turbo`。
@@ -28,6 +28,11 @@ export declare class ChannelRunner implements AgentRunner {
28
28
  private subAgentDiscovery;
29
29
  private activeModel;
30
30
  private currentSkills;
31
+ /** Last built system prompt (spec 025): feeds the boundary footer, /context and the debug manifest. */
32
+ private lastPromptBuild?;
33
+ /** The exact system prompt the provider last received (our prompt + pi's tail + footer). */
34
+ private lastFinalPrompt?;
35
+ private lastTurnContextStats?;
31
36
  private currentTools;
32
37
  private firstTurnMemoryBootstrapPending;
33
38
  /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
@@ -48,6 +53,7 @@ export declare class ChannelRunner implements AgentRunner {
48
53
  errorMessage?: string;
49
54
  usage: UsageTotals;
50
55
  durationMs: number;
56
+ silent: boolean;
51
57
  }>;
52
58
  handleBuiltinCommand(ctx: ChannelContext, command: RunnerBuiltInCommand): Promise<void>;
53
59
  /**
@@ -63,6 +69,18 @@ export declare class ChannelRunner implements AgentRunner {
63
69
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
64
70
  getStatusSnapshot(): RunnerStatusSnapshot;
65
71
  abort(): Promise<void>;
72
+ /**
73
+ * `/context` — read-only prompt accounting, no LLM cost. Reports the section
74
+ * breakdown of the system prompt, the tool schemas (billed on top of it, and
75
+ * often the larger half), and the last turn's dynamic context.
76
+ */
77
+ renderContextReport(args?: string): string;
78
+ /**
79
+ * The per-turn channel capsule. It replaces the channel paths that used to sit in
80
+ * the system prompt: memory/task/event tools are already bound to this channel, so
81
+ * the model only needs the directory when it wants to read a file directly.
82
+ */
83
+ private renderChannelTurnContext;
66
84
  private sendCommandReply;
67
85
  private recordMemoryActivity;
68
86
  private requireQueuedMessage;
@@ -97,6 +115,17 @@ export declare class ChannelRunner implements AgentRunner {
97
115
  private refreshSubAgentDiscovery;
98
116
  private reportSettingsDiagnostics;
99
117
  private reportConfigDiagnostics;
118
+ /**
119
+ * Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
120
+ * base prompt entirely: identity, execution contract, hard invariants, the tool
121
+ * catalog and the workspace files are ours. pi still appends its tail (skills,
122
+ * date, cwd), and the boundary footer is appended after that by the prompt
123
+ * extension.
124
+ *
125
+ * Nothing channel-specific enters this text — that is what lets two channels in
126
+ * one workspace share a cached prompt prefix. Channel facts ride the turn.
127
+ */
128
+ private buildSystemPrompt;
100
129
  private createResourceLoader;
101
130
  private createAgentSessionServices;
102
131
  private createEmptyExtensionsResult;
@@ -4,8 +4,9 @@ import { mkdir, readFile, writeFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import { createExecutor } from "../executor.js";
6
6
  import * as log from "../log.js";
7
- import { buildFirstTurnMemoryBootstrap as renderFirstTurnMemoryBootstrap } from "../memory/bootstrap.js";
7
+ import { buildFirstTurnMemoryBootstrapResult } from "../memory/bootstrap.js";
8
8
  import { createMemoryCandidateStore } from "../memory/candidates.js";
9
+ import { handleMemoryCommand } from "../memory/commands.js";
9
10
  import { getChannelMemoryPath } from "../memory/files.js";
10
11
  import { MemoryLifecycle } from "../memory/lifecycle.js";
11
12
  import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../memory/maintenance-state.js";
@@ -13,12 +14,13 @@ import { recallRelevantMemory } from "../memory/recall.js";
13
14
  import { buildTaskDigest } from "../memory/task-digest.js";
14
15
  import { getApiKeyForModel } from "../models/api-keys.js";
15
16
  import { createModelRegistry, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, } from "../models/utils.js";
17
+ import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
16
18
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
17
19
  import { PipiclawSettingsManager } from "../settings.js";
18
20
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
19
21
  import { errorMessage } from "../shared/text-utils.js";
20
22
  import { isRecord } from "../shared/type-guards.js";
21
- import { discoverSubAgents, formatSubAgentList } from "../subagents/discovery.js";
23
+ import { discoverSubAgents } from "../subagents/discovery.js";
22
24
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
23
25
  import { createPipiclawTools } from "../tools/index.js";
24
26
  import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
@@ -28,13 +30,16 @@ import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./comma
28
30
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
29
31
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
30
32
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
31
- import { buildAppendSystemPrompt } from "./prompt-builder.js";
33
+ import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
34
+ import { createPromptBoundaryExtension } from "./prompt/extension.js";
35
+ import { buildPromptManifest, renderContextReport } from "./prompt/manifest.js";
36
+ import { loadWorkspacePromptResources } from "./prompt/resources.js";
32
37
  import { createRunQueue } from "./run-queue.js";
33
38
  import { handleSessionEvent } from "./session-events.js";
34
39
  import { SessionResourceGate } from "./session-resource-gate.js";
35
40
  import { getLastAssistantUsage } from "./type-guards.js";
36
41
  import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
37
- import { getAgentConfig, getSoul, loadPipiclawSkills } from "./workspace-resources.js";
42
+ import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
38
43
  function isSilentOutcome(outcome) {
39
44
  return outcome.kind === "silent";
40
45
  }
@@ -102,6 +107,7 @@ export class ChannelRunner {
102
107
  this.memoryLifecycle = new MemoryLifecycle({
103
108
  channelId: this.channelId,
104
109
  channelDir: this.channelDir,
110
+ appHomeDir: this.appHomeDir,
105
111
  getMessages: () => this.session.messages,
106
112
  getSessionEntries: () => this.sessionManager.getBranch(),
107
113
  getModel: () => this.session.model ?? this.activeModel,
@@ -181,6 +187,13 @@ export class ChannelRunner {
181
187
  let promptSubmitted = false;
182
188
  let fallbackAttempted = false;
183
189
  let fallbackTargetRef;
190
+ // Hoisted so the debug dump in `finally` can report the turn as it was actually sent.
191
+ let promptText = "";
192
+ let recalledContextText = "";
193
+ let taskDigestText = "";
194
+ let durableMemoryBootstrapText = "";
195
+ let bootstrapCandidateIds = [];
196
+ let bootstrapPrepared = false;
184
197
  try {
185
198
  await this.ensureSessionReady();
186
199
  await this.maybeRestorePrimaryModel();
@@ -194,11 +207,17 @@ export class ChannelRunner {
194
207
  const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
195
208
  // Ensure channel directory exists
196
209
  await mkdir(this.channelDir, { recursive: true });
197
- let promptText = preserveRawInput ? clippedInput : userMessage;
198
- let recalledContextText = "";
199
- let taskDigestText = "";
200
- let durableMemoryBootstrapText = "";
210
+ promptText = preserveRawInput ? clippedInput : userMessage;
201
211
  if (!preserveRawInput) {
212
+ // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
213
+ // system prompt is what lets every channel in a workspace share one cached prefix.
214
+ promptText = `${this.renderChannelTurnContext()}\n\n<user_message>\n${promptText}\n</user_message>`;
215
+ if (this.firstTurnMemoryBootstrapPending) {
216
+ const bootstrap = await this.buildFirstTurnMemoryBootstrap();
217
+ durableMemoryBootstrapText = bootstrap.renderedText;
218
+ bootstrapCandidateIds = bootstrap.includedCandidateIds;
219
+ bootstrapPrepared = true;
220
+ }
202
221
  const recallSettings = this.settingsManager.getMemoryRecallSettings();
203
222
  if (recallSettings.enabled) {
204
223
  const recall = await recallRelevantMemory({
@@ -210,6 +229,7 @@ export class ChannelRunner {
210
229
  maxInjected: recallSettings.maxInjected,
211
230
  maxChars: recallSettings.maxChars,
212
231
  rerankWithModel: recallSettings.rerankWithModel,
232
+ excludedCandidateIds: bootstrapCandidateIds,
213
233
  // Let shouldUseModelRerank's own memory-intent gate decide (it already handles
214
234
  // Chinese phrasing) — forcing autoRerank for every Han-script message triggered a
215
235
  // model rerank (up to 8s) on nearly every Chinese turn once memory filled up.
@@ -219,7 +239,7 @@ export class ChannelRunner {
219
239
  });
220
240
  if (recall.renderedText) {
221
241
  recalledContextText = recall.renderedText;
222
- promptText = `${recall.renderedText}\n\n<user_message>\n${promptText}\n</user_message>`;
242
+ promptText = `${recall.renderedText}\n\n${promptText}`;
223
243
  }
224
244
  }
225
245
  // Gated by the same master autonomy switch as task_manage and the TaskDriver.
@@ -234,36 +254,28 @@ export class ChannelRunner {
234
254
  promptText = `${taskDigestText}\n\n${promptText}`;
235
255
  }
236
256
  }
237
- if (this.firstTurnMemoryBootstrapPending) {
238
- durableMemoryBootstrapText = await this.buildFirstTurnMemoryBootstrap();
239
- if (durableMemoryBootstrapText) {
240
- promptText = `${durableMemoryBootstrapText}\n\n${promptText}`;
241
- }
242
- this.firstTurnMemoryBootstrapPending = false;
257
+ if (durableMemoryBootstrapText) {
258
+ promptText = `${durableMemoryBootstrapText}\n\n${promptText}`;
243
259
  }
244
260
  }
245
261
  // Estimated against the fully assembled prompt (recall + task digest + bootstrap all
246
262
  // prepended above), not just the bare user message — those pieces can add thousands of
247
263
  // characters and must count against the projected context usage this guard is checking.
248
264
  await this.maybeRunPreventiveCompactionForIncomingText(promptText);
249
- // Debug: write context to last_prompt.json (only with PIPICLAW_DEBUG=1)
250
- if (process.env.PIPICLAW_DEBUG) {
251
- const debugContext = {
252
- systemPrompt: this.agent.state.systemPrompt,
253
- messages: this.session.messages,
254
- durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
255
- taskDigest: taskDigestText || undefined,
256
- recalledContext: recalledContextText || undefined,
257
- newUserMessage: promptText,
258
- };
259
- await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2));
260
- }
265
+ this.lastTurnContextStats = {
266
+ durableMemoryChars: durableMemoryBootstrapText.length,
267
+ taskDigestChars: taskDigestText.length,
268
+ recalledMemoryChars: recalledContextText.length,
269
+ userMessageChars: clippedInput.length,
270
+ };
261
271
  const fallbackDeps = {
262
272
  prompt: async (text) => {
263
273
  try {
264
274
  await this.sessionResourceGate.runPrompt(async () => {
265
275
  await this.session.prompt(text);
266
276
  promptSubmitted = true;
277
+ if (bootstrapPrepared)
278
+ this.firstTurnMemoryBootstrapPending = false;
267
279
  });
268
280
  }
269
281
  catch (err) {
@@ -318,6 +330,23 @@ export class ChannelRunner {
318
330
  }
319
331
  finally {
320
332
  this.turn.phase = "finishing";
333
+ // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
334
+ // string the provider actually received — base sections, pi's tail, and the boundary
335
+ // footer the prompt extension appends at before_agent_start.
336
+ if (process.env.PIPICLAW_DEBUG) {
337
+ const debugContext = {
338
+ systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
339
+ promptManifest: this.lastPromptBuild
340
+ ? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
341
+ : undefined,
342
+ messages: this.session.messages,
343
+ durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
344
+ taskDigest: taskDigestText || undefined,
345
+ recalledContext: recalledContextText || undefined,
346
+ newUserMessage: promptText,
347
+ };
348
+ await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
349
+ }
321
350
  if (!promptSubmitted) {
322
351
  const discarded = this.session.clearQueue();
323
352
  const discardedCount = discarded.steering.length + discarded.followUp.length;
@@ -437,6 +466,7 @@ export class ChannelRunner {
437
466
  errorMessage: this.runState.errorMessage,
438
467
  usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
439
468
  durationMs: Date.now() - startedAt,
469
+ silent: this.runState.finalOutcome.kind === "silent",
440
470
  };
441
471
  }
442
472
  async handleBuiltinCommand(ctx, command) {
@@ -445,6 +475,9 @@ export class ChannelRunner {
445
475
  case "help":
446
476
  await this.sendCommandReply(ctx, renderBuiltInHelp());
447
477
  return;
478
+ case "context":
479
+ await this.sendCommandReply(ctx, this.renderContextReport(command.args));
480
+ return;
448
481
  case "stop":
449
482
  await this.sendCommandReply(ctx, "No task is running. Use `/stop` only while a task is running.");
450
483
  return;
@@ -510,7 +543,7 @@ export class ChannelRunner {
510
543
  memoryGrowth: this.settingsManager.getMemoryGrowthSettings(),
511
544
  memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings(),
512
545
  },
513
- loadedSkills: this.currentSkills.map((skill) => ({
546
+ loadedSkills: this.currentSkills.skills.map((skill) => ({
514
547
  name: skill.name,
515
548
  description: skill.description,
516
549
  })),
@@ -539,7 +572,37 @@ export class ChannelRunner {
539
572
  async abort() {
540
573
  await this.session.abort();
541
574
  }
575
+ /**
576
+ * `/context` — read-only prompt accounting, no LLM cost. Reports the section
577
+ * breakdown of the system prompt, the tool schemas (billed on top of it, and
578
+ * often the larger half), and the last turn's dynamic context.
579
+ */
580
+ renderContextReport(args = "") {
581
+ const build = this.lastPromptBuild ?? this.buildSystemPrompt();
582
+ return renderContextReport({
583
+ build,
584
+ finalPrompt: this.lastFinalPrompt,
585
+ skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
586
+ toolNames: this.currentTools.map((tool) => tool.name),
587
+ toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
588
+ lastTurn: this.lastTurnContextStats,
589
+ detail: args.trim().toLowerCase() === "detail",
590
+ });
591
+ }
542
592
  // === Private helpers ===
593
+ /**
594
+ * The per-turn channel capsule. It replaces the channel paths that used to sit in
595
+ * the system prompt: memory/task/event tools are already bound to this channel, so
596
+ * the model only needs the directory when it wants to read a file directly.
597
+ */
598
+ renderChannelTurnContext() {
599
+ return [
600
+ "<runtime_turn_context>",
601
+ `Channel directory: ${this.channelDir}`,
602
+ "SESSION.md, MEMORY.md, HISTORY.md and tasks/ live there and are runtime-maintained. Prefer the context supplied with this turn and the channel-bound tools; read those files directly only when you need detail they did not provide.",
603
+ "</runtime_turn_context>",
604
+ ].join("\n");
605
+ }
543
606
  async sendCommandReply(ctx, text) {
544
607
  const delivered = await ctx.respondPlain(text);
545
608
  if (!delivered) {
@@ -755,6 +818,49 @@ export class ChannelRunner {
755
818
  log.logWarning(`[${this.channelId}] ${formatConfigDiagnostic(diagnostic)}`, diagnostic.path);
756
819
  }
757
820
  }
821
+ /**
822
+ * Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
823
+ * base prompt entirely: identity, execution contract, hard invariants, the tool
824
+ * catalog and the workspace files are ours. pi still appends its tail (skills,
825
+ * date, cwd), and the boundary footer is appended after that by the prompt
826
+ * extension.
827
+ *
828
+ * Nothing channel-specific enters this text — that is what lets two channels in
829
+ * one workspace share a cached prompt prefix. Channel facts ride the turn.
830
+ */
831
+ buildSystemPrompt() {
832
+ const toolNames = this.currentTools.map((tool) => tool.name);
833
+ const resources = loadWorkspacePromptResources(this.workspaceDir);
834
+ const build = buildPipiclawSystemPrompt({
835
+ mode: "normal",
836
+ cwd: process.cwd(),
837
+ workspaceDir: this.workspaceDir,
838
+ tools: this.currentTools.map((tool) => ({
839
+ name: tool.name,
840
+ description: tool.description,
841
+ hint: TOOL_PROMPT_HINTS[tool.name],
842
+ })),
843
+ soul: resources.soul,
844
+ agents: resources.agents,
845
+ playbooks: selectRuntimePlaybooks(loadRuntimePlaybookCatalog(), toolNames),
846
+ subAgents: this.subAgentDiscovery.agents.map((agent) => ({
847
+ name: agent.name,
848
+ description: agent.description,
849
+ })),
850
+ skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
851
+ });
852
+ for (const diagnostic of [...resources.diagnostics, ...build.diagnostics]) {
853
+ if (diagnostic.level === "info")
854
+ continue;
855
+ log.logWarning(`[${this.channelId}] Prompt ${diagnostic.level} (${diagnostic.sectionId})`, diagnostic.message);
856
+ }
857
+ // Only a real change is worth a line: a reload that produced the same bytes is noise.
858
+ if (this.lastPromptBuild?.fingerprint !== build.fingerprint) {
859
+ log.logInfo(`[${this.channelId}] System prompt rebuilt: ${build.totalChars} chars, ~${build.estimatedTokens} tokens, sha256:${build.fingerprint.slice(0, 12)} (was ${this.lastPromptBuild ? `sha256:${this.lastPromptBuild.fingerprint.slice(0, 12)}` : "none"})`);
860
+ }
861
+ this.lastPromptBuild = build;
862
+ return build;
863
+ }
758
864
  createResourceLoader() {
759
865
  return new DefaultResourceLoader({
760
866
  cwd: process.cwd(),
@@ -762,6 +868,12 @@ export class ChannelRunner {
762
868
  settingsManager: asSdkSettingsManager(this.settingsManager),
763
869
  extensionFactories: [
764
870
  this.memoryLifecycle.createExtensionFactory(),
871
+ createPromptBoundaryExtension({
872
+ getFooter: () => this.lastPromptBuild?.footer ?? "",
873
+ onFinalPrompt: (systemPrompt) => {
874
+ this.lastFinalPrompt = systemPrompt;
875
+ },
876
+ }),
765
877
  createCommandExtension({
766
878
  getCurrentModel: () => this.session.model ?? this.activeModel,
767
879
  getAvailableModels: async () => {
@@ -780,34 +892,25 @@ export class ChannelRunner {
780
892
  refreshSessionResources: async () => {
781
893
  await this.refreshSessionResources();
782
894
  },
895
+ runMemoryCommand: async (args) => handleMemoryCommand({ channelDir: this.channelDir, args }),
783
896
  }),
784
897
  ],
785
- appendSystemPromptOverride: (base) => {
786
- const soul = getSoul(this.workspaceDir);
787
- const sections = [...base];
788
- if (soul) {
789
- sections.unshift(soul);
898
+ // Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
899
+ // default identity, no pi docs index and no `Available tools: (none)` block.
900
+ systemPromptOverride: () => this.buildSystemPrompt().text,
901
+ // Nothing may slip in behind the section pipeline — not pi's app-level
902
+ // APPEND_SYSTEM.md, not a base append. SOUL/AGENTS are rendered as sections.
903
+ appendSystemPromptOverride: () => [],
904
+ agentsFilesOverride: () => ({ agentsFiles: [] }),
905
+ // Skills stay in the ResourceLoader: they drive `/skill:name` and pi's
906
+ // `<available_skills>` index together. Only the merge policy is ours.
907
+ skillsOverride: (base) => {
908
+ const merged = resolvePipiclawSkills(base, this.currentSkills);
909
+ for (const diagnostic of merged.diagnostics) {
910
+ log.logWarning(`[${this.channelId}] Skill ${diagnostic.type}`, `${diagnostic.message}${diagnostic.path ? ` (${diagnostic.path})` : ""}`);
790
911
  }
791
- sections.push(buildAppendSystemPrompt(this.workspaceDir, this.channelId, {
792
- subAgentList: formatSubAgentList(this.subAgentDiscovery.agents),
793
- tools: this.currentTools.map((tool) => ({
794
- name: tool.name,
795
- description: tool.description,
796
- hint: TOOL_PROMPT_HINTS[tool.name],
797
- })),
798
- }));
799
- return sections;
800
- },
801
- agentsFilesOverride: () => {
802
- const agentConfig = getAgentConfig(this.channelDir);
803
- return {
804
- agentsFiles: agentConfig ? [{ path: `${this.workspaceDir}/AGENTS.md`, content: agentConfig }] : [],
805
- };
912
+ return merged;
806
913
  },
807
- skillsOverride: (base) => ({
808
- skills: [...base.skills, ...this.currentSkills],
809
- diagnostics: base.diagnostics,
810
- }),
811
914
  });
812
915
  }
813
916
  createAgentSessionServices(resourceLoader) {
@@ -936,7 +1039,7 @@ export class ChannelRunner {
936
1039
  readOptionalFile(getChannelMemoryPath(this.channelDir)),
937
1040
  readOptionalFile(join(this.workspaceDir, "MEMORY.md")),
938
1041
  ]);
939
- return renderFirstTurnMemoryBootstrap({
1042
+ return buildFirstTurnMemoryBootstrapResult({
940
1043
  channelMemory,
941
1044
  workspaceMemory,
942
1045
  });
@@ -10,5 +10,6 @@ export interface PipiclawCommandExtensionOptions {
10
10
  getLastResponseModel?: () => string | undefined;
11
11
  switchModel: (model: Model<Api>) => Promise<void>;
12
12
  refreshSessionResources: () => Promise<void>;
13
+ runMemoryCommand: (args: string) => Promise<string>;
13
14
  }
14
15
  export declare function createCommandExtension(options: PipiclawCommandExtensionOptions): ExtensionFactory;
@@ -41,6 +41,12 @@ function sendCommandResult(sender, text) {
41
41
  }
42
42
  export function createCommandExtension(options) {
43
43
  return (pi) => {
44
+ pi.registerCommand("memory", {
45
+ description: sessionCommandDescription("memory"),
46
+ handler: async (args) => {
47
+ sendCommandResult(pi, await options.runMemoryCommand(args));
48
+ },
49
+ });
44
50
  pi.registerCommand("session", {
45
51
  description: sessionCommandDescription("session"),
46
52
  handler: async () => {
@@ -1,6 +1,6 @@
1
- export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage";
1
+ export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context";
2
2
  /** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
3
- export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup";
3
+ export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup" | "context";
4
4
  export interface BuiltInCommand {
5
5
  name: BuiltInCommandName;
6
6
  args: string;
@@ -71,6 +71,15 @@ export const BUILT_IN_COMMANDS = [
71
71
  examples: ["/usage", "/usage 7d", "/usage month"],
72
72
  availableWhileBusy: true,
73
73
  },
74
+ {
75
+ name: "context",
76
+ argumentHint: "[detail]",
77
+ description: "Show what the model is being sent: system prompt sections, tool schemas, and last-turn context",
78
+ examples: ["/context", "/context detail"],
79
+ // Read-only accounting of state the runner already holds: no LLM call, no session
80
+ // access, so it answers mid-turn like /status and /usage do.
81
+ availableWhileBusy: true,
82
+ },
74
83
  ];
75
84
  /**
76
85
  * Session commands: handled inside the Pipiclaw session layer (SDK command
@@ -78,6 +87,12 @@ export const BUILT_IN_COMMANDS = [
78
87
  * extension registration in `command-extension.ts`.
79
88
  */
80
89
  export const SESSION_COMMANDS = [
90
+ {
91
+ name: "memory",
92
+ argumentHint: "[status|list|show <id>|pending]",
93
+ description: "Inspect active memory, metadata, recall statistics, tombstones, and pending suggestions",
94
+ examples: ["/memory status", "/memory list", "/memory show m-1234abcd", "/memory pending"],
95
+ },
81
96
  {
82
97
  name: "session",
83
98
  description: "Show current session state, message stats, token usage, and model info",
@@ -114,7 +129,7 @@ export function sessionCommandDescription(name) {
114
129
  export function isBuiltInCommandName(name) {
115
130
  return BUILT_IN_NAMES.has(name);
116
131
  }
117
- const RUNNER_BUILT_IN_NAMES = new Set(["help", "stop", "steer", "followup"]);
132
+ const RUNNER_BUILT_IN_NAMES = new Set(["help", "stop", "steer", "followup", "context"]);
118
133
  /** Narrow a parsed built-in to one `ChannelRunner.handleBuiltinCommand` accepts. */
119
134
  export function isRunnerBuiltInCommand(command) {
120
135
  return RUNNER_BUILT_IN_NAMES.has(command.name);
@@ -64,7 +64,7 @@ export async function loadDetachedMaintenanceContext(options) {
64
64
  memoryGrowth: options.settingsManager.getMemoryGrowthSettings(),
65
65
  memoryMaintenance: options.settingsManager.getMemoryMaintenanceSettings(),
66
66
  },
67
- loadedSkills: loadPipiclawSkills(options.channelDir).map((skill) => ({
67
+ loadedSkills: loadPipiclawSkills(options.channelDir).skills.map((skill) => ({
68
68
  name: skill.name,
69
69
  description: skill.description,
70
70
  })),
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Prompt pipeline: filter → sort → render → budget → fingerprint (spec 025).
3
+ *
4
+ * The output is deterministic: same build context in, same bytes and same
5
+ * fingerprint out. Nothing here may read the clock, the filesystem iteration
6
+ * order, a channel id, or anything else that would make two channels in one
7
+ * workspace disagree — that is what makes the provider-side prompt cache hold.
8
+ */
9
+ import type { PromptBuildContext, PromptBuildResult, PromptSectionDefinition } from "./types.js";
10
+ /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
11
+ export declare const RUNTIME_PROMPT_VERSION = 2;
12
+ /** Above this the prompt still works but is worth a warning. */
13
+ export declare const SOFT_TOTAL_BUDGET_CHARS = 20000;
14
+ /**
15
+ * Above this we shrink user-owned catalogs and files; runtime core is never cut.
16
+ *
17
+ * Both totals cover the Pipiclaw-owned sections only. pi renders `<available_skills>`
18
+ * after them and Pipiclaw cannot trim that list without also destroying `/skill:name`
19
+ * (spec 025 §6.10), so skills are *warned about* here, not shrunk: the prompt actually
20
+ * sent can exceed this cap by the size of the skills catalog.
21
+ */
22
+ export declare const HARD_TOTAL_BUDGET_CHARS = 32000;
23
+ /** Skills are pi's to render; over this we can only tell the operator (spec 025 §8.1). */
24
+ export declare const SKILLS_BUDGET_CHARS = 6000;
25
+ export declare function sha256(text: string): string;
26
+ export declare function estimateTokens(text: string): number;
27
+ /**
28
+ * What pi's `<available_skills>` block will cost, close enough to budget against:
29
+ * name, description and location inside a five-line XML wrapper, plus the preamble.
30
+ */
31
+ export declare function estimateSkillsPromptChars(skills: PromptBuildContext["skills"]): number;
32
+ export declare function buildPipiclawSystemPrompt(context: PromptBuildContext, definitions?: PromptSectionDefinition[]): PromptBuildResult;