@oyasmi/pipiclaw 0.8.4 → 0.8.5

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 (46) hide show
  1. package/README.md +2 -1
  2. package/dist/agent/channel-runner.d.ts +28 -0
  3. package/dist/agent/channel-runner.js +137 -45
  4. package/dist/agent/commands.d.ts +2 -2
  5. package/dist/agent/commands.js +10 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/builder.d.ts +32 -0
  8. package/dist/agent/prompt/builder.js +252 -0
  9. package/dist/agent/prompt/extension.d.ts +22 -0
  10. package/dist/agent/prompt/extension.js +24 -0
  11. package/dist/agent/prompt/manifest.d.ts +51 -0
  12. package/dist/agent/prompt/manifest.js +84 -0
  13. package/dist/agent/prompt/resources.d.ts +18 -0
  14. package/dist/agent/prompt/resources.js +61 -0
  15. package/dist/agent/prompt/sections.d.ts +39 -0
  16. package/dist/agent/prompt/sections.js +267 -0
  17. package/dist/agent/prompt/types.d.ts +110 -0
  18. package/dist/agent/prompt/types.js +11 -0
  19. package/dist/agent/types.d.ts +2 -0
  20. package/dist/agent/workspace-resources.d.ts +25 -13
  21. package/dist/agent/workspace-resources.js +28 -41
  22. package/dist/index.d.ts +7 -2
  23. package/dist/index.js +6 -2
  24. package/dist/memory/transcript.js +7 -6
  25. package/dist/playbooks/catalog.d.ts +22 -1
  26. package/dist/playbooks/catalog.js +57 -4
  27. package/dist/playbooks/event-scheduling.md +2 -0
  28. package/dist/playbooks/memory-and-learning.md +2 -0
  29. package/dist/playbooks/runtime-orientation.md +1 -0
  30. package/dist/playbooks/task-closeout.md +3 -1
  31. package/dist/playbooks/task-delegation.md +3 -1
  32. package/dist/playbooks/task-driving.md +2 -0
  33. package/dist/playbooks/task-planning.md +2 -0
  34. package/dist/playbooks/task-recurring.md +2 -0
  35. package/dist/playbooks/task-repair.md +3 -1
  36. package/dist/runtime/bootstrap.js +7 -38
  37. package/dist/runtime/dingtalk.d.ts +1 -0
  38. package/dist/runtime/dingtalk.js +3 -0
  39. package/dist/runtime/workspace-templates.d.ts +11 -0
  40. package/dist/runtime/workspace-templates.js +51 -0
  41. package/dist/tui/commands.d.ts +1 -0
  42. package/dist/tui/commands.js +2 -0
  43. package/dist/tui/turn-controller.js +1 -0
  44. package/package.json +1 -1
  45. package/dist/agent/prompt-builder.d.ts +0 -12
  46. 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). */
@@ -63,6 +68,18 @@ export declare class ChannelRunner implements AgentRunner {
63
68
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
64
69
  getStatusSnapshot(): RunnerStatusSnapshot;
65
70
  abort(): Promise<void>;
71
+ /**
72
+ * `/context` — read-only prompt accounting, no LLM cost. Reports the section
73
+ * breakdown of the system prompt, the tool schemas (billed on top of it, and
74
+ * often the larger half), and the last turn's dynamic context.
75
+ */
76
+ renderContextReport(args?: string): string;
77
+ /**
78
+ * The per-turn channel capsule. It replaces the channel paths that used to sit in
79
+ * the system prompt: memory/task/event tools are already bound to this channel, so
80
+ * the model only needs the directory when it wants to read a file directly.
81
+ */
82
+ private renderChannelTurnContext;
66
83
  private sendCommandReply;
67
84
  private recordMemoryActivity;
68
85
  private requireQueuedMessage;
@@ -97,6 +114,17 @@ export declare class ChannelRunner implements AgentRunner {
97
114
  private refreshSubAgentDiscovery;
98
115
  private reportSettingsDiagnostics;
99
116
  private reportConfigDiagnostics;
117
+ /**
118
+ * Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
119
+ * base prompt entirely: identity, execution contract, hard invariants, the tool
120
+ * catalog and the workspace files are ours. pi still appends its tail (skills,
121
+ * date, cwd), and the boundary footer is appended after that by the prompt
122
+ * extension.
123
+ *
124
+ * Nothing channel-specific enters this text — that is what lets two channels in
125
+ * one workspace share a cached prompt prefix. Channel facts ride the turn.
126
+ */
127
+ private buildSystemPrompt;
100
128
  private createResourceLoader;
101
129
  private createAgentSessionServices;
102
130
  private createEmptyExtensionsResult;
@@ -13,12 +13,13 @@ import { recallRelevantMemory } from "../memory/recall.js";
13
13
  import { buildTaskDigest } from "../memory/task-digest.js";
14
14
  import { getApiKeyForModel } from "../models/api-keys.js";
15
15
  import { createModelRegistry, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, } from "../models/utils.js";
16
+ import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
16
17
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
17
18
  import { PipiclawSettingsManager } from "../settings.js";
18
19
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
19
20
  import { errorMessage } from "../shared/text-utils.js";
20
21
  import { isRecord } from "../shared/type-guards.js";
21
- import { discoverSubAgents, formatSubAgentList } from "../subagents/discovery.js";
22
+ import { discoverSubAgents } from "../subagents/discovery.js";
22
23
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
23
24
  import { createPipiclawTools } from "../tools/index.js";
24
25
  import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
@@ -28,13 +29,16 @@ import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./comma
28
29
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
29
30
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
30
31
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
31
- import { buildAppendSystemPrompt } from "./prompt-builder.js";
32
+ import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
33
+ import { createPromptBoundaryExtension } from "./prompt/extension.js";
34
+ import { buildPromptManifest, renderContextReport } from "./prompt/manifest.js";
35
+ import { loadWorkspacePromptResources } from "./prompt/resources.js";
32
36
  import { createRunQueue } from "./run-queue.js";
33
37
  import { handleSessionEvent } from "./session-events.js";
34
38
  import { SessionResourceGate } from "./session-resource-gate.js";
35
39
  import { getLastAssistantUsage } from "./type-guards.js";
36
40
  import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
37
- import { getAgentConfig, getSoul, loadPipiclawSkills } from "./workspace-resources.js";
41
+ import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
38
42
  function isSilentOutcome(outcome) {
39
43
  return outcome.kind === "silent";
40
44
  }
@@ -181,6 +185,11 @@ export class ChannelRunner {
181
185
  let promptSubmitted = false;
182
186
  let fallbackAttempted = false;
183
187
  let fallbackTargetRef;
188
+ // Hoisted so the debug dump in `finally` can report the turn as it was actually sent.
189
+ let promptText = "";
190
+ let recalledContextText = "";
191
+ let taskDigestText = "";
192
+ let durableMemoryBootstrapText = "";
184
193
  try {
185
194
  await this.ensureSessionReady();
186
195
  await this.maybeRestorePrimaryModel();
@@ -194,11 +203,11 @@ export class ChannelRunner {
194
203
  const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
195
204
  // Ensure channel directory exists
196
205
  await mkdir(this.channelDir, { recursive: true });
197
- let promptText = preserveRawInput ? clippedInput : userMessage;
198
- let recalledContextText = "";
199
- let taskDigestText = "";
200
- let durableMemoryBootstrapText = "";
206
+ promptText = preserveRawInput ? clippedInput : userMessage;
201
207
  if (!preserveRawInput) {
208
+ // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
209
+ // system prompt is what lets every channel in a workspace share one cached prefix.
210
+ promptText = `${this.renderChannelTurnContext()}\n\n<user_message>\n${promptText}\n</user_message>`;
202
211
  const recallSettings = this.settingsManager.getMemoryRecallSettings();
203
212
  if (recallSettings.enabled) {
204
213
  const recall = await recallRelevantMemory({
@@ -219,7 +228,7 @@ export class ChannelRunner {
219
228
  });
220
229
  if (recall.renderedText) {
221
230
  recalledContextText = recall.renderedText;
222
- promptText = `${recall.renderedText}\n\n<user_message>\n${promptText}\n</user_message>`;
231
+ promptText = `${recall.renderedText}\n\n${promptText}`;
223
232
  }
224
233
  }
225
234
  // Gated by the same master autonomy switch as task_manage and the TaskDriver.
@@ -246,18 +255,12 @@ export class ChannelRunner {
246
255
  // prepended above), not just the bare user message — those pieces can add thousands of
247
256
  // characters and must count against the projected context usage this guard is checking.
248
257
  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
- }
258
+ this.lastTurnContextStats = {
259
+ durableMemoryChars: durableMemoryBootstrapText.length,
260
+ taskDigestChars: taskDigestText.length,
261
+ recalledMemoryChars: recalledContextText.length,
262
+ userMessageChars: clippedInput.length,
263
+ };
261
264
  const fallbackDeps = {
262
265
  prompt: async (text) => {
263
266
  try {
@@ -318,6 +321,23 @@ export class ChannelRunner {
318
321
  }
319
322
  finally {
320
323
  this.turn.phase = "finishing";
324
+ // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
325
+ // string the provider actually received — base sections, pi's tail, and the boundary
326
+ // footer the prompt extension appends at before_agent_start.
327
+ if (process.env.PIPICLAW_DEBUG) {
328
+ const debugContext = {
329
+ systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
330
+ promptManifest: this.lastPromptBuild
331
+ ? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
332
+ : undefined,
333
+ messages: this.session.messages,
334
+ durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
335
+ taskDigest: taskDigestText || undefined,
336
+ recalledContext: recalledContextText || undefined,
337
+ newUserMessage: promptText,
338
+ };
339
+ 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)));
340
+ }
321
341
  if (!promptSubmitted) {
322
342
  const discarded = this.session.clearQueue();
323
343
  const discardedCount = discarded.steering.length + discarded.followUp.length;
@@ -445,6 +465,9 @@ export class ChannelRunner {
445
465
  case "help":
446
466
  await this.sendCommandReply(ctx, renderBuiltInHelp());
447
467
  return;
468
+ case "context":
469
+ await this.sendCommandReply(ctx, this.renderContextReport(command.args));
470
+ return;
448
471
  case "stop":
449
472
  await this.sendCommandReply(ctx, "No task is running. Use `/stop` only while a task is running.");
450
473
  return;
@@ -510,7 +533,7 @@ export class ChannelRunner {
510
533
  memoryGrowth: this.settingsManager.getMemoryGrowthSettings(),
511
534
  memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings(),
512
535
  },
513
- loadedSkills: this.currentSkills.map((skill) => ({
536
+ loadedSkills: this.currentSkills.skills.map((skill) => ({
514
537
  name: skill.name,
515
538
  description: skill.description,
516
539
  })),
@@ -539,7 +562,37 @@ export class ChannelRunner {
539
562
  async abort() {
540
563
  await this.session.abort();
541
564
  }
565
+ /**
566
+ * `/context` — read-only prompt accounting, no LLM cost. Reports the section
567
+ * breakdown of the system prompt, the tool schemas (billed on top of it, and
568
+ * often the larger half), and the last turn's dynamic context.
569
+ */
570
+ renderContextReport(args = "") {
571
+ const build = this.lastPromptBuild ?? this.buildSystemPrompt();
572
+ return renderContextReport({
573
+ build,
574
+ finalPrompt: this.lastFinalPrompt,
575
+ skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
576
+ toolNames: this.currentTools.map((tool) => tool.name),
577
+ toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
578
+ lastTurn: this.lastTurnContextStats,
579
+ detail: args.trim().toLowerCase() === "detail",
580
+ });
581
+ }
542
582
  // === Private helpers ===
583
+ /**
584
+ * The per-turn channel capsule. It replaces the channel paths that used to sit in
585
+ * the system prompt: memory/task/event tools are already bound to this channel, so
586
+ * the model only needs the directory when it wants to read a file directly.
587
+ */
588
+ renderChannelTurnContext() {
589
+ return [
590
+ "<runtime_turn_context>",
591
+ `Channel directory: ${this.channelDir}`,
592
+ "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.",
593
+ "</runtime_turn_context>",
594
+ ].join("\n");
595
+ }
543
596
  async sendCommandReply(ctx, text) {
544
597
  const delivered = await ctx.respondPlain(text);
545
598
  if (!delivered) {
@@ -755,6 +808,49 @@ export class ChannelRunner {
755
808
  log.logWarning(`[${this.channelId}] ${formatConfigDiagnostic(diagnostic)}`, diagnostic.path);
756
809
  }
757
810
  }
811
+ /**
812
+ * Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
813
+ * base prompt entirely: identity, execution contract, hard invariants, the tool
814
+ * catalog and the workspace files are ours. pi still appends its tail (skills,
815
+ * date, cwd), and the boundary footer is appended after that by the prompt
816
+ * extension.
817
+ *
818
+ * Nothing channel-specific enters this text — that is what lets two channels in
819
+ * one workspace share a cached prompt prefix. Channel facts ride the turn.
820
+ */
821
+ buildSystemPrompt() {
822
+ const toolNames = this.currentTools.map((tool) => tool.name);
823
+ const resources = loadWorkspacePromptResources(this.workspaceDir);
824
+ const build = buildPipiclawSystemPrompt({
825
+ mode: "normal",
826
+ cwd: process.cwd(),
827
+ workspaceDir: this.workspaceDir,
828
+ tools: this.currentTools.map((tool) => ({
829
+ name: tool.name,
830
+ description: tool.description,
831
+ hint: TOOL_PROMPT_HINTS[tool.name],
832
+ })),
833
+ soul: resources.soul,
834
+ agents: resources.agents,
835
+ playbooks: selectRuntimePlaybooks(loadRuntimePlaybookCatalog(), toolNames),
836
+ subAgents: this.subAgentDiscovery.agents.map((agent) => ({
837
+ name: agent.name,
838
+ description: agent.description,
839
+ })),
840
+ skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
841
+ });
842
+ for (const diagnostic of [...resources.diagnostics, ...build.diagnostics]) {
843
+ if (diagnostic.level === "info")
844
+ continue;
845
+ log.logWarning(`[${this.channelId}] Prompt ${diagnostic.level} (${diagnostic.sectionId})`, diagnostic.message);
846
+ }
847
+ // Only a real change is worth a line: a reload that produced the same bytes is noise.
848
+ if (this.lastPromptBuild?.fingerprint !== build.fingerprint) {
849
+ 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"})`);
850
+ }
851
+ this.lastPromptBuild = build;
852
+ return build;
853
+ }
758
854
  createResourceLoader() {
759
855
  return new DefaultResourceLoader({
760
856
  cwd: process.cwd(),
@@ -762,6 +858,12 @@ export class ChannelRunner {
762
858
  settingsManager: asSdkSettingsManager(this.settingsManager),
763
859
  extensionFactories: [
764
860
  this.memoryLifecycle.createExtensionFactory(),
861
+ createPromptBoundaryExtension({
862
+ getFooter: () => this.lastPromptBuild?.footer ?? "",
863
+ onFinalPrompt: (systemPrompt) => {
864
+ this.lastFinalPrompt = systemPrompt;
865
+ },
866
+ }),
765
867
  createCommandExtension({
766
868
  getCurrentModel: () => this.session.model ?? this.activeModel,
767
869
  getAvailableModels: async () => {
@@ -782,32 +884,22 @@ export class ChannelRunner {
782
884
  },
783
885
  }),
784
886
  ],
785
- appendSystemPromptOverride: (base) => {
786
- const soul = getSoul(this.workspaceDir);
787
- const sections = [...base];
788
- if (soul) {
789
- sections.unshift(soul);
887
+ // Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
888
+ // default identity, no pi docs index and no `Available tools: (none)` block.
889
+ systemPromptOverride: () => this.buildSystemPrompt().text,
890
+ // Nothing may slip in behind the section pipeline — not pi's app-level
891
+ // APPEND_SYSTEM.md, not a base append. SOUL/AGENTS are rendered as sections.
892
+ appendSystemPromptOverride: () => [],
893
+ agentsFilesOverride: () => ({ agentsFiles: [] }),
894
+ // Skills stay in the ResourceLoader: they drive `/skill:name` and pi's
895
+ // `<available_skills>` index together. Only the merge policy is ours.
896
+ skillsOverride: (base) => {
897
+ const merged = resolvePipiclawSkills(base, this.currentSkills);
898
+ for (const diagnostic of merged.diagnostics) {
899
+ log.logWarning(`[${this.channelId}] Skill ${diagnostic.type}`, `${diagnostic.message}${diagnostic.path ? ` (${diagnostic.path})` : ""}`);
790
900
  }
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
- };
901
+ return merged;
806
902
  },
807
- skillsOverride: (base) => ({
808
- skills: [...base.skills, ...this.currentSkills],
809
- diagnostics: base.diagnostics,
810
- }),
811
903
  });
812
904
  }
813
905
  createAgentSessionServices(resourceLoader) {
@@ -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
@@ -114,7 +123,7 @@ export function sessionCommandDescription(name) {
114
123
  export function isBuiltInCommandName(name) {
115
124
  return BUILT_IN_NAMES.has(name);
116
125
  }
117
- const RUNNER_BUILT_IN_NAMES = new Set(["help", "stop", "steer", "followup"]);
126
+ const RUNNER_BUILT_IN_NAMES = new Set(["help", "stop", "steer", "followup", "context"]);
118
127
  /** Narrow a parsed built-in to one `ChannelRunner.handleBuiltinCommand` accepts. */
119
128
  export function isRunnerBuiltInCommand(command) {
120
129
  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;