@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.13.1.gef1ce49691d6

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 (141) hide show
  1. package/INTEGRATION.md +31 -0
  2. package/LICENSE +21 -0
  3. package/PCC-INTEGRATION.md +17 -0
  4. package/README.md +53 -2
  5. package/dist/viewer/archive.js +249 -0
  6. package/dist/viewer/config.js +85 -0
  7. package/dist/viewer/contracts.js +1 -0
  8. package/dist/viewer/server.js +177 -0
  9. package/dist/viewer/source.js +29 -0
  10. package/dist/viewer/web/app.js +88 -0
  11. package/dist/viewer/web/index.html +41 -0
  12. package/dist/viewer/web/navigation.js +72 -0
  13. package/dist/viewer/web/posts.js +105 -0
  14. package/dist/viewer/web/render.js +147 -0
  15. package/dist/viewer/web/session.js +86 -0
  16. package/dist/viewer/web/style.css +517 -0
  17. package/dist/viewer/web/updates.js +106 -0
  18. package/docs/BOARD-CHANGELOG.md +49 -0
  19. package/docs/BOARD.md +124 -0
  20. package/docs/NOTES-CHANGELOG.md +127 -0
  21. package/docs/NOTES.md +122 -0
  22. package/index.ts +21 -0
  23. package/package.json +75 -5
  24. package/src/board/AGENTS.md +12 -0
  25. package/src/board/activity.ts +274 -0
  26. package/src/board/archive.ts +118 -0
  27. package/src/board/awareness.ts +179 -0
  28. package/src/board/briefing.ts +25 -0
  29. package/src/board/config.ts +192 -0
  30. package/src/board/consolidation.ts +32 -0
  31. package/src/board/context-briefing.ts +245 -0
  32. package/src/board/contract.ts +254 -0
  33. package/src/board/delivery.ts +85 -0
  34. package/src/board/feature.ts +91 -0
  35. package/src/board/identity.ts +238 -0
  36. package/src/board/integration.ts +55 -0
  37. package/src/board/paging.ts +54 -0
  38. package/src/board/protocol.ts +78 -0
  39. package/src/board/queries.ts +168 -0
  40. package/src/board/response.ts +82 -0
  41. package/src/board/runtime/activation.ts +50 -0
  42. package/src/board/runtime/catchup.ts +96 -0
  43. package/src/board/runtime/coordinator.ts +311 -0
  44. package/src/board/runtime/engine.ts +40 -0
  45. package/src/board/runtime/index.ts +63 -0
  46. package/src/board/runtime/owner.ts +168 -0
  47. package/src/board/runtime/routing.ts +152 -0
  48. package/src/board/runtime/turns.ts +109 -0
  49. package/src/board/search.ts +95 -0
  50. package/src/board/settings/panel.ts +193 -0
  51. package/src/board/store.ts +427 -0
  52. package/src/board/summaries.ts +124 -0
  53. package/src/board/summarizer.ts +201 -0
  54. package/src/board/tool.ts +27 -0
  55. package/src/board/viewer/AGENTS.md +1 -0
  56. package/src/board/viewer/archive.ts +308 -0
  57. package/src/board/viewer/config.ts +111 -0
  58. package/src/board/viewer/contracts.ts +98 -0
  59. package/src/board/viewer/index.ts +162 -0
  60. package/src/board/viewer/server.ts +204 -0
  61. package/src/board/viewer/source.ts +33 -0
  62. package/src/board/viewer/web/app.js +88 -0
  63. package/src/board/viewer/web/index.html +41 -0
  64. package/src/board/viewer/web/navigation.js +72 -0
  65. package/src/board/viewer/web/posts.js +105 -0
  66. package/src/board/viewer/web/render.js +147 -0
  67. package/src/board/viewer/web/session.js +86 -0
  68. package/src/board/viewer/web/style.css +517 -0
  69. package/src/board/viewer/web/updates.js +106 -0
  70. package/src/guidance.ts +121 -0
  71. package/src/notes/AGENTS.md +27 -0
  72. package/src/notes/activation.ts +150 -0
  73. package/src/notes/agent-identity.ts +221 -0
  74. package/src/notes/attachment-sharing.ts +165 -0
  75. package/src/notes/attachment-snapshot.ts +113 -0
  76. package/src/notes/binding-startup.ts +30 -0
  77. package/src/notes/bridge.ts +130 -0
  78. package/src/notes/compaction-projection.ts +88 -0
  79. package/src/notes/context-owner.ts +99 -0
  80. package/src/notes/context-sharing.ts +178 -0
  81. package/src/notes/extension-hooks.ts +200 -0
  82. package/src/notes/extension-sharing.ts +133 -0
  83. package/src/notes/feature.ts +168 -0
  84. package/src/notes/fresh-checkpoint.ts +143 -0
  85. package/src/notes/fresh-notes.ts +323 -0
  86. package/src/notes/history-search-protocol.ts +39 -0
  87. package/src/notes/history-search-pruning.mjs +120 -0
  88. package/src/notes/history-search-worker.mjs +258 -0
  89. package/src/notes/history-search.ts +269 -0
  90. package/src/notes/history-windows.ts +221 -0
  91. package/src/notes/history.ts +158 -0
  92. package/src/notes/idle-admission.ts +201 -0
  93. package/src/notes/index.ts +125 -0
  94. package/src/notes/integrations.ts +174 -0
  95. package/src/notes/lifecycle.ts +308 -0
  96. package/src/notes/model-role-config.ts +79 -0
  97. package/src/notes/model-role-screen.ts +74 -0
  98. package/src/notes/model-roles.ts +225 -0
  99. package/src/notes/note-query.ts +148 -0
  100. package/src/notes/note-result.ts +88 -0
  101. package/src/notes/note-save-marker.ts +128 -0
  102. package/src/notes/notes-lookup.ts +115 -0
  103. package/src/notes/notes.ts +302 -0
  104. package/src/notes/query-executor.ts +242 -0
  105. package/src/notes/query-input.ts +126 -0
  106. package/src/notes/remote.ts +376 -0
  107. package/src/notes/rollover.ts +224 -0
  108. package/src/notes/saved-session-access.ts +117 -0
  109. package/src/notes/saved-session-index.mjs +83 -0
  110. package/src/notes/saved-session.mjs +241 -0
  111. package/src/notes/saved-session.ts +51 -0
  112. package/src/notes/saved-sharing-records.ts +135 -0
  113. package/src/notes/session-pruning-content.ts +237 -0
  114. package/src/notes/session-pruning-plan.ts +243 -0
  115. package/src/notes/session-pruning-policy.ts +20 -0
  116. package/src/notes/session-pruning-screen.ts +204 -0
  117. package/src/notes/session-pruning-source.ts +44 -0
  118. package/src/notes/session-pruning-transaction.ts +141 -0
  119. package/src/notes/session-pruning.ts +155 -0
  120. package/src/notes/settings-command.ts +95 -0
  121. package/src/notes/settings-controls.ts +199 -0
  122. package/src/notes/settings-screen.ts +113 -0
  123. package/src/notes/settings.ts +287 -0
  124. package/src/notes/shared-notes.ts +411 -0
  125. package/src/notes/shared-session-reader.ts +143 -0
  126. package/src/notes/sharing-service.ts +282 -0
  127. package/src/notes/sqlite.mjs +33 -0
  128. package/src/notes/store.ts +283 -0
  129. package/src/notes/task-boundary.ts +37 -0
  130. package/src/notes/tool-contracts.ts +312 -0
  131. package/src/notes/tools.ts +148 -0
  132. package/src/notes/tree-archive-manifest.mjs +27 -0
  133. package/src/notes/tree-archive.ts +129 -0
  134. package/src/notes/tree-checkpoint.ts +170 -0
  135. package/src/notes/tree-handoff-read.ts +192 -0
  136. package/src/notes/window-checkpoint.ts +105 -0
  137. package/src/notes/window-message.ts +185 -0
  138. package/src/notes/windows.ts +272 -0
  139. package/src/settings-navigation.ts +11 -0
  140. package/src/timestamps.ts +3 -0
  141. package/tsconfig.json +9 -0
@@ -0,0 +1,44 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ import type {
4
+ SessionEntry,
5
+ SessionHeader,
6
+ } from "@earendil-works/pi-coding-agent";
7
+
8
+ export type PruningRecord = SessionEntry | SessionHeader;
9
+
10
+ /** Read a finite complete-line prefix, with at most one JSON record buffered. */
11
+ export async function scanSession(
12
+ path: string,
13
+ end: number,
14
+ visit: (entry: PruningRecord, raw: string) => void | Promise<void>,
15
+ ): Promise<void> {
16
+ if (end <= 0) throw new Error("Session has not been saved yet.");
17
+ const stream = createReadStream(path, {
18
+ start: 0,
19
+ end: end - 1,
20
+ highWaterMark: 64 * 1024,
21
+ });
22
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
23
+ try {
24
+ for await (const line of lines) {
25
+ if (!line) throw new Error("Session contains an empty record.");
26
+ const entry: PruningRecord = JSON.parse(line);
27
+ if (
28
+ !entry ||
29
+ typeof entry !== "object" ||
30
+ typeof entry.type !== "string" ||
31
+ typeof entry.id !== "string" ||
32
+ typeof entry.timestamp !== "string" ||
33
+ (entry.type !== "session" &&
34
+ entry.parentId !== null &&
35
+ typeof entry.parentId !== "string")
36
+ )
37
+ throw new Error("Session contains an invalid record.");
38
+ await visit(entry, line);
39
+ }
40
+ } finally {
41
+ lines.close();
42
+ stream.destroy();
43
+ }
44
+ }
@@ -0,0 +1,141 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ closeSync,
4
+ fsyncSync,
5
+ lstatSync,
6
+ openSync,
7
+ readSync,
8
+ renameSync,
9
+ type Stats,
10
+ statSync,
11
+ unlinkSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { open } from "node:fs/promises";
15
+ import type {
16
+ ExtensionAPI,
17
+ ExtensionContext,
18
+ } from "@earendil-works/pi-coding-agent";
19
+ import type { PruningPlan } from "./session-pruning-plan.js";
20
+ import {
21
+ pruningContext,
22
+ transformPruningEntry,
23
+ } from "./session-pruning-plan.js";
24
+ import { scanSession } from "./session-pruning-source.js";
25
+
26
+ const MAX_COMMIT_TAIL = 4 * 1024 * 1024;
27
+
28
+ function sameSource(plan: PruningPlan): Stats {
29
+ const current = lstatSync(plan.path);
30
+ if (
31
+ !current.isFile() ||
32
+ current.dev !== plan.source.dev ||
33
+ current.ino !== plan.source.ino ||
34
+ current.size < plan.source.size ||
35
+ (current.size === plan.source.size &&
36
+ current.mtimeMs !== plan.source.mtimeMs)
37
+ )
38
+ throw new Error(
39
+ "Session changed while pruning was prepared. Run now again.",
40
+ );
41
+ return current;
42
+ }
43
+
44
+ /** SDK writes to this already-flushed path are synchronous appends. No await from
45
+ * final identity check through rename: extension/monitor appends cannot interleave.
46
+ * Fork writes a different path; migration rewrites happen before session_start.
47
+ */
48
+ export async function commitSessionPruning(
49
+ pi: Pick<ExtensionAPI, "appendEntry">,
50
+ ctx: Pick<ExtensionContext, "sessionManager">,
51
+ plan: PruningPlan,
52
+ checkPolicy: () => void = () => {},
53
+ ): Promise<{ before: number; after: number }> {
54
+ const valid = () => {
55
+ checkPolicy();
56
+ if (
57
+ ctx.sessionManager.getSessionId() !== plan.sessionId ||
58
+ ctx.sessionManager.getSessionFile() !== plan.path
59
+ )
60
+ throw new Error("Active session changed. Run now again.");
61
+ for (const id of pruningContext(ctx.sessionManager).protectedIds)
62
+ if (plan.ids.has(id) && !plan.protectedIds.has(id))
63
+ throw new Error("Active context changed. Run now again.");
64
+ return sameSource(plan);
65
+ };
66
+ valid();
67
+ const generation = randomUUID();
68
+ pi.appendEntry("notes-session-prune", {
69
+ version: 1,
70
+ sessionId: plan.sessionId,
71
+ generation,
72
+ });
73
+ const temp = `${plan.path}.prune-${generation}.tmp`;
74
+ let output: Awaited<ReturnType<typeof open>> | undefined;
75
+ try {
76
+ output = await open(temp, "wx", plan.source.mode & 0o777);
77
+ const file = output;
78
+ await scanSession(plan.path, plan.source.size, async (entry, raw) => {
79
+ const transformed =
80
+ entry.type === "session"
81
+ ? {
82
+ ...entry,
83
+ notesPruning: {
84
+ version: 1,
85
+ sessionId: plan.sessionId,
86
+ generation,
87
+ },
88
+ }
89
+ : transformPruningEntry(plan, entry);
90
+ await file.writeFile(
91
+ `${transformed === entry ? raw : JSON.stringify(transformed)}\n`,
92
+ );
93
+ });
94
+ await file.sync();
95
+ await file.close();
96
+ output = undefined;
97
+ // Bounded synchronous commit includes every append since the preview prefix.
98
+ const current = valid();
99
+ const length = current.size - plan.source.size;
100
+ if (length > MAX_COMMIT_TAIL)
101
+ throw new Error("Session grew too much during pruning. Run now again.");
102
+ const input = openSync(plan.path, "r");
103
+ let tail: Buffer;
104
+ try {
105
+ tail = Buffer.alloc(length);
106
+ let offset = 0;
107
+ while (offset < length) {
108
+ const read = readSync(
109
+ input,
110
+ tail,
111
+ offset,
112
+ length - offset,
113
+ plan.source.size + offset,
114
+ );
115
+ if (!read) throw new Error("Session changed during pruning.");
116
+ offset += read;
117
+ }
118
+ } finally {
119
+ closeSync(input);
120
+ }
121
+ if (tail.length && tail.at(-1) !== 10)
122
+ throw new Error("Session has an incomplete append. Run now again.");
123
+ const fd = openSync(temp, "a");
124
+ try {
125
+ if (tail.length) writeFileSync(fd, tail);
126
+ fsyncSync(fd);
127
+ } finally {
128
+ closeSync(fd);
129
+ }
130
+ const after = statSync(temp).size;
131
+ renameSync(temp, plan.path);
132
+ return { before: current.size, after };
133
+ } finally {
134
+ await output?.close();
135
+ try {
136
+ unlinkSync(temp);
137
+ } catch (error) {
138
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
139
+ }
140
+ }
141
+ }
@@ -0,0 +1,155 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { HistorySearch } from "./history-search.js";
6
+ import { planSessionPruning } from "./session-pruning-plan.js";
7
+ import { RESTART_NOTICE } from "./session-pruning-policy.js";
8
+ import { commitSessionPruning } from "./session-pruning-transaction.js";
9
+ import type { NotesStore } from "./store.js";
10
+ import { windowDetails } from "./windows.js";
11
+
12
+ const bytes = (value: number) => `${(value / 1024 / 1024).toFixed(1)} MiB`;
13
+
14
+ export interface SessionPruningInteraction {
15
+ progress: (message: string) => void;
16
+ confirm: (title: string, message: string) => Promise<boolean>;
17
+ }
18
+
19
+ export class SessionPruning {
20
+ private running = false;
21
+ private observed: string | undefined;
22
+ private pending: string | undefined;
23
+ private epoch = 0;
24
+ private readonly pi: ExtensionAPI;
25
+ private readonly store: NotesStore;
26
+ private readonly search: HistorySearch;
27
+ private readonly admittedWindow: () => string | undefined;
28
+ constructor(
29
+ pi: ExtensionAPI,
30
+ store: NotesStore,
31
+ search: HistorySearch,
32
+ admittedWindow: () => string | undefined,
33
+ ) {
34
+ this.pi = pi;
35
+ this.store = store;
36
+ this.search = search;
37
+ this.admittedWindow = admittedWindow;
38
+ }
39
+
40
+ private persistedWindow(ctx: ExtensionContext): string | undefined {
41
+ for (const entry of ctx.sessionManager.getBranch().reverse()) {
42
+ const details = windowDetails(entry);
43
+ if (details?.kind === "window")
44
+ return `${ctx.sessionManager.getSessionId()}:${details.identity.currentWindowId}`;
45
+ }
46
+ }
47
+ start(ctx: ExtensionContext): void {
48
+ this.epoch++;
49
+ this.observed = this.persistedWindow(ctx);
50
+ this.pending = undefined;
51
+ }
52
+ register(): void {
53
+ this.pi.on("session_shutdown", () => {
54
+ this.epoch++;
55
+ this.pending = undefined;
56
+ });
57
+ this.pi.on("agent_start", (_event, ctx) => {
58
+ // Pi emits agent_start before persisting incoming messages. Notes already
59
+ // admitted the successor in before_agent_start; confirm its commit below.
60
+ const window = this.admittedWindow();
61
+ const current = window
62
+ ? `${ctx.sessionManager.getSessionId()}:${window}`
63
+ : undefined;
64
+ if (current && current !== this.observed) this.pending = current;
65
+ this.observed = current;
66
+ });
67
+ // The successor marker and complete turn_end checkpoint are now committed.
68
+ // Ordinary turns without a new-window admission do no pruning work.
69
+ this.pi.on("agent_settled", async (_event, ctx) => {
70
+ if (!this.pending) return;
71
+ const pending = this.pending;
72
+ this.pending = undefined;
73
+ if (pending === this.persistedWindow(ctx)) await this.run(ctx, false);
74
+ });
75
+ }
76
+
77
+ async run(
78
+ ctx: ExtensionContext,
79
+ manual: boolean,
80
+ interaction?: SessionPruningInteraction,
81
+ ): Promise<void> {
82
+ if (this.running) {
83
+ if (manual) ctx.ui.notify("Session pruning is already running.", "info");
84
+ return;
85
+ }
86
+ this.running = true;
87
+ const epoch = this.epoch;
88
+ let historyPruned = false;
89
+ try {
90
+ const policy = this.store.pruningPolicy(
91
+ ctx.sessionManager.getSessionId(),
92
+ );
93
+ if (!policy.windows && !policy.days) {
94
+ if (manual)
95
+ ctx.ui.notify(
96
+ "Session pruning is off. Choose a history or conversation limit first.",
97
+ "info",
98
+ );
99
+ return;
100
+ }
101
+ interaction?.progress("Preparing pruning preview…");
102
+ const plan = await planSessionPruning(ctx.sessionManager, policy);
103
+ if (!plan.changed) {
104
+ interaction?.progress("Cleaning ranked history…");
105
+ await this.search.pruneSession(plan.sessionId, plan.path);
106
+ if (manual)
107
+ ctx.ui.notify(
108
+ "Nothing to prune under this session's limits.",
109
+ "info",
110
+ );
111
+ return;
112
+ }
113
+ if (
114
+ manual &&
115
+ !(await (interaction?.confirm ?? ctx.ui.confirm)(
116
+ "Prune this session's history?",
117
+ `${bytes(plan.before)} → about ${bytes(plan.after)}; ${plan.changed} records changed. Current context and saved SQLite notes are protected. Older tool activity, injected instructions and exact execution replay are permanently lost. No backup is kept.${plan.opaque.length ? ` Opaque extension state is retained: ${plan.opaque.join(", ")}.` : ""} ${RESTART_NOTICE}`,
118
+ ))
119
+ )
120
+ return;
121
+ const currentPolicy = this.store.pruningPolicy(plan.sessionId);
122
+ if (
123
+ currentPolicy.windows !== policy.windows ||
124
+ currentPolicy.days !== policy.days
125
+ )
126
+ throw new Error("Session pruning settings changed. Run now again.");
127
+ interaction?.progress("Pruning session history…");
128
+ const result = await commitSessionPruning(this.pi, ctx, plan, () => {
129
+ if (this.epoch !== epoch)
130
+ throw new Error(
131
+ "Session changed while pruning was prepared. Run now again.",
132
+ );
133
+ const current = this.store.pruningPolicy(plan.sessionId);
134
+ if (current.windows !== policy.windows || current.days !== policy.days)
135
+ throw new Error("Session pruning settings changed. Run now again.");
136
+ });
137
+ historyPruned = true;
138
+ interaction?.progress("Cleaning ranked history…");
139
+ await this.search.pruneSession(plan.sessionId, plan.path);
140
+ ctx.ui.notify(
141
+ `Pruned session history: ${bytes(result.before)} → ${bytes(result.after)}. Saved notes unchanged. ${RESTART_NOTICE}`,
142
+ "info",
143
+ );
144
+ } catch (error) {
145
+ ctx.ui.notify(
146
+ historyPruned
147
+ ? `Session history was pruned, but ranked history cleanup did not complete. Run now again to retry cleanup. ${RESTART_NOTICE}`
148
+ : `Session pruning did not complete: ${error instanceof Error ? error.message : String(error)}`,
149
+ "error",
150
+ );
151
+ } finally {
152
+ this.running = false;
153
+ }
154
+ }
155
+ }
@@ -0,0 +1,95 @@
1
+ import type {
2
+ ExtensionCommandContext,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { SettingsTab } from "../settings-navigation.js";
6
+ import type { NotesRuntime } from "./index.js";
7
+ import { sessionRef } from "./notes.js";
8
+ import type { NotesSettings } from "./settings.js";
9
+ import { openNotesSettings } from "./settings-screen.js";
10
+ import type { NotesStore } from "./store.js";
11
+
12
+ export interface NotesSettingsOwner {
13
+ readonly settings: NotesSettings;
14
+ readonly runtime: NotesRuntime | undefined;
15
+ save(settings: NotesSettings, ctx: ExtensionContext): Promise<void>;
16
+ start(ctx: ExtensionContext): Promise<NotesRuntime>;
17
+ }
18
+
19
+ export function createNotesSettings(
20
+ owner: NotesSettingsOwner,
21
+ store: NotesStore,
22
+ settingsPath: string,
23
+ boardTab = true,
24
+ ) {
25
+ const open = async (
26
+ ctx: ExtensionCommandContext,
27
+ initial: "notes" | "roles" = "notes",
28
+ ): Promise<SettingsTab | undefined> => {
29
+ let tab = initial;
30
+ while (true) {
31
+ if (tab === "roles") {
32
+ const { roles } = await owner.start(ctx);
33
+ if ((await roles.command("", ctx)) !== "notes") return;
34
+ tab = "notes";
35
+ }
36
+ if (!ctx.hasUI) {
37
+ ctx.ui.notify("Notes settings require interactive Pi.", "warning");
38
+ return;
39
+ }
40
+ const save = (value: NotesSettings) => owner.save(value, ctx);
41
+ const prune = async () => {
42
+ await ctx.waitForIdle();
43
+ const { search } = await owner.start(ctx);
44
+ store.updateFile(sessionRef(ctx));
45
+ const sources = store.sessionFiles();
46
+ const result = store.prune(ctx.sessionManager.getSessionId());
47
+ const indexed = await search.prune(
48
+ ctx.sessionManager.getSessionId(),
49
+ sources,
50
+ );
51
+ ctx.ui.notify(
52
+ `Pruned ${result.removed} Notes sessions and ${indexed.removed} indexed sessions. Retained ${result.unknownPaths + indexed.unknownPaths} unknown paths and ${result.inaccessible + indexed.inaccessible} inaccessible files.${indexed.storageBusy ? " Index storage cleanup is pending; run Prune again when other agents are idle." : ""}`,
53
+ "info",
54
+ );
55
+ };
56
+ try {
57
+ const next = await openNotesSettings(ctx, {
58
+ boardTab,
59
+ settings: () => owner.settings,
60
+ save,
61
+ settingsPath,
62
+ prune,
63
+ sessionPruning: {
64
+ get: () => store.pruningPolicy(ctx.sessionManager.getSessionId()),
65
+ save: (value) =>
66
+ store.setPruningPolicy(ctx.sessionManager.getSessionId(), value),
67
+ run: async (interaction) => {
68
+ await ctx.waitForIdle();
69
+ const { sessionPruning } = await owner.start(ctx);
70
+ await sessionPruning.run(ctx, true, interaction);
71
+ },
72
+ },
73
+ status: () => {
74
+ const counts = store.status();
75
+ const activation = owner.runtime?.activation;
76
+ const lifecycle = owner.runtime?.lifecycle;
77
+ return [
78
+ lifecycle?.active
79
+ ? "Continuity active"
80
+ : `Continuity inactive: ${activation?.unavailable ?? (owner.settings.active === "off" ? "off" : "model not in whitelist")}`,
81
+ `${counts.sessions} sessions · ${counts.revisions} note revisions · ${counts.cachedResponses} cached responses`,
82
+ `Hybrid lookup: ${lifecycle?.bridge?.lookup ? "available" : "unavailable"} · Encrypted delivery: ${lifecycle?.bridge?.projectResult ? "available" : "unavailable"}`,
83
+ ];
84
+ },
85
+ });
86
+ if (next !== "roles") return next;
87
+ tab = "roles";
88
+ } catch (error) {
89
+ ctx.ui.notify(`Notes settings failed: ${String(error)}`, "error");
90
+ return;
91
+ }
92
+ }
93
+ };
94
+ return open;
95
+ }
@@ -0,0 +1,199 @@
1
+ import {
2
+ type ExtensionContext,
3
+ getSettingsListTheme,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { SettingsList } from "@earendil-works/pi-tui";
6
+ import {
7
+ IDLE_MINUTES,
8
+ NEW_WINDOW_REQUESTS,
9
+ type NotesSettings,
10
+ } from "./settings.js";
11
+ import { TASK_BOUNDARY_PRESETS, taskBoundaryLabel } from "./task-boundary.js";
12
+
13
+ export type NotesSettingsAction =
14
+ | "close"
15
+ | "prune"
16
+ | "sessionPruning"
17
+ | "roles"
18
+ | { settings: NotesSettings; selected: string };
19
+
20
+ export function createNotesSettingsControls(
21
+ ctx: ExtensionContext,
22
+ options: {
23
+ settings: () => NotesSettings;
24
+ settingsPath: string;
25
+ },
26
+ done: (action: NotesSettingsAction) => void,
27
+ requestRender: () => void,
28
+ ) {
29
+ const settings = options.settings();
30
+ const idleValue = (minutes: number) =>
31
+ minutes === 0
32
+ ? "Off"
33
+ : minutes < 60
34
+ ? `${minutes}m`
35
+ : `${Math.ceil(minutes / 60)}h`;
36
+ const list = new SettingsList(
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
+ {
47
+ 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"].`,
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…"],
63
+ },
64
+ {
65
+ id: "sharing",
66
+ label: "Share subagent context",
67
+ description:
68
+ "Let new child agents share notes and history. Existing families remain connected when off.",
69
+ currentValue: settings.shareSubagentContext ? "on" : "off",
70
+ values: ["off", "on"],
71
+ },
72
+ {
73
+ id: "rankedHistorySearch",
74
+ label: "Ranked history search",
75
+ description:
76
+ "BM25 for earlier user messages and assistant replies. Skips current context and tool activity.",
77
+ currentValue: settings.rankedHistorySearch ? "on" : "off",
78
+ values: ["off", "on"],
79
+ },
80
+ {
81
+ id: "noteSaveMarkers",
82
+ label: "Note-save markers",
83
+ currentValue: settings.noteSaveMarkers ? "on" : "off",
84
+ values: ["off", "on"],
85
+ },
86
+ {
87
+ id: "compact",
88
+ label: "Normal compaction",
89
+ description:
90
+ "Use Pi/PCC compaction for /compact and new_context. Off uses notes-only rollover; /compact then waits for your next prompt.",
91
+ currentValue: settings.normalCompaction ? "on" : "off",
92
+ values: ["off", "on"],
93
+ },
94
+ {
95
+ id: "newWindowRequests",
96
+ label: "New window requests",
97
+ description:
98
+ "Off disables new_context. Pi-limits keeps the current window when Pi finds too little history to compact. Unrestricted accepts requests at any size. Normal compaction still chooses how windows roll over. Manual /compact and idle rollover are separate.",
99
+ currentValue: settings.newWindowRequests,
100
+ values: [...NEW_WINDOW_REQUESTS],
101
+ },
102
+ {
103
+ id: "taskBoundaryReminder",
104
+ label: "Task-boundary reminder",
105
+ description:
106
+ "Suggest a separate-task rollover after this many used tokens, only with active capacity above 272k. Custom: edit taskBoundaryReminder in the notes settings JSON (whole tokens); 0 is off.",
107
+ currentValue: taskBoundaryLabel(settings.taskBoundaryReminder),
108
+ values: [
109
+ ...TASK_BOUNDARY_PRESETS.map(taskBoundaryLabel),
110
+ "custom (edit JSON)",
111
+ ],
112
+ },
113
+ {
114
+ id: "idle",
115
+ label: "Idle rollover",
116
+ description:
117
+ "Roll over before the next input only with fresh notes from a completed turn. Not a cache-expiry guarantee.",
118
+ currentValue: idleValue(settings.idleMinutes),
119
+ values: IDLE_MINUTES.map(idleValue),
120
+ },
121
+ {
122
+ id: "prune",
123
+ label: "Prune missing sessions",
124
+ description:
125
+ "Remove notes, cached responses and history index entries for missing session files. Keeps the active session, unknown paths and inaccessible files. Confirmation required.",
126
+ currentValue: "select…",
127
+ values: ["select…", "prune…"],
128
+ },
129
+ ],
130
+ 5,
131
+ getSettingsListTheme(),
132
+ (id, value) => {
133
+ if (id === "roles") {
134
+ done("roles");
135
+ return;
136
+ }
137
+ if (id === "sessionPruning") {
138
+ done("sessionPruning");
139
+ return;
140
+ }
141
+ if (id === "prune") {
142
+ done("prune");
143
+ return;
144
+ }
145
+ const current = options.settings();
146
+ if (id === "taskBoundaryReminder" && value === "custom (edit JSON)") {
147
+ ctx.ui.notify(
148
+ `Set taskBoundaryReminder to a positive whole token count in ${options.settingsPath}, then reload Pi. 0 is off.`,
149
+ "info",
150
+ );
151
+ list.updateValue(id, taskBoundaryLabel(current.taskBoundaryReminder));
152
+ return;
153
+ }
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,
190
+ );
191
+ if (idleMinutes !== undefined) save({ ...current, idleMinutes });
192
+ }
193
+ requestRender();
194
+ },
195
+ () => done("close"),
196
+ { enableSearch: false },
197
+ );
198
+ return list;
199
+ }