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

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 (45) hide show
  1. package/dist/agent/channel-runner.d.ts +5 -2
  2. package/dist/agent/channel-runner.js +80 -55
  3. package/dist/agent/job-manager.js +5 -1
  4. package/dist/agent/maintenance-context.js +7 -4
  5. package/dist/agent/prompt/builder.d.ts +11 -20
  6. package/dist/agent/prompt/builder.js +40 -87
  7. package/dist/agent/prompt/manifest.d.ts +28 -2
  8. package/dist/agent/prompt/manifest.js +50 -11
  9. package/dist/agent/prompt/resources.d.ts +11 -2
  10. package/dist/agent/prompt/resources.js +51 -12
  11. package/dist/agent/prompt/sections.d.ts +9 -10
  12. package/dist/agent/prompt/sections.js +46 -99
  13. package/dist/agent/prompt/types.d.ts +14 -0
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/memory/bootstrap.d.ts +6 -0
  17. package/dist/memory/bootstrap.js +53 -21
  18. package/dist/memory/recall.d.ts +8 -0
  19. package/dist/memory/recall.js +23 -15
  20. package/dist/memory/task-digest.d.ts +4 -0
  21. package/dist/memory/task-digest.js +9 -3
  22. package/dist/models/utils.d.ts +16 -3
  23. package/dist/models/utils.js +19 -8
  24. package/dist/playbooks/catalog.d.ts +7 -2
  25. package/dist/playbooks/catalog.js +10 -6
  26. package/dist/playbooks/event-scheduling.md +1 -1
  27. package/dist/playbooks/memory-and-learning.md +1 -1
  28. package/dist/playbooks/runtime-orientation.md +1 -1
  29. package/dist/playbooks/task-closeout.md +1 -1
  30. package/dist/playbooks/task-delegation.md +1 -1
  31. package/dist/playbooks/task-driving.md +1 -1
  32. package/dist/playbooks/task-planning.md +1 -1
  33. package/dist/playbooks/task-recurring.md +1 -1
  34. package/dist/playbooks/task-repair.md +1 -1
  35. package/dist/runtime/dingtalk.d.ts +0 -9
  36. package/dist/runtime/dingtalk.js +0 -17
  37. package/dist/runtime/durable-dispatch.js +1 -3
  38. package/dist/runtime/events.js +6 -1
  39. package/dist/security/config.js +16 -1
  40. package/dist/shared/prompt-units.d.ts +46 -0
  41. package/dist/shared/prompt-units.js +153 -0
  42. package/dist/tools/memory-manage.js +5 -1
  43. package/dist/tools/task-manage.js +1 -1
  44. package/dist/web/client.js +44 -9
  45. package/package.json +5 -5
@@ -17,19 +17,22 @@ export declare class ChannelRunner implements AgentRunner {
17
17
  private agent;
18
18
  private sessionManager;
19
19
  private readonly settingsManager;
20
- private readonly modelRegistry;
20
+ private modelRuntime;
21
+ private modelRegistry;
21
22
  private readonly memoryLifecycle;
22
23
  private readonly ledger;
23
24
  private readonly memoryCandidateStore;
24
25
  private readonly sessionResourceGate;
25
26
  private readonly sessionReady;
26
- private readonly sessionRuntime;
27
+ private sessionRuntime;
27
28
  private sessionUnsubscribe?;
28
29
  private subAgentDiscovery;
29
30
  private activeModel;
30
31
  private currentSkills;
31
32
  /** Last built system prompt (spec 025): feeds the boundary footer, /context and the debug manifest. */
32
33
  private lastPromptBuild?;
34
+ /** SOUL/AGENTS as resolved for the last build, for the `/context` independent-budget lines. */
35
+ private lastWorkspaceResources?;
33
36
  /** The exact system prompt the provider last received (our prompt + pi's tail + footer). */
34
37
  private lastFinalPrompt?;
35
38
  private lastTurnContextStats?;
@@ -1,23 +1,24 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
- import { AgentSession, AgentSessionRuntime, AuthStorage, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
2
+ import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
3
3
  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
- import { createModelRegistry, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, } from "../models/utils.js";
16
+ import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, wrapModelRegistry, } 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";
@@ -85,14 +86,10 @@ export class ChannelRunner {
85
86
  this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
86
87
  this.reportSettingsDiagnostics();
87
88
  this.memoryCandidateStore = createMemoryCandidateStore();
88
- // Create AuthStorage and ModelRegistry
89
- const authStorage = AuthStorage.create(this.authConfigPath);
90
- this.modelRegistry = createModelRegistry(authStorage, this.modelsConfigPath);
91
- // Resolve model: prefer saved global default, fall back to first available model
92
- this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
93
- log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
94
- this.subAgentDiscovery = this.refreshSubAgentDiscovery();
95
- const initialSessionManager = this.sessionManager;
89
+ // The real model/auth runtime is built asynchronously in initializeSession
90
+ // (ModelRuntime.create is async). Until then the agent runs on a placeholder
91
+ // model; initializeSession corrects it before any turn (via sessionReady).
92
+ this.activeModel = defaultModel;
96
93
  const initialTools = this.buildRuntimeTools();
97
94
  this.agent = new Agent({
98
95
  initialState: {
@@ -117,38 +114,9 @@ export class ChannelRunner {
117
114
  void this.recordMemoryActivity(event);
118
115
  },
119
116
  });
120
- const initialResourceLoader = this.createResourceLoader();
121
- const baseToolsOverride = Object.fromEntries(initialTools.map((tool) => [tool.name, tool]));
122
- this.session = new AgentSession({
123
- agent: this.agent,
124
- sessionManager: initialSessionManager,
125
- settingsManager: asSdkSettingsManager(this.settingsManager),
126
- cwd: process.cwd(),
127
- modelRegistry: this.modelRegistry,
128
- resourceLoader: initialResourceLoader,
129
- baseToolsOverride,
130
- });
131
- this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initialResourceLoader), async ({ sessionManager, sessionStartEvent }) => {
132
- const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
133
- return {
134
- session: next.session,
135
- extensionsResult: this.createEmptyExtensionsResult(),
136
- services: this.createAgentSessionServices(next.resourceLoader),
137
- diagnostics: [],
138
- };
139
- });
140
- this.sessionRuntime.setRebindSession(async (session) => {
141
- this.session = session;
142
- this.agent = session.agent;
143
- this.sessionManager = session.sessionManager;
144
- await this.bindSessionExtensions();
145
- this.subscribeToSessionEvents();
146
- });
147
117
  this.sessionResourceGate = new SessionResourceGate(async () => {
148
118
  await this.reloadSessionResources();
149
119
  });
150
- // Subscribe to session events
151
- this.subscribeToSessionEvents();
152
120
  this.sessionReady = this.initializeSession();
153
121
  }
154
122
  // === Public API ===
@@ -192,6 +160,7 @@ export class ChannelRunner {
192
160
  let recalledContextText = "";
193
161
  let taskDigestText = "";
194
162
  let durableMemoryBootstrapText = "";
163
+ let channelCapsuleText = "";
195
164
  let bootstrapCandidateIds = [];
196
165
  let bootstrapPrepared = false;
197
166
  try {
@@ -211,7 +180,8 @@ export class ChannelRunner {
211
180
  if (!preserveRawInput) {
212
181
  // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
213
182
  // 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>`;
183
+ channelCapsuleText = this.renderChannelTurnContext();
184
+ promptText = `${channelCapsuleText}\n\n<user_message>\n${promptText}\n</user_message>`;
215
185
  if (this.firstTurnMemoryBootstrapPending) {
216
186
  const bootstrap = await this.buildFirstTurnMemoryBootstrap();
217
187
  durableMemoryBootstrapText = bootstrap.renderedText;
@@ -228,6 +198,8 @@ export class ChannelRunner {
228
198
  maxCandidates: recallSettings.maxCandidates,
229
199
  maxInjected: recallSettings.maxInjected,
230
200
  maxChars: recallSettings.maxChars,
201
+ // The configured char cap and the runtime unit cap both apply; first to bind clips.
202
+ maxUnits: MEMORY_RECALL_MAX_UNITS,
231
203
  rerankWithModel: recallSettings.rerankWithModel,
232
204
  excludedCandidateIds: bootstrapCandidateIds,
233
205
  // Let shouldUseModelRerank's own memory-intent gate decide (it already handles
@@ -249,6 +221,7 @@ export class ChannelRunner {
249
221
  channelDir: this.channelDir,
250
222
  maxTasks: taskDigestSettings.maxTasks,
251
223
  maxChars: taskDigestSettings.maxChars,
224
+ maxUnits: TASK_AGENDA_MAX_UNITS,
252
225
  });
253
226
  if (taskDigestText) {
254
227
  promptText = `${taskDigestText}\n\n${promptText}`;
@@ -264,8 +237,12 @@ export class ChannelRunner {
264
237
  await this.maybeRunPreventiveCompactionForIncomingText(promptText);
265
238
  this.lastTurnContextStats = {
266
239
  durableMemoryChars: durableMemoryBootstrapText.length,
240
+ durableMemoryUnits: countPromptUnits(durableMemoryBootstrapText),
267
241
  taskDigestChars: taskDigestText.length,
242
+ taskDigestUnits: countPromptUnits(taskDigestText),
268
243
  recalledMemoryChars: recalledContextText.length,
244
+ recalledMemoryUnits: countPromptUnits(recalledContextText),
245
+ channelCapsuleUnits: countPromptUnits(channelCapsuleText),
269
246
  userMessageChars: clippedInput.length,
270
247
  };
271
248
  const fallbackDeps = {
@@ -591,6 +568,8 @@ export class ChannelRunner {
591
568
  skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
592
569
  toolNames: this.currentTools.map((tool) => tool.name),
593
570
  toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
571
+ soul: this.lastWorkspaceResources?.soul,
572
+ agents: this.lastWorkspaceResources?.agents,
594
573
  lastTurn: this.lastTurnContextStats,
595
574
  detail: args.trim().toLowerCase() === "detail",
596
575
  });
@@ -729,8 +708,8 @@ export class ChannelRunner {
729
708
  if (!reference) {
730
709
  return null;
731
710
  }
732
- this.modelRegistry.refresh();
733
- const available = await this.modelRegistry.getAvailable();
711
+ await this.modelRegistry.refresh();
712
+ const available = this.modelRegistry.getAvailable();
734
713
  const { match, ambiguous } = findExactModelReferenceMatch(reference, available);
735
714
  if (!match) {
736
715
  log.logWarning(`[${this.channelId}] fallbackModel "${reference}" ${ambiguous ? "is ambiguous" : "not found"}; skipping fallback`);
@@ -746,6 +725,46 @@ export class ChannelRunner {
746
725
  return match;
747
726
  }
748
727
  async initializeSession() {
728
+ // Build the canonical async model/auth runtime and its synchronous read shell.
729
+ this.modelRuntime = await createModelRuntime({
730
+ authConfigPath: this.authConfigPath,
731
+ modelsConfigPath: this.modelsConfigPath,
732
+ });
733
+ this.modelRegistry = wrapModelRegistry(this.modelRuntime);
734
+ // Resolve model: prefer saved global default, fall back to first available model.
735
+ this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
736
+ this.agent.state.model = this.activeModel; // correct the placeholder default
737
+ log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
738
+ this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
739
+ const initialResourceLoader = this.createResourceLoader();
740
+ const baseToolsOverride = Object.fromEntries(this.currentTools.map((tool) => [tool.name, tool]));
741
+ this.session = new AgentSession({
742
+ agent: this.agent,
743
+ sessionManager: this.sessionManager,
744
+ settingsManager: asSdkSettingsManager(this.settingsManager),
745
+ cwd: process.cwd(),
746
+ modelRuntime: this.modelRuntime,
747
+ resourceLoader: initialResourceLoader,
748
+ baseToolsOverride,
749
+ });
750
+ this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initialResourceLoader), async ({ sessionManager, sessionStartEvent }) => {
751
+ const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
752
+ return {
753
+ session: next.session,
754
+ extensionsResult: this.createEmptyExtensionsResult(),
755
+ services: this.createAgentSessionServices(next.resourceLoader),
756
+ diagnostics: [],
757
+ };
758
+ });
759
+ this.sessionRuntime.setRebindSession(async (session) => {
760
+ this.session = session;
761
+ this.agent = session.agent;
762
+ this.sessionManager = session.sessionManager;
763
+ await this.bindSessionExtensions();
764
+ this.subscribeToSessionEvents();
765
+ });
766
+ // Subscribe to session events
767
+ this.subscribeToSessionEvents();
749
768
  await this.reloadSessionResources();
750
769
  await this.bindSessionExtensions();
751
770
  }
@@ -754,7 +773,7 @@ export class ChannelRunner {
754
773
  this.reportSettingsDiagnostics();
755
774
  const skills = loadPipiclawSkills(this.channelDir);
756
775
  this.currentSkills = skills;
757
- this.subAgentDiscovery = this.refreshSubAgentDiscovery();
776
+ this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
758
777
  this.rebuildSessionTools();
759
778
  await this.session.reload();
760
779
  }
@@ -806,8 +825,8 @@ export class ChannelRunner {
806
825
  log.logWarning(`[${this.channelId}] Preventive compaction failed`, message);
807
826
  }
808
827
  }
809
- refreshSubAgentDiscovery() {
810
- this.modelRegistry.refresh();
828
+ async refreshSubAgentDiscovery() {
829
+ await this.modelRegistry.refresh();
811
830
  const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
812
831
  for (const warning of discovery.warnings) {
813
832
  log.logWarning(`Sub-agent config warning (${this.channelId})`, warning);
@@ -837,6 +856,7 @@ export class ChannelRunner {
837
856
  buildSystemPrompt() {
838
857
  const toolNames = this.currentTools.map((tool) => tool.name);
839
858
  const resources = loadWorkspacePromptResources(this.workspaceDir);
859
+ this.lastWorkspaceResources = resources;
840
860
  const build = buildPipiclawSystemPrompt({
841
861
  mode: "normal",
842
862
  cwd: process.cwd(),
@@ -883,8 +903,8 @@ export class ChannelRunner {
883
903
  createCommandExtension({
884
904
  getCurrentModel: () => this.session.model ?? this.activeModel,
885
905
  getAvailableModels: async () => {
886
- this.modelRegistry.refresh();
887
- return await this.modelRegistry.getAvailable();
906
+ await this.modelRegistry.refresh();
907
+ return this.modelRegistry.getAvailable();
888
908
  },
889
909
  getSessionStats: () => this.session.getSessionStats(),
890
910
  getThinkingLevel: () => this.session.thinkingLevel,
@@ -923,9 +943,8 @@ export class ChannelRunner {
923
943
  return {
924
944
  cwd: process.cwd(),
925
945
  agentDir: this.appHomeDir,
926
- authStorage: AuthStorage.create(this.authConfigPath),
927
946
  settingsManager: asSdkSettingsManager(this.settingsManager),
928
- modelRegistry: this.modelRegistry,
947
+ modelRuntime: this.modelRuntime,
929
948
  resourceLoader,
930
949
  diagnostics: [],
931
950
  };
@@ -955,7 +974,7 @@ export class ChannelRunner {
955
974
  sessionManager,
956
975
  settingsManager: asSdkSettingsManager(this.settingsManager),
957
976
  cwd: process.cwd(),
958
- modelRegistry: this.modelRegistry,
977
+ modelRuntime: this.modelRuntime,
959
978
  resourceLoader,
960
979
  baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
961
980
  sessionStartEvent,
@@ -1008,7 +1027,7 @@ export class ChannelRunner {
1008
1027
  // === Session event subscription ===
1009
1028
  subscribeToSessionEvents() {
1010
1029
  this.sessionUnsubscribe?.();
1011
- this.sessionUnsubscribe = this.session.subscribe(async (event) => {
1030
+ this.sessionUnsubscribe = this.session.subscribe((event) => {
1012
1031
  if (isRecord(event) && event.type === "message_start" && this.turn.phase === "preparing") {
1013
1032
  this.turn.phase = "streaming";
1014
1033
  }
@@ -1017,7 +1036,10 @@ export class ChannelRunner {
1017
1036
  }
1018
1037
  if (!this.runState.ctx || !this.runState.logCtx || !this.runState.queue)
1019
1038
  return;
1020
- await handleSessionEvent(event, {
1039
+ // The SDK listener signature is `(event) => void`, so the promise below is fire-and-forget.
1040
+ // Without this catch, a rejection inside handleSessionEvent becomes an unhandled rejection
1041
+ // that terminates the daemon under Node's default policy.
1042
+ handleSessionEvent(event, {
1021
1043
  ctx: this.runState.ctx,
1022
1044
  logCtx: this.runState.logCtx,
1023
1045
  queue: this.runState.queue,
@@ -1029,6 +1051,8 @@ export class ChannelRunner {
1029
1051
  refreshSessionResources: async () => {
1030
1052
  await this.refreshSessionResources();
1031
1053
  },
1054
+ }).catch((err) => {
1055
+ log.logWarning(`[${this.channelId}] session event handler failed`, errorMessage(err));
1032
1056
  });
1033
1057
  });
1034
1058
  }
@@ -1048,6 +1072,7 @@ export class ChannelRunner {
1048
1072
  return buildFirstTurnMemoryBootstrapResult({
1049
1073
  channelMemory,
1050
1074
  workspaceMemory,
1075
+ maxUnits: FIRST_TURN_BOOTSTRAP_MAX_UNITS,
1051
1076
  });
1052
1077
  }
1053
1078
  }
@@ -1,5 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import * as log from "../log.js";
2
3
  import { shellEscape } from "../shared/shell-escape.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
3
5
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
4
6
  export const MAX_RUNNING_JOBS = 5;
5
7
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -117,7 +119,9 @@ export class ChannelJobManager {
117
119
  try {
118
120
  for (const record of this.jobs.values()) {
119
121
  if (record.status === "running") {
120
- await this.refresh(record).catch(() => { });
122
+ await this.refresh(record).catch((error) => {
123
+ log.logWarning(`Background job sweep failed to refresh job ${record.id}`, errorMessage(error));
124
+ });
121
125
  }
122
126
  }
123
127
  }
@@ -1,8 +1,8 @@
1
1
  import { statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { AuthStorage, SessionManager } from "@earendil-works/pi-coding-agent";
3
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
4
4
  import { getApiKeyForModel } from "../models/api-keys.js";
5
- import { createModelRegistry, resolveInitialModel } from "../models/utils.js";
5
+ import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../models/utils.js";
6
6
  import { loadPipiclawSkills } from "./workspace-resources.js";
7
7
  // The maintenance scheduler visits idle channels every tick; re-parsing an
8
8
  // unchanged context.jsonl each time would be pure I/O waste for long-dead
@@ -47,8 +47,11 @@ export async function loadDetachedMaintenanceContext(options) {
47
47
  }
48
48
  transcriptCache.set(options.channelDir, cached);
49
49
  }
50
- const authStorage = AuthStorage.create(options.authConfigPath);
51
- const modelRegistry = createModelRegistry(authStorage, options.modelsConfigPath);
50
+ const modelRuntime = await createModelRuntime({
51
+ authConfigPath: options.authConfigPath,
52
+ modelsConfigPath: options.modelsConfigPath,
53
+ });
54
+ const modelRegistry = wrapModelRegistry(modelRuntime);
52
55
  const model = resolveInitialModel(modelRegistry, options.settingsManager);
53
56
  options.settingsManager.reload();
54
57
  return {
@@ -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;