@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,174 @@
1
+ import type {
2
+ AgentToolResult,
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import type { NotesActivation } from "./activation.js";
7
+ import type { NotesLifecycle } from "./lifecycle.js";
8
+ import {
9
+ GPT_NEW_CONTEXT_DESCRIPTION,
10
+ HISTORY_USAGE,
11
+ NEW_CONTEXT_DESCRIPTION,
12
+ NOTES_SCHEMA,
13
+ NOTES_USAGE,
14
+ } from "./tool-contracts.js";
15
+ import type { createTools } from "./tools.js";
16
+ import { projectTreeCheckpointBranch } from "./tree-checkpoint.js";
17
+ import { projectTreeHandoffBranch } from "./tree-handoff-read.js";
18
+ import type { WindowCheckpoints } from "./window-checkpoint.js";
19
+
20
+ export async function registerNotesToolIntegrations(
21
+ pi: ExtensionAPI,
22
+ lifecycle: NotesLifecycle,
23
+ activation: NotesActivation,
24
+ tools: ReturnType<typeof createTools>,
25
+ ) {
26
+ try {
27
+ const { registerGptPromptMode } = await import(
28
+ "@howaboua/pi-codex-conversion/prompt-mode"
29
+ );
30
+ const registration = registerGptPromptMode(pi, (active, ctx) => {
31
+ if (ctx) activation.refreshActivation(ctx);
32
+ const tool = tools.find((tool) => tool.name === "new_context");
33
+ const description = active
34
+ ? GPT_NEW_CONTEXT_DESCRIPTION
35
+ : NEW_CONTEXT_DESCRIPTION;
36
+ if (tool && tool.description !== description) {
37
+ tool.description = description;
38
+ pi.registerTool(tool);
39
+ }
40
+ return lifecycle.active ? tools : [];
41
+ });
42
+ lifecycle.gptPromptMode = () => registration.active;
43
+ } catch (error) {
44
+ if (
45
+ !(error instanceof Error) ||
46
+ !("code" in error) ||
47
+ ![
48
+ "ERR_MODULE_NOT_FOUND",
49
+ "MODULE_NOT_FOUND",
50
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
51
+ ].includes(String(error.code)) ||
52
+ !error.message.includes("@howaboua/pi-codex-conversion")
53
+ )
54
+ throw error;
55
+ }
56
+ let refreshNested = () => {};
57
+ try {
58
+ const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
59
+ await import("@howaboua/pi-codex-conversion/code-mode");
60
+ const registration = registerCodeModeExtensionTools(
61
+ pi,
62
+ () =>
63
+ tools
64
+ .filter((tool) => tool.name === "notes" || tool.name === "history")
65
+ .map((tool) => ({
66
+ ...adaptToolForCodeMode(tool, {
67
+ discovery: "help",
68
+ usage: tool.name === "notes" ? NOTES_USAGE : HISTORY_USAGE,
69
+ deferLoading: tool.name !== "notes",
70
+ opaqueResult: tool.name === "notes",
71
+ ...(tool.name === "history"
72
+ ? { resultValue: historyResultValue }
73
+ : {}),
74
+ }),
75
+ // Code checks inputs before Pi can normalise this body alias.
76
+ ...(tool.name === "notes"
77
+ ? {
78
+ inputSchema: {
79
+ ...NOTES_SCHEMA,
80
+ properties: {
81
+ ...NOTES_SCHEMA.properties,
82
+ content: NOTES_SCHEMA.properties.text,
83
+ },
84
+ },
85
+ }
86
+ : {}),
87
+ })),
88
+ { isActive: () => lifecycle.active },
89
+ );
90
+ refreshNested = registration.refresh;
91
+ pi.on("session_shutdown", () => registration.unregister());
92
+ const { withCodexDeveloperMessageDetails } = await import(
93
+ "@howaboua/pi-codex-conversion/developer-messages"
94
+ );
95
+ lifecycle.prepareReminder = withCodexDeveloperMessageDetails;
96
+ } catch (error) {
97
+ if (!optionalPccMissing(error)) throw error;
98
+ }
99
+ return refreshNested;
100
+ }
101
+
102
+ function historyResultValue(result: AgentToolResult<unknown>): unknown {
103
+ const [part] = result.content;
104
+ if (result.content.length === 1 && part?.type === "text") {
105
+ try {
106
+ return JSON.parse(part.text);
107
+ } catch {
108
+ return part.text;
109
+ }
110
+ }
111
+ return { content: result.content };
112
+ }
113
+
114
+ export async function registerNotesCompactionIntegration(
115
+ pi: ExtensionAPI,
116
+ activation: NotesActivation,
117
+ lifecycle: NotesLifecycle,
118
+ checkpoints: WindowCheckpoints,
119
+ ) {
120
+ let prepareProviderWindow:
121
+ | ((ctx: ExtensionContext) => Promise<void>)
122
+ | undefined;
123
+ const prepareCompaction = (
124
+ event: import("@earendil-works/pi-coding-agent").SessionBeforeCompactEvent,
125
+ ctx: ExtensionContext,
126
+ ) =>
127
+ activation.available
128
+ ? (checkpoints.prepare(event, ctx) ?? lifecycle.beforeCompact(event, ctx))
129
+ : undefined;
130
+ try {
131
+ const {
132
+ registerCompactionPreparation,
133
+ registerContextBranchProjection,
134
+ prepareContextWindow,
135
+ } = await import("@howaboua/pi-codex-conversion/compaction");
136
+ prepareProviderWindow = (ctx) => prepareContextWindow(pi, ctx);
137
+ const registration = registerCompactionPreparation(pi, prepareCompaction);
138
+ const stopProjection = registerContextBranchProjection(
139
+ pi,
140
+ (entries, ctx) =>
141
+ activation.available
142
+ ? projectTreeHandoffBranch(
143
+ lifecycle.windows.projectBranch(
144
+ projectTreeCheckpointBranch(
145
+ entries,
146
+ ctx.sessionManager.getEntries(),
147
+ ),
148
+ ),
149
+ )
150
+ : entries,
151
+ );
152
+ pi.on("session_shutdown", stopProjection);
153
+ pi.on("session_before_compact", registration.prepare);
154
+ pi.on("session_shutdown", () => registration.dispose());
155
+ } catch (error) {
156
+ if (!optionalPccMissing(error)) throw error;
157
+ pi.on("session_before_compact", prepareCompaction);
158
+ }
159
+
160
+ return prepareProviderWindow;
161
+ }
162
+
163
+ export function optionalPccMissing(error: unknown): boolean {
164
+ return (
165
+ error instanceof Error &&
166
+ "code" in error &&
167
+ [
168
+ "ERR_MODULE_NOT_FOUND",
169
+ "MODULE_NOT_FOUND",
170
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
171
+ ].includes(String(error.code)) &&
172
+ error.message.includes("@howaboua/pi-codex-conversion")
173
+ );
174
+ }
@@ -0,0 +1,308 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ AgentSettledEvent,
4
+ BeforeAgentStartEvent,
5
+ BeforeAgentStartEventResult,
6
+ CustomMessageEntryDraft,
7
+ ExtensionAPI,
8
+ ExtensionContext,
9
+ InputEvent,
10
+ InputEventResult,
11
+ SessionBeforeCompactEvent,
12
+ SessionCompactFailedEvent,
13
+ } from "@earendil-works/pi-coding-agent";
14
+ import type { NotesBridge } from "./bridge.js";
15
+ import { FreshCheckpoint } from "./fresh-checkpoint.js";
16
+ import {
17
+ hasFreshNotes,
18
+ hasPrecedingNoteWrite,
19
+ NOTES_RUN_ENTRY,
20
+ } from "./fresh-notes.js";
21
+ import { IdleAdmission } from "./idle-admission.js";
22
+ import type { ModelRoleHandoff } from "./model-roles.js";
23
+ import { noteHints, sessionRef } from "./notes.js";
24
+ import { RolloverRequests } from "./rollover.js";
25
+ import type { IdleMinutes, NewWindowRequests } from "./settings.js";
26
+ import { savedNotesIdentity } from "./shared-notes.js";
27
+ import type { NotesStore } from "./store.js";
28
+ import {
29
+ SETTLEMENT_ENTRY,
30
+ WINDOW_MESSAGE,
31
+ Windows,
32
+ windowDetails,
33
+ windowMessage,
34
+ } from "./windows.js";
35
+
36
+ // Public event coordinator owns window identity and orders settlement before admissions.
37
+ export class NotesLifecycle {
38
+ readonly windows = new Windows();
39
+ gptPromptMode = () => false;
40
+ active = false;
41
+ normalCompaction = false;
42
+ newWindowRequests: NewWindowRequests = "unrestricted";
43
+ idleMinutes: IdleMinutes = 0;
44
+ taskBoundaryReminder = 0;
45
+ bridge: NotesBridge | undefined;
46
+ prepareReminder: NotesBridge["prepareReminder"];
47
+ prepareWindow: ((ctx: ExtensionContext) => Promise<void>) | undefined;
48
+ runId = "";
49
+ private readonly checkpoint: FreshCheckpoint;
50
+ private readonly admission: IdleAdmission;
51
+ private readonly requests: RolloverRequests;
52
+
53
+ private readonly pi: ExtensionAPI;
54
+ private readonly store: NotesStore;
55
+ constructor(pi: ExtensionAPI, store: NotesStore) {
56
+ this.pi = pi;
57
+ this.store = store;
58
+ this.checkpoint = new FreshCheckpoint(this, (message, options) =>
59
+ this.sendMessage(message, options),
60
+ );
61
+ this.requests = new RolloverRequests(
62
+ this,
63
+ (ctx, triggerTurn, trim, handoff) =>
64
+ this.openWindow(ctx, triggerTurn, trim, handoff),
65
+ (message, options) => this.sendMessage(message, options),
66
+ (ctx, instructions) => this.checkpoint.start(ctx, instructions),
67
+ );
68
+ this.admission = new IdleAdmission(
69
+ this,
70
+ pi,
71
+ (ctx, triggerTurn) => this.requests.roll(ctx, triggerTurn),
72
+ () => this.requests.pending,
73
+ () => this.checkpoint.pending,
74
+ );
75
+ }
76
+ private sendMessage(
77
+ message: Omit<CustomMessageEntryDraft, "type">,
78
+ options: { triggerTurn: boolean },
79
+ ): void {
80
+ const draft: CustomMessageEntryDraft = {
81
+ type: "custom_message",
82
+ ...message,
83
+ details: message.details ?? {},
84
+ };
85
+ this.pi.sendMessage(this.prepareReminder?.(draft) ?? draft, options);
86
+ }
87
+ agent(ctx: ExtensionContext): string {
88
+ return (
89
+ this.bridge?.agentName?.(ctx) ??
90
+ savedNotesIdentity({
91
+ threadId: ctx.sessionManager.getSessionId(),
92
+ entries: ctx.sessionManager.getEntries(),
93
+ }).agentName
94
+ );
95
+ }
96
+ reset(ctx?: ExtensionContext): void {
97
+ this.admission.reset();
98
+ this.checkpoint.reset();
99
+ this.requests.reset();
100
+ this.runId = "";
101
+ this.windows.restore(ctx?.sessionManager.getBranch() ?? []);
102
+ }
103
+ private initialize(
104
+ ctx: ExtensionContext,
105
+ ): CustomMessageEntryDraft | undefined {
106
+ const branch = ctx.sessionManager.getBranch();
107
+ this.windows.restore(branch);
108
+ const latest = branch.findLast(
109
+ (entry) =>
110
+ entry.type === "custom_message" &&
111
+ entry.customType === WINDOW_MESSAGE &&
112
+ ["window", "identity"].includes(windowDetails(entry)?.kind ?? ""),
113
+ );
114
+ if (!this.windows.current || !latest) {
115
+ const inherited = Boolean(this.windows.current);
116
+ const ids = this.windows.current ?? this.windows.next();
117
+ this.windows.current = ids;
118
+ return windowMessage(
119
+ ids,
120
+ this.agent(ctx),
121
+ noteHints(this.store, ctx, this.agent(ctx)),
122
+ false,
123
+ inherited ? "identity" : "window",
124
+ this.gptPromptMode(),
125
+ );
126
+ } else if (
127
+ latest.type === "custom_message" &&
128
+ typeof latest.content === "string" &&
129
+ !latest.content.includes(`Agent name: ${this.agent(ctx)}\n`)
130
+ ) {
131
+ return windowMessage(
132
+ this.windows.current,
133
+ this.agent(ctx),
134
+ noteHints(this.store, ctx, this.agent(ctx)),
135
+ false,
136
+ "identity",
137
+ this.gptPromptMode(),
138
+ );
139
+ }
140
+ }
141
+ beforeStart(
142
+ ctx: ExtensionContext,
143
+ event: BeforeAgentStartEvent,
144
+ ): BeforeAgentStartEventResult | undefined {
145
+ // A custom kickoff is not in the branch until after before_agent_start.
146
+ // Adopt its boundary without restoring the outgoing window or emitting a duplicate.
147
+ const startingWindow =
148
+ event.messageType === "custom"
149
+ ? windowDetails({ ...event.message, type: "custom_message" })
150
+ : undefined;
151
+ let message: CustomMessageEntryDraft | undefined;
152
+ if (startingWindow?.kind === "window")
153
+ this.windows.current = startingWindow.identity;
154
+ else message = this.initialize(ctx);
155
+ this.runId = randomUUID();
156
+ this.pi.appendEntry(NOTES_RUN_ENTRY, { runId: this.runId });
157
+ this.checkpoint.bind(event, this.runId);
158
+ return message
159
+ ? { message: this.prepareReminder?.(message) ?? message }
160
+ : undefined;
161
+ }
162
+ fresh(ctx: ExtensionContext, runId?: string): boolean {
163
+ return hasFreshNotes(
164
+ ctx.sessionManager.getBranch(),
165
+ this.windows.current?.currentWindowId,
166
+ runId,
167
+ );
168
+ }
169
+ requestRollover(
170
+ ctx: ExtensionContext,
171
+ callId: string,
172
+ handoff?: ModelRoleHandoff,
173
+ ): boolean {
174
+ if (this.newWindowRequests === "off")
175
+ throw new Error(
176
+ "New window requests are disabled. Continue in the current window.",
177
+ );
178
+ if (this.checkpoint.pending || this.admission.pending) return false;
179
+ if (this.requests.pending) return false;
180
+ if (
181
+ !hasPrecedingNoteWrite(
182
+ ctx.sessionManager.getBranch(),
183
+ this.windows.current?.currentWindowId,
184
+ this.runId,
185
+ callId,
186
+ )
187
+ )
188
+ throw new Error(
189
+ "Save your progress in your own notes using a relative path, wait for the write to succeed, then call new_context next. Writing another agent's notes does not save your checkpoint.",
190
+ );
191
+ this.requests.schedule(ctx, handoff);
192
+ return true;
193
+ }
194
+ private async openWindow(
195
+ ctx: ExtensionContext,
196
+ triggerTurn: boolean,
197
+ trim: boolean,
198
+ handoff?: ModelRoleHandoff,
199
+ ): Promise<void> {
200
+ if (!ctx.isIdle())
201
+ throw new Error("Wait for the current run to settle before rollover");
202
+ const sessionId = ctx.sessionManager.getSessionId();
203
+ const windowId = this.windows.current?.currentWindowId;
204
+ if (trim) await this.prepareWindow?.(ctx);
205
+ const assertCurrentWindow = () => {
206
+ if (
207
+ !ctx.isIdle() ||
208
+ sessionId !== ctx.sessionManager.getSessionId() ||
209
+ windowId !== this.windows.current?.currentWindowId ||
210
+ !this.active
211
+ )
212
+ throw new Error("Session changed before rollover");
213
+ };
214
+ assertCurrentWindow();
215
+ // Prepare the outgoing provider first; the successor's full kickoff sees the new model.
216
+ if (handoff) {
217
+ await handoff.activate(ctx);
218
+ assertCurrentWindow();
219
+ }
220
+ const ids = this.windows.next();
221
+ const hint = noteHints(this.store, ctx, this.agent(ctx));
222
+ const message = windowMessage(
223
+ ids,
224
+ this.agent(ctx),
225
+ hint,
226
+ trim,
227
+ "window",
228
+ this.gptPromptMode(),
229
+ );
230
+ this.windows.current = ids;
231
+ if (handoff) message.content = `${message.content}\n\nRole: ${handoff.id}`;
232
+ this.sendMessage(message, { triggerTurn });
233
+ }
234
+
235
+ prepareCustomTurn(ctx: ExtensionContext): Promise<void> | undefined {
236
+ return this.admission.prepareCustomTurn(ctx);
237
+ }
238
+ outcome(outcome: "completed" | "aborted" | "error"): void {
239
+ this.checkpoint.outcome(outcome);
240
+ }
241
+ input(
242
+ event: InputEvent,
243
+ ctx: ExtensionContext,
244
+ ): Promise<InputEventResult | undefined> {
245
+ return this.admission.input(event, ctx);
246
+ }
247
+ beforeCompact(
248
+ event: SessionBeforeCompactEvent,
249
+ ctx: ExtensionContext,
250
+ ): { cancel: true } | undefined {
251
+ return this.requests.beforeCompact(event, ctx);
252
+ }
253
+ allowsCompaction(reason: SessionBeforeCompactEvent["reason"]): boolean {
254
+ return this.requests.allowsCompaction(reason);
255
+ }
256
+ compactFailed(
257
+ event: SessionCompactFailedEvent,
258
+ ctx: ExtensionContext,
259
+ ): Promise<void> {
260
+ return this.requests.compactFailed(event, ctx);
261
+ }
262
+ async settled(
263
+ event: AgentSettledEvent,
264
+ ctx: ExtensionContext,
265
+ ): Promise<void> {
266
+ const checkpoint = this.checkpoint.take();
267
+ try {
268
+ this.store.updateFile(sessionRef(ctx));
269
+ const terminal = ctx.sessionManager
270
+ .getBranch()
271
+ .findLast(
272
+ (entry) =>
273
+ entry.type === "message" && entry.message.role !== "system",
274
+ );
275
+ if (terminal && this.windows.current)
276
+ this.pi.appendEntry(SETTLEMENT_ENTRY, {
277
+ protocol: 1,
278
+ windowId: this.windows.current.currentWindowId,
279
+ completedEntryId: terminal.id,
280
+ settledAt: Date.now(),
281
+ aborted: event.aborted,
282
+ });
283
+ } catch (error) {
284
+ this.requests.clear();
285
+ if (
286
+ checkpoint &&
287
+ (event.aborted ||
288
+ checkpoint.outcome === "aborted" ||
289
+ checkpoint.outcome === undefined)
290
+ ) {
291
+ ctx.ui.notify(
292
+ "Checkpoint cancelled. The old context remains.",
293
+ "warning",
294
+ );
295
+ } else if (this.admission.pending) this.admission.fail(ctx, error);
296
+ else throw error;
297
+ return;
298
+ }
299
+ if (checkpoint) {
300
+ if (!this.checkpoint.permitsRollover(checkpoint, event, ctx)) return;
301
+ await this.requests.roll(ctx, false);
302
+ return;
303
+ }
304
+ if (this.admission.drain()) return;
305
+ const rollover = this.requests.settled(ctx);
306
+ if (rollover) await rollover;
307
+ }
308
+ }
@@ -0,0 +1,79 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+
5
+ const THINKING_LEVELS = [
6
+ "off",
7
+ "minimal",
8
+ "low",
9
+ "medium",
10
+ "high",
11
+ "xhigh",
12
+ "max",
13
+ ] as const;
14
+ type ThinkingLevel = (typeof THINKING_LEVELS)[number];
15
+
16
+ export interface ModelRole {
17
+ id: string;
18
+ description: string;
19
+ provider: string;
20
+ model: string;
21
+ reasoning: ThinkingLevel;
22
+ }
23
+
24
+ export interface RoleConfig {
25
+ roles: ModelRole[];
26
+ }
27
+
28
+ export function roleConfigPath(): string {
29
+ return join(getAgentDir(), "notes-compaction", "model-roles.json");
30
+ }
31
+
32
+ export function readRoleConfig(path = roleConfigPath()): RoleConfig {
33
+ if (!existsSync(path)) return { roles: [] };
34
+ const value: unknown = JSON.parse(readFileSync(path, "utf8"));
35
+ if (
36
+ !value ||
37
+ typeof value !== "object" ||
38
+ !("roles" in value) ||
39
+ !Array.isArray(value.roles)
40
+ )
41
+ throw new Error(
42
+ `Model roles configuration must contain a roles array. Edit ${path}; /roles shows the format`,
43
+ );
44
+ const ids = new Set<string>();
45
+ const roles = value.roles.map((role: unknown): ModelRole => {
46
+ if (
47
+ !role ||
48
+ typeof role !== "object" ||
49
+ !("id" in role) ||
50
+ typeof role.id !== "string" ||
51
+ !/^[a-z][a-z0-9-]*$/.test(role.id) ||
52
+ !("description" in role) ||
53
+ typeof role.description !== "string" ||
54
+ !role.description.trim() ||
55
+ !("provider" in role) ||
56
+ typeof role.provider !== "string" ||
57
+ !role.provider.trim() ||
58
+ !("model" in role) ||
59
+ typeof role.model !== "string" ||
60
+ !role.model.trim() ||
61
+ !("reasoning" in role) ||
62
+ typeof role.reasoning !== "string" ||
63
+ !THINKING_LEVELS.includes(role.reasoning as ThinkingLevel) ||
64
+ ids.has(role.id)
65
+ )
66
+ throw new Error(
67
+ `Invalid or duplicate model role. Edit ${path}; /roles shows the format`,
68
+ );
69
+ ids.add(role.id);
70
+ return {
71
+ id: role.id,
72
+ description: role.description,
73
+ provider: role.provider,
74
+ model: role.model,
75
+ reasoning: role.reasoning as ThinkingLevel,
76
+ };
77
+ });
78
+ return { roles };
79
+ }
@@ -0,0 +1,74 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Key,
4
+ matchesKey,
5
+ truncateToWidth,
6
+ wrapTextWithAnsi,
7
+ } from "@earendil-works/pi-tui";
8
+ import type { ModelRole } from "./model-role-config.js";
9
+
10
+ export function openModelRoleScreen(
11
+ ctx: ExtensionContext,
12
+ roles: ModelRole[],
13
+ configPath: string,
14
+ error?: string,
15
+ ) {
16
+ return ctx.ui.custom<"notes-tab" | undefined>((tui, theme, _kb, done) => {
17
+ let offset = 0;
18
+ let maxOffset = 0;
19
+ let pageSize = 1;
20
+ return {
21
+ render: (width: number) => {
22
+ const content = [
23
+ ...(error ? [`Configuration error: ${error}`, ""] : []),
24
+ ...(roles.length
25
+ ? roles.flatMap((role) => [
26
+ `${role.id}: ${role.provider}/${role.model} (${role.reasoning})`,
27
+ role.description,
28
+ "",
29
+ ])
30
+ : ["No roles configured.", ""]),
31
+ "Edit JSON to configure roles:",
32
+ configPath,
33
+ "Create the parent directory and file if missing. Example:",
34
+ '{"roles":[{"id":"planning","description":"Sustained planning and design work","provider":"your-provider","model":"your-model-id","reasoning":"high"}]}',
35
+ "Use an available Pi provider and exact model ID. Reasoning: off, minimal, low, medium, high, xhigh or max.",
36
+ "Defined roles are available to the agent. Only role IDs and descriptions are shared with it. Legacy enabled is ignored.",
37
+ "Changes apply on the next turn or when reopening this tab. This view is read-only.",
38
+ ].flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width - 4)));
39
+ pageSize = Math.max(1, Math.min(20, tui.terminal.rows - 8));
40
+ maxOffset = Math.max(0, content.length - pageSize);
41
+ offset = Math.min(offset, maxOffset);
42
+ return [
43
+ ` ${theme.fg("dim", "Notes")} / ${theme.bold("Roles")}`,
44
+ "",
45
+ ...content
46
+ .slice(offset, offset + pageSize)
47
+ .map((line) => ` ${line}`),
48
+ "",
49
+ ` Tab Notes · ↑/↓ PgUp/PgDn scroll · Esc close${maxOffset ? ` · ${offset + 1}-${Math.min(offset + pageSize, content.length)}/${content.length}` : ""}`,
50
+ ].map((line) => truncateToWidth(line, width));
51
+ },
52
+ invalidate: () => {},
53
+ handleInput: (data: string) => {
54
+ if (matchesKey(data, Key.tab) || matchesKey(data, Key.shift(Key.tab))) {
55
+ done("notes-tab");
56
+ return;
57
+ }
58
+ if (matchesKey(data, Key.escape)) {
59
+ done(undefined);
60
+ return;
61
+ }
62
+ if (matchesKey(data, Key.up)) offset--;
63
+ else if (matchesKey(data, Key.down)) offset++;
64
+ else if (matchesKey(data, Key.pageUp)) offset -= pageSize;
65
+ else if (matchesKey(data, Key.pageDown)) offset += pageSize;
66
+ else if (matchesKey(data, Key.home)) offset = 0;
67
+ else if (matchesKey(data, Key.end)) offset = maxOffset;
68
+ else return;
69
+ offset = Math.max(0, Math.min(offset, maxOffset));
70
+ tui.requestRender();
71
+ },
72
+ };
73
+ });
74
+ }