pi-posthorse 0.10.24 → 0.10.26

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.
@@ -0,0 +1,43 @@
1
+ import { presentText, unknownArray } from "./contracts.ts";
2
+
3
+ /** Where a search page stopped: the anchor entry, its rank, its offset, and the search it belongs to. */
4
+ export type HistoryCursor = readonly [id: string, priority: 0 | 1, offset: number, key: string];
5
+
6
+ export function encodeCursor(cursor: HistoryCursor): string {
7
+ return Buffer.from(JSON.stringify(cursor)).toString("base64url");
8
+ }
9
+ export function cursorFor(
10
+ key: string,
11
+ hit: { readonly id: string; readonly priority: 0 | 1 },
12
+ offset: number,
13
+ ): string {
14
+ return encodeCursor([hit.id, hit.priority, offset, key]);
15
+ }
16
+ function cursorOffset(value: unknown, storedKey: unknown, key: string): number {
17
+ if (
18
+ typeof value !== "number" ||
19
+ !Number.isSafeInteger(value) ||
20
+ value < 0 ||
21
+ storedKey !== key
22
+ ) {
23
+ throw new Error("Invalid cursor offset or scope.");
24
+ }
25
+ return value;
26
+ }
27
+ /** A cursor is anonymous unless it decodes to the same query and scope that produced it. */
28
+ export function decodeCursor(encoded: string | undefined, key: string): HistoryCursor | undefined {
29
+ const cursor = presentText(encoded);
30
+ if (cursor === undefined) {
31
+ return undefined;
32
+ }
33
+ const value: unknown = JSON.parse(Buffer.from(cursor, "base64url").toString());
34
+ const parts = unknownArray(value);
35
+ if (parts === undefined || parts.length !== 4) {
36
+ throw new Error("Invalid cursor tuple.");
37
+ }
38
+ const [id, priority, offset, storedKey] = parts;
39
+ if (typeof id !== "string" || id === "" || (priority !== 0 && priority !== 1)) {
40
+ throw new Error("Invalid cursor anchor.");
41
+ }
42
+ return [id, priority, cursorOffset(offset, storedKey, key), key];
43
+ }
@@ -1,5 +1,4 @@
1
1
  import {
2
- isRecord,
3
2
  isReminderType,
4
3
  unknownArray,
5
4
  type EntryLike,
@@ -7,6 +6,7 @@ import {
7
6
  type MessageLike,
8
7
  type WindowedEntry,
9
8
  } from "./contracts.ts";
9
+ import { isWindow } from "./boundary.ts";
10
10
  import {
11
11
  assistantFailure,
12
12
  excerptAround,
@@ -20,32 +20,6 @@ import {
20
20
  toolIdentity,
21
21
  } from "./message-text.ts";
22
22
 
23
- export function isWindow(entry: EntryLike): boolean {
24
- return (
25
- entry.type === "context_window" ||
26
- (entry.type === "compaction" && isRecord(entry.details) && entry.details.posthorse === 1)
27
- );
28
- }
29
- export function windowHandoff(entry: EntryLike | undefined): string | undefined {
30
- return entry?.type === "compaction" ? entry.summary : entry?.handoff;
31
- }
32
- /** First active branch entry, including tails retained by Pi's own /compact. */
33
- export function contextStart(entries: readonly EntryLike[]): {
34
- start: number;
35
- boundary?: EntryLike;
36
- } {
37
- for (let i = entries.length - 1; i >= 0; i--) {
38
- const entry = entries[i];
39
- if (entry?.type === "context_window") {
40
- return { start: i + 1, boundary: entry };
41
- }
42
- if (entry?.type === "compaction") {
43
- const kept = entries.findIndex((candidate) => candidate.id === entry.firstKeptEntryId);
44
- return { start: kept >= 0 ? kept : i + 1, boundary: entry };
45
- }
46
- }
47
- return { start: 0 };
48
- }
49
23
  export function contextEdits(entries: readonly EntryLike[]): Map<string, EntryLike> {
50
24
  return new Map(
51
25
  entries.flatMap((entry) =>
@@ -7,6 +7,7 @@ import {
7
7
  type WindowedEntry,
8
8
  } from "./contracts.ts";
9
9
  import { excerpt, shortKey, sourceTag } from "./message-text.ts";
10
+ import { cursorFor as cursorAt } from "./history-cursor.ts";
10
11
  import type { HistoryMatches, HistoryParams } from "./history-search.ts";
11
12
  import type { PageAccess } from "./paging.ts";
12
13
 
@@ -18,11 +19,6 @@ type SearchPage = {
18
19
  readonly spans: readonly { readonly headerLength: number; readonly length: number }[];
19
20
  readonly continuation: Continuation<string>;
20
21
  };
21
- function cursorFor(matches: HistoryMatches, hit: HistoryHit, offset: number): string {
22
- return Buffer.from(JSON.stringify([hit.id, hit.priority, offset, matches.key])).toString(
23
- "base64url",
24
- );
25
- }
26
22
  function searchFooter(next: string): string {
27
23
  return `\n[More results; continue with cursor "${next}" and the same query/scope.]`;
28
24
  }
@@ -70,7 +66,7 @@ function searchParts(matches: HistoryMatches, chars: number): SearchPage {
70
66
  available -= fragment.part.length + 1;
71
67
  continuation =
72
68
  fragment.end < hit.text.length || parts.length < matches.hits.length
73
- ? { kind: "more", next: cursorFor(matches, hit, fragment.end) }
69
+ ? { kind: "more", next: cursorAt(matches.key, hit, fragment.end) }
74
70
  : { kind: "complete" };
75
71
  if (available <= 0 || parts.length >= matches.limit) {
76
72
  break;
@@ -87,7 +83,9 @@ export function searchPage(
87
83
  const chars = pages.size(host);
88
84
  const reserve = Math.max(
89
85
  0,
90
- ...matches.hits.map((hit) => searchFooter(cursorFor(matches, hit, hit.text.length)).length),
86
+ ...matches.hits.map(
87
+ (hit) => searchFooter(cursorAt(matches.key, hit, hit.text.length)).length,
88
+ ),
91
89
  );
92
90
  if (reserve >= chars) {
93
91
  pages.error(host, "History entry id is too large for pagination.");
@@ -3,11 +3,11 @@ import type { LineMatcher } from "./session-lines.ts";
3
3
  import {
4
4
  isReminderType,
5
5
  requireValue,
6
- unknownArray,
7
6
  type EntryLike,
8
7
  type HistoryHit,
9
8
  type ProjectedEntry,
10
9
  } from "./contracts.ts";
10
+ import { decodeCursor, type HistoryCursor } from "./history-cursor.ts";
11
11
  import { historyHit, seenText, reverseWindowEntries } from "./history-entries.ts";
12
12
  import { shortKey } from "./message-text.ts";
13
13
  import {
@@ -34,7 +34,6 @@ export type HistorySource = {
34
34
  readonly branch: () => readonly EntryLike[];
35
35
  readonly projection: () => readonly ProjectedEntry[];
36
36
  };
37
- export type HistoryCursor = readonly [id: string, priority: 0 | 1, offset: number, key: string];
38
37
  export type HistoryMatches = {
39
38
  readonly hits: readonly HistoryHit[];
40
39
  readonly skipped: number;
@@ -42,32 +41,6 @@ export type HistoryMatches = {
42
41
  readonly key: string;
43
42
  readonly limit: number;
44
43
  };
45
- function cursorOffset(value: unknown, storedKey: unknown, key: string): number {
46
- if (
47
- typeof value !== "number" ||
48
- !Number.isSafeInteger(value) ||
49
- value < 0 ||
50
- storedKey !== key
51
- ) {
52
- throw new Error("Invalid cursor offset or scope.");
53
- }
54
- return value;
55
- }
56
- function decodeCursor(encoded: string | undefined, key: string): HistoryCursor | undefined {
57
- if (encoded === undefined || encoded === "") {
58
- return undefined;
59
- }
60
- const value: unknown = JSON.parse(Buffer.from(encoded, "base64url").toString());
61
- const parts = unknownArray(value);
62
- if (parts === undefined || parts.length !== 4) {
63
- throw new Error("Invalid cursor tuple.");
64
- }
65
- const [id, priority, offset, storedKey] = parts;
66
- if (typeof id !== "string" || id === "" || (priority !== 0 && priority !== 1)) {
67
- throw new Error("Invalid cursor anchor.");
68
- }
69
- return [id, priority, cursorOffset(offset, storedKey, key), key];
70
- }
71
44
  function entryMessage(entry: EntryLike) {
72
45
  switch (entry.type) {
73
46
  case "message":
@@ -109,15 +82,20 @@ function contextVisibility(project: HistorySource["projection"]): (entry: EntryL
109
82
  };
110
83
  }
111
84
  type SearchProgress = {
112
- readonly cursor?: HistoryCursor | undefined;
113
85
  readonly limit: number;
114
86
  readonly add: (hit: HistoryHit) => void;
115
87
  readonly seeking: (priority: 0 | 1) => boolean;
116
88
  readonly enough: () => boolean;
89
+ readonly fileFeed: () => FileFeed;
117
90
  };
118
91
  type CursorProgress =
119
92
  | { readonly kind: "seeking"; readonly cursor: HistoryCursor }
120
93
  | { readonly kind: "collecting"; readonly cursor?: HistoryCursor };
94
+ /** One archive file's newest-first hits: a bounded window per rank, closing at the seek anchor. */
95
+ export type FileFeed = {
96
+ readonly add: (hit: HistoryHit) => void;
97
+ readonly finish: () => readonly (readonly HistoryHit[])[];
98
+ };
121
99
  /** Owns ranking, lookahead and one cursor's progress; never holds the whole archive. */
122
100
  class SearchAccumulator {
123
101
  readonly groups: [HistoryHit[], HistoryHit[]] = [[], []];
@@ -170,36 +148,37 @@ class SearchAccumulator {
170
148
  }
171
149
  return this.groups.flat();
172
150
  }
173
- }
174
- function archiveCollector(accumulator: SearchProgress): {
175
- readonly add: (hit: HistoryHit) => void;
176
- readonly finish: () => readonly (readonly HistoryHit[])[];
177
- } {
178
- const recent: [HistoryHit[], HistoryHit[]] = [[], []];
179
- let anchorHere = false;
180
- return {
181
- add: (hit) => {
182
- const seeking = accumulator.seeking(hit.priority);
183
- if (seeking && anchorHere) {
184
- return;
185
- }
186
- if (seeking && hit.id === accumulator.cursor?.[0]) {
187
- anchorHere = true;
188
- }
189
- const group = recent[hit.priority];
190
- group.push(hit);
191
- if (group.length > accumulator.limit + 2) {
192
- group.shift();
193
- }
194
- },
195
- finish: () => {
196
- const cursor = accumulator.cursor;
197
- if (cursor !== undefined && accumulator.seeking(cursor[1]) && !anchorHere) {
198
- recent[cursor[1]] = [];
199
- }
200
- return recent;
201
- },
202
- };
151
+ /**
152
+ * A file may hold the anchor. Its window keeps two extra hits, and a file that never reaches
153
+ * the anchor contributes nothing to the rank being sought.
154
+ */
155
+ fileFeed(): FileFeed {
156
+ const recent: [HistoryHit[], HistoryHit[]] = [[], []];
157
+ let anchorHere = false;
158
+ return {
159
+ add: (hit) => {
160
+ const seeking = this.seeking(hit.priority);
161
+ if (seeking && anchorHere) {
162
+ return;
163
+ }
164
+ if (seeking && hit.id === this.cursor?.[0]) {
165
+ anchorHere = true;
166
+ }
167
+ const group = recent[hit.priority];
168
+ group.push(hit);
169
+ if (group.length > this.limit + 2) {
170
+ group.shift();
171
+ }
172
+ },
173
+ finish: () => {
174
+ const cursor = this.cursor;
175
+ if (cursor !== undefined && this.seeking(cursor[1]) && !anchorHere) {
176
+ recent[cursor[1]] = [];
177
+ }
178
+ return recent;
179
+ },
180
+ };
181
+ }
203
182
  }
204
183
  async function scanArchive(
205
184
  file: string,
@@ -212,7 +191,7 @@ async function scanArchive(
212
191
  },
213
192
  accumulator: SearchProgress,
214
193
  ): Promise<{ readonly groups: readonly (readonly HistoryHit[])[]; readonly skipped: number }> {
215
- const collector = archiveCollector(accumulator);
194
+ const collector = accumulator.fileFeed();
216
195
  let skipped = 0;
217
196
  for await (const item of sessionWindowEntries(
218
197
  file,
package/src/host.ts ADDED
@@ -0,0 +1,78 @@
1
+ import type { EntryLike, ProjectedEntry } from "./contracts.ts";
2
+
3
+ /** Only the session-manager members Posthorse reads; a host may omit any of them. */
4
+ export type SessionHost = {
5
+ readonly getEntry?: (id: string) => EntryLike | undefined;
6
+ readonly getSessionId?: () => string;
7
+ readonly getSessionFile?: () => string | undefined;
8
+ readonly getLeafId?: () => string | null;
9
+ readonly getBranch?: (fromId?: string) => readonly EntryLike[];
10
+ readonly buildSessionProjection?: () => { readonly entries: readonly ProjectedEntry[] };
11
+ };
12
+ /** Only the registry members Posthorse reads. */
13
+ export type ToolInfo = {
14
+ readonly name: string;
15
+ readonly namespace?: unknown;
16
+ readonly description?: unknown;
17
+ readonly parameters?: unknown;
18
+ };
19
+ export type ToolRegistry = {
20
+ readonly getActiveTools: () => readonly string[];
21
+ readonly getAllTools: () => readonly ToolInfo[];
22
+ };
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
+ export type SessionIdentity = {
26
+ readonly sessionId: string;
27
+ readonly file: string | undefined;
28
+ readonly leaf: EntryLike | undefined;
29
+ };
30
+
31
+ /** A host that omits a member reports no data for it instead of failing the caller. */
32
+ export function sessionEntry(
33
+ manager: SessionHost,
34
+ id: string | null | undefined,
35
+ ): EntryLike | undefined {
36
+ return id === undefined || id === null || id === "" || manager.getEntry === undefined
37
+ ? undefined
38
+ : manager.getEntry(id);
39
+ }
40
+ export function sessionIdentity(manager: SessionHost): SessionIdentity {
41
+ return {
42
+ sessionId: manager.getSessionId?.() ?? "",
43
+ file: manager.getSessionFile?.(),
44
+ leaf: sessionEntry(manager, manager.getLeafId?.() ?? null),
45
+ };
46
+ }
47
+ export function sessionBranch(manager: SessionHost): readonly EntryLike[] | undefined {
48
+ return manager.getBranch?.();
49
+ }
50
+ export function sessionProjection(manager: SessionHost): readonly ProjectedEntry[] | undefined {
51
+ return manager.buildSessionProjection?.().entries;
52
+ }
53
+
54
+ export type ToolFacts = {
55
+ readonly active: ReadonlySet<string>;
56
+ /** Registered names an active tool can carry without a namespace. */
57
+ readonly unnamespaced: ReadonlySet<string>;
58
+ readonly activeUnnamespaced: ReadonlySet<string>;
59
+ /** The one registry read both sets were derived from. */
60
+ readonly tools: readonly ToolInfo[];
61
+ };
62
+ /** Active tools share names with namespaced registrations, so capabilities read the intersected set. */
63
+ export function toolFacts(pi: ToolRegistry): ToolFacts {
64
+ const tools = pi.getAllTools();
65
+ const active = new Set(pi.getActiveTools());
66
+ const unnamespaced = new Set(
67
+ tools.filter((tool) => tool.namespace === undefined).map((tool) => tool.name),
68
+ );
69
+ return {
70
+ active,
71
+ unnamespaced,
72
+ activeUnnamespaced: new Set([...active].filter((name) => unnamespaced.has(name))),
73
+ tools,
74
+ };
75
+ }
76
+ export function ownerQuestionRegistered(pi: ToolRegistry): boolean {
77
+ return toolFacts(pi).unnamespaced.has(OWNER_QUESTION_TOOL);
78
+ }
@@ -1,6 +1,7 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
- import { join, relative } from "node:path";
2
+ import { basename, join, relative } from "node:path";
3
3
  import { isRecord } from "./contracts.ts";
4
+ import { isPublicationTemporaryName } from "./files.ts";
4
5
  import { sessionNoteTouches } from "./note-evidence.ts";
5
6
  import { notesUnder, type NoteFile } from "./note-inventory.ts";
6
7
  import {
@@ -118,8 +119,11 @@ async function readReference(
118
119
  path: string,
119
120
  signal: AbortSignal | undefined,
120
121
  ): Promise<DiscoveredNote | undefined> {
121
- const target = await session.read(path, { signal });
122
- if (target.writable) {
122
+ if (isPublicationTemporaryName(basename(path))) {
123
+ return;
124
+ }
125
+ const target = await session.access(path, { signal });
126
+ if (target.kind === "own") {
123
127
  return;
124
128
  }
125
129
  const info = await stat(target.path).catch((error: unknown) => {
@@ -248,10 +252,9 @@ export class NoteDiscovery {
248
252
  const paths = new Set(touches.map((touch) => touch.notePath));
249
253
  const candidates = [...paths].filter(
250
254
  (path) =>
251
- !session.owns(path) &&
252
- (options.path === undefined ||
253
- path === options.path ||
254
- path.startsWith(`${options.path}/`)),
255
+ options.path === undefined ||
256
+ path === options.path ||
257
+ path.startsWith(`${options.path}/`),
255
258
  );
256
259
  const resolved = await mapBatch(candidates, (path) =>
257
260
  readReference(session, path, options.signal),
@@ -76,8 +76,11 @@ async function prepareOperation(operation: NoteOperation, captured: CapturedCall
76
76
  if (address === undefined || !sameScope(address, session.binding)) {
77
77
  return;
78
78
  }
79
- if (existingEdit(tool, operation) && !session.owns(address.path)) {
80
- await withFileMutationQueue(path, () => session.adopt(address.path, call));
79
+ if (existingEdit(tool, operation)) {
80
+ const access = await session.access(address.path, { includeDirectories: false });
81
+ if (access.kind === "inherited") {
82
+ await withFileMutationQueue(path, () => session.adopt(address.path, call));
83
+ }
81
84
  }
82
85
  await session.prepareWrite();
83
86
  }
@@ -1,6 +1,7 @@
1
1
  import { readdir, realpath, stat } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { isRecord } from "./contracts.ts";
2
+ import { basename, join } from "node:path";
3
+ import { isRecord, presentText } from "./contracts.ts";
4
+ import { isPublicationTemporaryName } from "./files.ts";
4
5
  import {
5
6
  canonicalPath,
6
7
  inside,
@@ -26,7 +27,9 @@ async function statIfPresent(path: string) {
26
27
  }
27
28
  /** Preserve depth-first listing order and recheck later entries after visiting each folder. */
28
29
  async function* folderEntries(directory: string, signal: AbortSignal | undefined) {
29
- const entries = await readdir(directory, { withFileTypes: true });
30
+ const entries = (await readdir(directory, { withFileTypes: true })).filter(
31
+ (entry) => !isPublicationTemporaryName(entry.name),
32
+ );
30
33
  let start = 0;
31
34
  while (start < entries.length) {
32
35
  signal?.throwIfAborted();
@@ -94,10 +97,14 @@ export async function notesUnder(
94
97
  folder: string | undefined,
95
98
  options: { readonly signal: AbortSignal | undefined; readonly notice: (text: string) => void },
96
99
  ): Promise<NoteFile[]> {
100
+ const requested = presentText(folder);
97
101
  const target =
98
- folder === undefined || folder === "" || folder === "."
102
+ requested === undefined || requested === "."
99
103
  ? scopeDirectory(scope)
100
- : notePath(scope, folder);
104
+ : notePath(scope, requested);
105
+ if (isPublicationTemporaryName(basename(target))) {
106
+ return [];
107
+ }
101
108
  const info = await statIfPresent(target);
102
109
  options.signal?.throwIfAborted();
103
110
  if (info === undefined) {
package/src/note-store.ts CHANGED
@@ -32,15 +32,19 @@ import {
32
32
  import type { NotesRecovery } from "./note-evidence.ts";
33
33
 
34
34
  type NotesManager = ExtensionContext["sessionManager"];
35
+ /** The journal member the notes store borrows; the host's full API satisfies this. */
36
+ type NotesApi = Pick<ExtensionAPI, "appendEntry">;
35
37
  export type NoteCall = { readonly id: string; readonly rootId: string };
36
- type Adoption = "owned" | "unavailable" | "adopted";
37
- export type NoteRead = {
38
- readonly address: NoteAddress;
39
- readonly path: string;
40
- readonly writable: boolean;
41
- };
38
+ type Adoption = "owned" | "adopted";
39
+ /**
40
+ * One note path as this session may use it: a private copy it can write (own scope, whether or not
41
+ * the file exists yet), or an inherited file it reads in place and copies on first edit.
42
+ */
43
+ export type NoteAccess =
44
+ | { readonly kind: "own"; readonly address: NoteAddress; readonly path: string }
45
+ | { readonly kind: "inherited"; readonly address: NoteAddress; readonly path: string };
42
46
  export class SessionNotes {
43
- readonly #pi: ExtensionAPI;
47
+ readonly #pi: NotesApi;
44
48
  readonly binding: NoteBinding;
45
49
  readonly #manager: NotesManager;
46
50
  readonly #source: NoteSource;
@@ -48,7 +52,7 @@ export class SessionNotes {
48
52
  readonly scopes: readonly NoteScope[];
49
53
  readonly #calls = new Map<string, string>();
50
54
  readonly #revisions = new Map<string, number>();
51
- constructor(pi: ExtensionAPI, binding: NoteBinding, manager: NotesManager, source: NoteSource) {
55
+ constructor(pi: NotesApi, binding: NoteBinding, manager: NotesManager, source: NoteSource) {
52
56
  this.#pi = pi;
53
57
  this.binding = binding;
54
58
  this.#manager = manager;
@@ -87,7 +91,8 @@ export class SessionNotes {
87
91
  call(id: string): NoteCall {
88
92
  return { id, rootId: this.#calls.get(id) ?? id };
89
93
  }
90
- owns(path: string): boolean {
94
+ /** A project session owns its whole scope; a fork owns recorded paths and files it already has. */
95
+ #ownsPath(path: string): boolean {
91
96
  return (
92
97
  this.binding.kind === "project" ||
93
98
  this.#owned.has(path) ||
@@ -153,45 +158,53 @@ export class SessionNotes {
153
158
  includeDirectories: options.includeDirectories,
154
159
  });
155
160
  }
156
- async read(
161
+ async access(
157
162
  path: string,
158
163
  options: {
159
164
  readonly scope?: string | undefined;
165
+ readonly includeDirectories?: boolean | undefined;
160
166
  readonly signal?: AbortSignal | undefined;
161
167
  } = {},
162
- ): Promise<NoteRead> {
168
+ ): Promise<NoteAccess> {
163
169
  if (options.scope !== undefined) {
164
170
  const relative = noteRelative(path);
165
171
  const scope = await this.selectScope(options.scope);
166
172
  return {
173
+ kind: sameScope(scope, this.binding) ? "own" : "inherited",
167
174
  address: addressIn(scope, relative),
168
175
  path: notePath(scope, relative),
169
- writable: sameScope(scope, this.binding),
170
176
  };
171
177
  }
172
178
  const relative = scopeNoteRelative(this.binding, path);
173
- const reference = this.owns(relative)
174
- ? undefined
175
- : await this.#reference(relative, {
176
- includeDirectories: true,
177
- signal: options.signal,
178
- });
179
- const address = reference ?? addressIn(this.binding, relative);
180
- return { address, path: notePath(address, relative), writable: reference === undefined };
179
+ if (this.#ownsPath(relative)) {
180
+ return {
181
+ kind: "own",
182
+ address: addressIn(this.binding, relative),
183
+ path: notePath(this.binding, relative),
184
+ };
185
+ }
186
+ const reference = await this.#reference(relative, {
187
+ includeDirectories: options.includeDirectories,
188
+ signal: options.signal,
189
+ });
190
+ return reference === undefined
191
+ ? {
192
+ kind: "own",
193
+ address: addressIn(this.binding, relative),
194
+ path: notePath(this.binding, relative),
195
+ }
196
+ : { kind: "inherited", address: reference, path: notePath(reference, relative) };
181
197
  }
182
198
  async adopt(path: string, call: NoteCall): Promise<Adoption> {
183
199
  const relative = noteRelative(path);
184
- if (this.owns(relative)) {
200
+ const access = await this.access(relative, { includeDirectories: false });
201
+ if (access.kind === "own") {
185
202
  return "owned";
186
203
  }
187
- const source = await this.#reference(relative);
188
- if (source === undefined) {
189
- return "unavailable";
190
- }
191
204
  const result = await adoptNote(this.binding, {
192
205
  path: relative,
193
- source,
194
- lineage: source,
206
+ source: access.address,
207
+ lineage: access.address,
195
208
  anchors: [],
196
209
  });
197
210
  this.record(
@@ -240,8 +253,9 @@ export type NotesStore = {
240
253
  type SessionState =
241
254
  | { readonly kind: "initializing"; readonly value: Promise<SessionNotes> }
242
255
  | { readonly kind: "ready"; readonly value: SessionNotes };
243
- export function createNotesStore(pi: ExtensionAPI): NotesStore {
256
+ export function createNotesStore(pi: NotesApi): NotesStore {
244
257
  const sessions = new Map<string, SessionState>();
258
+
245
259
  const get = (ctx: ExtensionContext): Promise<SessionNotes> => {
246
260
  const key = sessionKey(ctx);
247
261
  const existing = sessions.get(key);
package/src/notes.ts CHANGED
@@ -11,6 +11,11 @@ import { Type } from "typebox";
11
11
  import { toolCards } from "../ui.ts";
12
12
  import {
13
13
  MAX_PAGE_CHARS,
14
+ noteAppendReceipt,
15
+ noteReadHeader,
16
+ noteWriteReceipt,
17
+ notesDirectoryHeader,
18
+ presentText,
14
19
  requireValue,
15
20
  textResult,
16
21
  type PolicyContext,
@@ -54,7 +59,7 @@ async function listNotes(
54
59
  access: NotesAccess,
55
60
  ): Promise<TextResult> {
56
61
  const { host, pages, signal } = access;
57
- const folder = params.path;
62
+ const folder = presentText(params.path);
58
63
  const [inventory, selectedScope] = await Promise.all([
59
64
  access.discovery.list(session, {
60
65
  path: folder,
@@ -82,8 +87,8 @@ async function listNotes(
82
87
  rows,
83
88
  offset: params.offset ?? 0,
84
89
  kind: "notes-list",
85
- empty: folder === undefined || folder === "" ? "(no notes yet)" : `(no notes in ${folder})`,
86
- header: `Notes directory: ${dir}\n`,
90
+ empty: folder === undefined ? "(no notes yet)" : `(no notes in ${folder})`,
91
+ header: notesDirectoryHeader(dir),
87
92
  });
88
93
  }
89
94
  async function readNote(
@@ -93,7 +98,11 @@ async function readNote(
93
98
  ): Promise<TextResult> {
94
99
  const { pages } = access;
95
100
  const requested = requireValue(params.path, "path", params.op);
96
- const target = await session.read(requested, { scope: params.scope, signal: access.signal });
101
+ const target = await session.access(requested, {
102
+ scope: params.scope,
103
+ includeDirectories: true,
104
+ signal: access.signal,
105
+ });
97
106
  const relative = target.address.path;
98
107
  const path = target.path;
99
108
  const info = statSync(path, { throwIfNoEntry: false });
@@ -117,9 +126,10 @@ async function readNote(
117
126
  if (offset > 0 && offset >= text.length) {
118
127
  throw new Error(`Offset ${offset} is past the end of ${relative} (${text.length} chars).`);
119
128
  }
120
- const header = target.writable
121
- ? `File: ${path}\n`
122
- : `Read-only live reference: notes read ${JSON.stringify({ scope: scopeDirectory(target.address), path: target.address.path })}\n`;
129
+ const header =
130
+ target.kind === "own"
131
+ ? noteReadHeader(path)
132
+ : `Read-only live reference: notes read ${JSON.stringify({ scope: scopeDirectory(target.address), path: target.address.path })}\n`;
123
133
  const end = Math.min(
124
134
  text.length,
125
135
  offset + pages.size(access.host(), { headerChars: header.length }),
@@ -164,7 +174,7 @@ async function writeNote(
164
174
  access.call,
165
175
  );
166
176
  });
167
- return textResult(`Wrote ${path}`, [], { kind: "note-write" });
177
+ return textResult(noteWriteReceipt(path), [], { kind: "note-write" });
168
178
  }
169
179
  async function appendNote(
170
180
  session: SessionNotes,
@@ -197,7 +207,7 @@ async function appendNote(
197
207
  access.call,
198
208
  );
199
209
  });
200
- return textResult(`Appended to ${path}`, [], { kind: "note-append" });
210
+ return textResult(noteAppendReceipt(path), [], { kind: "note-append" });
201
211
  }
202
212
  /** One note's matching lines as `path:line: excerpt` rows. */
203
213
  function matchingLines(name: string, text: string, query: string): string[] {
@@ -283,10 +293,9 @@ async function searchNotes(
283
293
  header: hits.skipped > 0 ? `[Not searched: ${skipped} over 1 MiB.]\n` : "",
284
294
  });
285
295
  }
286
- /** Some models send every optional argument; an empty scope means no scope. */
287
296
  function withoutEmptyScope(params: NotesParams): NotesParams {
288
297
  const { scope, ...unscoped } = params;
289
- return scope === "" ? unscoped : params;
298
+ return presentText(scope) === undefined ? unscoped : params;
290
299
  }
291
300
  const notesParameters = Type.Object({
292
301
  op: Type.Union(