@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.14.1.g7d1d3da173aa

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,170 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import {
3
+ buildSessionContext,
4
+ type SessionEntry,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ buildTreeArchiveIndex,
8
+ hasTreeArchiveSuccessor,
9
+ TREE_ARCHIVE_ENTRY_TYPE,
10
+ } from "./tree-archive.js";
11
+ import { windowDetails } from "./windows.js";
12
+
13
+ /** Restore the archived checkpoint's source path only in model/replay context. */
14
+ export function projectTreeCheckpointBranch(
15
+ active: readonly SessionEntry[],
16
+ all: readonly SessionEntry[],
17
+ ): readonly SessionEntry[] {
18
+ const index = buildTreeArchiveIndex(all, active);
19
+ const hiddenSummaries = new Set(
20
+ index.archives
21
+ .filter(
22
+ (item) =>
23
+ !item.manifest.compactionEntryId ||
24
+ hasTreeArchiveSuccessor(active, item.manifest.windowId),
25
+ )
26
+ .map((item) => item.summary.id),
27
+ );
28
+ const manifestIndex = active.findLastIndex(
29
+ (entry) =>
30
+ entry.type === "custom" && entry.customType === TREE_ARCHIVE_ENTRY_TYPE,
31
+ );
32
+ if (manifestIndex < 0) return hideArchiveSummaries(active, hiddenSummaries);
33
+ const tail = active.slice(manifestIndex + 1);
34
+ // Validate only the archive the live checkpoint still needs, not retired history.
35
+ if (
36
+ tail.some(
37
+ (entry) =>
38
+ entry.type === "compaction" ||
39
+ (entry.type === "custom_message" &&
40
+ windowDetails(entry)?.kind === "window" &&
41
+ windowDetails(entry)?.trim),
42
+ )
43
+ )
44
+ return hideArchiveSummaries(active, hiddenSummaries);
45
+ const archive = index.archives.find(
46
+ (item) => item.summary.id === active[manifestIndex]!.parentId,
47
+ );
48
+ if (!archive)
49
+ throw new Error("Invalid active Tree archive checkpoint metadata");
50
+ if (
51
+ !archive.manifest.compactionEntryId ||
52
+ !hasTreeArchiveSuccessor(active, archive.manifest.windowId)
53
+ )
54
+ return hideArchiveSummaries(active, hiddenSummaries);
55
+ if (!archive.entries)
56
+ throw new Error(
57
+ "The active Tree checkpoint is unavailable in this session copy; resume the source session",
58
+ );
59
+ const byId = new Map(all.map((entry) => [entry.id, entry]));
60
+ const source: SessionEntry[] = [];
61
+ const visited = new Set<string>();
62
+ let id: string | null = archive.manifest.archivedLeafId;
63
+ while (id !== null) {
64
+ if (visited.has(id) || source.length >= 50_000)
65
+ throw new Error("Invalid Tree checkpoint ancestry");
66
+ visited.add(id);
67
+ const entry = byId.get(id);
68
+ if (!entry) throw new Error("Tree checkpoint ancestry is missing");
69
+ source.push(entry);
70
+ id = entry.parentId;
71
+ }
72
+ source.reverse();
73
+ const checkpointIndex = source.findIndex(
74
+ (entry) => entry.id === archive.manifest.compactionEntryId,
75
+ );
76
+ const checkpoint = source[checkpointIndex];
77
+ if (
78
+ checkpoint?.type !== "compaction" ||
79
+ !source
80
+ .slice(0, checkpointIndex)
81
+ .some((entry) => entry.id === checkpoint.firstKeptEntryId)
82
+ )
83
+ throw new Error("Tree checkpoint kept history is missing");
84
+ return hideArchiveSummaries(
85
+ [...source, ...tail].map((entry, position, entries): SessionEntry => {
86
+ const parentId = position === 0 ? null : entries[position - 1]!.id;
87
+ return entry.parentId === parentId ? entry : { ...entry, parentId };
88
+ }),
89
+ hiddenSummaries,
90
+ );
91
+ }
92
+
93
+ function hideArchiveSummaries(
94
+ entries: readonly SessionEntry[],
95
+ hidden: ReadonlySet<string>,
96
+ ): readonly SessionEntry[] {
97
+ if (hidden.size === 0) return entries;
98
+ return entries.map(
99
+ (entry): SessionEntry =>
100
+ entry.type === "branch_summary" && hidden.has(entry.id)
101
+ ? // Keep entry IDs as replay cut points without sending archive summaries.
102
+ {
103
+ type: "custom",
104
+ id: entry.id,
105
+ parentId: entry.parentId,
106
+ timestamp: entry.timestamp,
107
+ customType: "codex-context-tree-summary",
108
+ data: {},
109
+ }
110
+ : entry,
111
+ );
112
+ }
113
+
114
+ /** Replace only persisted context displaced by the archive; retain extension edits/additions. */
115
+ export function projectTreeCheckpointMessages(
116
+ active: readonly SessionEntry[],
117
+ projected: readonly SessionEntry[],
118
+ messages: readonly AgentMessage[] | undefined,
119
+ ): readonly AgentMessage[] | undefined {
120
+ if (!messages || active === projected) return messages;
121
+ const original = new Set(
122
+ buildSessionContext([...active]).messages.map(messageKey),
123
+ );
124
+ const reconstructed = buildSessionContext([...projected]).messages;
125
+ const desired = new Set(reconstructed.map(messageKey));
126
+ const retained = messages.filter(
127
+ (message) =>
128
+ !original.has(messageKey(message)) || desired.has(messageKey(message)),
129
+ );
130
+ const positions = new Map<string, number[]>();
131
+ retained.forEach((message, index) => {
132
+ const key = messageKey(message);
133
+ positions.set(key, [...(positions.get(key) ?? []), index]);
134
+ });
135
+ const insertions = new Map<number, AgentMessage[]>();
136
+ let pending: AgentMessage[] = [];
137
+ let last = -1;
138
+ for (const message of reconstructed) {
139
+ const key = messageKey(message);
140
+ const position = positions.get(key)?.shift();
141
+ if (position !== undefined) {
142
+ if (pending.length)
143
+ insertions.set(position, [
144
+ ...(insertions.get(position) ?? []),
145
+ ...pending,
146
+ ]);
147
+ pending = [];
148
+ last = position;
149
+ } else if (!original.has(key)) pending.push(message);
150
+ }
151
+ if (pending.length)
152
+ insertions.set(last + 1, [...(insertions.get(last + 1) ?? []), ...pending]);
153
+ return retained
154
+ .flatMap((message, index) => [...(insertions.get(index) ?? []), message])
155
+ .concat(insertions.get(retained.length) ?? []);
156
+ }
157
+
158
+ function messageKey(message: AgentMessage): string {
159
+ return JSON.stringify([
160
+ message.role,
161
+ message.timestamp,
162
+ message.role === "custom"
163
+ ? message.customType
164
+ : message.role === "toolResult"
165
+ ? message.toolCallId
166
+ : message.role === "branchSummary"
167
+ ? message.fromId
168
+ : undefined,
169
+ ]);
170
+ }
@@ -0,0 +1,192 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { JsonValue } from "@earendil-works/pi-ai";
3
+ import {
4
+ buildSessionProjection,
5
+ type SessionEntry,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+ import { Check } from "typebox/value";
9
+
10
+ const READ_KEY = "codexContextNoteRead";
11
+ const READ_SCHEMA = Type.Object(
12
+ {
13
+ protocol: Type.Literal(1),
14
+ origin: Type.Literal("host"),
15
+ id: Type.String({ pattern: "^[a-f0-9-]{36}$" }),
16
+ path: Type.String({ minLength: 1 }),
17
+ namespace: Type.Optional(Type.Literal("notes")),
18
+ api: Type.String({ minLength: 1 }),
19
+ provider: Type.String({ minLength: 1 }),
20
+ model: Type.String({ minLength: 1 }),
21
+ timestamp: Type.Number({ minimum: 0 }),
22
+ content: Type.Array(
23
+ Type.Union([
24
+ Type.Object({ type: Type.Literal("text"), text: Type.String() }),
25
+ Type.Object({
26
+ type: Type.Literal("image"),
27
+ data: Type.String(),
28
+ mimeType: Type.String(),
29
+ detail: Type.Optional(
30
+ Type.Union([
31
+ Type.Literal("auto"),
32
+ Type.Literal("high"),
33
+ Type.Literal("original"),
34
+ ]),
35
+ ),
36
+ }),
37
+ ]),
38
+ ),
39
+ details: Type.Object({
40
+ codexHistoryNotes: Type.Record(Type.String(), Type.Unknown()),
41
+ }),
42
+ },
43
+ { additionalProperties: false },
44
+ );
45
+
46
+ function callId(id: string): string {
47
+ const name = "tree_handoff_" + id.replaceAll("-", "");
48
+ return `${name}|fc_${name}`;
49
+ }
50
+
51
+ function isJson(value: unknown): value is JsonValue {
52
+ return (
53
+ value === null ||
54
+ typeof value === "string" ||
55
+ typeof value === "boolean" ||
56
+ (typeof value === "number" && Number.isFinite(value)) ||
57
+ (Array.isArray(value)
58
+ ? value.every(isJson)
59
+ : typeof value === "object" && Object.values(value).every(isJson))
60
+ );
61
+ }
62
+
63
+ /** Expand only surviving summaries, after Pi compaction and window retirement. */
64
+ export function projectTreeHandoffReads(
65
+ messages: readonly AgentMessage[],
66
+ entries: readonly SessionEntry[],
67
+ ): AgentMessage[] {
68
+ const summaries = new Map(
69
+ entries
70
+ .filter((entry) => entry.type === "branch_summary")
71
+ .map((entry) => [
72
+ JSON.stringify([entry.fromId, new Date(entry.timestamp).getTime()]),
73
+ entry,
74
+ ]),
75
+ );
76
+ const calls = new Set(
77
+ messages.flatMap((message) =>
78
+ message.role === "assistant"
79
+ ? message.content.flatMap((part) =>
80
+ part.type === "toolCall" ? [part.id] : [],
81
+ )
82
+ : [],
83
+ ),
84
+ );
85
+ const results = new Set(
86
+ messages.flatMap((message) =>
87
+ message.role === "toolResult" ? [message.toolCallId] : [],
88
+ ),
89
+ );
90
+ return messages.flatMap((message): AgentMessage[] => {
91
+ if (message.role !== "branchSummary") return [message];
92
+ const details = summaries.get(
93
+ JSON.stringify([message.fromId, message.timestamp]),
94
+ )?.details;
95
+ if (!details || typeof details !== "object" || !(READ_KEY in details))
96
+ return [message];
97
+ const read = details[READ_KEY];
98
+ if (!Check(READ_SCHEMA, read))
99
+ throw new Error("Invalid persisted tree handoff read");
100
+ const resultDetails = read.details;
101
+ if (!isJson(resultDetails))
102
+ throw new Error("Invalid persisted tree handoff result");
103
+ const id = callId(read.id);
104
+ if (calls.has(id) !== results.has(id))
105
+ throw new Error("Incomplete tree handoff read in context");
106
+ if (calls.has(id)) return [message];
107
+ const call = {
108
+ type: "toolCall" as const,
109
+ id,
110
+ name: "notes",
111
+ arguments: { action: "read_file", path: read.path },
112
+ ...(read.namespace
113
+ ? { namespace: read.namespace, responsesNamespace: read.namespace }
114
+ : {}),
115
+ };
116
+ return [
117
+ message,
118
+ {
119
+ role: "assistant",
120
+ api: read.api,
121
+ provider: read.provider,
122
+ model: read.model,
123
+ content: [call],
124
+ // This host operation has no generated tokens or provider response ID.
125
+ usage: {
126
+ input: 0,
127
+ output: 0,
128
+ cacheRead: 0,
129
+ cacheWrite: 0,
130
+ totalTokens: 0,
131
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
132
+ },
133
+ stopReason: "toolUse",
134
+ timestamp: read.timestamp,
135
+ },
136
+ {
137
+ role: "toolResult",
138
+ toolCallId: id,
139
+ toolName: "notes",
140
+ isError: false,
141
+ content: read.content,
142
+ details: resultDetails,
143
+ timestamp: read.timestamp,
144
+ },
145
+ ];
146
+ });
147
+ }
148
+
149
+ /** Compaction-only contributions: never append these entries to the session file.
150
+ * IDs belong to the original summary; Pi's persisted kept boundary stays physical.
151
+ */
152
+ export function projectTreeHandoffBranch(
153
+ entries: readonly SessionEntry[],
154
+ ): readonly SessionEntry[] {
155
+ const projection = buildSessionProjection([...entries]);
156
+ const expanded = projectTreeHandoffReads(projection.messages, entries);
157
+ if (expanded.length === projection.messages.length) return entries;
158
+ const additions = new Map<string, AgentMessage[]>();
159
+ for (const entry of projection.entries) {
160
+ if (entry.sourceEntry.type !== "branch_summary") continue;
161
+ const message = entry.messages.find(
162
+ (item) => item.role === "branchSummary",
163
+ );
164
+ if (!message) continue;
165
+ const offset = expanded.indexOf(message);
166
+ const next = projection.messages[projection.messages.indexOf(message) + 1];
167
+ const end = next ? expanded.indexOf(next) : expanded.length;
168
+ const inserted = expanded.slice(offset + 1, end);
169
+ if (inserted.length) additions.set(entry.sourceEntry.id, inserted);
170
+ }
171
+ const ids = new Set(entries.map((entry) => entry.id));
172
+ let parentId: string | null = null;
173
+ return entries.flatMap((entry): SessionEntry[] => {
174
+ const result: SessionEntry[] = [
175
+ entry.parentId === parentId ? entry : { ...entry, parentId },
176
+ ];
177
+ parentId = entry.id;
178
+ for (const [index, message] of (additions.get(entry.id) ?? []).entries()) {
179
+ const id = entry.id + ":notes-handoff:" + index;
180
+ if (ids.has(id)) throw new Error("Conflicting tree handoff contribution");
181
+ result.push({
182
+ type: "message",
183
+ id,
184
+ parentId,
185
+ timestamp: entry.timestamp,
186
+ message,
187
+ });
188
+ parentId = id;
189
+ }
190
+ return result;
191
+ });
192
+ }
@@ -0,0 +1,105 @@
1
+ import {
2
+ buildSessionProjection,
3
+ type CompactionEntryDraft,
4
+ calculateContextTokens,
5
+ type ExtensionContext,
6
+ estimateTokens,
7
+ getLastAssistantUsage,
8
+ type SessionBeforeCompactEvent,
9
+ type SessionBeforeCompactResult,
10
+ type SessionEntry,
11
+ } from "@earendil-works/pi-coding-agent";
12
+
13
+ const MARKER = "pi-notes-compaction/window-checkpoint";
14
+
15
+ export function isWindowCheckpoint(entry: SessionEntry): boolean {
16
+ return (
17
+ entry.type === "compaction" &&
18
+ entry.details !== null &&
19
+ typeof entry.details === "object" &&
20
+ MARKER in entry.details &&
21
+ entry.details[MARKER] === 1
22
+ );
23
+ }
24
+
25
+ /** Persist one complete native cut, never a partially edited conversation. */
26
+ export class WindowCheckpoints {
27
+ private pending: { session: string; firstKeptEntryId: string } | undefined;
28
+ private readonly project: (
29
+ entries: readonly SessionEntry[],
30
+ ) => SessionEntry[];
31
+
32
+ constructor(project: (entries: readonly SessionEntry[]) => SessionEntry[]) {
33
+ this.project = project;
34
+ }
35
+
36
+ draft(entries: readonly SessionEntry[]): CompactionEntryDraft | undefined {
37
+ const kept = this.project(entries);
38
+ const first = kept[0];
39
+ if (!first || first.id === entries[0]?.id) return;
40
+ const previous = entries.findLast((entry) => entry.type === "compaction");
41
+ if (previous?.firstKeptEntryId === first.id) return;
42
+ return {
43
+ type: "compaction",
44
+ summary: "",
45
+ firstKeptEntryId: first.id,
46
+ details: { [MARKER]: 1 },
47
+ };
48
+ }
49
+
50
+ prepare(
51
+ event: SessionBeforeCompactEvent,
52
+ ctx: ExtensionContext,
53
+ ): SessionBeforeCompactResult | undefined {
54
+ if (!this.pending) return;
55
+ const draft = this.draft(event.branchEntries);
56
+ if (
57
+ event.reason !== "manual" ||
58
+ ctx.sessionManager.getSessionId() !== this.pending.session ||
59
+ draft?.firstKeptEntryId !== this.pending.firstKeptEntryId
60
+ )
61
+ return { cancel: true };
62
+ const kept = this.project(event.branchEntries);
63
+ const messages = buildSessionProjection(kept).messages;
64
+ const usage = getLastAssistantUsage(kept);
65
+ return {
66
+ compaction: {
67
+ summary: draft.summary,
68
+ firstKeptEntryId: this.pending.firstKeptEntryId,
69
+ tokensBefore: usage
70
+ ? calculateContextTokens(usage)
71
+ : messages.reduce(
72
+ (tokens, message) => tokens + estimateTokens(message),
73
+ 0,
74
+ ),
75
+ details: draft.details,
76
+ },
77
+ };
78
+ }
79
+
80
+ /** Align restored sessions before Pi's first request-time structuredClone. */
81
+ async restore(ctx: ExtensionContext): Promise<void> {
82
+ const draft = this.draft(ctx.sessionManager.getBranch());
83
+ if (!draft?.firstKeptEntryId || !ctx.model) return;
84
+ this.pending = {
85
+ session: ctx.sessionManager.getSessionId(),
86
+ firstKeptEntryId: draft.firstKeptEntryId,
87
+ };
88
+ try {
89
+ await new Promise<void>((resolve, reject) => {
90
+ ctx.compact({
91
+ onComplete: () => resolve(),
92
+ onError: (error) => {
93
+ // Pi cannot cut a small conversation yet. The next completed
94
+ // turn can persist the same complete cut as a boundary draft.
95
+ if (error.message === "Nothing to compact (session too small)")
96
+ resolve();
97
+ else reject(error);
98
+ },
99
+ });
100
+ });
101
+ } finally {
102
+ this.pending = undefined;
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,185 @@
1
+ import type {
2
+ CustomMessageEntryDraft,
3
+ ExtensionAPI,
4
+ SessionEntry,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { Box, Text, TruncatedText } from "@earendil-works/pi-tui";
7
+ import type { WindowIdentity } from "./bridge.js";
8
+
9
+ export const WINDOW_MESSAGE = "notes-compaction:window:v1";
10
+ export const SETTLEMENT_ENTRY = "notes-compaction:settled:v1";
11
+ export interface WindowDetails {
12
+ protocol: 1;
13
+ kind: "window" | "identity" | "reminder" | "urgent" | "task-boundary";
14
+ identity: WindowIdentity;
15
+ trim: boolean;
16
+ }
17
+ const GUIDANCE = `<context_window_guidance>
18
+ Notes are recovery state, not diary. Storage is virtual, not disk. Create relative paths.
19
+
20
+ MUST maintain one authoritative checkpoint per task/topic: request, constraints, decision, status, next steps and relevant history IDs.
21
+
22
+ Near a substantive turn's end, before replying, consolidate changed recovery state. notes write creates or replaces; append adds. Do not interleave saves with ordinary tool calls. Skip routine turns and unchanged state. Explicit reminders and earlier handoffs still apply.
23
+
24
+ Link existing notes rather than duplicate. Recording does not authorise implementation.
25
+
26
+ Immediately before new_context, MUST save the checkpoint via notes. Save before handoff too. For rollover, call new_context after saving.
27
+
28
+ When recovering context, read the checkpoint and necessary links if available, then retrieve a few relevant user messages with history for intent and communication preferences. Past messages are context, not renewed requests. Current instructions take precedence. Resume the current task; read further history only as needed. Do not reread unchanged notes.
29
+
30
+ MUST reread required skills after rollover.
31
+ </context_window_guidance>`;
32
+
33
+ const GPT_GUIDANCE = `<context_window_guidance>
34
+ Notes=virtual recovery state, NOT disk/diary. Create relative paths. MUST maintain one authoritative checkpoint/task→request/constraints/decision/status/next steps/history IDs. Link existing notes≠duplicate; recording≠implementation permission.
35
+
36
+ Near substantive turn end, before reply→consolidate CHANGED recovery. notes write→create/replace; append→add. No saves amid ordinary tool calls; skip routine/unchanged state. Explicit reminders/earlier handoffs still apply.
37
+
38
+ Immediately before new_context MUST save checkpoint via notes; before handoff too. Rollover→new_context after save.
39
+
40
+ Context recovery→notes checkpoint/necessary links if available→a few relevant user messages via history for intent/communication preferences→resume current task. Past messages=context≠renewed requests; current instructions win. Further history as needed; no unchanged-note rereads.
41
+
42
+ After rollover MUST reread required skills.
43
+ </context_window_guidance>`;
44
+
45
+ export function registerWindowRenderer(pi: ExtensionAPI): void {
46
+ pi.registerMessageRenderer(
47
+ WINDOW_MESSAGE,
48
+ (message, { expanded, outputPad, keyHint }, theme) => {
49
+ const details = parseWindowDetails(message.details);
50
+ if (!details || typeof message.content !== "string") return undefined;
51
+ const title =
52
+ details.kind === "task-boundary"
53
+ ? "Task-boundary reminder"
54
+ : details.kind === "urgent"
55
+ ? "Context nearly full · Save notes and start a new window now"
56
+ : details.kind === "reminder"
57
+ ? "Context checkpoint reminder · Save notes and start a new window"
58
+ : `Context window ${details.identity.windowNumber + 1} · Notes and history`;
59
+ const box = new Box(outputPad, 1, (text) =>
60
+ theme.bg("customMessageBg", text),
61
+ );
62
+ box.addChild(
63
+ expanded
64
+ ? new Text(theme.fg("customMessageText", message.content), 0, 0)
65
+ : new TruncatedText(
66
+ theme.fg(
67
+ details.kind === "urgent" ? "warning" : "customMessageLabel",
68
+ title,
69
+ ) +
70
+ theme.fg(
71
+ "dim",
72
+ ` (${keyHint("app.tools.expand", "to expand")})`,
73
+ ),
74
+ 0,
75
+ 0,
76
+ ),
77
+ );
78
+ return box;
79
+ },
80
+ );
81
+ }
82
+
83
+ function identity(value: unknown): WindowIdentity | undefined {
84
+ if (!value || typeof value !== "object") return;
85
+ const data = value as Partial<WindowIdentity>;
86
+ if (
87
+ typeof data.firstWindowId !== "string" ||
88
+ !data.firstWindowId ||
89
+ typeof data.currentWindowId !== "string" ||
90
+ !data.currentWindowId ||
91
+ !Number.isInteger(data.windowNumber) ||
92
+ data.windowNumber! < 0 ||
93
+ (data.previousWindowId !== undefined &&
94
+ typeof data.previousWindowId !== "string")
95
+ )
96
+ return;
97
+ return data as WindowIdentity;
98
+ }
99
+
100
+ function parseWindowDetails(value: unknown): WindowDetails | undefined {
101
+ if (!value || typeof value !== "object") return;
102
+ const details = value as Partial<WindowDetails>;
103
+ const ids = identity(details.identity);
104
+ if (
105
+ details.protocol !== 1 ||
106
+ !ids ||
107
+ !["window", "identity", "reminder", "urgent", "task-boundary"].includes(
108
+ details.kind ?? "",
109
+ ) ||
110
+ typeof details.trim !== "boolean"
111
+ )
112
+ return;
113
+ return {
114
+ protocol: 1,
115
+ kind: details.kind!,
116
+ identity: ids,
117
+ trim: details.trim,
118
+ };
119
+ }
120
+
121
+ /** Understand previous PCC window IDs for familiar history lookup, without importing its runtime. */
122
+ export function windowDetails(
123
+ entry: SessionEntry | CustomMessageEntryDraft,
124
+ ): WindowDetails | undefined {
125
+ if (entry.type !== "custom_message") return;
126
+ return messageWindowDetails(entry.customType, entry.details);
127
+ }
128
+
129
+ export function messageWindowDetails(
130
+ customType: string,
131
+ data: unknown,
132
+ ): WindowDetails | undefined {
133
+ if (customType === WINDOW_MESSAGE) return parseWindowDetails(data);
134
+ if (
135
+ customType !== "codex-context-window" ||
136
+ !data ||
137
+ typeof data !== "object" ||
138
+ !("contextManagement" in data)
139
+ )
140
+ return;
141
+ const details = data.contextManagement;
142
+ if (
143
+ !details ||
144
+ typeof details !== "object" ||
145
+ !("kind" in details) ||
146
+ (details.kind !== "window" && details.kind !== "task-boundary")
147
+ )
148
+ return;
149
+ const ids = identity(details);
150
+ return ids
151
+ ? {
152
+ protocol: 1,
153
+ kind: details.kind,
154
+ identity: ids,
155
+ trim:
156
+ "trimPreviousWindow" in details &&
157
+ details.trimPreviousWindow === true,
158
+ }
159
+ : undefined;
160
+ }
161
+
162
+ export function windowMessage(
163
+ ids: WindowIdentity,
164
+ agent: string,
165
+ hint: string,
166
+ trim: boolean,
167
+ kind: "window" | "identity" = "window",
168
+ gpt = false,
169
+ ): CustomMessageEntryDraft {
170
+ // History exposes lookup IDs on demand; rollover must not churn this text just for UUIDs.
171
+ const lines = [`Agent name: ${agent}`];
172
+ if (hint) lines.push(hint);
173
+ return {
174
+ type: "custom_message",
175
+ customType: WINDOW_MESSAGE,
176
+ content: `${gpt ? GPT_GUIDANCE : GUIDANCE}\n\n<context_window>\n${lines.join("\n")}\n</context_window>`,
177
+ display: true,
178
+ details: {
179
+ protocol: 1,
180
+ kind,
181
+ identity: ids,
182
+ trim,
183
+ } satisfies WindowDetails,
184
+ };
185
+ }