@oyasmi/pipiclaw 0.8.10-beta.3 → 0.8.10-beta.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 (84) hide show
  1. package/dist/agent/channel-runner.js +24 -13
  2. package/dist/agent/effect-ledger.d.ts +12 -0
  3. package/dist/agent/effect-ledger.js +27 -0
  4. package/dist/agent/job-manager.d.ts +18 -0
  5. package/dist/agent/job-manager.js +49 -1
  6. package/dist/agent/prompt/manifest.d.ts +32 -1
  7. package/dist/agent/prompt/manifest.js +41 -2
  8. package/dist/agent/session-events.js +2 -1
  9. package/dist/log.js +3 -16
  10. package/dist/memory/commands.js +3 -2
  11. package/dist/memory/consolidation.js +7 -3
  12. package/dist/memory/extraction.js +2 -0
  13. package/dist/memory/files.d.ts +1 -5
  14. package/dist/memory/files.js +30 -21
  15. package/dist/memory/lifecycle.js +4 -3
  16. package/dist/memory/maintenance-gates.js +3 -2
  17. package/dist/memory/maintenance-jobs.js +8 -7
  18. package/dist/memory/metadata.js +9 -7
  19. package/dist/memory/prompt-safety.d.ts +6 -0
  20. package/dist/memory/prompt-safety.js +7 -0
  21. package/dist/memory/review-log.js +7 -0
  22. package/dist/memory/session-search.js +18 -8
  23. package/dist/memory/session.js +4 -7
  24. package/dist/memory/task-digest.js +1 -1
  25. package/dist/memory/transcript.js +1 -1
  26. package/dist/playbooks/event-scheduling.md +1 -1
  27. package/dist/playbooks/task-delegation.md +2 -0
  28. package/dist/playbooks/task-driving.md +6 -3
  29. package/dist/playbooks/task-planning.md +3 -3
  30. package/dist/runtime/bootstrap.js +35 -13
  31. package/dist/runtime/channel-queue.d.ts +2 -0
  32. package/dist/runtime/channel-queue.js +4 -0
  33. package/dist/runtime/delivery.d.ts +12 -2
  34. package/dist/runtime/delivery.js +26 -9
  35. package/dist/runtime/dingtalk.d.ts +9 -0
  36. package/dist/runtime/dingtalk.js +40 -1
  37. package/dist/runtime/event-validation.d.ts +2 -0
  38. package/dist/runtime/event-validation.js +20 -5
  39. package/dist/runtime/events.d.ts +1 -1
  40. package/dist/runtime/events.js +32 -32
  41. package/dist/runtime/store.js +3 -2
  42. package/dist/runtime/task-commands.js +129 -46
  43. package/dist/runtime/task-driver.d.ts +4 -4
  44. package/dist/runtime/task-driver.js +9 -7
  45. package/dist/security/config.d.ts +1 -1
  46. package/dist/security/logger.js +2 -1
  47. package/dist/settings.d.ts +11 -1
  48. package/dist/settings.js +14 -0
  49. package/dist/shared/{config-diagnostics.d.ts → config-diagnostic.d.ts} +1 -0
  50. package/dist/shared/file-stamp.d.ts +10 -0
  51. package/dist/shared/file-stamp.js +19 -0
  52. package/dist/shared/local-time.d.ts +35 -0
  53. package/dist/shared/local-time.js +104 -0
  54. package/dist/subagents/tool.js +2 -1
  55. package/dist/tasks/control.d.ts +2 -0
  56. package/dist/tasks/control.js +52 -12
  57. package/dist/{shared/task-ledger.d.ts → tasks/ledger.d.ts} +13 -2
  58. package/dist/{shared/task-ledger.js → tasks/ledger.js} +23 -8
  59. package/dist/tasks/mutation-lock.d.ts +8 -0
  60. package/dist/tasks/mutation-lock.js +23 -0
  61. package/dist/tasks/store.d.ts +3 -2
  62. package/dist/tasks/store.js +20 -13
  63. package/dist/tasks/transitions.d.ts +3 -2
  64. package/dist/tasks/transitions.js +13 -4
  65. package/dist/tasks/verification.js +2 -1
  66. package/dist/tools/config.d.ts +1 -1
  67. package/dist/tools/event-manage.js +1 -1
  68. package/dist/tools/memory-manage.js +7 -4
  69. package/dist/tools/task-manage/create.js +1 -1
  70. package/dist/tools/task-manage/lifecycle.js +4 -4
  71. package/dist/tools/task-manage/schema.d.ts +1 -3
  72. package/dist/tools/task-manage/schema.js +16 -8
  73. package/dist/tools/task-manage/shared.d.ts +8 -0
  74. package/dist/tools/task-manage/shared.js +48 -8
  75. package/dist/tools/task-manage/types.d.ts +20 -21
  76. package/dist/tools/task-manage/verification.js +1 -1
  77. package/dist/tools/task-manage.js +15 -18
  78. package/dist/tui/turn-controller.js +2 -1
  79. package/dist/usage/ledger.js +4 -3
  80. package/dist/usage/render.js +8 -8
  81. package/package.json +1 -1
  82. /package/dist/memory/{policy.d.ts → secret-redaction.d.ts} +0 -0
  83. /package/dist/memory/{policy.js → secret-redaction.js} +0 -0
  84. /package/dist/shared/{config-diagnostics.js → config-diagnostic.js} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
2
  import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
3
- import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
3
+ import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SettingsManager as SDKSettingsManager, SessionManager, } from "@earendil-works/pi-coding-agent";
4
4
  import { mkdir, readFile, writeFile } from "fs/promises";
5
5
  import { dirname, join, resolve } from "path";
6
6
  import { createExecutor } from "../executor.js";
@@ -18,7 +18,8 @@ import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatM
18
18
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
19
19
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
20
20
  import { PipiclawSettingsManager } from "../settings.js";
21
- import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
21
+ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
22
+ import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
22
23
  import { countPromptUnits } from "../shared/prompt-units.js";
23
24
  import { errorMessage } from "../shared/text-utils.js";
24
25
  import { isRecord } from "../shared/type-guards.js";
@@ -33,7 +34,7 @@ import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } fro
33
34
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
34
35
  import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
35
36
  import { createPromptBoundaryExtension } from "./prompt/extension.js";
36
- import { buildPromptManifest, renderContextReport } from "./prompt/manifest.js";
37
+ import { buildPromptManifest, measureToolSchemas, renderContextReport, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning, } from "./prompt/manifest.js";
37
38
  import { loadWorkspacePromptResources } from "./prompt/resources.js";
38
39
  import { createRunQueue } from "./run-queue.js";
39
40
  import { handleSessionEvent } from "./session-events.js";
@@ -51,7 +52,17 @@ function getFinalOutcomeText(outcome) {
51
52
  return isFinalOutcome(outcome) ? outcome.text : null;
52
53
  }
53
54
  function asSdkSettingsManager(manager) {
54
- return manager;
55
+ // The upstream session needs its broad interactive SettingsManager surface, while
56
+ // Pipiclaw deliberately owns a small runtime-specific settings contract. Build a
57
+ // real upstream manager from that contract instead of making PipiclawSettingsManager
58
+ // pretend to implement dozens of unrelated no-op UI preferences.
59
+ return SDKSettingsManager.inMemory({
60
+ defaultProvider: manager.getDefaultProvider(),
61
+ defaultModel: manager.getDefaultModel(),
62
+ defaultThinkingLevel: manager.getDefaultThinkingLevel(),
63
+ compaction: manager.getCompactionSettings(),
64
+ retry: manager.getRetrySettings(),
65
+ });
55
66
  }
56
67
  const DEFAULT_MAIN_THINKING_LEVEL = "medium";
57
68
  export class ChannelRunner {
@@ -569,7 +580,7 @@ export class ChannelRunner {
569
580
  finalPrompt: this.lastFinalPrompt,
570
581
  skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
571
582
  toolNames: this.currentTools.map((tool) => tool.name),
572
- toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
583
+ toolSchemas: measureToolSchemas(this.currentTools),
573
584
  soul: this.lastWorkspaceResources?.soul,
574
585
  agents: this.lastWorkspaceResources?.agents,
575
586
  lastTurn: this.lastTurnContextStats,
@@ -639,7 +650,7 @@ export class ChannelRunner {
639
650
  try {
640
651
  const dir = join(this.channelDir, "inbox");
641
652
  await mkdir(dir, { recursive: true });
642
- const path = join(dir, `message-${new Date().toISOString().replace(/[:.]/g, "-")}.txt`);
653
+ const path = join(dir, `message-${localStampForFilename()}.txt`);
643
654
  await writeFile(path, text.replace(/\r/g, ""), { mode: 0o600 });
644
655
  return path;
645
656
  }
@@ -649,13 +660,7 @@ export class ChannelRunner {
649
660
  }
650
661
  }
651
662
  formatUserMessage(text, userName, now = new Date()) {
652
- const pad = (n) => n.toString().padStart(2, "0");
653
- const offset = -now.getTimezoneOffset();
654
- const offsetSign = offset >= 0 ? "+" : "-";
655
- const offsetHours = pad(Math.floor(Math.abs(offset) / 60));
656
- const offsetMins = pad(Math.abs(offset) % 60);
657
- const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;
658
- return `[${timestamp}] [${userName || "unknown"}]: ${text}`;
663
+ return `[${formatLocalTime(now)}] [${userName || "unknown"}]: ${text}`;
659
664
  }
660
665
  /**
661
666
  * Single source of truth for the busy-message window: steer is accepted while
@@ -1054,6 +1059,12 @@ export class ChannelRunner {
1054
1059
  mediaSender: this.mediaSender,
1055
1060
  });
1056
1061
  this.currentTools = tools;
1062
+ // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
1063
+ // Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
1064
+ const schemas = measureToolSchemas(tools);
1065
+ if (schemas.units > TOOL_SCHEMA_TARGET_UNITS) {
1066
+ log.logWarning(`[${this.channelId}] Tool schema budget`, toolSchemaBudgetWarning(schemas));
1067
+ }
1057
1068
  return tools;
1058
1069
  }
1059
1070
  rebuildSessionTools() {
@@ -1,5 +1,17 @@
1
1
  export declare function noteChannelEffect(channelId: string): void;
2
2
  export declare function channelEffectCount(channelId: string): number;
3
+ /**
4
+ * Credit one task-driver turn's effects to that task.
5
+ *
6
+ * The channel tally above answers "how much has happened here", which is the wrong question for
7
+ * the governor: it also counts the user's small talk, so every task in a busy channel looked like
8
+ * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
9
+ * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
10
+ * turns are serialized per channel — and credits it to the task that turn was dispatched for.
11
+ */
12
+ export declare function noteTaskEffects(channelId: string, taskId: string, delta: number): void;
13
+ /** Effects produced by this task's own driver turns so far (spec 031, D7). */
14
+ export declare function taskEffectCount(channelId: string, taskId: string): number;
3
15
  /** Test seam: drop all tallies. */
4
16
  export declare function resetChannelEffects(): void;
5
17
  /**
@@ -14,8 +14,12 @@ import { isRecord } from "../shared/type-guards.js";
14
14
  *
15
15
  * The tally lives in process memory, exactly like the driver's futile counter it feeds; a restart
16
16
  * resets both, which costs at most one extra round of patience before the governor intervenes.
17
+ *
18
+ * Two tallies are kept: one per channel (raw, the measurement point) and one per task, credited
19
+ * a turn at a time by the runtime. The governor reads the second — see `noteTaskEffects`.
17
20
  */
18
21
  const counts = new Map();
22
+ const taskCounts = new Map();
19
23
  /** Tools whose successful completion is, by itself, a visible change to the world. */
20
24
  const EFFECT_TOOLS = new Set(["write", "edit", "send_media", "subagent"]);
21
25
  export function noteChannelEffect(channelId) {
@@ -24,9 +28,32 @@ export function noteChannelEffect(channelId) {
24
28
  export function channelEffectCount(channelId) {
25
29
  return counts.get(channelId) ?? 0;
26
30
  }
31
+ function taskKey(channelId, taskId) {
32
+ return `${channelId}\0${taskId}`;
33
+ }
34
+ /**
35
+ * Credit one task-driver turn's effects to that task.
36
+ *
37
+ * The channel tally above answers "how much has happened here", which is the wrong question for
38
+ * the governor: it also counts the user's small talk, so every task in a busy channel looked like
39
+ * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
40
+ * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
41
+ * turns are serialized per channel — and credits it to the task that turn was dispatched for.
42
+ */
43
+ export function noteTaskEffects(channelId, taskId, delta) {
44
+ if (delta <= 0)
45
+ return;
46
+ const key = taskKey(channelId, taskId);
47
+ taskCounts.set(key, (taskCounts.get(key) ?? 0) + delta);
48
+ }
49
+ /** Effects produced by this task's own driver turns so far (spec 031, D7). */
50
+ export function taskEffectCount(channelId, taskId) {
51
+ return taskCounts.get(taskKey(channelId, taskId)) ?? 0;
52
+ }
27
53
  /** Test seam: drop all tallies. */
28
54
  export function resetChannelEffects() {
29
55
  counts.clear();
56
+ taskCounts.clear();
30
57
  }
31
58
  /**
32
59
  * Whether a completed tool call counts as an effect.
@@ -67,6 +67,7 @@ export declare class ChannelJobManager {
67
67
  private readonly executor;
68
68
  private readonly jobs;
69
69
  private sweepTimer?;
70
+ private garbageCollectionTimer?;
70
71
  private sweeping;
71
72
  private readonly options;
72
73
  private readonly sweepIntervalMs;
@@ -80,8 +81,16 @@ export declare class ChannelJobManager {
80
81
  * Called from the sweeper and from restore, so leftovers never outlive a daemon restart.
81
82
  */
82
83
  private collectGarbage;
84
+ /**
85
+ * Arrange the next terminal-record cleanup independently of future job activity. A repeating
86
+ * sweeper is necessary while processes are running; after that, one unref'ed timeout is enough
87
+ * to enforce the retention promise without keeping an idle channel awake every few seconds.
88
+ */
89
+ private scheduleGarbageCollection;
83
90
  get channel(): string;
84
91
  runningCount(): number;
92
+ /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
93
+ runningTaskIds(): Set<string>;
85
94
  /**
86
95
  * Launch a command in the background and return its job id. The wrapper writes merged
87
96
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
@@ -156,6 +165,15 @@ interface JobRuntimeConfig {
156
165
  * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
157
166
  */
158
167
  export declare function configureJobRuntime(config: JobRuntimeConfig): void;
168
+ /**
169
+ * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
170
+ *
171
+ * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
172
+ * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
173
+ * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
174
+ * manager simply has no jobs, and the empty set is the right answer.
175
+ */
176
+ export declare function channelJobTaskIds(channelId: string): Set<string>;
159
177
  export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
160
178
  /**
161
179
  * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import * as log from "../log.js";
5
6
  import { writeFileAtomically } from "../shared/atomic-file.js";
@@ -28,7 +29,7 @@ export const FINISHED_JOB_RETENTION_MS = 24 * 60 * 60_000;
28
29
  /** Bytes of captured output carried inline in the completion wake. */
29
30
  const WAKE_OUTPUT_TAIL_BYTES = 2_000;
30
31
  function jobSpillPath(id) {
31
- return `/tmp/pipiclaw-job-${id}.log`;
32
+ return join(tmpdir(), `pipiclaw-job-${id}.log`);
32
33
  }
33
34
  function isTerminal(status) {
34
35
  return status !== "running";
@@ -113,12 +114,46 @@ export class ChannelJobManager {
113
114
  }
114
115
  }
115
116
  }
117
+ /**
118
+ * Arrange the next terminal-record cleanup independently of future job activity. A repeating
119
+ * sweeper is necessary while processes are running; after that, one unref'ed timeout is enough
120
+ * to enforce the retention promise without keeping an idle channel awake every few seconds.
121
+ */
122
+ scheduleGarbageCollection() {
123
+ if (this.garbageCollectionTimer) {
124
+ clearTimeout(this.garbageCollectionTimer);
125
+ this.garbageCollectionTimer = undefined;
126
+ }
127
+ const now = Date.now();
128
+ const nextExpiry = Array.from(this.jobs.values())
129
+ .filter((record) => isTerminal(record.status) && record.finishedAt)
130
+ .map((record) => record.finishedAt + FINISHED_JOB_RETENTION_MS)
131
+ .reduce((earliest, expiry) => (earliest === undefined ? expiry : Math.min(earliest, expiry)), undefined);
132
+ if (nextExpiry === undefined) {
133
+ return;
134
+ }
135
+ this.garbageCollectionTimer = setTimeout(() => {
136
+ this.garbageCollectionTimer = undefined;
137
+ void this.collectGarbage().finally(() => this.scheduleGarbageCollection());
138
+ }, Math.max(0, nextExpiry - now));
139
+ this.garbageCollectionTimer.unref?.();
140
+ }
116
141
  get channel() {
117
142
  return this.channelId;
118
143
  }
119
144
  runningCount() {
120
145
  return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
121
146
  }
147
+ /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
148
+ runningTaskIds() {
149
+ const ids = new Set();
150
+ for (const job of this.jobs.values()) {
151
+ if (job.status === "running" && job.contract.notify && job.contract.taskId) {
152
+ ids.add(job.contract.taskId);
153
+ }
154
+ }
155
+ return ids;
156
+ }
122
157
  /**
123
158
  * Launch a command in the background and return its job id. The wrapper writes merged
124
159
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
@@ -286,6 +321,7 @@ export class ChannelJobManager {
286
321
  }
287
322
  await this.persist(record);
288
323
  await this.announce(record, signal);
324
+ this.scheduleGarbageCollection();
289
325
  }
290
326
  /**
291
327
  * Wake the channel for a finished job. `notified` is persisted before anything else can run
@@ -430,6 +466,7 @@ export class ChannelJobManager {
430
466
  });
431
467
  }
432
468
  await this.collectGarbage();
469
+ this.scheduleGarbageCollection();
433
470
  this.ensureSweeper();
434
471
  return restored;
435
472
  }
@@ -454,6 +491,17 @@ let runtimeConfig = {};
454
491
  export function configureJobRuntime(config) {
455
492
  runtimeConfig = config;
456
493
  }
494
+ /**
495
+ * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
496
+ *
497
+ * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
498
+ * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
499
+ * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
500
+ * manager simply has no jobs, and the empty set is the right answer.
501
+ */
502
+ export function channelJobTaskIds(channelId) {
503
+ return managers.get(channelId)?.runningTaskIds() ?? new Set();
504
+ }
457
505
  export function getChannelJobManager(channelId, executor) {
458
506
  let manager = managers.get(channelId);
459
507
  if (!manager) {
@@ -12,6 +12,37 @@
12
12
  import type { LoadedPromptResource, PromptBuildResult } from "./types.js";
13
13
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
14
  export declare const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3000;
15
+ /**
16
+ * Soft budget for the tool JSON schemas, in the same units as the prompt sections.
17
+ *
18
+ * Tool schemas are the larger half of the fixed per-turn cost and were the only part of it with
19
+ * no budget at all: the runtime-authored prompt is capped at 700 units while the schemas beside it
20
+ * run several thousand. They sit in the provider's cache prefix, so the steady-state price is low —
21
+ * but every `rebuildSessionTools` (a `skill_manage` write, `/reload`, any resource reload) swaps
22
+ * that prefix and pays for all of it again.
23
+ *
24
+ * There is no hard cap on purpose. A schema cannot be auto-trimmed the way a prompt section can:
25
+ * the fix is always a human deciding which tool says less, or which tool should not be registered.
26
+ * So this is a warning line in the log and in `/context`, not an enforcement point. It is set just
27
+ * above the current set (≈2.8k units for 15 tools) — one more heavyweight tool crosses it, which
28
+ * is exactly when someone should be looking.
29
+ */
30
+ export declare const TOOL_SCHEMA_TARGET_UNITS = 3000;
31
+ export interface ToolSchemaMeasurement {
32
+ chars: number;
33
+ units: number;
34
+ }
35
+ /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
36
+ export declare function toolSchemaBudgetWarning(measurement: ToolSchemaMeasurement): string;
37
+ /**
38
+ * What the tool set costs on top of the system prompt. Counts what the provider is actually sent
39
+ * per tool — name, description and the JSON schema — the same way `/context` has always reported it.
40
+ */
41
+ export declare function measureToolSchemas(tools: Array<{
42
+ name: string;
43
+ description: string;
44
+ parameters?: unknown;
45
+ }>): ToolSchemaMeasurement;
15
46
  export interface PromptTurnContextStats {
16
47
  durableMemoryChars: number;
17
48
  durableMemoryUnits: number;
@@ -31,7 +62,7 @@ export interface PromptContextReportInput {
31
62
  description: string;
32
63
  }>;
33
64
  toolNames: string[];
34
- toolSchemaChars: number;
65
+ toolSchemas: ToolSchemaMeasurement;
35
66
  /** Resolved SOUL.md / AGENTS.md, for the independent body-budget lines. */
36
67
  soul?: LoadedPromptResource;
37
68
  agents?: LoadedPromptResource;
@@ -9,9 +9,44 @@
9
9
  * owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
10
10
  * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
11
  */
12
+ import { countPromptUnits } from "../../shared/prompt-units.js";
12
13
  import { estimateTokens, RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
13
14
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
15
  export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
16
+ /**
17
+ * Soft budget for the tool JSON schemas, in the same units as the prompt sections.
18
+ *
19
+ * Tool schemas are the larger half of the fixed per-turn cost and were the only part of it with
20
+ * no budget at all: the runtime-authored prompt is capped at 700 units while the schemas beside it
21
+ * run several thousand. They sit in the provider's cache prefix, so the steady-state price is low —
22
+ * but every `rebuildSessionTools` (a `skill_manage` write, `/reload`, any resource reload) swaps
23
+ * that prefix and pays for all of it again.
24
+ *
25
+ * There is no hard cap on purpose. A schema cannot be auto-trimmed the way a prompt section can:
26
+ * the fix is always a human deciding which tool says less, or which tool should not be registered.
27
+ * So this is a warning line in the log and in `/context`, not an enforcement point. It is set just
28
+ * above the current set (≈2.8k units for 15 tools) — one more heavyweight tool crosses it, which
29
+ * is exactly when someone should be looking.
30
+ */
31
+ export const TOOL_SCHEMA_TARGET_UNITS = 3_000;
32
+ /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
33
+ export function toolSchemaBudgetWarning(measurement) {
34
+ return `tool JSON schemas are ${measurement.units} units (${measurement.chars} chars), over the ${TOOL_SCHEMA_TARGET_UNITS} unit target. Shorten a tool description, move detail into a playbook, or unregister a tool; \`/context detail\` lists the set.`;
35
+ }
36
+ /**
37
+ * What the tool set costs on top of the system prompt. Counts what the provider is actually sent
38
+ * per tool — name, description and the JSON schema — the same way `/context` has always reported it.
39
+ */
40
+ export function measureToolSchemas(tools) {
41
+ let chars = 0;
42
+ let units = 0;
43
+ for (const tool of tools) {
44
+ const text = `${tool.name}${tool.description}${JSON.stringify(tool.parameters ?? {})}`;
45
+ chars += text.length;
46
+ units += countPromptUnits(text);
47
+ }
48
+ return { chars, units };
49
+ }
15
50
  /**
16
51
  * What pi's `<available_skills>` block will cost, close enough to report on:
17
52
  * name, description and location inside a five-line XML wrapper, plus the preamble.
@@ -82,7 +117,8 @@ export function renderContextReport(input) {
82
117
  lines.push(agentsLine);
83
118
  }
84
119
  lines.push("");
85
- lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemaChars)} chars (billed on top of the system prompt)`);
120
+ const overToolBudget = input.toolSchemas.units > TOOL_SCHEMA_TARGET_UNITS;
121
+ lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemas.units)} / ${formatNumber(TOOL_SCHEMA_TARGET_UNITS)} units, ${formatNumber(input.toolSchemas.chars)} chars${overToolBudget ? " — over target" : ""} (billed on top of the system prompt)`);
86
122
  lines.push(`Skills: ${input.skills.length} visible, ≈${formatNumber(estimateSkillsPromptChars(input.skills))} chars (rendered and managed by pi, not budgeted by Pipiclaw)`);
87
123
  if (input.lastTurn) {
88
124
  const turn = input.lastTurn;
@@ -95,12 +131,15 @@ export function renderContextReport(input) {
95
131
  lines.push(`- durable bootstrap: ${formatNumber(turn.durableMemoryUnits)} units / ${formatNumber(turn.durableMemoryChars)} chars`);
96
132
  lines.push(`- user message: ${formatNumber(turn.userMessageChars)} chars (not automatic; not capped here)`);
97
133
  }
98
- if (build.diagnostics.length > 0) {
134
+ if (build.diagnostics.length > 0 || overToolBudget) {
99
135
  lines.push("");
100
136
  lines.push("Diagnostics:");
101
137
  for (const diagnostic of build.diagnostics) {
102
138
  lines.push(`- [${diagnostic.level}] ${diagnostic.sectionId}: ${diagnostic.message}`);
103
139
  }
140
+ if (overToolBudget) {
141
+ lines.push(`- [warning] tools: ${toolSchemaBudgetWarning(input.toolSchemas)}`);
142
+ }
104
143
  }
105
144
  if (detail) {
106
145
  lines.push("");
@@ -1,4 +1,5 @@
1
1
  import * as log from "../log.js";
2
+ import { formatLocalTime } from "../shared/local-time.js";
2
3
  import { extractLabelFromArgs, truncate } from "../shared/text-utils.js";
3
4
  import { isRecord } from "../shared/type-guards.js";
4
5
  import { toolResultDetails } from "../tools/tool-details.js";
@@ -106,7 +107,7 @@ export async function handleSessionEvent(event, context) {
106
107
  cost: { ...subAgentDetails.usage.cost },
107
108
  });
108
109
  queue.enqueue(() => store?.logSubAgentRun(logCtx.channelId, {
109
- date: new Date().toISOString(),
110
+ date: formatLocalTime(),
110
111
  toolCallId: event.toolCallId,
111
112
  label,
112
113
  agent: subAgentDetails.agent,
package/dist/log.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { styleText } from "node:util";
2
2
  import { RUNTIME_LOG_PATH } from "./paths.js";
3
3
  import { createJsonlAppender } from "./shared/jsonl-appender.js";
4
+ import { formatLocalTime } from "./shared/local-time.js";
4
5
  const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
5
6
  const MAX_VALUE_LENGTH = 240;
6
7
  const MAX_COLLECTION_ITEMS = 10;
@@ -96,20 +97,6 @@ function sanitizeFields(fields) {
96
97
  }
97
98
  return result;
98
99
  }
99
- function formatTimestamp(date = new Date()) {
100
- const offsetMinutes = -date.getTimezoneOffset();
101
- const sign = offsetMinutes >= 0 ? "+" : "-";
102
- const offsetHours = String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0");
103
- const offsetRemainder = String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
104
- const year = date.getFullYear();
105
- const month = String(date.getMonth() + 1).padStart(2, "0");
106
- const day = String(date.getDate()).padStart(2, "0");
107
- const hours = String(date.getHours()).padStart(2, "0");
108
- const minutes = String(date.getMinutes()).padStart(2, "0");
109
- const seconds = String(date.getSeconds()).padStart(2, "0");
110
- const milliseconds = String(date.getMilliseconds()).padStart(3, "0");
111
- return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${sign}${offsetHours}:${offsetRemainder}`;
112
- }
113
100
  function renderField(value) {
114
101
  if (typeof value === "string")
115
102
  return JSON.stringify(value);
@@ -131,7 +118,7 @@ function formatConsoleLine(level, event, message, options) {
131
118
  .sort(([left], [right]) => left.localeCompare(right))
132
119
  .map(([key, value]) => `${key}=${renderField(value)}`)
133
120
  .join(" ");
134
- return `${formatTimestamp()} ${level.toUpperCase().padEnd(5)} ${event} ${summarizeString(message)}${suffix ? ` ${suffix}` : ""}`;
121
+ return `${formatLocalTime()} ${level.toUpperCase().padEnd(5)} ${event} ${summarizeString(message)}${suffix ? ` ${suffix}` : ""}`;
135
122
  }
136
123
  function colorFor(level) {
137
124
  if (level === "debug")
@@ -153,7 +140,7 @@ function emit(level, event, message, options) {
153
140
  const fields = sanitizeFields(options.fields);
154
141
  const details = options.details ? summarizeString(options.details) : undefined;
155
142
  fileSink.tryAppend({
156
- ts: new Date().toISOString(),
143
+ ts: formatLocalTime(),
157
144
  level,
158
145
  event,
159
146
  message: summarizeString(message),
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readOptionalTextFile } from "../shared/fs-utils.js";
3
+ import { localDayKey } from "../shared/local-time.js";
3
4
  import { clipText } from "../shared/text-utils.js";
4
5
  import { getChannelMemoryPath, parseChannelMemoryEntries, readChannelMemory } from "./files.js";
5
6
  import { syncMemoryMetadata } from "./metadata.js";
@@ -41,8 +42,8 @@ export async function handleMemoryCommand(options) {
41
42
  const records = Object.values(metadata.entries);
42
43
  const active = records.filter((entry) => entry.status === "active");
43
44
  const since = new Date();
44
- since.setUTCDate(since.getUTCDate() - 29);
45
- const sinceDay = since.toISOString().slice(0, 10);
45
+ since.setDate(since.getDate() - 29);
46
+ const sinceDay = localDayKey(since);
46
47
  const recalls30d = active.reduce((sum, entry) => sum +
47
48
  Object.entries(entry.recallByDay ?? {}).reduce((entrySum, [day, count]) => entrySum + (day >= sinceDay ? count : 0), 0), 0);
48
49
  const lastFailure = (await readOptionalTextFile(getMemoryReviewLogPath(options.channelDir)))
@@ -1,8 +1,10 @@
1
1
  import { getLatestCompactionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { formatLocalTime } from "../shared/local-time.js";
2
3
  import { splitH2Sections } from "../shared/markdown-sections.js";
3
4
  import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
4
5
  import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
5
6
  import { DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, shouldAutoWriteMemory, } from "./promotion.js";
7
+ import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
6
8
  import { runSidecarTask } from "./sidecar-worker.js";
7
9
  import { sanitizeMessagesForMemory } from "./transcript.js";
8
10
  const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
@@ -19,6 +21,7 @@ const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMOR
19
21
  Return Markdown only. Do not use code fences.
20
22
 
21
23
  Goals:
24
+ ${MEMORY_INPUT_SAFETY_RULES}
22
25
  - Keep only durable and useful channel memory.
23
26
  - Remove outdated entries, duplicates, verbose phrasing, transient working state, temporary debugging observations, and completed worklog.
24
27
  - Organize the result with stable sections where relevant.
@@ -43,6 +46,7 @@ const HISTORY_FOLDING_SYSTEM_PROMPT = `You are folding older HISTORY.md blocks f
43
46
  Return Markdown only. Do not use code fences.
44
47
 
45
48
  Goals:
49
+ ${MEMORY_INPUT_SAFETY_RULES}
46
50
  - Compress older history blocks into one concise summary block.
47
51
  - Keep important decisions, milestones, and unresolved outcomes.
48
52
  - Remove redundancy and transcript-like detail.
@@ -145,7 +149,7 @@ export async function runInlineConsolidation(options) {
145
149
  includeHistoryBlock: mode === "boundary",
146
150
  usageContext: usageContextFor(options.channelId, correlationId),
147
151
  });
148
- const timestamp = new Date().toISOString();
152
+ const timestamp = formatLocalTime();
149
153
  // The same bar the growth review applies. Consolidation used to write whatever the model
150
154
  // returned, which is how transient state reached durable memory: the strictest reviewer
151
155
  // was gated behind a keyword scan while the ungated paths wrote freely. Rejected material
@@ -242,13 +246,13 @@ export async function foldChannelHistory(options, currentHistory) {
242
246
  // Preserve the raw blocks before folding turns them lossy, so nothing is
243
247
  // permanently blurred by repeated folds.
244
248
  await appendChannelHistoryArchive(options.channelDir, {
245
- timestamp: new Date().toISOString(),
249
+ timestamp: formatLocalTime(),
246
250
  content: renderedOlder,
247
251
  });
248
252
  const prompt = `Older history blocks to fold:
249
253
  ${renderedOlder}`;
250
254
  const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
251
- const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? new Date().toISOString()}`;
255
+ const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? formatLocalTime()}`;
252
256
  const rebuiltHistory = [
253
257
  "# Channel History",
254
258
  "",
@@ -3,6 +3,7 @@ import { parseJsonObject } from "../shared/llm-json.js";
3
3
  import { clipText } from "../shared/text-utils.js";
4
4
  import { isRecord } from "../shared/type-guards.js";
5
5
  import { parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
6
+ import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
6
7
  import { runRetriedSidecarTask } from "./sidecar-worker.js";
7
8
  import { sanitizeMessagesForMemory } from "./transcript.js";
8
9
  /**
@@ -49,6 +50,7 @@ export function buildMemoryExtractionSystemPrompt(options) {
49
50
  "}",
50
51
  "",
51
52
  "Rules:",
53
+ MEMORY_INPUT_SAFETY_RULES,
52
54
  MEMORY_OPS_RULES,
53
55
  ...(options.includeHistoryBlock ? [HISTORY_BLOCK_RULES] : []),
54
56
  ].join("\n");
@@ -42,6 +42,7 @@ export interface ApplyMemoryOpsResult {
42
42
  forgotten: number;
43
43
  blockedByPolicy: number;
44
44
  blockedByTombstone: number;
45
+ skippedDuplicate: number;
45
46
  }
46
47
  /**
47
48
  * Apply add/supersede/invalidate ops to a channel MEMORY.md with line-level edits,
@@ -49,10 +50,6 @@ export interface ApplyMemoryOpsResult {
49
50
  * missing invalidate targets are skipped. Mutating edits are backed up first.
50
51
  */
51
52
  export declare function applyChannelMemoryOps(channelDir: string, ops: MemoryOp[], timestamp?: string): Promise<ApplyMemoryOpsResult>;
52
- export interface MemoryUpdateBlock {
53
- timestamp: string;
54
- entries: string[];
55
- }
56
53
  export interface HistoryBlock {
57
54
  timestamp: string;
58
55
  content: string;
@@ -68,7 +65,6 @@ export declare function readChannelSession(channelDir: string): Promise<string>;
68
65
  export declare function rewriteChannelMemory(channelDir: string, content: string): Promise<void>;
69
66
  export declare function rewriteChannelHistory(channelDir: string, content: string): Promise<void>;
70
67
  export declare function rewriteChannelSession(channelDir: string, content: string): Promise<void>;
71
- export declare function appendChannelMemoryUpdate(channelDir: string, block: MemoryUpdateBlock): Promise<void>;
72
68
  export declare function getChannelHistoryArchivePath(channelDir: string): string;
73
69
  /** Append raw history blocks to a never-rewritten archive before lossy folding. */
74
70
  export declare function appendChannelHistoryArchive(channelDir: string, block: HistoryBlock): Promise<void>;