@howaboua/pi-notes-compaction 0.0.15 → 0.0.16

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 (81) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +5 -2
  4. package/index.ts +8 -0
  5. package/package.json +16 -13
  6. package/src/board/context-briefing.ts +245 -0
  7. package/src/board/delivery.ts +85 -0
  8. package/src/guidance.ts +121 -0
  9. package/src/notes/AGENTS.md +27 -0
  10. package/src/{activation.ts → notes/activation.ts} +8 -10
  11. package/src/{attachment-sharing.ts → notes/attachment-sharing.ts} +1 -1
  12. package/src/{attachment-snapshot.ts → notes/attachment-snapshot.ts} +33 -20
  13. package/src/{context-sharing.ts → notes/context-sharing.ts} +7 -2
  14. package/src/{extension-hooks.ts → notes/extension-hooks.ts} +1 -12
  15. package/src/{extension-sharing.ts → notes/extension-sharing.ts} +1 -1
  16. package/src/notes/feature.ts +168 -0
  17. package/src/{history-windows.ts → notes/history-windows.ts} +10 -22
  18. package/src/{history.ts → notes/history.ts} +6 -5
  19. package/src/{index.ts → notes/index.ts} +20 -11
  20. package/src/{integrations.ts → notes/integrations.ts} +19 -3
  21. package/src/{lifecycle.ts → notes/lifecycle.ts} +0 -2
  22. package/src/{note-query.ts → notes/note-query.ts} +3 -5
  23. package/src/notes/note-result.ts +119 -0
  24. package/src/{note-save-marker.ts → notes/note-save-marker.ts} +3 -1
  25. package/src/{query-executor.ts → notes/query-executor.ts} +7 -2
  26. package/src/{query-input.ts → notes/query-input.ts} +1 -0
  27. package/src/{remote.ts → notes/remote.ts} +1 -1
  28. package/src/{saved-session-access.ts → notes/saved-session-access.ts} +14 -10
  29. package/src/{saved-session.ts → notes/saved-session.ts} +31 -15
  30. package/src/notes/saved-sharing-records.ts +170 -0
  31. package/src/{session-pruning.ts → notes/session-pruning.ts} +5 -5
  32. package/src/{settings-command.ts → notes/settings-command.ts} +29 -42
  33. package/src/{settings-controls.ts → notes/settings-controls.ts} +62 -72
  34. package/src/{settings-screen.ts → notes/settings-screen.ts} +25 -7
  35. package/src/{settings.ts → notes/settings.ts} +37 -6
  36. package/src/{shared-notes.ts → notes/shared-notes.ts} +21 -13
  37. package/src/{shared-session-reader.ts → notes/shared-session-reader.ts} +8 -11
  38. package/src/{sharing-service.ts → notes/sharing-service.ts} +1 -1
  39. package/src/{tool-contracts.ts → notes/tool-contracts.ts} +71 -44
  40. package/src/{tools.ts → notes/tools.ts} +2 -2
  41. package/src/{tree-handoff-read.ts → notes/tree-handoff-read.ts} +47 -32
  42. package/src/{window-message.ts → notes/window-message.ts} +15 -20
  43. package/src/settings-navigation.ts +11 -0
  44. package/src/timestamps.ts +3 -0
  45. package/tsconfig.json +9 -0
  46. package/src/note-result.ts +0 -70
  47. package/src/saved-sharing-records.ts +0 -135
  48. /package/src/{agent-identity.ts → notes/agent-identity.ts} +0 -0
  49. /package/src/{binding-startup.ts → notes/binding-startup.ts} +0 -0
  50. /package/src/{bridge.ts → notes/bridge.ts} +0 -0
  51. /package/src/{compaction-projection.ts → notes/compaction-projection.ts} +0 -0
  52. /package/src/{context-owner.ts → notes/context-owner.ts} +0 -0
  53. /package/src/{fresh-checkpoint.ts → notes/fresh-checkpoint.ts} +0 -0
  54. /package/src/{fresh-notes.ts → notes/fresh-notes.ts} +0 -0
  55. /package/src/{history-search-protocol.ts → notes/history-search-protocol.ts} +0 -0
  56. /package/src/{history-search-pruning.mjs → notes/history-search-pruning.mjs} +0 -0
  57. /package/src/{history-search-worker.mjs → notes/history-search-worker.mjs} +0 -0
  58. /package/src/{history-search.ts → notes/history-search.ts} +0 -0
  59. /package/src/{idle-admission.ts → notes/idle-admission.ts} +0 -0
  60. /package/src/{model-role-config.ts → notes/model-role-config.ts} +0 -0
  61. /package/src/{model-role-screen.ts → notes/model-role-screen.ts} +0 -0
  62. /package/src/{model-roles.ts → notes/model-roles.ts} +0 -0
  63. /package/src/{notes-lookup.ts → notes/notes-lookup.ts} +0 -0
  64. /package/src/{notes.ts → notes/notes.ts} +0 -0
  65. /package/src/{rollover.ts → notes/rollover.ts} +0 -0
  66. /package/src/{saved-session-index.mjs → notes/saved-session-index.mjs} +0 -0
  67. /package/src/{saved-session.mjs → notes/saved-session.mjs} +0 -0
  68. /package/src/{session-pruning-content.ts → notes/session-pruning-content.ts} +0 -0
  69. /package/src/{session-pruning-plan.ts → notes/session-pruning-plan.ts} +0 -0
  70. /package/src/{session-pruning-policy.ts → notes/session-pruning-policy.ts} +0 -0
  71. /package/src/{session-pruning-screen.ts → notes/session-pruning-screen.ts} +0 -0
  72. /package/src/{session-pruning-source.ts → notes/session-pruning-source.ts} +0 -0
  73. /package/src/{session-pruning-transaction.ts → notes/session-pruning-transaction.ts} +0 -0
  74. /package/src/{sqlite.mjs → notes/sqlite.mjs} +0 -0
  75. /package/src/{store.ts → notes/store.ts} +0 -0
  76. /package/src/{task-boundary.ts → notes/task-boundary.ts} +0 -0
  77. /package/src/{tree-archive-manifest.mjs → notes/tree-archive-manifest.mjs} +0 -0
  78. /package/src/{tree-archive.ts → notes/tree-archive.ts} +0 -0
  79. /package/src/{tree-checkpoint.ts → notes/tree-checkpoint.ts} +0 -0
  80. /package/src/{window-checkpoint.ts → notes/window-checkpoint.ts} +0 -0
  81. /package/src/{windows.ts → notes/windows.ts} +0 -0
@@ -10,14 +10,20 @@ import {
10
10
  } from "./settings.js";
11
11
  import { TASK_BOUNDARY_PRESETS, taskBoundaryLabel } from "./task-boundary.js";
12
12
 
13
+ export type NotesSettingsAction =
14
+ | "close"
15
+ | "prune"
16
+ | "sessionPruning"
17
+ | "roles"
18
+ | { settings: NotesSettings; selected: string };
19
+
13
20
  export function createNotesSettingsControls(
14
21
  ctx: ExtensionContext,
15
22
  options: {
16
23
  settings: () => NotesSettings;
17
24
  settingsPath: string;
18
- save: (settings: NotesSettings) => void;
19
25
  },
20
- done: (action: "close" | "prune" | "sessionPruning") => void,
26
+ done: (action: NotesSettingsAction) => void,
21
27
  requestRender: () => void,
22
28
  ) {
23
29
  const settings = options.settings();
@@ -41,8 +47,19 @@ export function createNotesSettingsControls(
41
47
  id: "active",
42
48
  label: "Active",
43
49
  description: `Whitelist matches exact model IDs from any provider. Edit modelWhitelist in ${options.settingsPath}, then reload Pi. Example: ["gpt-6-luna", "gpt-6.1-sol"].`,
44
- currentValue: settings.active === "all" ? "All models" : "Whitelist",
45
- values: ["All models", "Whitelist"],
50
+ currentValue:
51
+ settings.active === "off"
52
+ ? "Off"
53
+ : settings.active === "all"
54
+ ? "All models"
55
+ : "Whitelist",
56
+ values: ["Off", "All models", "Whitelist"],
57
+ },
58
+ {
59
+ id: "roles",
60
+ label: "Model roles",
61
+ currentValue: "select…",
62
+ values: ["select…", "view…"],
46
63
  },
47
64
  {
48
65
  id: "sharing",
@@ -113,6 +130,10 @@ export function createNotesSettingsControls(
113
130
  5,
114
131
  getSettingsListTheme(),
115
132
  (id, value) => {
133
+ if (id === "roles") {
134
+ done("roles");
135
+ return;
136
+ }
116
137
  if (id === "sessionPruning") {
117
138
  done("sessionPruning");
118
139
  return;
@@ -130,75 +151,44 @@ export function createNotesSettingsControls(
130
151
  list.updateValue(id, taskBoundaryLabel(current.taskBoundaryReminder));
131
152
  return;
132
153
  }
133
- try {
134
- if (id === "active")
135
- options.save({
136
- ...current,
137
- active: value === "All models" ? "all" : "whitelist",
138
- });
139
- else if (id === "sharing")
140
- options.save({
141
- ...current,
142
- shareSubagentContext: value === "on",
143
- });
144
- else if (id === "noteSaveMarkers")
145
- options.save({ ...current, noteSaveMarkers: value === "on" });
146
- else if (id === "rankedHistorySearch")
147
- options.save({
148
- ...current,
149
- rankedHistorySearch: value === "on",
150
- });
151
- else if (id === "compact")
152
- options.save({ ...current, normalCompaction: value === "on" });
153
- else if (id === "newWindowRequests") {
154
- const newWindowRequests = NEW_WINDOW_REQUESTS.find(
155
- (mode) => mode === value,
156
- );
157
- if (newWindowRequests)
158
- options.save({ ...current, newWindowRequests });
159
- } else if (id === "taskBoundaryReminder")
160
- options.save({
161
- ...current,
162
- taskBoundaryReminder:
163
- TASK_BOUNDARY_PRESETS.find(
164
- (tokens) => taskBoundaryLabel(tokens) === value,
165
- ) ?? current.taskBoundaryReminder,
166
- });
167
- else {
168
- const idleMinutes = IDLE_MINUTES.find(
169
- (minutes) => idleValue(minutes) === value,
170
- );
171
- if (idleMinutes !== undefined)
172
- options.save({ ...current, idleMinutes });
173
- }
174
- } catch (error) {
175
- if (id === "rankedHistorySearch") {
176
- list.updateValue(id, current.rankedHistorySearch ? "on" : "off");
177
- } else
178
- list.updateValue(
179
- id,
180
- id === "active"
181
- ? current.active === "all"
182
- ? "All models"
183
- : "Whitelist"
184
- : id === "taskBoundaryReminder"
185
- ? taskBoundaryLabel(current.taskBoundaryReminder)
186
- : id === "newWindowRequests"
187
- ? current.newWindowRequests
188
- : id === "noteSaveMarkers"
189
- ? current.noteSaveMarkers
190
- ? "on"
191
- : "off"
192
- : id === "compact"
193
- ? current.normalCompaction
194
- ? "on"
195
- : "off"
196
- : idleValue(current.idleMinutes),
197
- );
198
- ctx.ui.notify(
199
- `Could not save notes settings: ${String(error)}`,
200
- "error",
154
+ const save = (settings: NotesSettings) =>
155
+ done({ settings, selected: id });
156
+ if (id === "active")
157
+ save({
158
+ ...current,
159
+ active:
160
+ value === "Off"
161
+ ? "off"
162
+ : value === "All models"
163
+ ? "all"
164
+ : "whitelist",
165
+ });
166
+ else if (id === "sharing")
167
+ save({ ...current, shareSubagentContext: value === "on" });
168
+ else if (id === "noteSaveMarkers")
169
+ save({ ...current, noteSaveMarkers: value === "on" });
170
+ else if (id === "rankedHistorySearch")
171
+ save({ ...current, rankedHistorySearch: value === "on" });
172
+ else if (id === "compact")
173
+ save({ ...current, normalCompaction: value === "on" });
174
+ else if (id === "newWindowRequests") {
175
+ const newWindowRequests = NEW_WINDOW_REQUESTS.find(
176
+ (mode) => mode === value,
177
+ );
178
+ if (newWindowRequests) save({ ...current, newWindowRequests });
179
+ } else if (id === "taskBoundaryReminder")
180
+ save({
181
+ ...current,
182
+ taskBoundaryReminder:
183
+ TASK_BOUNDARY_PRESETS.find(
184
+ (tokens) => taskBoundaryLabel(tokens) === value,
185
+ ) ?? current.taskBoundaryReminder,
186
+ });
187
+ else {
188
+ const idleMinutes = IDLE_MINUTES.find(
189
+ (minutes) => idleValue(minutes) === value,
201
190
  );
191
+ if (idleMinutes !== undefined) save({ ...current, idleMinutes });
202
192
  }
203
193
  requestRender();
204
194
  },
@@ -10,27 +10,33 @@ import {
10
10
  type SessionPruningSettings,
11
11
  } from "./session-pruning-screen.js";
12
12
  import type { NotesSettings } from "./settings.js";
13
- import { createNotesSettingsControls } from "./settings-controls.js";
13
+ import {
14
+ createNotesSettingsControls,
15
+ type NotesSettingsAction,
16
+ } from "./settings-controls.js";
14
17
 
15
- type ScreenAction = "close" | "prune" | "sessionPruning" | "roles";
18
+ type ScreenAction = NotesSettingsAction | "board";
16
19
 
17
20
  export async function openNotesSettings(
18
21
  ctx: ExtensionContext,
19
22
  options: {
23
+ boardTab?: boolean;
20
24
  settings: () => NotesSettings;
21
25
  settingsPath: string;
22
- save: (settings: NotesSettings) => void;
26
+ save: (settings: NotesSettings) => Promise<void>;
23
27
  status: () => string[];
24
28
  prune: () => Promise<void>;
25
29
  sessionPruning: SessionPruningSettings;
26
30
  },
27
- ): Promise<"roles" | undefined> {
31
+ ): Promise<"roles" | "board" | undefined> {
32
+ let selected = "sessionPruning";
28
33
  while (true) {
29
34
  const action = await ctx.ui.custom<ScreenAction>(
30
35
  (tui, theme, _kb, done) => {
31
36
  const list = createNotesSettingsControls(ctx, options, done, () =>
32
37
  tui.requestRender(),
33
38
  );
39
+ list.selectItem(selected);
34
40
  return {
35
41
  render: (width) => {
36
42
  const wrap = (text: string) =>
@@ -40,7 +46,7 @@ export async function openNotesSettings(
40
46
  const rule = theme.fg("accent", "─".repeat(Math.max(0, width)));
41
47
  return [
42
48
  rule,
43
- ` ${theme.bold("Notes")} / ${theme.fg("dim", "Roles")}`,
49
+ ` ${theme.bold("Notes & Compaction")} / ${theme.fg("dim", options.boardTab === false ? "Roles" : "Board")}`,
44
50
  "",
45
51
  ...options
46
52
  .status()
@@ -69,7 +75,7 @@ export async function openNotesSettings(
69
75
  matchesKey(data, Key.tab) ||
70
76
  matchesKey(data, Key.shift(Key.tab))
71
77
  ) {
72
- done("roles");
78
+ done(options.boardTab === false ? "roles" : "board");
73
79
  return;
74
80
  }
75
81
  list.handleInput(data);
@@ -78,8 +84,20 @@ export async function openNotesSettings(
78
84
  };
79
85
  },
80
86
  );
87
+ if (typeof action === "object") {
88
+ selected = action.selected;
89
+ try {
90
+ await options.save(action.settings);
91
+ } catch (error) {
92
+ ctx.ui.notify(
93
+ `Could not save notes settings: ${String(error)}`,
94
+ "error",
95
+ );
96
+ }
97
+ continue;
98
+ }
81
99
  if (action === "close") return;
82
- if (action === "roles") return "roles";
100
+ if (action === "roles" || action === "board") return action;
83
101
  if (action === "sessionPruning") {
84
102
  await openSessionPruningSettings(ctx, options.sessionPruning);
85
103
  continue;
@@ -1,5 +1,10 @@
1
1
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
- import { dirname } from "node:path";
2
+ import { dirname, join } from "node:path";
3
+ import {
4
+ CONFIG_DIR_NAME,
5
+ type ExtensionContext,
6
+ getAgentDir,
7
+ } from "@earendil-works/pi-coding-agent";
3
8
 
4
9
  // Hour presets store their effective duration, with five minutes of headroom.
5
10
  export const IDLE_MINUTES = [0, 25, 55, 115, 355, 715] as const;
@@ -17,7 +22,7 @@ const DEFAULT_MODEL_WHITELIST = [
17
22
  "gpt-6.1-sol",
18
23
  ];
19
24
  export interface NotesSettings {
20
- active: "all" | "whitelist";
25
+ active: "all" | "whitelist" | "off";
21
26
  modelWhitelist: string[];
22
27
  normalCompaction: boolean;
23
28
  noteSaveMarkers: boolean;
@@ -28,7 +33,32 @@ export interface NotesSettings {
28
33
  taskBoundaryReminder: number;
29
34
  }
30
35
 
31
- export function readSettings(
36
+ export function notesSettingsPath(): string {
37
+ return join(getAgentDir(), "notes-compaction", "settings.json");
38
+ }
39
+
40
+ function legacySettingsPaths(ctx: ExtensionContext): string[] {
41
+ return [
42
+ join(getAgentDir(), "pi-codex-conversion.json"),
43
+ ...(ctx.isProjectTrusted()
44
+ ? [join(ctx.cwd, CONFIG_DIR_NAME, "pi-codex-conversion.json")]
45
+ : []),
46
+ ];
47
+ }
48
+
49
+ export function loadNotesSettings(ctx: ExtensionContext): NotesSettings {
50
+ return readSettings(notesSettingsPath(), legacySettingsPaths(ctx));
51
+ }
52
+
53
+ export function legacyNotesConfigured(ctx: ExtensionContext): boolean {
54
+ const { compaction } = readLegacyPreferences(legacySettingsPaths(ctx));
55
+ return (
56
+ compaction["continuity"] === "notes" ||
57
+ compaction["continuity"] === "notes-and-compaction"
58
+ );
59
+ }
60
+
61
+ function readSettings(
32
62
  path: string,
33
63
  legacyPaths: readonly string[] = [],
34
64
  ): NotesSettings {
@@ -67,9 +97,9 @@ export function readSettings(
67
97
  "Invalid notes settings. Save a setting in /notes, then reload Pi.",
68
98
  );
69
99
  const active = "active" in settings ? settings.active : "all";
70
- if (active !== "all" && active !== "whitelist")
100
+ if (active !== "all" && active !== "whitelist" && active !== "off")
71
101
  throw new Error(
72
- `Invalid active setting in ${path}. Use "all" or "whitelist", then reload Pi.`,
102
+ `Invalid active setting in ${path}. Use "all", "whitelist" or "off", then reload Pi.`,
73
103
  );
74
104
  const modelWhitelist =
75
105
  "modelWhitelist" in settings
@@ -140,7 +170,8 @@ export function modelIsActive(
140
170
  ): boolean {
141
171
  return (
142
172
  settings.active === "all" ||
143
- Boolean(model && settings.modelWhitelist.includes(model.id))
173
+ (settings.active === "whitelist" &&
174
+ Boolean(model && settings.modelWhitelist.includes(model.id)))
144
175
  );
145
176
  }
146
177
 
@@ -1,7 +1,6 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import type { Static } from "typebox";
4
- import { Check } from "typebox/value";
3
+ import { compile, type Static } from "@earendil-works/pi-schema";
5
4
  import {
6
5
  canonicalAgentName,
7
6
  contextAgentNames,
@@ -28,6 +27,12 @@ import type { NotesStore } from "./store.js";
28
27
 
29
28
  export { savedNotesIdentity } from "./saved-sharing-records.js";
30
29
 
30
+ const detachmentValidator = compile(Detachment);
31
+ const memberValidator = compile(Member);
32
+ const parentValidator = compile(Parent);
33
+ const planValidator = compile(Plan);
34
+ const routeValidator = compile(Route);
35
+
31
36
  function records(session: SavedNotesSession, kind: string): unknown[] {
32
37
  return session.entries.flatMap((entry) =>
33
38
  entry.type === "custom" && entry.customType === kind ? [entry.data] : [],
@@ -193,7 +198,7 @@ async function readSharedSession(
193
198
  const routes = new Map<string, Static<typeof Route>>();
194
199
  for (const value of records(session, "shepherdr-attachment-route"))
195
200
  if (
196
- Check(Route, value) &&
201
+ routeValidator.check(value) &&
197
202
  value.plan.controllerSessionId === identity.threadId
198
203
  )
199
204
  routes.set(`${value.machine}\0${value.sessionFile}`, value);
@@ -232,10 +237,11 @@ async function readSharedSession(
232
237
  }
233
238
  const owner = records(session, "shepherdr-attachment-owner").findLast(
234
239
  (value) =>
235
- Check(Plan, value) && value.targetSessionId === identity.threadId,
240
+ planValidator.check(value) &&
241
+ value.targetSessionId === identity.threadId,
236
242
  );
237
243
  if (
238
- Check(Plan, owner) &&
244
+ planValidator.check(owner) &&
239
245
  owner.context &&
240
246
  (inside(destination, owner.context.controllerAlias) ||
241
247
  destination === canonicalAgentName(owner.context.controller.threadId))
@@ -253,9 +259,10 @@ async function readSharedSession(
253
259
  "shepherdr-attachment-detached",
254
260
  ).findLast(
255
261
  (value) =>
256
- Check(Detachment, value) && isDeepStrictEqual(value.plan, owner),
262
+ detachmentValidator.check(value) &&
263
+ isDeepStrictEqual(value.plan, owner),
257
264
  );
258
- const snapshot = Check(Detachment, detached)
265
+ const snapshot = detachmentValidator.check(detached)
259
266
  ? detached.context
260
267
  : undefined;
261
268
  return reference(
@@ -289,15 +296,16 @@ async function readSharedSession(
289
296
  let result: Record<string, unknown> | undefined;
290
297
  const members = records(session, "herdr-context-child").filter(
291
298
  (value) =>
292
- Check(Member, value) &&
299
+ memberValidator.check(value) &&
293
300
  value.threadId === identity.threadId &&
294
301
  value.sessionId === identity.sessionId,
295
302
  );
296
303
  const direct = members.filter(
297
- (member) => Check(Member, member) && member.agentName === destination,
304
+ (member) =>
305
+ memberValidator.check(member) && member.agentName === destination,
298
306
  );
299
307
  for (const member of direct.length ? direct : members) {
300
- if (!Check(Member, member)) continue;
308
+ if (!memberValidator.check(member)) continue;
301
309
  const location = locator(session, member.machine, member.sessionFile);
302
310
  // Only exploratory edges may be skipped. A recorded target must report its failure.
303
311
  const saved = await (direct.length
@@ -312,7 +320,7 @@ async function readSharedSession(
312
320
  contextStorageAgentName(child) !== member.agentName)
313
321
  )
314
322
  throw new Error(
315
- "Saved shared notes belong to a different agent family",
323
+ "This session cannot access the requested saved context. Request an accessible handoff or note path from its owner.",
316
324
  );
317
325
  const candidate = await resolve(saved, destination, query);
318
326
  if (candidate) {
@@ -326,7 +334,7 @@ async function readSharedSession(
326
334
  if (direct.length) return result;
327
335
  const routing = identity.routing;
328
336
  const suffix = ".jsonl.shepherdr-context.json";
329
- if (Check(Parent, routing)) {
337
+ if (parentValidator.check(routing)) {
330
338
  const parentLocator = routing.savedParent
331
339
  ? locator(
332
340
  session,
@@ -401,7 +409,7 @@ async function readSharedSession(
401
409
  )
402
410
  throw Object.assign(
403
411
  new Error(
404
- `Saved shared ${namespace} are unavailable on this machine. Restore access to the saved Pi JSONL session, then retry.`,
412
+ `Saved ${namespace} could not be read on this machine. Request a handoff from the owner, or ask the user to restore access before retrying.`,
405
413
  { cause: error },
406
414
  ),
407
415
  { code: "SAVED_SESSION_UNAVAILABLE" },
@@ -1,5 +1,6 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { Check } from "typebox/value";
2
+ import { compile } from "@earendil-works/pi-schema";
3
+ import { minuteTimestamp } from "../timestamps.js";
3
4
  import { contextStorageAgentName } from "./agent-identity.js";
4
5
  import type { SavedSessionLocator } from "./context-sharing.js";
5
6
  import { useHistory } from "./history.js";
@@ -15,6 +16,8 @@ import {
15
16
  } from "./saved-sharing-records.js";
16
17
  import type { NotesStore } from "./store.js";
17
18
 
19
+ const snapshotValidator = compile(Snapshot);
20
+
18
21
  export function createSharedSessionReader(
19
22
  store: Pick<NotesStore, "read">,
20
23
  access:
@@ -69,16 +72,9 @@ export function createSharedSessionReader(
69
72
  normalizeNoteParams(query, native),
70
73
  outputAgent,
71
74
  )),
72
- ...(namespace === "notes"
73
- ? {
74
- read_only: true,
75
- warning:
76
- "Only saved notes are included; other notes may be missing",
77
- }
78
- : {}),
79
75
  ...(session.savedAt === undefined
80
76
  ? {}
81
- : { saved_at: new Date(session.savedAt).toISOString() }),
77
+ : { saved_at: minuteTimestamp(session.savedAt) }),
82
78
  };
83
79
  }
84
80
  async function reference(
@@ -114,7 +110,7 @@ export function createSharedSessionReader(
114
110
  namespace === "history" ||
115
111
  (destination !== identity.agentName &&
116
112
  destination !== contextStorageAgentName(identity)) ||
117
- !Check(Snapshot, retained)
113
+ !snapshotValidator.check(retained)
118
114
  )
119
115
  return;
120
116
  const entry: SessionEntry = {
@@ -138,7 +134,8 @@ export function createSharedSessionReader(
138
134
  query,
139
135
  destination,
140
136
  )),
141
- captured_at: new Date(retained.timestamp).toISOString(),
137
+ read_only: true,
138
+ captured_at: minuteTimestamp(retained.timestamp),
142
139
  warning: detached
143
140
  ? "Read-only notes captured when sharing ended; later changes are not included"
144
141
  : "The latest notes are unavailable; this read-only copy may be outdated",
@@ -264,7 +264,7 @@ export function registerContextSharingService(
264
264
  if (!savedSessionLoader)
265
265
  throw Object.assign(
266
266
  new Error(
267
- "Saved shared sessions on that machine are unavailable. Resume the shared agent and reconnect its machine, or make its saved Pi JSONL session available locally.",
267
+ "Saved context on that machine is unavailable. Request a handoff from its owner, or ask the user to reconnect the machine before retrying.",
268
268
  ),
269
269
  { code: "SAVED_SESSION_UNAVAILABLE" },
270
270
  );
@@ -1,7 +1,17 @@
1
- import { StringEnum } from "@earendil-works/pi-ai";
2
1
  import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
3
- import { Type } from "typebox";
4
- import { Check } from "typebox/value";
2
+ import {
3
+ bool,
4
+ compile,
5
+ int,
6
+ nul,
7
+ obj,
8
+ oneOf,
9
+ opt,
10
+ type Schema,
11
+ str,
12
+ union,
13
+ type Validator,
14
+ } from "@earendil-works/pi-schema";
5
15
  import type { LookupQuery } from "./bridge.js";
6
16
  import { noteResult } from "./note-result.js";
7
17
  import { internalQueryArguments, normalizeQueryInput } from "./query-input.js";
@@ -29,14 +39,14 @@ export const NOTES_ROUTING_GUIDELINE =
29
39
  export const NEW_CONTEXT_DESCRIPTION =
30
40
  "Start fresh context window. MUST save notes before calling";
31
41
  export const GPT_NEW_CONTEXT_DESCRIPTION = "Save notes→fresh context";
32
- const STRING = Type.Optional(Type.String());
33
- const INTEGER = Type.Optional(Type.Integer({ minimum: 1 }));
34
- const LINE = Type.Optional(Type.Union([Type.Integer(), Type.Null()]));
35
- export const NOTES_SCHEMA = Type.Object(
42
+ const STRING = opt(str());
43
+ const INTEGER = opt(int({ minimum: 1 }));
44
+ const LINE = opt(union([int(), nul()]));
45
+ export const NOTES_SCHEMA = obj(
36
46
  {
37
- action: Type.Optional(StringEnum(NOTES_ACTIONS)),
38
- path: Type.Optional(
39
- Type.Union([Type.String(), Type.Null()], {
47
+ action: opt({ ...oneOf(NOTES_ACTIONS), type: "string" }),
48
+ path: opt(
49
+ union([str(), nul()], {
40
50
  description:
41
51
  "File for read/write/append; prefix for list/search; virtual filesystem, not files in the project",
42
52
  }),
@@ -47,49 +57,52 @@ export const NOTES_SCHEMA = Type.Object(
47
57
  stop_line: LINE,
48
58
  limit: INTEGER,
49
59
  max_matches_per_file: INTEGER,
50
- file_order: Type.Optional(StringEnum(["ascending", "descending"])),
51
- file_order_by: Type.Optional(
52
- StringEnum(["name", "created_at", "updated_at"]),
53
- ),
54
- recent_file_first: Type.Optional(Type.Boolean()),
60
+ file_order: opt({ ...oneOf(["ascending", "descending"]), type: "string" }),
61
+ file_order_by: opt({
62
+ ...oneOf(["name", "created_at", "updated_at"]),
63
+ type: "string",
64
+ }),
65
+ recent_file_first: opt(bool()),
55
66
  },
56
- { additionalProperties: false },
67
+ { open: false },
57
68
  );
58
- const NEW_CONTEXT_SCHEMA = Type.Object(
69
+ const NEW_CONTEXT_SCHEMA = obj(
59
70
  {
60
- role: Type.Optional(
61
- Type.String({
71
+ role: opt(
72
+ str({
62
73
  minLength: 1,
63
74
  description:
64
75
  "Configured model-role ID, not an agent name or handoff text",
65
76
  }),
66
77
  ),
67
78
  },
68
- { additionalProperties: false },
79
+ { open: false },
69
80
  );
70
81
 
82
+ const newContextSchemaValidator = compile(NEW_CONTEXT_SCHEMA);
83
+
71
84
  export function newContextSchema(roleIds: string[]) {
72
- return Type.Object(
73
- roleIds.length ? { role: Type.Optional(StringEnum(roleIds)) } : {},
74
- { additionalProperties: false },
85
+ return obj(
86
+ roleIds.length ? { role: opt({ ...oneOf(roleIds), type: "string" }) } : {},
87
+ { open: false },
75
88
  );
76
89
  }
77
90
 
78
91
  export function prepareNewContextArguments(input: unknown) {
79
92
  const args = input ?? {};
80
- if (!Check(NEW_CONTEXT_SCHEMA, args))
93
+ if (!newContextSchemaValidator.check(args))
81
94
  throw new Error(
82
95
  'Use {} to keep the current model, or {role: "name"} for a configured role.',
83
96
  );
84
97
  return args;
85
98
  }
86
- export const HISTORY_SCHEMA = Type.Object(
99
+ export const HISTORY_SCHEMA = obj(
87
100
  {
88
- action: Type.Optional(StringEnum(HISTORY_ACTIONS)),
89
- agent_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
90
- item_id: Type.Optional(Type.String()),
91
- window_id: Type.Optional(
92
- Type.Union([Type.String(), Type.Null()], {
101
+ action: opt({ ...oneOf(HISTORY_ACTIONS), type: "string" }),
102
+ agent_name: opt(union([str(), nul()])),
103
+ item_id: opt(str()),
104
+ window_id: opt(
105
+ union([str(), nul()], {
93
106
  description: "Required with item_id for read",
94
107
  }),
95
108
  ),
@@ -97,18 +110,21 @@ export const HISTORY_SCHEMA = Type.Object(
97
110
  limit: INTEGER,
98
111
  limit_chars: INTEGER,
99
112
  max_chars_per_item: INTEGER,
100
- offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
101
- recent_first: Type.Optional(Type.Boolean()),
102
- role: Type.Optional(
103
- Type.Union([
104
- StringEnum(["user", "assistant", "tool", "system", "developer"]),
105
- Type.Null(),
113
+ offset_chars: opt(int({ minimum: 0 })),
114
+ recent_first: opt(bool()),
115
+ role: opt(
116
+ union([
117
+ {
118
+ ...oneOf(["user", "assistant", "tool", "system", "developer"]),
119
+ type: "string",
120
+ },
121
+ nul(),
106
122
  ]),
107
123
  ),
108
- tool_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
109
- tool_namespace: Type.Optional(Type.Union([Type.String(), Type.Null()])),
124
+ tool_name: opt(union([str(), nul()])),
125
+ tool_namespace: opt(union([str(), nul()])),
110
126
  },
111
- { additionalProperties: false },
127
+ { open: false },
112
128
  );
113
129
 
114
130
  const FIELDS: Record<string, readonly string[]> = {
@@ -272,25 +288,36 @@ export function queryHelp(
272
288
 
273
289
  export function prepareNotesArguments(args: unknown) {
274
290
  const params = normalizeQueryInput("notes", args);
275
- validateArguments("notes", params, NOTES_SCHEMA);
291
+ validateArguments("notes", params, NOTES_FIELD_VALIDATORS);
276
292
  return params;
277
293
  }
278
294
 
279
295
  export function prepareHistoryArguments(args: unknown) {
280
296
  const params = normalizeQueryInput("history", args);
281
- validateArguments("history", params, HISTORY_SCHEMA);
297
+ validateArguments("history", params, HISTORY_FIELD_VALIDATORS);
282
298
  return params;
283
299
  }
284
300
 
301
+ const NOTES_FIELD_VALIDATORS = fieldValidators(NOTES_SCHEMA);
302
+ const HISTORY_FIELD_VALIDATORS = fieldValidators(HISTORY_SCHEMA);
303
+
304
+ function fieldValidators(schema: Schema): Record<string, Validator> {
305
+ return Object.fromEntries(
306
+ Object.entries(schema["properties"] as Record<string, Schema>).map(
307
+ ([field, property]) => [field, compile(property)],
308
+ ),
309
+ );
310
+ }
311
+
285
312
  function validateArguments(
286
313
  namespace: LookupQuery["namespace"],
287
314
  params: Record<string, unknown>,
288
- schema: import("typebox").TObject,
315
+ validators: Record<string, Validator>,
289
316
  ) {
290
317
  if (!queryHelp(namespace, params)) queryArguments(namespace, params);
291
318
  for (const [field, value] of Object.entries(params)) {
292
- const property = schema.properties[field];
293
- if (!property || !Check(property, value))
319
+ const validator = validators[field];
320
+ if (!validator || !validator.check(value))
294
321
  throw new Error(
295
322
  `Invalid ${namespace} ${field}; use {} for exact arguments`,
296
323
  );