@howaboua/pi-agent-comms 0.0.1 → 0.0.3

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 (47) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/dist/viewer/web/app.js +6 -6
  4. package/dist/viewer/web/render.js +2 -2
  5. package/docs/BOARD.md +1 -1
  6. package/docs/NOTES.md +19 -2
  7. package/package.json +75 -74
  8. package/src/board/activity.ts +1 -0
  9. package/src/board/briefing.ts +2 -2
  10. package/src/board/delivery.ts +8 -6
  11. package/src/board/runtime/activation.ts +2 -3
  12. package/src/board/runtime/catchup.ts +1 -1
  13. package/src/board/settings/panel.ts +11 -8
  14. package/src/board/viewer/web/app.js +6 -6
  15. package/src/board/viewer/web/render.js +2 -2
  16. package/src/guidance.ts +14 -14
  17. package/src/notes/AGENTS.md +3 -3
  18. package/src/notes/activation.ts +1 -0
  19. package/src/notes/bridge.ts +4 -2
  20. package/src/notes/context-owner.ts +5 -5
  21. package/src/notes/feature.ts +67 -1
  22. package/src/notes/fresh-notes.ts +46 -5
  23. package/src/notes/history-search-pruning.mjs +110 -76
  24. package/src/notes/history-search-worker.mjs +1 -1
  25. package/src/notes/history-windows.ts +1 -1
  26. package/src/notes/index.ts +9 -3
  27. package/src/notes/integrations.ts +83 -45
  28. package/src/notes/lifecycle.ts +11 -2
  29. package/src/notes/model-roles.ts +2 -2
  30. package/src/notes/notes-lookup.ts +1 -1
  31. package/src/notes/rollover.ts +34 -5
  32. package/src/notes/session-pruning-cleanup.mjs +164 -0
  33. package/src/notes/session-pruning-exit.mjs +312 -0
  34. package/src/notes/session-pruning-screen.ts +1 -1
  35. package/src/notes/session-pruning-sparse.mjs +133 -0
  36. package/src/notes/session-pruning-state.mjs +123 -0
  37. package/src/notes/session-pruning-transaction.ts +1 -0
  38. package/src/notes/session-pruning.ts +34 -1
  39. package/src/notes/settings-controls.ts +23 -17
  40. package/src/notes/settings-screen.ts +2 -6
  41. package/src/notes/settings.ts +13 -6
  42. package/src/notes/shared-notes.ts +52 -30
  43. package/src/notes/tool-contracts.ts +24 -5
  44. package/src/notes/tools.ts +51 -29
  45. package/src/notes/tree-checkpoint.ts +12 -13
  46. package/src/notes/window-message.ts +6 -18
  47. package/src/notes/windows.ts +10 -11
@@ -0,0 +1,133 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ import {
4
+ isTreeArchiveManifestData,
5
+ TREE_ARCHIVE_ENTRY_TYPE,
6
+ } from "./tree-archive-manifest.mjs";
7
+
8
+ /** @typedef {import("@earendil-works/pi-coding-agent").SessionEntry} SessionEntry */
9
+ /** @typedef {import("@earendil-works/pi-coding-agent").SessionHeader & {notesPruning?:{version:number;sessionId:string;generation:string}}} Header */
10
+
11
+ /** A finite complete source, never a live SessionManager.
12
+ * @param {string} path @param {number} size
13
+ * @param {(entry:SessionEntry|Header, raw:string)=>void|Promise<void>} visit
14
+ */
15
+ export async function scanSparseSource(path, size, visit) {
16
+ if (!size) throw new Error("Session file is empty.");
17
+ const input = createReadStream(path, { start: 0, end: size - 1 });
18
+ const lines = createInterface({ input, crlfDelay: Infinity });
19
+ let bytes = 0;
20
+ try {
21
+ for await (const raw of lines) {
22
+ bytes += Buffer.byteLength(raw) + 1;
23
+ const entry = JSON.parse(raw);
24
+ if (
25
+ !entry ||
26
+ typeof entry.id !== "string" ||
27
+ typeof entry.timestamp !== "string" ||
28
+ typeof entry.type !== "string" ||
29
+ (entry.type !== "session" &&
30
+ entry.parentId !== null &&
31
+ typeof entry.parentId !== "string")
32
+ )
33
+ throw new Error("Session contains an invalid record.");
34
+ await visit(entry, raw);
35
+ }
36
+ if (bytes !== size)
37
+ throw new Error("Session requires complete LF-delimited records.");
38
+ } finally {
39
+ lines.close();
40
+ input.destroy();
41
+ }
42
+ }
43
+
44
+ /** Remove only existing retired tombstones; retention/content decisions stay with
45
+ * live Notes pruning. Keep navigation anchors and supported structured references.
46
+ * @param {string} path @param {number} size
47
+ */
48
+ export async function planSparsePruning(path, size) {
49
+ /** @type {Map<string,string|null>} */
50
+ const parents = new Map();
51
+ /** @type {Map<string,number>} */
52
+ const children = new Map();
53
+ const removed = new Set();
54
+ const anchors = new Set();
55
+ /** @type {Header|undefined} */
56
+ let header;
57
+ let last;
58
+ await scanSparseSource(path, size, (entry) => {
59
+ if (entry.type === "session") {
60
+ if (header || parents.size || entry.version !== 3)
61
+ throw new Error("Session requires a single version 3 header first.");
62
+ header = entry;
63
+ return;
64
+ }
65
+ if (
66
+ !header ||
67
+ parents.has(entry.id) ||
68
+ (entry.parentId !== null && !parents.has(entry.parentId))
69
+ )
70
+ throw new Error(
71
+ "Session has duplicate IDs or invalid source-order ancestry.",
72
+ );
73
+ last = entry.id;
74
+ parents.set(entry.id, entry.parentId);
75
+ if (entry.parentId === null) anchors.add(entry.id);
76
+ else children.set(entry.parentId, (children.get(entry.parentId) ?? 0) + 1);
77
+ if (
78
+ entry.type === "custom" &&
79
+ entry.customType === "notes-compaction:pruned:v1"
80
+ )
81
+ removed.add(entry.id);
82
+ for (const id of references(entry)) anchors.add(id);
83
+ });
84
+ if (!header) throw new Error("Session header is missing.");
85
+ const marker = header.notesPruning;
86
+ if (
87
+ marker !== undefined &&
88
+ (!marker ||
89
+ marker.version !== 1 ||
90
+ marker.sessionId !== header.id ||
91
+ typeof marker.generation !== "string")
92
+ )
93
+ throw new Error(
94
+ "The saved session has an invalid pruning generation. Session cleanup was skipped.",
95
+ );
96
+ if (last) anchors.add(last);
97
+ for (const id of parents.keys()) {
98
+ if (children.get(id) !== 1) anchors.add(id);
99
+ }
100
+ for (const id of anchors) removed.delete(id);
101
+ /** @type {Map<string,string|null>} */
102
+ const nearest = new Map();
103
+ for (const [id, parent] of parents) {
104
+ // Source-order ancestry makes this a linear pass, including long chains.
105
+ const ancestor = parent === null ? null : (nearest.get(parent) ?? null);
106
+ nearest.set(id, removed.has(id) ? ancestor : id);
107
+ parents.set(id, ancestor);
108
+ }
109
+ return { removed, parents, header };
110
+ }
111
+
112
+ /** @param {SessionEntry} entry @returns {string[]} */
113
+ function references(entry) {
114
+ if (entry.type === "compaction") return [entry.firstKeptEntryId];
115
+ if (entry.type === "branch_summary") return [entry.fromId];
116
+ if (entry.type === "label" || entry.type === "context_edit")
117
+ return [entry.targetId];
118
+ if (entry.type === "custom" && entry.customType === TREE_ARCHIVE_ENTRY_TYPE) {
119
+ if (!isTreeArchiveManifestData(entry.data))
120
+ throw new Error(
121
+ "Invalid Tree archive metadata; session history was not removed.",
122
+ );
123
+ const data = entry.data;
124
+ return [
125
+ data.boundaryEntryId,
126
+ data.summaryEntryId,
127
+ data.archivedLeafId,
128
+ ...(data.branchBaseId ? [data.branchBaseId] : []),
129
+ ...(data.compactionEntryId ? [data.compactionEntryId] : []),
130
+ ];
131
+ }
132
+ return [];
133
+ }
@@ -0,0 +1,123 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ closeSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ openSync,
7
+ readSync,
8
+ realpathSync,
9
+ unlinkSync,
10
+ } from "node:fs";
11
+ import { dirname, join, resolve } from "node:path";
12
+
13
+ /** @param {string} root */
14
+ function privateRoot(root) {
15
+ const stat = lstatSync(root);
16
+ if (
17
+ !stat.isDirectory() ||
18
+ stat.uid !== process.getuid?.() ||
19
+ (stat.mode & 0o077) !== 0
20
+ )
21
+ throw new Error(
22
+ `Session cleanup state ${JSON.stringify(root)} must be a private directory owned by this user. Restore its ownership/permissions before restarting Pi.`,
23
+ );
24
+ }
25
+
26
+ /** Exact-file coordination stays outside session directories so inactive Notes
27
+ * never needs to write beside a read-only saved session. No global process scan.
28
+ * @param {string} file
29
+ */
30
+ function cleanupKey(file) {
31
+ let canonical;
32
+ try {
33
+ canonical = realpathSync(file);
34
+ } catch (error) {
35
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
36
+ throw error;
37
+ canonical = resolve(file);
38
+ }
39
+ return createHash("sha256").update(canonical).digest("hex");
40
+ }
41
+
42
+ /** @param {string} file @param {string} storageDirectory */
43
+ export function cleanupStatus(file, storageDirectory) {
44
+ return resolve(
45
+ storageDirectory,
46
+ "session-cleanup",
47
+ `${cleanupKey(file)}.json`,
48
+ );
49
+ }
50
+
51
+ /** @param {string} file */
52
+ export function cleanupPaths(file) {
53
+ // Automatic cleanup is Linux-only. A fixed OS location, not TMPDIR, keeps
54
+ // two local Pi launch environments in the same admission domain.
55
+ const directory = join(
56
+ "/tmp",
57
+ `pi-notes-cleanup-${process.getuid?.() ?? "user"}`,
58
+ cleanupKey(file),
59
+ );
60
+ try {
61
+ privateRoot(dirname(directory));
62
+ } catch (error) {
63
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
64
+ throw error;
65
+ }
66
+ return {
67
+ directory,
68
+ owners: join(directory, "owners"),
69
+ lock: join(directory, "lock"),
70
+ };
71
+ }
72
+
73
+ /** @param {string} file */
74
+ function ensureCleanupState(file) {
75
+ const paths = cleanupPaths(file);
76
+ const root = dirname(paths.directory);
77
+ mkdirSync(root, { recursive: true, mode: 0o700 });
78
+ privateRoot(root);
79
+ mkdirSync(paths.directory, { recursive: true, mode: 0o700 });
80
+ return paths;
81
+ }
82
+
83
+ /** Shared by startup admission and the after-exit writer.
84
+ * @param {string} file @returns {(()=>void)|undefined}
85
+ */
86
+ export function tryCleanupLock(file) {
87
+ const paths = ensureCleanupState(file);
88
+ try {
89
+ const fd = openSync(paths.lock, "wx", 0o600);
90
+ closeSync(fd);
91
+ return () => {
92
+ unlinkSync(paths.lock);
93
+ };
94
+ } catch (error) {
95
+ if (error instanceof Error && "code" in error && error.code === "EEXIST")
96
+ return;
97
+ throw error;
98
+ }
99
+ }
100
+
101
+ /** Pi accepts large headers. Read exactly the first complete source record,
102
+ * accumulating pieces once instead of imposing a smaller extension-only limit.
103
+ * @param {string} file @returns {unknown}
104
+ */
105
+ export function cleanupHeader(file) {
106
+ const fd = openSync(file, "r");
107
+ /** @type {Buffer[]} */
108
+ const pieces = [];
109
+ let position = 0;
110
+ try {
111
+ while (true) {
112
+ const buffer = Buffer.alloc(8192);
113
+ const read = readSync(fd, buffer, 0, buffer.length, position);
114
+ if (!read) throw new Error("The saved session header is incomplete.");
115
+ position += read;
116
+ const end = buffer.subarray(0, read).indexOf(10);
117
+ pieces.push(buffer.subarray(0, end < 0 ? read : end));
118
+ if (end >= 0) return JSON.parse(Buffer.concat(pieces).toString("utf8"));
119
+ }
120
+ } finally {
121
+ closeSync(fd);
122
+ }
123
+ }
@@ -135,6 +135,7 @@ export async function commitSessionPruning(
135
135
  try {
136
136
  unlinkSync(temp);
137
137
  } catch (error) {
138
+ // oxlint-disable-next-line no-unsafe-finally -- Cleanup failure must remain visible, even when the primary operation failed.
138
139
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
139
140
  }
140
141
  }
@@ -1,10 +1,16 @@
1
+ import { dirname } from "node:path";
1
2
  import type {
2
3
  ExtensionAPI,
3
4
  ExtensionContext,
4
5
  } from "@earendil-works/pi-coding-agent";
5
6
  import type { HistorySearch } from "./history-search.js";
7
+ import {
8
+ recordCleanupFailure,
9
+ scheduleSessionCleanup,
10
+ } from "./session-pruning-exit.mjs";
6
11
  import { planSessionPruning } from "./session-pruning-plan.js";
7
12
  import { RESTART_NOTICE } from "./session-pruning-policy.js";
13
+ import { cleanupStatus } from "./session-pruning-state.mjs";
8
14
  import { commitSessionPruning } from "./session-pruning-transaction.js";
9
15
  import type { NotesStore } from "./store.js";
10
16
  import { windowDetails } from "./windows.js";
@@ -50,9 +56,36 @@ export class SessionPruning {
50
56
  this.pending = undefined;
51
57
  }
52
58
  register(): void {
53
- this.pi.on("session_shutdown", () => {
59
+ this.pi.on("session_shutdown", async (event, ctx) => {
54
60
  this.epoch++;
55
61
  this.pending = undefined;
62
+ if (event.reason !== "quit") {
63
+ return;
64
+ }
65
+ const file = ctx.sessionManager.getSessionFile();
66
+ if (!file) return;
67
+ const statusPath = cleanupStatus(file, dirname(this.store.path));
68
+ try {
69
+ const policy = this.store.pruningPolicy(
70
+ ctx.sessionManager.getSessionId(),
71
+ );
72
+ if (process.platform === "linux" && (policy.windows || policy.days))
73
+ await scheduleSessionCleanup(
74
+ file,
75
+ ctx.sessionManager.getSessionId(),
76
+ statusPath,
77
+ );
78
+ } catch (error) {
79
+ const message = `Session record cleanup could not start: ${String(error)}. Check local session storage and that Node.js is available as node, then exit Pi normally again. Retired payloads remain pruned.`;
80
+ recordCleanupFailure(
81
+ statusPath,
82
+ ctx.sessionManager.getSessionId(),
83
+ new Error(message),
84
+ );
85
+ ctx.ui.notify(message, "warning");
86
+ } finally {
87
+ this.store.close();
88
+ }
56
89
  });
57
90
  this.pi.on("agent_start", (_event, ctx) => {
58
91
  // Pi emits agent_start before persisting incoming messages. Notes already
@@ -35,25 +35,25 @@ export function createNotesSettingsControls(
35
35
  : `${Math.ceil(minutes / 60)}h`;
36
36
  const list = new SettingsList(
37
37
  [
38
- {
39
- id: "sessionPruning",
40
- label: "Session auto-pruning",
41
- currentValue: "select…",
42
- values: ["select…", "settings…"],
43
- description:
44
- "Per-session history limits and Run now. Memory savings require restarting Pi.",
45
- },
46
38
  {
47
39
  id: "active",
48
- label: "Active",
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"].`,
40
+ label: "Enabled",
41
+ description: `On uses all models. Whitelist matches exact model IDs from any provider. Edit modelWhitelist in ${options.settingsPath}, then reload Pi.`,
50
42
  currentValue:
51
43
  settings.active === "off"
52
44
  ? "Off"
53
45
  : settings.active === "all"
54
- ? "All models"
46
+ ? "On"
55
47
  : "Whitelist",
56
- values: ["Off", "All models", "Whitelist"],
48
+ values: ["Off", "On", "Whitelist"],
49
+ },
50
+ {
51
+ id: "sessionPruning",
52
+ label: "Session auto-pruning",
53
+ currentValue: "select…",
54
+ values: ["select…", "settings…"],
55
+ description:
56
+ "Per-session history limits and Run now. Memory savings require restarting Pi.",
57
57
  },
58
58
  {
59
59
  id: "roles",
@@ -99,6 +99,14 @@ export function createNotesSettingsControls(
99
99
  currentValue: settings.newWindowRequests,
100
100
  values: [...NEW_WINDOW_REQUESTS],
101
101
  },
102
+ {
103
+ id: "taskCompletionRollover",
104
+ label: "Task-completion rollover",
105
+ description:
106
+ "Allow new_context({resume: false}) when a task is complete: finish the reply, then wait in fresh context. Off keeps immediate continuation only.",
107
+ currentValue: settings.taskCompletionRollover ? "on" : "off",
108
+ values: ["off", "on"],
109
+ },
102
110
  {
103
111
  id: "taskBoundaryReminder",
104
112
  label: "Task-boundary reminder",
@@ -157,11 +165,7 @@ export function createNotesSettingsControls(
157
165
  save({
158
166
  ...current,
159
167
  active:
160
- value === "Off"
161
- ? "off"
162
- : value === "All models"
163
- ? "all"
164
- : "whitelist",
168
+ value === "Off" ? "off" : value === "On" ? "all" : "whitelist",
165
169
  });
166
170
  else if (id === "sharing")
167
171
  save({ ...current, shareSubagentContext: value === "on" });
@@ -171,6 +175,8 @@ export function createNotesSettingsControls(
171
175
  save({ ...current, rankedHistorySearch: value === "on" });
172
176
  else if (id === "compact")
173
177
  save({ ...current, normalCompaction: value === "on" });
178
+ else if (id === "taskCompletionRollover")
179
+ save({ ...current, taskCompletionRollover: value === "on" });
174
180
  else if (id === "newWindowRequests") {
175
181
  const newWindowRequests = NEW_WINDOW_REQUESTS.find(
176
182
  (mode) => mode === value,
@@ -29,7 +29,7 @@ export async function openNotesSettings(
29
29
  sessionPruning: SessionPruningSettings;
30
30
  },
31
31
  ): Promise<"roles" | "board" | undefined> {
32
- let selected = "sessionPruning";
32
+ let selected = "active";
33
33
  while (true) {
34
34
  const action = await ctx.ui.custom<ScreenAction>(
35
35
  (tui, theme, _kb, done) => {
@@ -46,7 +46,7 @@ export async function openNotesSettings(
46
46
  const rule = theme.fg("accent", "─".repeat(Math.max(0, width)));
47
47
  return [
48
48
  rule,
49
- ` ${theme.bold("Notes & Compaction")} / ${theme.fg("dim", options.boardTab === false ? "Roles" : "Board")}`,
49
+ ` ${theme.bold("Notes")} / ${theme.fg("dim", options.boardTab === false ? "Roles" : "Board")}`,
50
50
  "",
51
51
  ...options
52
52
  .status()
@@ -54,10 +54,6 @@ export async function openNotesSettings(
54
54
  wrap(line).map((part) => theme.fg("dim", part)),
55
55
  ),
56
56
  "",
57
- ...wrap(
58
- "This extension works best on GPT6+ models. For other models we recommend switching the active option to whitelist or switching normal compaction on to work alongside the notes system.",
59
- ),
60
- "",
61
57
  ...list.render(width).slice(0, -2),
62
58
  "",
63
59
  ...wrap(
@@ -15,12 +15,7 @@ export const NEW_WINDOW_REQUESTS = [
15
15
  "unrestricted",
16
16
  ] as const;
17
17
  export type NewWindowRequests = (typeof NEW_WINDOW_REQUESTS)[number];
18
- const DEFAULT_MODEL_WHITELIST = [
19
- "gpt-6-astra",
20
- "gpt-6-sol",
21
- "gpt-6-luna",
22
- "gpt-6.1-sol",
23
- ];
18
+ const DEFAULT_MODEL_WHITELIST = ["gpt-6.2-astra", "gpt-6.2-sol", "gpt-6-luna"];
24
19
  export interface NotesSettings {
25
20
  active: "all" | "whitelist" | "off";
26
21
  modelWhitelist: string[];
@@ -29,6 +24,7 @@ export interface NotesSettings {
29
24
  rankedHistorySearch: boolean;
30
25
  shareSubagentContext: boolean;
31
26
  newWindowRequests: NewWindowRequests;
27
+ taskCompletionRollover: boolean;
32
28
  idleMinutes: IdleMinutes;
33
29
  taskBoundaryReminder: number;
34
30
  }
@@ -79,6 +75,7 @@ function readSettings(
79
75
  noteSaveMarkers: preferences().noteSaveMarkers,
80
76
  shareSubagentContext: false,
81
77
  newWindowRequests: "unrestricted",
78
+ taskCompletionRollover: false,
82
79
  idleMinutes: 0,
83
80
  taskBoundaryReminder: 0,
84
81
  }
@@ -129,6 +126,14 @@ function readSettings(
129
126
  );
130
127
  const taskBoundaryReminder =
131
128
  "taskBoundaryReminder" in settings ? settings.taskBoundaryReminder : 0;
129
+ const taskCompletionRollover =
130
+ "taskCompletionRollover" in settings
131
+ ? settings.taskCompletionRollover
132
+ : false;
133
+ if (typeof taskCompletionRollover !== "boolean")
134
+ throw new Error(
135
+ "Invalid task-completion rollover setting. Choose on or off in /notes.",
136
+ );
132
137
  if (
133
138
  typeof taskBoundaryReminder !== "number" ||
134
139
  !Number.isSafeInteger(taskBoundaryReminder) ||
@@ -159,6 +164,7 @@ function readSettings(
159
164
  ? settings.shareSubagentContext === true
160
165
  : preferences().compaction["shareSubagentContext"] === true,
161
166
  newWindowRequests: newWindowRequests as NewWindowRequests,
167
+ taskCompletionRollover,
162
168
  idleMinutes: idleMinutes as IdleMinutes,
163
169
  taskBoundaryReminder,
164
170
  };
@@ -208,6 +214,7 @@ function readLegacySettings(
208
214
  newWindowRequests: NEW_WINDOW_REQUESTS.some((item) => item === requests)
209
215
  ? (requests as NewWindowRequests)
210
216
  : "unrestricted",
217
+ taskCompletionRollover: false,
211
218
  idleMinutes: [...IDLE_MINUTES, 5, 15].some((item) => item === idle)
212
219
  ? (idle as IdleMinutes)
213
220
  : 0,
@@ -160,7 +160,6 @@ async function readSharedSession(
160
160
  const { containingMachine, locator, load, indexed, find } =
161
161
  createSavedSessionAccess(store, namespace, loader, signal);
162
162
  let unavailable: unknown;
163
- let targetReached = false;
164
163
  async function exploratoryLoad(location: Parameters<typeof load>[0]) {
165
164
  try {
166
165
  return await load(location);
@@ -181,6 +180,31 @@ async function readSharedSession(
181
180
  resolve,
182
181
  sharedNotesUnavailable,
183
182
  );
183
+ async function discover(
184
+ target: string,
185
+ ): Promise<SavedNotesSession | undefined> {
186
+ const family = savedFamilyIdentity(current);
187
+ if (!family) return;
188
+ const candidates: SavedNotesSession[] = [];
189
+ for (const location of await find(target)) {
190
+ const saved = await exploratoryLoad(location);
191
+ if (!saved) continue;
192
+ if (saved.threadId !== target.slice(1))
193
+ throw new Error("Saved session discovery returned a different thread");
194
+ const member = savedFamilyIdentity(saved);
195
+ if (
196
+ member?.storage === "session" &&
197
+ member.sessionId === family.sessionId &&
198
+ member.agentName === target
199
+ )
200
+ candidates.push(saved);
201
+ }
202
+ if (candidates.length > 1)
203
+ throw new Error(
204
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
205
+ );
206
+ return candidates[0];
207
+ }
184
208
  async function resolve(
185
209
  session: SavedNotesSession,
186
210
  destination: string,
@@ -192,7 +216,6 @@ async function readSharedSession(
192
216
  visited.add(key);
193
217
  const identity = savedNotesIdentity(session);
194
218
  if (contextAgentNames(identity).includes(destination)) {
195
- targetReached = true;
196
219
  return read(session, query, destination);
197
220
  }
198
221
  const routes = new Map<string, Static<typeof Route>>();
@@ -216,7 +239,6 @@ async function readSharedSession(
216
239
  "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
217
240
  );
218
241
  for (const route of matching) {
219
- targetReached = true;
220
242
  const link = route.plan.context;
221
243
  if (route.phase !== "ready" || !link) continue;
222
244
  const alias =
@@ -246,7 +268,6 @@ async function readSharedSession(
246
268
  (inside(destination, owner.context.controllerAlias) ||
247
269
  destination === canonicalAgentName(owner.context.controller.threadId))
248
270
  ) {
249
- targetReached = true;
250
271
  const link = owner.context;
251
272
  const alias =
252
273
  destination === canonicalAgentName(link.controller.threadId)
@@ -304,6 +325,33 @@ async function readSharedSession(
304
325
  (member) =>
305
326
  memberValidator.check(member) && member.agentName === destination,
306
327
  );
328
+ if (session === current && !direct.length) {
329
+ // Exact native discovery avoids reading every sibling's conversation.
330
+ // Explicit routes and local hints above retain precedence.
331
+ let saved: SavedNotesSession | undefined;
332
+ try {
333
+ saved = await discover(destination);
334
+ } catch (error) {
335
+ signal?.throwIfAborted();
336
+ if (!sharedNotesUnavailable(error)) throw error;
337
+ unavailable ??= error;
338
+ }
339
+ if (saved) {
340
+ return read(saved, query, destination);
341
+ }
342
+ // Do not crawl an entire family to guess a shortened UUID. A real
343
+ // explicitly named session still works via a route, member or exact hint.
344
+ if (/^\/[a-f0-9]{8}-[a-f0-9]{4}$/i.test(destination))
345
+ throw (
346
+ unavailable ??
347
+ Object.assign(
348
+ new Error(
349
+ "This looks like a shortened agent address. Use the complete agent address from the owner and retry.",
350
+ ),
351
+ { code: "SAVED_SESSION_UNAVAILABLE" },
352
+ )
353
+ );
354
+ }
307
355
  for (const member of direct.length ? direct : members) {
308
356
  if (!memberValidator.check(member)) continue;
309
357
  const location = locator(session, member.machine, member.sessionFile);
@@ -373,32 +421,6 @@ async function readSharedSession(
373
421
  if (!sharedNotesUnavailable(error)) throw error;
374
422
  unavailable ??= error;
375
423
  }
376
- // Legacy remote children may record only a now-dead relay parent. Find the
377
- // requested native thread once, never aliases or intermediate graph nodes.
378
- const family = savedFamilyIdentity(current);
379
- if (!result && !targetReached && family) {
380
- const candidates: SavedNotesSession[] = [];
381
- for (const location of await find(target)) {
382
- const saved = await exploratoryLoad(location);
383
- if (!saved) continue;
384
- if (saved.threadId !== target.slice(1))
385
- throw new Error(
386
- "Saved session discovery returned a different thread",
387
- );
388
- const member = savedFamilyIdentity(saved);
389
- if (
390
- member?.storage === "session" &&
391
- member.sessionId === family.sessionId &&
392
- member.agentName === target
393
- )
394
- candidates.push(saved);
395
- }
396
- if (candidates.length > 1)
397
- throw new Error(
398
- "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
399
- );
400
- if (candidates[0]) result = await read(candidates[0], params, target);
401
- }
402
424
  if (!result && unavailable) throw unavailable;
403
425
  return result;
404
426
  } catch (error) {
@@ -31,8 +31,8 @@ const HISTORY_ACTIONS = [
31
31
  "read",
32
32
  "search",
33
33
  ] as const;
34
- export const NOTES_USAGE = "await tools.notes()";
35
- export const HISTORY_USAGE = "await tools.history()";
34
+ export const NOTES_USAGE = "tools.notes()";
35
+ export const HISTORY_USAGE = "tools.history()";
36
36
  export const NOTES_DESCRIPTION = "Virtual filesystem task checkpoints";
37
37
  export const NOTES_ROUTING_GUIDELINE =
38
38
  "notes: task checkpoints and internal handoffs. MUST revise via write/append actions. Paths are virtual: read/write only through notes, never shell/filesystem tools. MUST NOT store project files or deliverables";
@@ -68,6 +68,7 @@ export const NOTES_SCHEMA = obj(
68
68
  );
69
69
  const NEW_CONTEXT_SCHEMA = obj(
70
70
  {
71
+ resume: opt(bool()),
71
72
  role: opt(
72
73
  str({
73
74
  minLength: 1,
@@ -81,9 +82,27 @@ const NEW_CONTEXT_SCHEMA = obj(
81
82
 
82
83
  const newContextSchemaValidator = compile(NEW_CONTEXT_SCHEMA);
83
84
 
84
- export function newContextSchema(roleIds: string[]) {
85
+ export function newContextSchema(
86
+ roleIds: string[],
87
+ taskCompletionRollover = false,
88
+ ) {
85
89
  return obj(
86
- roleIds.length ? { role: opt({ ...oneOf(roleIds), type: "string" }) } : {},
90
+ {
91
+ ...(roleIds.length
92
+ ? { role: opt({ ...oneOf(roleIds), type: "string" }) }
93
+ : {}),
94
+ ...(taskCompletionRollover
95
+ ? {
96
+ resume: opt(
97
+ bool({
98
+ default: true,
99
+ description:
100
+ "False: task complete; finish reply, then wait in fresh context. True: continue immediately",
101
+ }),
102
+ ),
103
+ }
104
+ : {}),
105
+ },
87
106
  { open: false },
88
107
  );
89
108
  }
@@ -92,7 +111,7 @@ export function prepareNewContextArguments(input: unknown) {
92
111
  const args = input ?? {};
93
112
  if (!newContextSchemaValidator.check(args))
94
113
  throw new Error(
95
- 'Use {} to keep the current model, or {role: "name"} for a configured role.',
114
+ "Use {} to continue in fresh context; optional role selects a configured preset. resume must be true or false.",
96
115
  );
97
116
  return args;
98
117
  }