@oyasmi/pipiclaw 0.8.7-beta.1 → 0.8.7-beta.2

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 (34) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -0
  2. package/dist/agent/channel-runner.js +18 -4
  3. package/dist/agent/prompt/builder.d.ts +11 -20
  4. package/dist/agent/prompt/builder.js +40 -87
  5. package/dist/agent/prompt/manifest.d.ts +28 -2
  6. package/dist/agent/prompt/manifest.js +50 -11
  7. package/dist/agent/prompt/resources.d.ts +11 -2
  8. package/dist/agent/prompt/resources.js +51 -12
  9. package/dist/agent/prompt/sections.d.ts +9 -10
  10. package/dist/agent/prompt/sections.js +46 -99
  11. package/dist/agent/prompt/types.d.ts +14 -0
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/memory/bootstrap.d.ts +6 -0
  15. package/dist/memory/bootstrap.js +53 -21
  16. package/dist/memory/recall.d.ts +8 -0
  17. package/dist/memory/recall.js +19 -13
  18. package/dist/memory/task-digest.d.ts +4 -0
  19. package/dist/memory/task-digest.js +9 -3
  20. package/dist/playbooks/catalog.d.ts +7 -2
  21. package/dist/playbooks/catalog.js +10 -6
  22. package/dist/playbooks/event-scheduling.md +1 -1
  23. package/dist/playbooks/memory-and-learning.md +1 -1
  24. package/dist/playbooks/runtime-orientation.md +1 -1
  25. package/dist/playbooks/task-closeout.md +1 -1
  26. package/dist/playbooks/task-delegation.md +1 -1
  27. package/dist/playbooks/task-driving.md +1 -1
  28. package/dist/playbooks/task-planning.md +1 -1
  29. package/dist/playbooks/task-recurring.md +1 -1
  30. package/dist/playbooks/task-repair.md +1 -1
  31. package/dist/runtime/events.js +6 -1
  32. package/dist/shared/prompt-units.d.ts +46 -0
  33. package/dist/shared/prompt-units.js +153 -0
  34. package/package.json +1 -1
@@ -30,6 +30,8 @@ export declare class ChannelRunner implements AgentRunner {
30
30
  private currentSkills;
31
31
  /** Last built system prompt (spec 025): feeds the boundary footer, /context and the debug manifest. */
32
32
  private lastPromptBuild?;
33
+ /** SOUL/AGENTS as resolved for the last build, for the `/context` independent-budget lines. */
34
+ private lastWorkspaceResources?;
33
35
  /** The exact system prompt the provider last received (our prompt + pi's tail + footer). */
34
36
  private lastFinalPrompt?;
35
37
  private lastTurnContextStats?;
@@ -4,20 +4,21 @@ 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 { buildFirstTurnMemoryBootstrapResult } from "../memory/bootstrap.js";
7
+ import { buildFirstTurnMemoryBootstrapResult, FIRST_TURN_BOOTSTRAP_MAX_UNITS, } from "../memory/bootstrap.js";
8
8
  import { createMemoryCandidateStore } from "../memory/candidates.js";
9
9
  import { handleMemoryCommand } from "../memory/commands.js";
10
10
  import { getChannelMemoryPath } from "../memory/files.js";
11
11
  import { MemoryLifecycle } from "../memory/lifecycle.js";
12
12
  import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../memory/maintenance-state.js";
13
- import { recallRelevantMemory } from "../memory/recall.js";
14
- import { buildTaskDigest } from "../memory/task-digest.js";
13
+ import { MEMORY_RECALL_MAX_UNITS, recallRelevantMemory } from "../memory/recall.js";
14
+ import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
15
15
  import { getApiKeyForModel } from "../models/api-keys.js";
16
16
  import { createModelRegistry, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, } from "../models/utils.js";
17
17
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
18
18
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
19
19
  import { PipiclawSettingsManager } from "../settings.js";
20
20
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
21
+ import { countPromptUnits } from "../shared/prompt-units.js";
21
22
  import { errorMessage } from "../shared/text-utils.js";
22
23
  import { isRecord } from "../shared/type-guards.js";
23
24
  import { discoverSubAgents } from "../subagents/discovery.js";
@@ -192,6 +193,7 @@ export class ChannelRunner {
192
193
  let recalledContextText = "";
193
194
  let taskDigestText = "";
194
195
  let durableMemoryBootstrapText = "";
196
+ let channelCapsuleText = "";
195
197
  let bootstrapCandidateIds = [];
196
198
  let bootstrapPrepared = false;
197
199
  try {
@@ -211,7 +213,8 @@ export class ChannelRunner {
211
213
  if (!preserveRawInput) {
212
214
  // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
213
215
  // 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>`;
216
+ channelCapsuleText = this.renderChannelTurnContext();
217
+ promptText = `${channelCapsuleText}\n\n<user_message>\n${promptText}\n</user_message>`;
215
218
  if (this.firstTurnMemoryBootstrapPending) {
216
219
  const bootstrap = await this.buildFirstTurnMemoryBootstrap();
217
220
  durableMemoryBootstrapText = bootstrap.renderedText;
@@ -228,6 +231,8 @@ export class ChannelRunner {
228
231
  maxCandidates: recallSettings.maxCandidates,
229
232
  maxInjected: recallSettings.maxInjected,
230
233
  maxChars: recallSettings.maxChars,
234
+ // The configured char cap and the runtime unit cap both apply; first to bind clips.
235
+ maxUnits: MEMORY_RECALL_MAX_UNITS,
231
236
  rerankWithModel: recallSettings.rerankWithModel,
232
237
  excludedCandidateIds: bootstrapCandidateIds,
233
238
  // Let shouldUseModelRerank's own memory-intent gate decide (it already handles
@@ -249,6 +254,7 @@ export class ChannelRunner {
249
254
  channelDir: this.channelDir,
250
255
  maxTasks: taskDigestSettings.maxTasks,
251
256
  maxChars: taskDigestSettings.maxChars,
257
+ maxUnits: TASK_AGENDA_MAX_UNITS,
252
258
  });
253
259
  if (taskDigestText) {
254
260
  promptText = `${taskDigestText}\n\n${promptText}`;
@@ -264,8 +270,12 @@ export class ChannelRunner {
264
270
  await this.maybeRunPreventiveCompactionForIncomingText(promptText);
265
271
  this.lastTurnContextStats = {
266
272
  durableMemoryChars: durableMemoryBootstrapText.length,
273
+ durableMemoryUnits: countPromptUnits(durableMemoryBootstrapText),
267
274
  taskDigestChars: taskDigestText.length,
275
+ taskDigestUnits: countPromptUnits(taskDigestText),
268
276
  recalledMemoryChars: recalledContextText.length,
277
+ recalledMemoryUnits: countPromptUnits(recalledContextText),
278
+ channelCapsuleUnits: countPromptUnits(channelCapsuleText),
269
279
  userMessageChars: clippedInput.length,
270
280
  };
271
281
  const fallbackDeps = {
@@ -591,6 +601,8 @@ export class ChannelRunner {
591
601
  skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
592
602
  toolNames: this.currentTools.map((tool) => tool.name),
593
603
  toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
604
+ soul: this.lastWorkspaceResources?.soul,
605
+ agents: this.lastWorkspaceResources?.agents,
594
606
  lastTurn: this.lastTurnContextStats,
595
607
  detail: args.trim().toLowerCase() === "detail",
596
608
  });
@@ -837,6 +849,7 @@ export class ChannelRunner {
837
849
  buildSystemPrompt() {
838
850
  const toolNames = this.currentTools.map((tool) => tool.name);
839
851
  const resources = loadWorkspacePromptResources(this.workspaceDir);
852
+ this.lastWorkspaceResources = resources;
840
853
  const build = buildPipiclawSystemPrompt({
841
854
  mode: "normal",
842
855
  cwd: process.cwd(),
@@ -1048,6 +1061,7 @@ export class ChannelRunner {
1048
1061
  return buildFirstTurnMemoryBootstrapResult({
1049
1062
  channelMemory,
1050
1063
  workspaceMemory,
1064
+ maxUnits: FIRST_TURN_BOOTSTRAP_MAX_UNITS,
1051
1065
  });
1052
1066
  }
1053
1067
  }
@@ -1,32 +1,23 @@
1
1
  /**
2
- * Prompt pipeline: filter → sort → render → budget → fingerprint (spec 025).
2
+ * Prompt pipeline: filter → sort → render → budget → fingerprint (spec 025, 026).
3
3
  *
4
4
  * The output is deterministic: same build context in, same bytes and same
5
5
  * fingerprint out. Nothing here may read the clock, the filesystem iteration
6
6
  * order, a channel id, or anything else that would make two channels in one
7
7
  * workspace disagree — that is what makes the provider-side prompt cache hold.
8
+ *
9
+ * Budget model (spec 026 §5, §10.3): there is no single global char cap that lets
10
+ * runtime text, SOUL, AGENTS and skills compete. The only budget enforced here is
11
+ * on the sections Pipiclaw *authors* — measured in prompt units. SOUL/AGENTS are
12
+ * budgeted independently in resources.ts, and skills are pi's to render.
8
13
  */
9
14
  import type { PromptBuildContext, PromptBuildResult, PromptSectionDefinition } from "./types.js";
10
15
  /** 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;
16
+ export declare const RUNTIME_PROMPT_VERSION = 3;
17
+ /** Over this, the runtime-authored prompt still works but is worth a warning (spec 026 §5.2). */
18
+ export declare const RUNTIME_PROMPT_TARGET_UNITS = 700;
19
+ /** Over this it is a development error: runtime text has drifted well past its budget. */
20
+ export declare const RUNTIME_PROMPT_HARD_UNITS = 1200;
25
21
  export declare function sha256(text: string): string;
26
22
  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
23
  export declare function buildPipiclawSystemPrompt(context: PromptBuildContext, definitions?: PromptSectionDefinition[]): PromptBuildResult;
@@ -1,36 +1,39 @@
1
1
  /**
2
- * Prompt pipeline: filter → sort → render → budget → fingerprint (spec 025).
2
+ * Prompt pipeline: filter → sort → render → budget → fingerprint (spec 025, 026).
3
3
  *
4
4
  * The output is deterministic: same build context in, same bytes and same
5
5
  * fingerprint out. Nothing here may read the clock, the filesystem iteration
6
6
  * order, a channel id, or anything else that would make two channels in one
7
7
  * workspace disagree — that is what makes the provider-side prompt cache hold.
8
+ *
9
+ * Budget model (spec 026 §5, §10.3): there is no single global char cap that lets
10
+ * runtime text, SOUL, AGENTS and skills compete. The only budget enforced here is
11
+ * on the sections Pipiclaw *authors* — measured in prompt units. SOUL/AGENTS are
12
+ * budgeted independently in resources.ts, and skills are pi's to render.
8
13
  */
9
14
  import { createHash } from "node:crypto";
15
+ import { countPromptUnits } from "../../shared/prompt-units.js";
10
16
  import { FINAL_BOUNDARY_SECTION, MAIN_PROMPT_SECTIONS } from "./sections.js";
11
17
  /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
12
- export const RUNTIME_PROMPT_VERSION = 2;
13
- /** Above this the prompt still works but is worth a warning. */
14
- export const SOFT_TOTAL_BUDGET_CHARS = 20_000;
15
- /**
16
- * Above this we shrink user-owned catalogs and files; runtime core is never cut.
17
- *
18
- * Both totals cover the Pipiclaw-owned sections only. pi renders `<available_skills>`
19
- * after them and Pipiclaw cannot trim that list without also destroying `/skill:name`
20
- * (spec 025 §6.10), so skills are *warned about* here, not shrunk: the prompt actually
21
- * sent can exceed this cap by the size of the skills catalog.
22
- */
23
- export const HARD_TOTAL_BUDGET_CHARS = 32_000;
24
- /** Skills are pi's to render; over this we can only tell the operator (spec 025 §8.1). */
25
- export const SKILLS_BUDGET_CHARS = 6_000;
18
+ export const RUNTIME_PROMPT_VERSION = 3;
26
19
  /**
27
- * Least-important first: the order in which sections give up characters when the
28
- * whole prompt exceeds the hard cap (spec 025 §8.2). Runtime-authored sections
29
- * are absent by design — they are never shrunk.
20
+ * The sections Pipiclaw authors and must keep tight (spec 026 §10.3): identity,
21
+ * execution, invariants, persistent-task rules, the runtime-guide catalog and the
22
+ * final boundary. SOUL/AGENTS, the sub-agent catalog (its descriptions are user
23
+ * text) and pi's skills are deliberately excluded.
30
24
  */
31
- const SHRINK_ORDER = ["subagents", "playbooks", "workspace.agents", "workspace.soul"];
32
- /** A shrunk workspace file still keeps this much of itself; below it, the file says nothing useful. */
33
- const MIN_SHRUNK_SECTION_CHARS = 800;
25
+ const RUNTIME_AUTHORED_SECTION_IDS = new Set([
26
+ "runtime.identity",
27
+ "runtime.execution",
28
+ "runtime.invariants",
29
+ "runtime.tasks",
30
+ "playbooks",
31
+ "runtime.boundary",
32
+ ]);
33
+ /** Over this, the runtime-authored prompt still works but is worth a warning (spec 026 §5.2). */
34
+ export const RUNTIME_PROMPT_TARGET_UNITS = 700;
35
+ /** Over this it is a development error: runtime text has drifted well past its budget. */
36
+ export const RUNTIME_PROMPT_HARD_UNITS = 1_200;
34
37
  export function sha256(text) {
35
38
  return createHash("sha256").update(text, "utf8").digest("hex");
36
39
  }
@@ -141,66 +144,12 @@ function resolve(definition, context, diagnostics) {
141
144
  content,
142
145
  rawChars: raw.length,
143
146
  injectedChars: content.length,
147
+ rawUnits: countPromptUnits(raw),
148
+ injectedUnits: countPromptUnits(content),
144
149
  truncated,
145
150
  sha256: sha256(content),
146
151
  };
147
152
  }
148
- /** Re-shrink user-owned sections until the whole prompt fits the hard cap. */
149
- function enforceTotalBudget(sections, diagnostics) {
150
- const total = () => sections.reduce((sum, section) => sum + section.injectedChars, 0) + 2 * (sections.length - 1);
151
- for (const id of SHRINK_ORDER) {
152
- if (total() <= HARD_TOTAL_BUDGET_CHARS) {
153
- return;
154
- }
155
- const index = sections.findIndex((section) => section.id === id);
156
- if (index < 0)
157
- continue;
158
- const section = sections[index];
159
- const overBy = total() - HARD_TOTAL_BUDGET_CHARS;
160
- const target = section.injectedChars - overBy;
161
- if (target < MIN_SHRUNK_SECTION_CHARS) {
162
- sections.splice(index, 1);
163
- diagnostics.push({
164
- level: "warning",
165
- sectionId: id,
166
- message: `dropped to keep the prompt under the ${HARD_TOTAL_BUDGET_CHARS} char hard cap. Run /context detail to see what is competing for space.`,
167
- });
168
- continue;
169
- }
170
- const content = truncateHeadTail(section.content, target, "shrunk to fit the total prompt budget");
171
- sections[index] = {
172
- ...section,
173
- content,
174
- injectedChars: content.length,
175
- truncated: true,
176
- sha256: sha256(content),
177
- };
178
- diagnostics.push({
179
- level: "warning",
180
- sectionId: id,
181
- message: `shrunk to fit the ${HARD_TOTAL_BUDGET_CHARS} char hard cap. Run /context detail.`,
182
- });
183
- }
184
- if (total() > HARD_TOTAL_BUDGET_CHARS) {
185
- diagnostics.push({
186
- level: "error",
187
- sectionId: "prompt",
188
- message: `system prompt is ${total()} chars, over the ${HARD_TOTAL_BUDGET_CHARS} char hard cap even after shrinking every user-owned section.`,
189
- });
190
- }
191
- }
192
- /**
193
- * What pi's `<available_skills>` block will cost, close enough to budget against:
194
- * name, description and location inside a five-line XML wrapper, plus the preamble.
195
- */
196
- export function estimateSkillsPromptChars(skills) {
197
- if (!skills || skills.length === 0)
198
- return 0;
199
- const SKILL_WRAPPER_CHARS = 90;
200
- const PREAMBLE_CHARS = 290;
201
- return (PREAMBLE_CHARS +
202
- skills.reduce((sum, skill) => sum + skill.name.length + skill.description.length + SKILL_WRAPPER_CHARS, 0));
203
- }
204
153
  export function buildPipiclawSystemPrompt(context, definitions = MAIN_PROMPT_SECTIONS) {
205
154
  const diagnostics = [];
206
155
  const ids = new Set();
@@ -217,27 +166,29 @@ export function buildPipiclawSystemPrompt(context, definitions = MAIN_PROMPT_SEC
217
166
  .sort((a, b) => a.order - b.order)
218
167
  .map((definition) => resolve(definition, context, diagnostics))
219
168
  .filter((section) => section !== undefined);
220
- enforceTotalBudget(sections, diagnostics);
221
169
  const footerSection = resolve(FINAL_BOUNDARY_SECTION, context, diagnostics);
222
170
  const text = sections.map((section) => section.content).join("\n\n");
223
171
  const footer = footerSection?.content ?? "";
224
172
  const allSections = footerSection ? [...sections, footerSection] : sections;
225
173
  const totalChars = text.length + footer.length;
226
- if (totalChars > SOFT_TOTAL_BUDGET_CHARS) {
174
+ // The only budget enforced at build time: the sections Pipiclaw authors (spec 026 §10.3).
175
+ // SOUL/AGENTS are budgeted independently in resources.ts; skills are rendered by pi.
176
+ const runtimeAuthoredUnits = allSections
177
+ .filter((section) => RUNTIME_AUTHORED_SECTION_IDS.has(section.id))
178
+ .reduce((sum, section) => sum + section.injectedUnits, 0);
179
+ const totalUnits = allSections.reduce((sum, section) => sum + section.injectedUnits, 0);
180
+ if (runtimeAuthoredUnits > RUNTIME_PROMPT_HARD_UNITS) {
227
181
  diagnostics.push({
228
- level: "warning",
182
+ level: "error",
229
183
  sectionId: "prompt",
230
- message: `system prompt is ${totalChars} chars, over the ${SOFT_TOTAL_BUDGET_CHARS} char soft target. Run /context detail.`,
184
+ message: `runtime-authored prompt is ${runtimeAuthoredUnits} units, over the ${RUNTIME_PROMPT_HARD_UNITS} unit hard cap. Shorten the runtime sections in src/agent/prompt/sections.ts.`,
231
185
  });
232
186
  }
233
- // Skills sit outside every budget above: pi renders them and owns the same list that
234
- // backs `/skill:name`, so trimming here would delete commands. Report instead of cut.
235
- const skillsChars = estimateSkillsPromptChars(context.skills);
236
- if (skillsChars > SKILLS_BUDGET_CHARS) {
187
+ else if (runtimeAuthoredUnits > RUNTIME_PROMPT_TARGET_UNITS) {
237
188
  diagnostics.push({
238
189
  level: "warning",
239
- sectionId: "skills",
240
- message: `skills catalog is ≈${skillsChars} chars, over the ${SKILLS_BUDGET_CHARS} char budget, and is appended after the sections above (Pipiclaw cannot trim it without dropping /skill:name). Run /context detail, then shorten or remove workspace skill descriptions.`,
190
+ sectionId: "prompt",
191
+ message: `runtime-authored prompt is ${runtimeAuthoredUnits} units, over the ${RUNTIME_PROMPT_TARGET_UNITS} unit target. Run /context detail and trim the runtime sections.`,
241
192
  });
242
193
  }
243
194
  return {
@@ -246,6 +197,8 @@ export function buildPipiclawSystemPrompt(context, definitions = MAIN_PROMPT_SEC
246
197
  sections: allSections,
247
198
  diagnostics,
248
199
  totalChars,
200
+ totalUnits,
201
+ runtimeAuthoredUnits,
249
202
  estimatedTokens: estimateTokens(text) + estimateTokens(footer),
250
203
  fingerprint: sha256(`v${RUNTIME_PROMPT_VERSION}\n${text}\n${footer}`),
251
204
  };
@@ -1,15 +1,25 @@
1
1
  /**
2
- * Prompt manifest and the `/context` report (spec 025 §9).
2
+ * Prompt manifest and the `/context` report (spec 025 §9, spec 026 §10.9).
3
3
  *
4
4
  * Zero LLM cost: everything here is computed from the last build plus counters
5
5
  * the runner already keeps. Tool JSON schemas are reported alongside the system
6
6
  * prompt because they are billed the same way and are often the larger half.
7
+ *
8
+ * Skills are reported here, never budgeted: pi renders `<available_skills>` and
9
+ * owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
10
+ * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
7
11
  */
8
- import type { PromptBuildResult } from "./types.js";
12
+ import type { LoadedPromptResource, PromptBuildResult } from "./types.js";
13
+ /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
+ export declare const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3000;
9
15
  export interface PromptTurnContextStats {
10
16
  durableMemoryChars: number;
17
+ durableMemoryUnits: number;
11
18
  taskDigestChars: number;
19
+ taskDigestUnits: number;
12
20
  recalledMemoryChars: number;
21
+ recalledMemoryUnits: number;
22
+ channelCapsuleUnits: number;
13
23
  userMessageChars: number;
14
24
  }
15
25
  export interface PromptContextReportInput {
@@ -22,6 +32,9 @@ export interface PromptContextReportInput {
22
32
  }>;
23
33
  toolNames: string[];
24
34
  toolSchemaChars: number;
35
+ /** Resolved SOUL.md / AGENTS.md, for the independent body-budget lines. */
36
+ soul?: LoadedPromptResource;
37
+ agents?: LoadedPromptResource;
25
38
  lastTurn?: PromptTurnContextStats;
26
39
  detail: boolean;
27
40
  }
@@ -33,12 +46,16 @@ export interface PromptSectionManifestEntry {
33
46
  cacheClass: string;
34
47
  rawChars: number;
35
48
  injectedChars: number;
49
+ rawUnits: number;
50
+ injectedUnits: number;
36
51
  truncated: boolean;
37
52
  sha256: string;
38
53
  }
39
54
  export interface PromptManifest {
40
55
  fingerprint: string;
41
56
  totalChars: number;
57
+ totalUnits: number;
58
+ runtimeAuthoredUnits: number;
42
59
  estimatedTokens: number;
43
60
  sections: PromptSectionManifestEntry[];
44
61
  diagnostics: PromptBuildResult["diagnostics"];
@@ -46,6 +63,15 @@ export interface PromptManifest {
46
63
  finalPromptSha256?: string;
47
64
  finalPromptChars?: number;
48
65
  }
66
+ /**
67
+ * What pi's `<available_skills>` block will cost, close enough to report on:
68
+ * name, description and location inside a five-line XML wrapper, plus the preamble.
69
+ * This is observation only — Pipiclaw never trims skills (spec 026 §9).
70
+ */
71
+ export declare function estimateSkillsPromptChars(skills: Array<{
72
+ name: string;
73
+ description: string;
74
+ }>): number;
49
75
  /** Section metadata without any section body — safe to write next to a channel. */
50
76
  export declare function buildPromptManifest(build: PromptBuildResult, finalPrompt?: string): PromptManifest;
51
77
  export declare function renderContextReport(input: PromptContextReportInput): string;
@@ -1,16 +1,37 @@
1
1
  /**
2
- * Prompt manifest and the `/context` report (spec 025 §9).
2
+ * Prompt manifest and the `/context` report (spec 025 §9, spec 026 §10.9).
3
3
  *
4
4
  * Zero LLM cost: everything here is computed from the last build plus counters
5
5
  * the runner already keeps. Tool JSON schemas are reported alongside the system
6
6
  * prompt because they are billed the same way and are often the larger half.
7
+ *
8
+ * Skills are reported here, never budgeted: pi renders `<available_skills>` and
9
+ * owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
10
+ * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
+ */
12
+ import { estimateTokens, RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
13
+ /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
+ export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
15
+ /**
16
+ * What pi's `<available_skills>` block will cost, close enough to report on:
17
+ * name, description and location inside a five-line XML wrapper, plus the preamble.
18
+ * This is observation only — Pipiclaw never trims skills (spec 026 §9).
7
19
  */
8
- import { estimateSkillsPromptChars, estimateTokens, sha256 } from "./builder.js";
20
+ export function estimateSkillsPromptChars(skills) {
21
+ if (!skills || skills.length === 0)
22
+ return 0;
23
+ const SKILL_WRAPPER_CHARS = 90;
24
+ const PREAMBLE_CHARS = 290;
25
+ return (PREAMBLE_CHARS +
26
+ skills.reduce((sum, skill) => sum + skill.name.length + skill.description.length + SKILL_WRAPPER_CHARS, 0));
27
+ }
9
28
  /** Section metadata without any section body — safe to write next to a channel. */
10
29
  export function buildPromptManifest(build, finalPrompt) {
11
30
  return {
12
31
  fingerprint: build.fingerprint,
13
32
  totalChars: build.totalChars,
33
+ totalUnits: build.totalUnits,
34
+ runtimeAuthoredUnits: build.runtimeAuthoredUnits,
14
35
  estimatedTokens: build.estimatedTokens,
15
36
  sections: build.sections.map(({ content: _content, ...entry }) => entry),
16
37
  diagnostics: build.diagnostics,
@@ -24,10 +45,16 @@ function formatNumber(value) {
24
45
  function pad(text, width) {
25
46
  return text.length >= width ? text : text + " ".repeat(width - text.length);
26
47
  }
48
+ function renderWorkspaceResourceLine(label, resource) {
49
+ if (!resource || resource.isDefaultTemplate)
50
+ return undefined;
51
+ const state = resource.truncated ? "truncated" : "complete";
52
+ return `- ${pad(label, 10)}${formatNumber(resource.injectedUnits)} / ${formatNumber(resource.budgetUnits)} units, ${state}`;
53
+ }
27
54
  export function renderContextReport(input) {
28
55
  const { build, finalPrompt, detail } = input;
29
56
  const lines = ["# Context Report", ""];
30
- lines.push(`System prompt (Pipiclaw-owned): ${formatNumber(build.totalChars)} chars, ~${formatNumber(build.estimatedTokens)} tokens`);
57
+ 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`);
31
58
  if (finalPrompt) {
32
59
  // The string the provider actually caches: our sections + pi's skills/date/cwd tail +
33
60
  // the boundary footer. It is the fingerprint that matters for cache hits — the build
@@ -41,20 +68,32 @@ export function renderContextReport(input) {
41
68
  for (const section of build.sections) {
42
69
  const flags = [section.cacheClass];
43
70
  if (section.truncated)
44
- flags.push(`truncated from ${formatNumber(section.rawChars)}`);
45
- lines.push(`- ${pad(section.id, width)}${formatNumber(section.injectedChars).padStart(7)} chars ${flags.join(", ")}`);
71
+ flags.push(`truncated from ${formatNumber(section.rawUnits)} units`);
72
+ lines.push(`- ${pad(section.id, width)}${formatNumber(section.injectedUnits).padStart(6)} units ${formatNumber(section.injectedChars).padStart(7)} chars ${flags.join(", ")}`);
73
+ }
74
+ const soulLine = renderWorkspaceResourceLine("SOUL.md", input.soul);
75
+ const agentsLine = renderWorkspaceResourceLine("AGENTS.md", input.agents);
76
+ if (soulLine || agentsLine) {
77
+ lines.push("");
78
+ lines.push("Workspace resources (independent budgets, not competing with the runtime):");
79
+ if (soulLine)
80
+ lines.push(soulLine);
81
+ if (agentsLine)
82
+ lines.push(agentsLine);
46
83
  }
47
84
  lines.push("");
48
85
  lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemaChars)} chars (billed on top of the system prompt)`);
49
- lines.push(`Skills: ${input.skills.length} visible, ≈${formatNumber(estimateSkillsPromptChars(input.skills))} chars (rendered by pi after the sections above, outside the section budgets)`);
86
+ lines.push(`Skills: ${input.skills.length} visible, ≈${formatNumber(estimateSkillsPromptChars(input.skills))} chars (rendered and managed by pi, not budgeted by Pipiclaw)`);
50
87
  if (input.lastTurn) {
51
88
  const turn = input.lastTurn;
89
+ const automaticUnits = turn.channelCapsuleUnits + turn.recalledMemoryUnits + turn.taskDigestUnits + turn.durableMemoryUnits;
52
90
  lines.push("");
53
- lines.push("Last turn context (per-turn, not cached):");
54
- lines.push(`- durable memory bootstrap: ${formatNumber(turn.durableMemoryChars)} chars`);
55
- lines.push(`- recalled memory: ${formatNumber(turn.recalledMemoryChars)} chars`);
56
- lines.push(`- task digest: ${formatNumber(turn.taskDigestChars)} chars`);
57
- lines.push(`- user message: ${formatNumber(turn.userMessageChars)} chars`);
91
+ lines.push(`Last automatic turn context: ${formatNumber(automaticUnits)} / ${formatNumber(AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS)} units (per-turn, not cached):`);
92
+ lines.push(`- channel capsule: ${formatNumber(turn.channelCapsuleUnits)} units`);
93
+ lines.push(`- recalled memory: ${formatNumber(turn.recalledMemoryUnits)} units / ${formatNumber(turn.recalledMemoryChars)} chars`);
94
+ lines.push(`- task agenda: ${formatNumber(turn.taskDigestUnits)} units / ${formatNumber(turn.taskDigestChars)} chars`);
95
+ lines.push(`- durable bootstrap: ${formatNumber(turn.durableMemoryUnits)} units / ${formatNumber(turn.durableMemoryChars)} chars`);
96
+ lines.push(`- user message: ${formatNumber(turn.userMessageChars)} chars (not automatic; not capped here)`);
58
97
  }
59
98
  if (build.diagnostics.length > 0) {
60
99
  lines.push("");
@@ -5,10 +5,19 @@
5
5
  * so that their order, budget and framing are ours. Budgets are applied to the
6
6
  * file body here — not to the rendered section — so a truncated file can never
7
7
  * cut its own closing tag.
8
+ *
9
+ * SOUL and AGENTS are high-value user instructions (spec 026 §2.2, §8). Each has
10
+ * its own generous unit + character budget and never competes with the other, with
11
+ * the runtime catalog, or with skills for space; only a genuinely oversized file is
12
+ * head/tail clipped.
8
13
  */
9
14
  import type { LoadedPromptResource, PromptDiagnostic } from "./types.js";
10
- export declare const SOUL_BUDGET_CHARS = 5000;
11
- export declare const AGENTS_BUDGET_CHARS = 8000;
15
+ /** SOUL.md is identity and voice: normally short, so a tight independent budget (spec 026 §5.2). */
16
+ export declare const SOUL_BUDGET_UNITS = 3000;
17
+ export declare const SOUL_BUDGET_CHARS = 24000;
18
+ /** AGENTS.md carries team procedure and is allowed to be larger (spec 026 §5.2). */
19
+ export declare const AGENTS_BUDGET_UNITS = 6000;
20
+ export declare const AGENTS_BUDGET_CHARS = 48000;
12
21
  export interface WorkspacePromptResources {
13
22
  soul?: LoadedPromptResource;
14
23
  agents?: LoadedPromptResource;
@@ -5,14 +5,23 @@
5
5
  * so that their order, budget and framing are ours. Budgets are applied to the
6
6
  * file body here — not to the rendered section — so a truncated file can never
7
7
  * cut its own closing tag.
8
+ *
9
+ * SOUL and AGENTS are high-value user instructions (spec 026 §2.2, §8). Each has
10
+ * its own generous unit + character budget and never competes with the other, with
11
+ * the runtime catalog, or with skills for space; only a genuinely oversized file is
12
+ * head/tail clipped.
8
13
  */
9
14
  import { existsSync, readFileSync } from "node:fs";
10
15
  import { join } from "node:path";
11
16
  import * as log from "../../log.js";
12
17
  import { DEFAULT_AGENTS, DEFAULT_SOUL, isDefaultWorkspaceTemplate } from "../../runtime/workspace-templates.js";
13
- import { clipText } from "../../shared/text-utils.js";
14
- export const SOUL_BUDGET_CHARS = 5_000;
15
- export const AGENTS_BUDGET_CHARS = 8_000;
18
+ import { clipTextByPromptUnits, countPromptUnits } from "../../shared/prompt-units.js";
19
+ /** SOUL.md is identity and voice: normally short, so a tight independent budget (spec 026 §5.2). */
20
+ export const SOUL_BUDGET_UNITS = 3_000;
21
+ export const SOUL_BUDGET_CHARS = 24_000;
22
+ /** AGENTS.md carries team procedure and is allowed to be larger (spec 026 §5.2). */
23
+ export const AGENTS_BUDGET_UNITS = 6_000;
24
+ export const AGENTS_BUDGET_CHARS = 48_000;
16
25
  function readWorkspaceFile(path) {
17
26
  if (!existsSync(path)) {
18
27
  return "";
@@ -30,32 +39,62 @@ function loadResource(path, template, budget, sectionId, overflowAdvice, diagnos
30
39
  if (!content) {
31
40
  return undefined;
32
41
  }
42
+ const rawUnits = countPromptUnits(content);
33
43
  if (isDefaultWorkspaceTemplate(content, template)) {
34
44
  diagnostics.push({
35
45
  level: "info",
36
46
  sectionId,
37
47
  message: `${path} still holds the bootstrap template; not injected.`,
38
48
  });
39
- return { path, content, isDefaultTemplate: true };
49
+ return {
50
+ path,
51
+ content,
52
+ isDefaultTemplate: true,
53
+ rawUnits,
54
+ injectedUnits: rawUnits,
55
+ budgetUnits: budget.units,
56
+ truncated: false,
57
+ };
40
58
  }
41
- if (content.length <= budget) {
42
- return { path, content, isDefaultTemplate: false };
59
+ if (rawUnits <= budget.units && content.length <= budget.chars) {
60
+ return {
61
+ path,
62
+ content,
63
+ isDefaultTemplate: false,
64
+ rawUnits,
65
+ injectedUnits: rawUnits,
66
+ budgetUnits: budget.units,
67
+ truncated: false,
68
+ };
43
69
  }
70
+ // Diagnose in units (the stable budget) but note whichever limit was hit.
71
+ const limit = rawUnits > budget.units
72
+ ? `${rawUnits} prompt units; injected ${budget.units}`
73
+ : `${content.length} chars; injected ${budget.chars}`;
44
74
  diagnostics.push({
45
75
  level: "warning",
46
76
  sectionId,
47
- message: `${path} is ${content.length} chars; injected ${budget}. ${overflowAdvice}`,
77
+ message: `${path} is unusually large: ${limit}. ${overflowAdvice}`,
48
78
  });
49
- const clipped = clipText(content, budget, {
79
+ const clipped = clipTextByPromptUnits(content, budget.units, {
50
80
  headRatio: 0.6,
51
- omitHint: `\n\n[... truncated: injected ${budget} of ${content.length} characters. ${overflowAdvice} ...]\n\n`,
81
+ maxChars: budget.chars,
82
+ marker: `\n\n[... truncated: kept ${budget.units} of ${rawUnits} prompt units. ${overflowAdvice} ...]\n\n`,
52
83
  });
53
- return { path, content: clipped, isDefaultTemplate: false };
84
+ return {
85
+ path,
86
+ content: clipped.text,
87
+ isDefaultTemplate: false,
88
+ rawUnits,
89
+ injectedUnits: clipped.injectedUnits,
90
+ budgetUnits: budget.units,
91
+ truncated: clipped.truncated,
92
+ };
54
93
  }
55
94
  /** Read SOUL.md and AGENTS.md from the workspace root, budgeted and template-aware. */
56
95
  export function loadWorkspacePromptResources(workspaceDir) {
57
96
  const diagnostics = [];
58
- const soul = loadResource(join(workspaceDir, "SOUL.md"), DEFAULT_SOUL, SOUL_BUDGET_CHARS, "workspace.soul", "Run /context detail, and keep SOUL.md to identity and voice.", diagnostics);
59
- const agents = loadResource(join(workspaceDir, "AGENTS.md"), DEFAULT_AGENTS, AGENTS_BUDGET_CHARS, "workspace.agents", "Run /context detail, and move task-specific procedures into workspace skills so they load on demand.", diagnostics);
97
+ const soul = loadResource(join(workspaceDir, "SOUL.md"), DEFAULT_SOUL, { units: SOUL_BUDGET_UNITS, chars: SOUL_BUDGET_CHARS }, "workspace.soul", "Run /context detail, and keep SOUL.md to identity and voice.", diagnostics);
98
+ const agents = loadResource(join(workspaceDir, "AGENTS.md"), DEFAULT_AGENTS, { units: AGENTS_BUDGET_UNITS, chars: AGENTS_BUDGET_CHARS }, "workspace.agents", "Run /context detail. Keep global rules in AGENTS.md and move conditional procedures into workspace skills; pi will keep managing all skills.", diagnostics);
60
99
  return { soul, agents, diagnostics };
61
100
  }