pi-posthorse 0.10.29 → 0.10.30

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.
package/index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import {
8
8
  SettingsManager,
9
+ estimateTokens,
9
10
  type ExtensionAPI,
10
11
  type ExtensionContext,
11
12
  } from "@earendil-works/pi-coding-agent";
@@ -14,8 +15,6 @@ import { policySnapshot } from "./src/budget.ts";
14
15
  import type { CompactionPolicy, PolicyReader } from "./src/contracts.ts";
15
16
  import { createWindowGuidance } from "./src/guidance.ts";
16
17
  import { registerHistory } from "./src/history.ts";
17
- import { toolFacts } from "./src/host.ts";
18
- import { safeJsonStringify } from "./src/message-text.ts";
19
18
  import { registerNotes } from "./src/notes.ts";
20
19
  import { createNotesStore } from "./src/note-store.ts";
21
20
  import { registerNoteGuards } from "./src/note-guards.ts";
@@ -23,21 +22,14 @@ import { PageReservations } from "./src/paging.ts";
23
22
  import { registerRollover } from "./src/rollover.ts";
24
23
 
25
24
  function activeToolTokens(pi: ExtensionAPI): number {
26
- const { active, tools } = toolFacts(pi);
27
- return tools
25
+ const active = new Set(pi.getActiveTools());
26
+ const toolsAdded = pi
27
+ .getAllTools()
28
28
  .filter((tool) => active.has(tool.name))
29
- .reduce(
30
- (total, tool) =>
31
- total +
32
- Math.ceil(
33
- safeJsonStringify({
34
- name: tool.name,
35
- description: tool.description,
36
- parameters: tool.parameters,
37
- }).length / 4,
38
- ),
39
- 0,
40
- );
29
+ .map(({ name, description, parameters }) => ({ name, description, parameters }));
30
+ return toolsAdded.length === 0
31
+ ? 0
32
+ : estimateTokens({ role: "system", content: "", toolsAdded, timestamp: 0 });
41
33
  }
42
34
  /** Use Pi's live effective settings by default; SDK hosts can inject a policy reader. */
43
35
  export function createPosthorse(getPolicy?: PolicyReader): (pi: ExtensionAPI) => void {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-posthorse",
3
- "version": "0.10.29",
3
+ "version": "0.10.30",
4
4
  "type": "module",
5
5
  "description": "Posthorse: fresh context, same journey. No-summary context rollover for Pi, with sparse budget reminders, handoffs, notes, and history.",
6
6
  "keywords": [
package/src/boundary.ts CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  AUTO_HANDOFF_PREFIX,
3
3
  POSTHORSE_COMPACTION,
4
4
  isRecord,
5
+ presentText,
5
6
  type EntryLike,
6
7
  type ProjectedEntry,
7
8
  } from "./contracts.ts";
@@ -87,15 +88,16 @@ export function contextStart(entries: readonly EntryLike[]): {
87
88
  start: number;
88
89
  boundary?: EntryLike;
89
90
  } {
90
- for (let i = entries.length - 1; i >= 0; i--) {
91
- const entry = entries[i];
92
- if (entry?.type === "context_window") {
93
- return { start: i + 1, boundary: entry };
94
- }
95
- if (entry?.type === "compaction") {
96
- const kept = entries.findIndex((candidate) => candidate.id === entry.firstKeptEntryId);
97
- return { start: kept >= 0 ? kept : i + 1, boundary: entry };
98
- }
91
+ const index = entries.findLastIndex((entry) => classifyBoundary(entry) !== undefined);
92
+ const boundary = entries[index];
93
+ if (boundary === undefined) {
94
+ return { start: 0 };
99
95
  }
100
- return { start: 0 };
96
+ const firstKeptId =
97
+ boundary.type === "compaction" ? presentText(boundary.firstKeptEntryId) : undefined;
98
+ const kept =
99
+ firstKeptId === undefined
100
+ ? -1
101
+ : entries.findIndex((candidate) => candidate.id === firstKeptId);
102
+ return { start: kept >= 0 ? kept : index + 1, boundary };
101
103
  }
package/src/budget.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { estimateTokens, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
- ESTIMATED_IMAGE_CHARS,
4
3
  MAX_HANDOFF_CHARS,
5
4
  MAX_PAGE_CHARS,
6
5
  PAGE_MARGIN_TOKENS,
@@ -178,12 +177,17 @@ export function freshPayloadChars(
178
177
  const line = budget.state === "enabled" ? budget.rolloverAt : budget.contextWindow;
179
178
  const reservedGuidance =
180
179
  guidance === "rebuild" ? guidanceTokenCount(buildGuidance(ctx)) : guidanceTokens(ctx);
181
- const promptTokens = Math.ceil(ctx.getSystemPrompt().length / 4) + reservedGuidance;
180
+ const promptTokens =
181
+ estimateTokens({ role: "system", content: ctx.getSystemPrompt(), timestamp: 0 }) +
182
+ reservedGuidance;
182
183
  const pendingTokens = pendingMessages.reduce(
183
184
  (total, message) =>
184
185
  total +
185
- Math.ceil(textOf(message).length / 4) +
186
- imagesOf(message.content).length * (ESTIMATED_IMAGE_CHARS / 4),
186
+ estimateTokens({
187
+ role: "user",
188
+ content: [{ type: "text", text: textOf(message) }, ...imagesOf(message.content)],
189
+ timestamp: 0,
190
+ }),
187
191
  0,
188
192
  );
189
193
  return Math.min(
package/src/files.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { createHash, randomUUID } from "node:crypto";
1
+ import { hash, randomUUID } from "node:crypto";
2
2
  import {
3
3
  createReadStream,
4
4
  existsSync,
@@ -24,7 +24,7 @@ import {
24
24
  type FileHandle,
25
25
  } from "node:fs/promises";
26
26
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
27
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
27
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
28
28
  import { errorCode } from "./contracts.ts";
29
29
 
30
30
  async function lstatOrMissing(path: string) {
@@ -230,13 +230,13 @@ function projectPackageNotes(root: string, cwd: string): string | undefined {
230
230
  if (existsSync(join(dir, ".git")) && realpathSync(dir) === root) {
231
231
  checkout = dir;
232
232
  }
233
- if (basename(dir) !== "git" || basename(dirname(dir)) !== ".pi") {
233
+ if (basename(dir) !== "git" || basename(dirname(dir)) !== CONFIG_DIR_NAME) {
234
234
  continue;
235
235
  }
236
236
  const path = packageRelativePath(dir, checkout);
237
237
  if (path !== undefined) {
238
238
  // Flat full keys keep arbitrary Git URL prefix paths out of one another's note stores.
239
- const key = createHash("sha256").update(path.split(sep).join("/")).digest("hex");
239
+ const key = hash("sha256", path.replaceAll(sep, "/"), "hex");
240
240
  moved = join(realpathSync(dirname(dir)), "package-notes", key, "notes");
241
241
  }
242
242
  }
@@ -279,7 +279,7 @@ function migrationTarget(moved: string): string {
279
279
  /** The notes directory for `cwd`, moving any notes found inside a Pi package checkout. */
280
280
  export function notesDir(cwd: string): string {
281
281
  const root = notesRoot(cwd);
282
- const local = join(root, ".pi", "notes");
282
+ const local = join(root, CONFIG_DIR_NAME, "notes");
283
283
  const moved = packageNotes(root, cwd);
284
284
  if (moved === undefined) {
285
285
  return local;
@@ -20,7 +20,8 @@ import {
20
20
  } from "./session-files.ts";
21
21
 
22
22
  export const historyParameters = Type.Object({
23
- op: Type.Union([Type.Literal("search"), Type.Literal("read")], {
23
+ op: Type.Enum(["search", "read"], {
24
+ type: "string",
24
25
  description: "Operation to perform",
25
26
  }),
26
27
  query: Type.Optional(Type.String({ description: "Case-insensitive text to find (search)" })),
@@ -276,7 +277,7 @@ async function archivedMatches(
276
277
  );
277
278
  skipped += recent.skipped;
278
279
  for (const group of recent.groups) {
279
- for (const hit of [...group].reverse()) {
280
+ for (const hit of group.toReversed()) {
280
281
  accumulator.add(hit);
281
282
  }
282
283
  }
package/src/host.ts CHANGED
@@ -13,8 +13,6 @@ export type SessionHost = {
13
13
  export type ToolInfo = {
14
14
  readonly name: string;
15
15
  readonly namespace?: unknown;
16
- readonly description?: unknown;
17
- readonly parameters?: unknown;
18
16
  };
19
17
  export type ToolRegistry = {
20
18
  readonly getActiveTools: () => readonly string[];
@@ -54,8 +52,6 @@ export type ToolFacts = {
54
52
  /** Registered names an active tool can carry without a namespace. */
55
53
  readonly unnamespaced: ReadonlySet<string>;
56
54
  readonly activeUnnamespaced: ReadonlySet<string>;
57
- /** The one registry read both sets were derived from. */
58
- readonly tools: readonly ToolInfo[];
59
55
  };
60
56
  /** Active tools share names with namespaced registrations, so capabilities read the intersected set. */
61
57
  export function toolFacts(pi: ToolRegistry): ToolFacts {
@@ -67,8 +63,7 @@ export function toolFacts(pi: ToolRegistry): ToolFacts {
67
63
  return {
68
64
  active,
69
65
  unnamespaced,
70
- activeUnnamespaced: new Set([...active].filter((name) => unnamespaced.has(name))),
71
- tools,
66
+ activeUnnamespaced: active.intersection(unnamespaced),
72
67
  };
73
68
  }
74
69
  export function ownerQuestionRegistered(pi: ToolRegistry): boolean {
@@ -1,4 +1,4 @@
1
- import { createHash } from "node:crypto";
1
+ import { hash } from "node:crypto";
2
2
  import { sep } from "node:path";
3
3
  import {
4
4
  isRecord,
@@ -114,7 +114,7 @@ export function isRecoveryCall(part: unknown): boolean {
114
114
  }
115
115
  /** Ten base64url characters of SHA-256; legacy whole-digest keys start with these. */
116
116
  export function shortKey(text: string): string {
117
- return createHash("sha256").update(text).digest("base64url").slice(0, 10);
117
+ return hash("sha256", text, "base64url").slice(0, 10);
118
118
  }
119
119
  /** Nested session files are subagent runs, whose input came from a parent agent. */
120
120
  export function sourceTag(source: string): string {
@@ -194,13 +194,7 @@ export class NoteDiscovery {
194
194
  session: SessionNotes,
195
195
  options: ComparisonOptions,
196
196
  ): Promise<DiscoveredNote[]> {
197
- const groups = new Map<string, DiscoveredNote[]>();
198
- for (const file of files) {
199
- const key = `${noteKey(file.lineage)}\0${file.size}`;
200
- const group = groups.get(key) ?? [];
201
- group.push(file);
202
- groups.set(key, group);
203
- }
197
+ const groups = Map.groupBy(files, (file) => `${noteKey(file.lineage)}\0${file.size}`);
204
198
  const selected: DiscoveredNote[] = [];
205
199
  for (const group of groups.values()) {
206
200
  if (group.length === 1) {
@@ -50,13 +50,7 @@ const touchSchema = Type.Object({
50
50
  Type.Object({
51
51
  ...addressSchema.properties,
52
52
  seed: Type.Optional(seedSchema),
53
- kind: Type.Union([
54
- Type.Literal("read"),
55
- Type.Literal("write"),
56
- Type.Literal("clear"),
57
- Type.Literal("delete"),
58
- Type.Literal("adopt"),
59
- ]),
53
+ kind: Type.Enum(["read", "write", "clear", "delete", "adopt"]),
60
54
  }),
61
55
  ),
62
56
  });
@@ -1,11 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
- import { constants } from "node:fs";
2
+ import { constants, createReadStream } from "node:fs";
3
3
  import {
4
4
  copyFile,
5
5
  lstat,
6
6
  mkdir,
7
7
  mkdtemp,
8
- open,
9
8
  readFile,
10
9
  rename,
11
10
  rm,
@@ -14,6 +13,7 @@ import {
14
13
  writeFile,
15
14
  } from "node:fs/promises";
16
15
  import { dirname, join } from "node:path";
16
+ import { pipeline } from "node:stream/promises";
17
17
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
18
18
  import { errorCode } from "./contracts.ts";
19
19
  import { publishFile } from "./files.ts";
@@ -49,21 +49,10 @@ export function sameIdentity(left: NoteIdentity, right: NoteIdentity): boolean {
49
49
  );
50
50
  }
51
51
  export async function fileDigest(path: string, signal?: AbortSignal): Promise<string> {
52
- const file = await open(path, "r");
53
- try {
54
- const hash = createHash("sha256");
55
- for await (const chunk of file.createReadStream({ autoClose: false })) {
56
- signal?.throwIfAborted();
57
- const bytes: unknown = chunk;
58
- if (!(bytes instanceof Uint8Array)) {
59
- throw new TypeError("Expected binary file data.");
60
- }
61
- hash.update(bytes);
62
- }
63
- return hash.digest("hex");
64
- } finally {
65
- await file.close();
66
- }
52
+ signal?.throwIfAborted();
53
+ const hasher = createHash("sha256");
54
+ await pipeline(createReadStream(path, { signal }), hasher);
55
+ return hasher.digest("hex");
67
56
  }
68
57
  export async function readManifest(directory: string): Promise<ForkBinding | undefined> {
69
58
  try {
package/src/notes.ts CHANGED
@@ -289,16 +289,10 @@ function withoutEmptyScope(params: NotesParams): NotesParams {
289
289
  return presentText(scope) === undefined ? unscoped : params;
290
290
  }
291
291
  const notesParameters = Type.Object({
292
- op: Type.Union(
293
- [
294
- Type.Literal("list"),
295
- Type.Literal("read"),
296
- Type.Literal("write"),
297
- Type.Literal("append"),
298
- Type.Literal("search"),
299
- ],
300
- { description: "Operation to perform" },
301
- ),
292
+ op: Type.Enum(["list", "read", "write", "append", "search"], {
293
+ type: "string",
294
+ description: "Operation to perform",
295
+ }),
302
296
  path: Type.Optional(
303
297
  Type.String({
304
298
  description:
package/src/paging.ts CHANGED
@@ -1,5 +1,5 @@
1
+ import { estimateTokens } from "@earendil-works/pi-coding-agent";
1
2
  import { pageCapacity } from "./budget.ts";
2
- import { textOf } from "./message-text.ts";
3
3
  import {
4
4
  ESTIMATED_IMAGE_CHARS,
5
5
  MAX_PAGE_CHARS,
@@ -85,12 +85,10 @@ export class PageReservations {
85
85
  private settle(ctx: PolicyContext): void {
86
86
  this.accounting = reconcile(this.accounting, ctx.getContextUsage()?.tokens);
87
87
  }
88
- private reserve(text: string, imageCount = 0): void {
88
+ private reserve(content: TextResult["content"] | string): void {
89
89
  this.accounting = withTokens(
90
90
  this.accounting,
91
- this.accounting.tokens +
92
- Math.ceil(text.length / 4) +
93
- imageCount * (ESTIMATED_IMAGE_CHARS / 4),
91
+ this.accounting.tokens + estimateTokens({ role: "user", content, timestamp: 0 }),
94
92
  );
95
93
  }
96
94
  deliver(
@@ -99,7 +97,7 @@ export class PageReservations {
99
97
  build: (chars: number) => TextResult,
100
98
  ): TextResult {
101
99
  const result = build(this.size(ctx, request));
102
- this.reserve(textOf(result), result.content.filter((part) => part.type === "image").length);
100
+ this.reserve(result.content);
103
101
  return result;
104
102
  }
105
103
  error(ctx: PolicyContext, message: string): never {
@@ -81,7 +81,7 @@ function anchors(records: readonly RecoveryRecord[]): {
81
81
  others: RecoveryRecord[];
82
82
  } {
83
83
  const firstOwner = records.find((record) => record.label === "owner input") ?? records[0];
84
- const latestOwner = [...records].reverse().find((record) => record.kind === "owner");
84
+ const latestOwner = records.findLast((record) => record.kind === "owner");
85
85
  const latestOverall = records.at(-1);
86
86
  const selected = new Set([firstOwner, latestOwner, latestOverall]);
87
87
  return {
@@ -1,4 +1,5 @@
1
1
  import { posix } from "node:path";
2
+ import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
2
3
  import {
3
4
  NOTE_RECEIPT,
4
5
  isRecord,
@@ -72,21 +73,35 @@ function normalizeRelPath(raw: string): string {
72
73
  return invalid ? "" : cleaned;
73
74
  }
74
75
 
76
+ const CONFIG_DIR_PATTERN = RegExp.escape(CONFIG_DIR_NAME);
77
+ const PACKAGE_NOTES_PATTERN = new RegExp(
78
+ `\\/${CONFIG_DIR_PATTERN}\\/package-notes\\/[0-9a-f]{64}\\/notes\\/(.+)$`,
79
+ "u",
80
+ );
81
+ const GLOBAL_NOTES_PATTERN = new RegExp(
82
+ `\\/${CONFIG_DIR_PATTERN}\\/(?:agent\\/)?notes\\/[^/]+\\/[^/]+\\/[^/]+\\/(.+)$`,
83
+ "u",
84
+ );
85
+ const RELATIVE_NOTES_PREFIX = new RegExp(`^(?:\\.\\/)?${CONFIG_DIR_PATTERN}\\/notes\\/`, "u");
86
+
75
87
  function matchMarkerPath(slash: string): string | undefined {
76
- for (const marker of ["/.pi/notes/", "/posthorse-notes/"]) {
88
+ for (const marker of [`/${CONFIG_DIR_NAME}/notes/`, "/posthorse-notes/"]) {
77
89
  const idx = slash.lastIndexOf(marker);
78
90
  if (idx >= 0) {
79
91
  return slash.slice(idx + marker.length);
80
92
  }
81
93
  }
82
- if (slash.startsWith(".pi/notes/") || slash.startsWith("./.pi/notes/")) {
83
- return slash.replace(/^(?:\.\/)?\.pi\/notes\//u, "");
94
+ if (
95
+ slash.startsWith(`${CONFIG_DIR_NAME}/notes/`) ||
96
+ slash.startsWith(`./${CONFIG_DIR_NAME}/notes/`)
97
+ ) {
98
+ return slash.replace(RELATIVE_NOTES_PREFIX, "");
84
99
  }
85
- const pkgMatch = /\/\.pi\/package-notes\/[0-9a-f]{64}\/notes\/(.+)$/u.exec(slash);
100
+ const pkgMatch = PACKAGE_NOTES_PATTERN.exec(slash);
86
101
  if (pkgMatch !== null) {
87
102
  return pkgMatch[1];
88
103
  }
89
- return /\/\.pi\/(?:agent\/)?notes\/[^/]+\/[^/]+\/[^/]+\/(.+)$/u.exec(slash)?.[1];
104
+ return GLOBAL_NOTES_PATTERN.exec(slash)?.[1];
90
105
  }
91
106
 
92
107
  function absoluteSlashPath(slash: string): boolean {
@@ -95,7 +110,7 @@ function absoluteSlashPath(slash: string): boolean {
95
110
 
96
111
  /** Receipt lines are a storage format: parse exactly what the notes tool emits. */
97
112
  function receiptPattern(prefix: string): RegExp {
98
- return new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}([^\\r\\n]+)$`, "mu");
113
+ return new RegExp(`^${RegExp.escape(prefix)}([^\\r\\n]+)$`, "mu");
99
114
  }
100
115
  const receiptPatterns: readonly (readonly [RegExp, ContentTouchKind])[] = [
101
116
  [receiptPattern(NOTE_RECEIPT.wrote), "full-write"],
@@ -412,7 +427,7 @@ export function collectTouches(
412
427
  readonly defaultDir?: string | undefined;
413
428
  } {
414
429
  const results = collectResultMap(entries);
415
- const knownDirs = new Set([...directories, ...learnNotesDirs(entries, results)]);
430
+ const knownDirs = new Set(directories).union(learnNotesDirs(entries, results));
416
431
  const handledResultIds = new Set<string>();
417
432
  const touches: NoteTouch[] = [];
418
433
  for (const item of entries) {
@@ -2,6 +2,7 @@ import { execFile } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { readdir, stat } from "node:fs/promises";
4
4
  import { join, relative, resolve, sep } from "node:path";
5
+ import { promisify } from "node:util";
5
6
 
6
7
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
8
  import {
@@ -22,23 +23,15 @@ const FIRST_SEARCH_BYTES = 256 * 1024 * 1024;
22
23
  const ARGUMENT_CHARS = 256 * 1024;
23
24
  /** Pi writes these keys first, so most lines yield window metadata without JSON.parse. */
24
25
  const ENTRY_HEAD = /^\{"type":"([^"\\]*)","id":"([^"\\]*)","parentId":(null|"[^"\\]*")[,}]/u;
26
+ const execFileAsync = promisify(execFile);
25
27
 
26
- function execFileText(
28
+ async function execFileText(
27
29
  file: string,
28
30
  args: readonly string[],
29
31
  cwd: string,
30
32
  signal?: AbortSignal,
31
33
  ): Promise<string> {
32
- return new Promise((resolveOutput, reject) => {
33
- execFile(file, args, { cwd, signal, maxBuffer: 64 * 1024 * 1024 }, (error, stdout) => {
34
- if (error !== null) {
35
- const failure: Error = error;
36
- reject(failure);
37
- } else {
38
- resolveOutput(stdout);
39
- }
40
- });
41
- });
34
+ return (await execFileAsync(file, args, { cwd, signal, maxBuffer: 64 * 1024 * 1024 })).stdout;
42
35
  }
43
36
  /** Label text normalization adds, and raw JSONL that every entry showing it contains. */
44
37
  const LABEL_SOURCES: readonly (readonly [label: string, needles: readonly string[]])[] = [
package/src/ui/display.ts CHANGED
@@ -21,17 +21,11 @@ export const displaySchema = Type.Union([
21
21
  Type.Object({
22
22
  kind: Type.Literal("context"),
23
23
  usage: Type.Optional(usageSchema),
24
- rollover: Type.Optional(
25
- Type.Union([
26
- Type.Literal("enabled"),
27
- Type.Literal("disabled"),
28
- Type.Literal("unsupported"),
29
- ]),
30
- ),
24
+ rollover: Type.Optional(Type.Enum(["enabled", "disabled", "unsupported"])),
31
25
  rolloverAt: Type.Optional(Type.Number()),
32
26
  }),
33
27
  Type.Object({
34
- kind: Type.Union([Type.Literal("notes-list"), Type.Literal("notes-search")]),
28
+ kind: Type.Enum(["notes-list", "notes-search"]),
35
29
  count: Type.Number(),
36
30
  headerLength: Type.Optional(Type.Number()),
37
31
  page: Type.Optional(pageRangeSchema),
@@ -43,11 +37,7 @@ export const displaySchema = Type.Union([
43
37
  headerLength: Type.Optional(Type.Number()),
44
38
  }),
45
39
  Type.Object({
46
- kind: Type.Union([
47
- Type.Literal("note-write"),
48
- Type.Literal("note-append"),
49
- Type.Literal("new-context"),
50
- ]),
40
+ kind: Type.Enum(["note-write", "note-append", "new-context"]),
51
41
  }),
52
42
  Type.Object({
53
43
  kind: Type.Literal("history-search"),