pi-posthorse 0.10.28 → 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.28",
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,9 +1,9 @@
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,
6
+ formatCount,
7
7
  type CompactionPolicy,
8
8
  type ContextUsage,
9
9
  type MessageLike,
@@ -95,11 +95,10 @@ export function budgetGuidanceKey(ctx: PolicyContext): string {
95
95
  : `1:${budget.contextWindow}:${budget.reserveTokens}`;
96
96
  }
97
97
  export function unsupportedMessage(budget: Budget, newContextAvailable = true): string {
98
- const n = (value: number) => value.toLocaleString("en-US");
99
98
  const reset = newContextAvailable
100
99
  ? " new_context remains available with a model-aware handoff limit."
101
100
  : "";
102
- return `Posthorse: unsupported configuration. The model's context window (${n(budget.contextWindow)} tokens) minus Pi's compaction.reserveTokens (${n(budget.reserveTokens)}) leaves ${n(budget.usable)} usable tokens; Posthorse needs at least ${n(MIN_USABLE_TOKENS)}. Automatic Posthorse rollover and checkpoint reminders are off for this model, so Pi's own compaction applies. Lower compaction.reserveTokens in Pi settings or use a larger-context model.${reset}`;
101
+ return `Posthorse: unsupported configuration. The model's context window (${formatCount(budget.contextWindow)} tokens) minus Pi's compaction.reserveTokens (${formatCount(budget.reserveTokens)}) leaves ${formatCount(budget.usable)} usable tokens; Posthorse needs at least ${formatCount(MIN_USABLE_TOKENS)}. Automatic Posthorse rollover and checkpoint reminders are off for this model, so Pi's own compaction applies. Lower compaction.reserveTokens in Pi settings or use a larger-context model.${reset}`;
103
102
  }
104
103
  function automaticGuidance(
105
104
  budget: Budget | undefined,
@@ -116,7 +115,7 @@ function automaticGuidance(
116
115
  const line =
117
116
  budget === undefined
118
117
  ? ""
119
- : `The rollover line is ${budget.rolloverAt.toLocaleString("en-US")} tokens used. `;
118
+ : `The rollover line is ${formatCount(budget.rolloverAt)} tokens used. `;
120
119
  const reset = tools.newContext ? " new_context is an optional clean reset." : "";
121
120
  return `Pi rolls context over automatically, so the context window is not a deadline. Do not reduce scope, skip steps or verification, or write a final summary because rollover is near, and do not wait for the user to say "continue". Finish when the requested work and its verification are complete, or report a genuine blocker.
122
121
  ${line}Rollover keeps a recent-message tail without summarizing. One task-note reminder may arrive at the end of a working turn near the line: update the note only if it is stale, or write one if the task has none, then continue with the next step in the same run.${reset}`;
@@ -131,7 +130,7 @@ export function buildGuidance(
131
130
  const capacity =
132
131
  budget === undefined
133
132
  ? "Configured context capacity is unknown."
134
- : `Configured context capacity: ${budget.contextWindow.toLocaleString("en-US")} tokens (not remaining space).`;
133
+ : `Configured context capacity: ${formatCount(budget.contextWindow)} tokens (not remaining space).`;
135
134
  const checkRemaining = tools.getContextRemaining
136
135
  ? " Before reporting a remaining-token count or changing your work plan because of context limits, call get_context_remaining."
137
136
  : "";
@@ -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(
@@ -3,13 +3,8 @@ import { Type } from "typebox";
3
3
  import { toolCards, type PosthorseDisplay } from "../ui.ts";
4
4
  import { budgetFor, freshPayloadChars, unsupportedMessage, type Budget } from "./budget.ts";
5
5
  import { activeGuidanceTools } from "./guidance.ts";
6
- import {
7
- EMPTY_HANDOFF,
8
- MAX_HANDOFF_CHARS,
9
- textResult,
10
- type PolicyContext,
11
- type TextResult,
12
- } from "./contracts.ts";
6
+ import { EMPTY_HANDOFF, MAX_HANDOFF_CHARS, formatCount, type PolicyContext } from "./contracts.ts";
7
+ import { textResult, type TextResult } from "./ui/display.ts";
13
8
 
14
9
  function rolloverStatus(budget: Budget | undefined): "disabled" | "enabled" | "unsupported" {
15
10
  return budget?.state ?? "disabled";
@@ -21,16 +16,15 @@ function contextReport(host: PolicyContext, newContextAvailable: boolean): TextR
21
16
  kind: "context",
22
17
  });
23
18
  }
24
- const n = (value: number) => value.toLocaleString("en-US");
25
19
  const budget = budgetFor(host, usage.contextWindow);
26
20
  const rollover = rolloverStatus(budget);
27
21
  const display: PosthorseDisplay = {
28
22
  kind: "context",
29
23
  usage,
30
24
  rollover,
31
- rolloverAt: budget?.rolloverAt,
25
+ ...(budget?.rolloverAt === undefined ? {} : { rolloverAt: budget.rolloverAt }),
32
26
  };
33
- const configured = `≈${n(Math.max(0, usage.contextWindow - usage.tokens))} tokens until the configured context limit (${n(usage.tokens)}/${n(usage.contextWindow)} used, ${Math.round(usage.percent ?? 0)}%). Best available native estimate.`;
27
+ const configured = `≈${formatCount(Math.max(0, usage.contextWindow - usage.tokens))} tokens until the configured context limit (${formatCount(usage.tokens)}/${formatCount(usage.contextWindow)} used, ${Math.round(usage.percent ?? 0)}%). Best available native estimate.`;
34
28
  if (budget === undefined || budget.state === "disabled") {
35
29
  return textResult(
36
30
  `Automatic rollover is disabled in the available settings (Pi compaction.enabled=false). ${configured}`,
@@ -46,7 +40,7 @@ function contextReport(host: PolicyContext, newContextAvailable: boolean): TextR
46
40
  );
47
41
  }
48
42
  return textResult(
49
- `≈${n(Math.max(0, budget.rolloverAt - usage.tokens))} tokens until automatic rollover (line at ${n(budget.rolloverAt)}); ${configured}`,
43
+ `≈${formatCount(Math.max(0, budget.rolloverAt - usage.tokens))} tokens until automatic rollover (line at ${formatCount(budget.rolloverAt)}); ${configured}`,
50
44
  [],
51
45
  display,
52
46
  );
@@ -77,7 +71,7 @@ export function registerContextTools(
77
71
  const limit = freshPayloadChars(policy(ctx), activeToolTokens());
78
72
  if (trimmed !== undefined && trimmed !== "" && trimmed.length > limit) {
79
73
  throw new Error(
80
- `Handoff is too large for the active model (${trimmed.length.toLocaleString("en-US")} characters; limit ${limit.toLocaleString("en-US")}). Save fuller state in notes, then retry with a shorter handoff or no handoff.`,
74
+ `Handoff is too large for the active model (${formatCount(trimmed.length)} characters; limit ${formatCount(limit)}). Save fuller state in notes, then retry with a shorter handoff or no handoff.`,
81
75
  );
82
76
  }
83
77
  const result = textResult(
package/src/contracts.ts CHANGED
@@ -1,7 +1,24 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { PosthorseDisplay } from "./ui/display.ts";
3
2
 
4
- export { isRecord } from "./records.ts";
3
+ export function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+
7
+ export type Immutable<T> = T extends
8
+ | string
9
+ | number
10
+ | boolean
11
+ | bigint
12
+ | symbol
13
+ | null
14
+ | undefined
15
+ | ((...args: never[]) => unknown)
16
+ ? T
17
+ : T extends readonly (infer Item)[]
18
+ ? readonly Immutable<Item>[]
19
+ : T extends object
20
+ ? { readonly [Key in keyof T]: Immutable<T[Key]> }
21
+ : T;
5
22
 
6
23
  export type CompactionPolicy = {
7
24
  readonly enabled: boolean;
@@ -98,12 +115,6 @@ export type ReminderFingerprint = {
98
115
  readonly contextWindow?: number | undefined;
99
116
  readonly reserveTokens?: number | undefined;
100
117
  };
101
- export type TextResult = {
102
- content: Array<
103
- { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }
104
- >;
105
- details: PosthorseDisplay | undefined;
106
- };
107
118
 
108
119
  export const MAX_HANDOFF_CHARS = 20_000;
109
120
  export const MAX_PAGE_CHARS = 40_000;
@@ -111,6 +122,8 @@ export const MIN_PAGE_CHARS = 1_000;
111
122
  export const PAGE_MARGIN_TOKENS = 1_000;
112
123
  export const ESTIMATED_IMAGE_CHARS = 4_800;
113
124
  export const REMINDER_TYPE = "posthorse-reminder";
125
+ /** The session's model may answer an owner question; only the plain tool registration is owner provenance. */
126
+ export const OWNER_QUESTION_TOOL = "ask_question";
114
127
  export const AUTO_HANDOFF_PREFIX = "Automatic context rollover recovery record.";
115
128
  export const EMPTY_HANDOFF = "Fresh context. Restore relevant notes and history before continuing.";
116
129
 
@@ -162,6 +175,12 @@ export function unknownArray(value: unknown): readonly unknown[] | undefined {
162
175
  export function optionalString(value: unknown): string | undefined {
163
176
  return typeof value === "string" ? value : undefined;
164
177
  }
178
+ export function errorCode(error: unknown): string | undefined {
179
+ return isRecord(error) ? optionalString(error.code) : undefined;
180
+ }
181
+ export function formatCount(value: number): string {
182
+ return value.toLocaleString("en-US");
183
+ }
165
184
  /** Some models send every optional argument; an empty string means the argument was omitted. */
166
185
  export function presentText(value: unknown): string | undefined {
167
186
  return typeof value === "string" && value !== "" ? value : undefined;
@@ -175,10 +194,3 @@ export function requireValue(value: string | undefined, name: string, op: string
175
194
  export function isReminderType(customType: unknown): boolean {
176
195
  return customType === REMINDER_TYPE;
177
196
  }
178
- export function textResult(
179
- text: string,
180
- images: readonly ImageLike[] = [],
181
- display?: PosthorseDisplay,
182
- ): TextResult {
183
- return { content: [{ type: "text", text }, ...images], details: display };
184
- }
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,21 +24,21 @@ 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";
28
- import { isRecord } from "./contracts.ts";
27
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
28
+ import { errorCode } from "./contracts.ts";
29
29
 
30
30
  async function lstatOrMissing(path: string) {
31
31
  try {
32
32
  return await lstat(path);
33
33
  } catch (error) {
34
- if (isRecord(error) && error.code === "ENOENT") {
34
+ if (errorCode(error) === "ENOENT") {
35
35
  return;
36
36
  }
37
37
  throw error;
38
38
  }
39
39
  }
40
40
  /** Resolve every link before normalization, preserving path traversal constraints. */
41
- export async function resolveFileTarget(absolutePath: string): Promise<string> {
41
+ async function resolveFileTarget(absolutePath: string): Promise<string> {
42
42
  let target = absolutePath;
43
43
  const links = new Set<string>();
44
44
  for (;;) {
@@ -53,10 +53,8 @@ export async function resolveFileTarget(absolutePath: string): Promise<string> {
53
53
  if (!(await stat(parentInput)).isDirectory()) {
54
54
  throw Object.assign(new Error(`Not a directory: ${parentInput}`), { code: "ENOTDIR" });
55
55
  }
56
- // Each parent must resolve before its child link can be examined.
57
56
  const parent = await realpath(parentInput);
58
57
  target = join(parent, basename(target));
59
- // Link targets cannot be known before examining the current link.
60
58
  const info = await lstatOrMissing(target);
61
59
  if (info === undefined) {
62
60
  return target;
@@ -232,13 +230,13 @@ function projectPackageNotes(root: string, cwd: string): string | undefined {
232
230
  if (existsSync(join(dir, ".git")) && realpathSync(dir) === root) {
233
231
  checkout = dir;
234
232
  }
235
- if (basename(dir) !== "git" || basename(dirname(dir)) !== ".pi") {
233
+ if (basename(dir) !== "git" || basename(dirname(dir)) !== CONFIG_DIR_NAME) {
236
234
  continue;
237
235
  }
238
236
  const path = packageRelativePath(dir, checkout);
239
237
  if (path !== undefined) {
240
238
  // Flat full keys keep arbitrary Git URL prefix paths out of one another's note stores.
241
- const key = createHash("sha256").update(path.split(sep).join("/")).digest("hex");
239
+ const key = hash("sha256", path.replaceAll(sep, "/"), "hex");
242
240
  moved = join(realpathSync(dirname(dir)), "package-notes", key, "notes");
243
241
  }
244
242
  }
@@ -281,7 +279,7 @@ function migrationTarget(moved: string): string {
281
279
  /** The notes directory for `cwd`, moving any notes found inside a Pi package checkout. */
282
280
  export function notesDir(cwd: string): string {
283
281
  const root = notesRoot(cwd);
284
- const local = join(root, ".pi", "notes");
282
+ const local = join(root, CONFIG_DIR_NAME, "notes");
285
283
  const moved = packageNotes(root, cwd);
286
284
  if (moved === undefined) {
287
285
  return local;
@@ -300,7 +298,7 @@ export function notesDir(cwd: string): string {
300
298
  }
301
299
  try {
302
300
  // Sessions still running an older Posthorse keep reaching the notes until they reload.
303
- symlinkSync(moved, local, "junction");
301
+ symlinkSync(moved, local);
304
302
  } catch (error) {
305
303
  if (lstatSync(local, { throwIfNoEntry: false })?.isDirectory() === true) {
306
304
  throw error;
@@ -3,7 +3,7 @@ import { presentText, unknownArray } from "./contracts.ts";
3
3
  /** Where a search page stopped: the anchor entry, its rank, its offset, and the search it belongs to. */
4
4
  export type HistoryCursor = readonly [id: string, priority: 0 | 1, offset: number, key: string];
5
5
 
6
- export function encodeCursor(cursor: HistoryCursor): string {
6
+ function encodeCursor(cursor: HistoryCursor): string {
7
7
  return Buffer.from(JSON.stringify(cursor)).toString("base64url");
8
8
  }
9
9
  export function cursorFor(
@@ -9,6 +9,7 @@ import {
9
9
  import { isWindow } from "./boundary.ts";
10
10
  import {
11
11
  assistantFailure,
12
+ contentText,
12
13
  excerptAround,
13
14
  imageSummary,
14
15
  imagesOf,
@@ -59,19 +60,19 @@ export function flattenEntry(entry: EntryLike): string | undefined {
59
60
  case "context_window":
60
61
  return `[context_window] ${entry.handoff === undefined || entry.handoff === "" ? "No handoff" : `Handoff: ${entry.handoff}`}`;
61
62
  case "custom_message":
62
- return `[custom:${entry.customType ?? "unknown"}] ${contentText(entry.content)}`;
63
+ return `[custom:${entry.customType ?? "unknown"}] ${entryBodyText(entry.content)}`;
63
64
  case "context_edit":
64
65
  return entry.replacement === undefined || entry.replacement === null
65
66
  ? undefined
66
- : `[context_edit] ${contentText(entry.replacement.content)}`;
67
+ : `[context_edit] ${entryBodyText(entry.replacement.content)}`;
67
68
  case undefined:
68
69
  return undefined;
69
70
  default:
70
71
  return undefined;
71
72
  }
72
73
  }
73
- function contentText(content: unknown): string {
74
- return [textOf({ content }), imageSummary(imagesOf(content))]
74
+ function entryBodyText(content: unknown): string {
75
+ return [contentText(content), imageSummary(imagesOf(content))]
75
76
  .filter((part) => part !== "")
76
77
  .join("\n");
77
78
  }
@@ -83,7 +84,7 @@ function ownAssistantText(message: MessageLike, images: WindowedEntry["images"])
83
84
  originals.push(current);
84
85
  current = "";
85
86
  } else {
86
- const partText = textOf({ content: [part] });
87
+ const partText = contentText([part]);
87
88
  if (partText !== "") {
88
89
  current = current === "" ? partText : `${current}\n${partText}`;
89
90
  }
@@ -159,7 +160,7 @@ export function historyHit(
159
160
  headerLength: header.length,
160
161
  };
161
162
  }
162
- export function entryContent(entry: EntryLike): unknown {
163
+ function entryContent(entry: EntryLike): unknown {
163
164
  switch (entry.type) {
164
165
  case "context_edit":
165
166
  return entry.replacement?.content;
@@ -1,12 +1,11 @@
1
1
  import {
2
2
  MIN_PAGE_CHARS,
3
3
  ESTIMATED_IMAGE_CHARS,
4
- textResult,
5
4
  type HistoryHit,
6
5
  type PolicyContext,
7
- type TextResult,
8
6
  type WindowedEntry,
9
7
  } from "./contracts.ts";
8
+ import { textResult, type TextResult } from "./ui/display.ts";
10
9
  import { excerpt, shortKey, sourceTag } from "./message-text.ts";
11
10
  import { cursorFor as cursorAt } from "./history-cursor.ts";
12
11
  import type { HistoryMatches, HistoryParams } from "./history-search.ts";
@@ -1,10 +1,12 @@
1
1
  import { relative, resolve } from "node:path";
2
+ import { Type, type Static } from "typebox";
2
3
  import type { LineMatcher } from "./session-lines.ts";
3
4
  import {
4
5
  isReminderType,
5
6
  requireValue,
6
7
  type EntryLike,
7
8
  type HistoryHit,
9
+ type Immutable,
8
10
  type ProjectedEntry,
9
11
  } from "./contracts.ts";
10
12
  import { decodeCursor, type HistoryCursor } from "./history-cursor.ts";
@@ -17,16 +19,42 @@ import {
17
19
  sessionWindowEntries,
18
20
  } from "./session-files.ts";
19
21
 
20
- export type HistoryParams = {
21
- readonly op: "search" | "read";
22
- readonly query?: string;
23
- readonly id?: string;
24
- readonly all?: boolean;
25
- readonly limit?: number;
26
- readonly cursor?: string;
27
- readonly offset?: number;
28
- readonly imageOffset?: number;
29
- };
22
+ export const historyParameters = Type.Object({
23
+ op: Type.Enum(["search", "read"], {
24
+ type: "string",
25
+ description: "Operation to perform",
26
+ }),
27
+ query: Type.Optional(Type.String({ description: "Case-insensitive text to find (search)" })),
28
+ id: Type.Optional(Type.String({ description: "Entry id exactly as search printed it (read)" })),
29
+ all: Type.Optional(
30
+ Type.Boolean({
31
+ description: "Also search this project's other sessions and subagent runs",
32
+ }),
33
+ ),
34
+ limit: Type.Optional(
35
+ Type.Integer({
36
+ description: "Maximum search results per page (default 10, max 50)",
37
+ minimum: 1,
38
+ maximum: 50,
39
+ }),
40
+ ),
41
+ cursor: Type.Optional(
42
+ Type.String({
43
+ description: "Continuation from the previous search page; keep query and all unchanged",
44
+ maxLength: 512,
45
+ }),
46
+ ),
47
+ offset: Type.Optional(
48
+ Type.Integer({ description: "Character offset for read (default 0)", minimum: 0 }),
49
+ ),
50
+ imageOffset: Type.Optional(
51
+ Type.Integer({
52
+ description: "First image to return (read); use the value from the continuation",
53
+ minimum: 0,
54
+ }),
55
+ ),
56
+ });
57
+ export type HistoryParams = Immutable<Static<typeof historyParameters>>;
30
58
  export type HistorySource = {
31
59
  readonly dir: string;
32
60
  readonly cwd: string;
@@ -249,7 +277,7 @@ async function archivedMatches(
249
277
  );
250
278
  skipped += recent.skipped;
251
279
  for (const group of recent.groups) {
252
- for (const hit of [...group].reverse()) {
280
+ for (const hit of group.toReversed()) {
253
281
  accumulator.add(hit);
254
282
  }
255
283
  }
package/src/history.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  import { relative, resolve } from "node:path";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { Type } from "typebox";
4
3
  import { toolCards } from "../ui.ts";
5
4
  import { requireValue, type PolicyContext, type WindowedEntry } from "./contracts.ts";
6
5
  import { toWindowedEntry, windowProjection } from "./history-entries.ts";
7
6
  import { historyReadPage, searchPage } from "./history-pages.ts";
8
- import { historyMatches, type HistorySource } from "./history-search.ts";
7
+ import { historyMatches, historyParameters, type HistorySource } from "./history-search.ts";
9
8
  import type { PageAccess } from "./paging.ts";
10
9
  import { scopedSessionFiles, sessionWindowEntries } from "./session-files.ts";
11
10
 
@@ -87,46 +86,7 @@ export function registerHistory(
87
86
  promptGuidelines: [
88
87
  "Use history search first, then history read with the entry id exactly as printed",
89
88
  ],
90
- parameters: Type.Object({
91
- op: Type.Union([Type.Literal("search"), Type.Literal("read")], {
92
- description: "Operation to perform",
93
- }),
94
- query: Type.Optional(
95
- Type.String({ description: "Case-insensitive text to find (search)" }),
96
- ),
97
- id: Type.Optional(
98
- Type.String({ description: "Entry id exactly as search printed it (read)" }),
99
- ),
100
- all: Type.Optional(
101
- Type.Boolean({
102
- description: "Also search this project's other sessions and subagent runs",
103
- }),
104
- ),
105
- limit: Type.Optional(
106
- Type.Integer({
107
- description: "Maximum search results per page (default 10, max 50)",
108
- minimum: 1,
109
- maximum: 50,
110
- }),
111
- ),
112
- cursor: Type.Optional(
113
- Type.String({
114
- description:
115
- "Continuation from the previous search page; keep query and all unchanged",
116
- maxLength: 512,
117
- }),
118
- ),
119
- offset: Type.Optional(
120
- Type.Integer({ description: "Character offset for read (default 0)", minimum: 0 }),
121
- ),
122
- imageOffset: Type.Optional(
123
- Type.Integer({
124
- description:
125
- "First image to return (read); use the value from the continuation",
126
- minimum: 0,
127
- }),
128
- ),
129
- }),
89
+ parameters: historyParameters,
130
90
  async execute(...[, params, signal, , ctx]) {
131
91
  const source = historySource(ctx);
132
92
  if (params.op === "search") {
package/src/host.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { EntryLike, ProjectedEntry } from "./contracts.ts";
1
+ import { OWNER_QUESTION_TOOL, type EntryLike, type ProjectedEntry } from "./contracts.ts";
2
2
 
3
3
  /** Only the session-manager members Posthorse reads; a host may omit any of them. */
4
4
  export type SessionHost = {
@@ -13,15 +13,11 @@ 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[];
21
19
  readonly getAllTools: () => readonly ToolInfo[];
22
20
  };
23
- /** The session's model may answer an owner question; only the plain tool registration is owner provenance. */
24
- export const OWNER_QUESTION_TOOL = "ask_question";
25
21
  export type SessionIdentity = {
26
22
  readonly sessionId: string;
27
23
  readonly file: string | undefined;
@@ -56,8 +52,6 @@ export type ToolFacts = {
56
52
  /** Registered names an active tool can carry without a namespace. */
57
53
  readonly unnamespaced: ReadonlySet<string>;
58
54
  readonly activeUnnamespaced: ReadonlySet<string>;
59
- /** The one registry read both sets were derived from. */
60
- readonly tools: readonly ToolInfo[];
61
55
  };
62
56
  /** Active tools share names with namespaced registrations, so capabilities read the intersected set. */
63
57
  export function toolFacts(pi: ToolRegistry): ToolFacts {
@@ -69,8 +63,7 @@ export function toolFacts(pi: ToolRegistry): ToolFacts {
69
63
  return {
70
64
  active,
71
65
  unnamespaced,
72
- activeUnnamespaced: new Set([...active].filter((name) => unnamespaced.has(name))),
73
- tools,
66
+ activeUnnamespaced: active.intersection(unnamespaced),
74
67
  };
75
68
  }
76
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,
@@ -9,7 +9,7 @@ import {
9
9
  type ToolCallLike,
10
10
  } from "./contracts.ts";
11
11
 
12
- export function isImage(part: unknown): part is ImageLike {
12
+ function isImage(part: unknown): part is ImageLike {
13
13
  return (
14
14
  isRecord(part) &&
15
15
  part.type === "image" &&
@@ -47,7 +47,7 @@ export function executionArgumentsText(call: ToolCallLike): string {
47
47
  ? ""
48
48
  : `\nExecution arguments: ${safeJsonStringify(call.executionArguments)}`;
49
49
  }
50
- export function toolCallOf(part: unknown): ToolCallLike | undefined {
50
+ function toolCallOf(part: unknown): ToolCallLike | undefined {
51
51
  if (!isRecord(part) || part.type !== "toolCall") {
52
52
  return undefined;
53
53
  }
@@ -83,15 +83,18 @@ function blockText(part: unknown): string {
83
83
  }
84
84
  return `${toolIdentity(call.name, call.namespace)} ${safeJsonStringify(call.arguments ?? {})}${call.id === undefined ? "" : `\nCall ID: ${call.id}`}${executionArgumentsText(call)}`;
85
85
  }
86
- export function textOf(message: MessageLike): string {
87
- if (typeof message.content === "string") {
88
- return message.content;
86
+ export function contentText(content: unknown): string {
87
+ if (typeof content === "string") {
88
+ return content;
89
89
  }
90
- return (unknownArray(message.content) ?? [])
90
+ return (unknownArray(content) ?? [])
91
91
  .map(blockText)
92
92
  .filter((text) => text !== "")
93
93
  .join("\n");
94
94
  }
95
+ export function textOf(message: MessageLike): string {
96
+ return contentText(message.content);
97
+ }
95
98
  export function assistantFailure(message: MessageLike): string {
96
99
  if (message.role !== "assistant") {
97
100
  return "";
@@ -111,7 +114,7 @@ export function isRecoveryCall(part: unknown): boolean {
111
114
  }
112
115
  /** Ten base64url characters of SHA-256; legacy whole-digest keys start with these. */
113
116
  export function shortKey(text: string): string {
114
- return createHash("sha256").update(text).digest("base64url").slice(0, 10);
117
+ return hash("sha256", text, "base64url").slice(0, 10);
115
118
  }
116
119
  /** Nested session files are subagent runs, whose input came from a parent agent. */
117
120
  export function sourceTag(source: string): string {