@howaboua/pi-notes-compaction 0.0.12 → 0.0.14

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 (42) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/PCC-INTEGRATION.md +3 -1
  3. package/README.md +36 -22
  4. package/package.json +4 -6
  5. package/src/agent-identity.ts +112 -10
  6. package/src/attachment-sharing.ts +37 -6
  7. package/src/attachment-snapshot.ts +16 -6
  8. package/src/context-sharing.ts +15 -1
  9. package/src/extension-hooks.ts +15 -2
  10. package/src/extension-sharing.ts +25 -11
  11. package/src/fresh-checkpoint.ts +30 -4
  12. package/src/fresh-notes.ts +44 -33
  13. package/src/history-search.ts +1 -1
  14. package/src/history-windows.ts +12 -2
  15. package/src/history.ts +7 -1
  16. package/src/index.ts +5 -19
  17. package/src/integrations.ts +26 -26
  18. package/src/lifecycle.ts +26 -10
  19. package/src/model-role-config.ts +10 -30
  20. package/src/model-role-screen.ts +48 -32
  21. package/src/model-roles.ts +177 -315
  22. package/src/note-result.ts +70 -0
  23. package/src/note-save-marker.ts +23 -9
  24. package/src/notes-lookup.ts +5 -2
  25. package/src/notes.ts +8 -3
  26. package/src/query-executor.ts +34 -15
  27. package/src/query-input.ts +12 -1
  28. package/src/remote.ts +26 -7
  29. package/src/rollover.ts +17 -5
  30. package/src/saved-session.ts +1 -0
  31. package/src/saved-sharing-records.ts +18 -9
  32. package/src/settings-command.ts +1 -1
  33. package/src/shared-notes.ts +49 -20
  34. package/src/shared-session-reader.ts +8 -4
  35. package/src/sharing-service.ts +25 -8
  36. package/src/task-boundary.ts +1 -1
  37. package/src/tool-contracts.ts +50 -58
  38. package/src/tools.ts +34 -50
  39. package/src/window-message.ts +19 -8
  40. package/src/windows.ts +2 -2
  41. package/changelog.ts +0 -337
  42. package/src/model-role-editor.ts +0 -40
@@ -7,15 +7,14 @@ import { NOTE_RECEIPT, type NoteReceipt, noteReceipt } from "./notes.js";
7
7
  import { isNoteWrite } from "./query-input.js";
8
8
 
9
9
  export const NESTED_NOTE_OUTCOME = "notes-compaction:nested-write:v1";
10
- export interface NestedNoteOutcome {
10
+ export type NestedNoteOutcome = {
11
11
  protocol: 1;
12
12
  runId: string;
13
13
  windowId: string;
14
14
  callId: string;
15
15
  parentCallId: string;
16
- saved: boolean;
17
16
  origin?: "routed";
18
- }
17
+ } & ({ pending: true; saved: false } | { pending: false; saved: boolean });
19
18
  export const NOTES_RUN_ENTRY = "notes-compaction:run:v1";
20
19
 
21
20
  /** A receipt proves persistence. Current-run tool outcomes prove the checkpoint actually completed. */
@@ -53,7 +52,7 @@ export function hasFreshNotes(
53
52
  );
54
53
  }
55
54
 
56
- /** The current request is already in history; only its preceding completed invocation qualifies. */
55
+ /** Only the preceding tool-call group (or completed same-group predecessors) qualifies. */
57
56
  export function hasPrecedingNoteWrite(
58
57
  branch: readonly SessionEntry[],
59
58
  windowId: string | undefined,
@@ -73,33 +72,34 @@ export function hasPrecedingNoteWrite(
73
72
  ),
74
73
  );
75
74
  if (request < 0) return false;
76
- const calls = messages
75
+ const groups = messages
77
76
  .slice(0, request + 1)
78
77
  .flatMap((message) =>
79
78
  message.role === "assistant"
80
- ? message.content.filter((block) => block.type === "toolCall")
79
+ ? [message.content.filter((block) => block.type === "toolCall")]
81
80
  : [],
82
- );
83
- const call =
84
- calls[calls.findLastIndex((call) => call.id === requestCallId) - 1];
85
- if (!call) return false;
86
- const previous = messages.findLast(
87
- (message) =>
88
- message.role === "toolResult" &&
89
- message.toolCallId === call.id &&
90
- message.toolName === call.name,
81
+ )
82
+ .filter((calls) => calls.length > 0);
83
+ const current = groups.pop() ?? [];
84
+ const predecessors = current.slice(
85
+ 0,
86
+ current.findIndex((call) => call.id === requestCallId),
87
+ );
88
+ const calls = predecessors.length ? predecessors : (groups.at(-1) ?? []);
89
+ const allResults = messages.flatMap((message) =>
90
+ message.role === "toolResult" ? [message] : [],
91
+ );
92
+ const results = allResults.filter((result) =>
93
+ calls.some(
94
+ (call) => call.id === result.toolCallId && call.name === result.toolName,
95
+ ),
91
96
  );
92
97
  return (
93
- previous?.role === "toolResult" &&
94
- completedWrites(
95
- [call],
96
- [previous],
97
- receipts,
98
- outcomes,
99
- messages.flatMap((message) =>
100
- message.role === "toolResult" ? [message] : [],
101
- ),
102
- )
98
+ calls.length > 0 &&
99
+ calls.every((call) =>
100
+ results.some((result) => result.toolCallId === call.id),
101
+ ) &&
102
+ completedWrites(calls, results, receipts, outcomes, allResults)
103
103
  );
104
104
  }
105
105
 
@@ -156,11 +156,16 @@ function noteEvidence(
156
156
  typeof value.callId === "string" &&
157
157
  typeof value.parentCallId === "string" &&
158
158
  (value.origin === undefined || value.origin === "routed") &&
159
+ typeof value.pending === "boolean" &&
160
+ (!value.pending || value.saved === false) &&
159
161
  typeof value.saved === "boolean"
160
162
  ? [value as NestedNoteOutcome]
161
163
  : [];
162
164
  });
163
- return { messages, receipts, outcomes };
165
+ // Starts remain failed proof until their matching completion replaces them.
166
+ const latest = new Map<string, NestedNoteOutcome>();
167
+ for (const outcome of outcomes) latest.set(outcome.callId, outcome);
168
+ return { messages, receipts, outcomes: [...latest.values()] };
164
169
  }
165
170
 
166
171
  function completedWrites(
@@ -268,16 +273,22 @@ function completedWrites(
268
273
  : noteCalls.filter(
269
274
  (call) => !outcomes.some((item) => item.callId === call.id),
270
275
  );
276
+ const untrackedWrites = uncovered.filter(
277
+ (call) => !call.arguments || isNoteWrite(call.arguments),
278
+ );
279
+ // Pi also marks argument omission as incomplete. Notes' start/end ledger
280
+ // proves write completion even when that bounded record loses arguments or calls.
281
+ const tracked =
282
+ completed.length > 0 && completed.every((item) => item.pending === false);
271
283
  if (
272
- uncovered.some(
273
- (call) =>
274
- call.status !== "ok" &&
275
- (!call.arguments || isNoteWrite(call.arguments)),
276
- ) ||
277
- (uncovered.length && !nested?.complete)
284
+ untrackedWrites.some((call) => call.status !== "ok") ||
285
+ (nested?.complete === false &&
286
+ (noteCalls.length > 0 || completed.length > 0) &&
287
+ !(legacy === true && !completed.length) &&
288
+ (!tracked || untrackedWrites.length > 0))
278
289
  )
279
290
  return false;
280
- const nestedWrites = uncovered.filter((call) =>
291
+ const nestedWrites = untrackedWrites.filter((call) =>
281
292
  isNoteWrite(call.arguments),
282
293
  );
283
294
  if (
@@ -8,7 +8,7 @@ import type {
8
8
  } from "./history-search-protocol.js";
9
9
 
10
10
  const UNAVAILABLE =
11
- "Ranked history search is unavailable. list and read still work. Ask the user to check local storage or turn off Ranked history search in /notes.";
11
+ "History request failed. Use list/read or ask user to check /notes.";
12
12
 
13
13
  /** Worker owns derived storage; JSONL and the caller own content and scope. */
14
14
  export class HistorySearch {
@@ -91,13 +91,23 @@ export async function historyWindows(
91
91
  });
92
92
  let windowId = `session:${sessionId}`;
93
93
  let activeStart = 0;
94
+ let hasWindowBoundary = false;
94
95
  const positions = new Map(
95
96
  entries.map((entry, position) => [entry.id, position]),
96
97
  );
97
98
  for (const [position, entry] of entries.entries()) {
98
99
  const boundary = windowDetails(entry);
99
- if (boundary?.kind === "window" && boundary.trim)
100
- activeStart = position + 1;
100
+ if (boundary?.kind === "window") {
101
+ // Pi persists the initial kickoff before the returned window message.
102
+ if (
103
+ !hasWindowBoundary &&
104
+ !boundary.trim &&
105
+ boundary.identity.windowNumber === 0
106
+ )
107
+ windowId = boundary.identity.currentWindowId;
108
+ hasWindowBoundary = true;
109
+ if (boundary.trim) activeStart = position + 1;
110
+ }
101
111
  if (entry.type === "compaction") {
102
112
  const kept = positions.get(entry.firstKeptEntryId);
103
113
  if (kept !== undefined && kept <= position)
package/src/history.ts CHANGED
@@ -62,7 +62,13 @@ export async function useHistory(
62
62
  throw new Error(
63
63
  `history read requires ${typeof windowId !== "string" ? "window_id" : "item_id"} as a string. Copy window_id and item_id from the same search or list result`,
64
64
  );
65
- const item = windows.get(windowId)?.find((item) => item.item_id === itemId);
65
+ // Keep exact pre-initialisation references saved by earlier releases readable.
66
+ const items =
67
+ windows.get(windowId) ??
68
+ (windowId === `session:${sessionId}`
69
+ ? windows.values().next().value
70
+ : undefined);
71
+ const item = items?.find((item) => item.item_id === itemId);
66
72
  if (!item) return { item: null };
67
73
  const offset = integer(params["offset_chars"], 0, item.content.length);
68
74
  const limit = integer(params["limit_chars"], 8000, 8000);
package/src/index.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  import { join } from "node:path";
2
2
  import {
3
3
  type ExtensionAPI,
4
- type ExtensionContext,
5
4
  getAgentDir,
6
5
  } from "@earendil-works/pi-coding-agent";
7
6
  import { createNotesActivation } from "./activation.js";
8
7
  import { createNotesContextOwner } from "./context-owner.js";
9
8
  import { registerNotesHooks } from "./extension-hooks.js";
10
9
  import { registerNotesSharing } from "./extension-sharing.js";
10
+ import { registerCheckpointRenderer } from "./fresh-checkpoint.js";
11
11
  import { HistorySearch } from "./history-search.js";
12
12
  import { registerNotesToolIntegrations } from "./integrations.js";
13
13
  import { NotesLifecycle } from "./lifecycle.js";
@@ -16,13 +16,13 @@ import { registerNoteSaveMarkers } from "./note-save-marker.js";
16
16
  import { SessionPruning } from "./session-pruning.js";
17
17
  import { registerNotesSettingsCommand } from "./settings-command.js";
18
18
  import { NotesStore } from "./store.js";
19
- import { notesSchema } from "./tool-contracts.js";
20
19
  import { createTools } from "./tools.js";
21
20
  import { WindowCheckpoints } from "./window-checkpoint.js";
22
21
  import { registerWindowRenderer } from "./windows.js";
23
22
 
24
23
  export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
25
24
  registerWindowRenderer(pi);
25
+ registerCheckpointRenderer(pi);
26
26
  const dir = join(getAgentDir(), "notes-compaction");
27
27
  const settingsPath = join(dir, "settings.json");
28
28
  const store = new NotesStore(join(dir, "notes.sqlite"));
@@ -58,28 +58,13 @@ export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
58
58
  }
59
59
  },
60
60
  );
61
- const refreshRoleContract = (ctx?: ExtensionContext) => {
62
- if (ctx) activation.refreshActivation(ctx);
63
- const tool = tools.find((tool) => tool.name === "notes");
64
- if (!tool) return;
65
- const schema = notesSchema(roles.enabled());
66
- if (JSON.stringify(tool.parameters) === JSON.stringify(schema)) return;
67
- tool.parameters = schema;
68
- pi.registerTool(tool);
69
- refreshNested();
70
- };
71
- const roles = createModelRoles(
72
- pi,
73
- activation,
74
- lifecycle,
75
- refreshRoleContract,
76
- );
61
+ const roles = createModelRoles(pi, activation, lifecycle);
77
62
  const tools = createTools(pi, store, lifecycle, search, roles);
78
63
  refreshNested = await registerNotesToolIntegrations(
79
64
  pi,
80
65
  lifecycle,
66
+ activation,
81
67
  tools,
82
- refreshRoleContract,
83
68
  );
84
69
  for (const tool of tools) pi.registerTool(tool);
85
70
  const owner = createNotesContextOwner(pi, store, lifecycle, search);
@@ -92,6 +77,7 @@ export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
92
77
  const markers = registerNoteSaveMarkers(
93
78
  pi,
94
79
  () => lifecycle.active && activation.settings.noteSaveMarkers,
80
+ () => lifecycle.windows.current?.currentWindowId,
95
81
  );
96
82
  await registerNotesHooks(
97
83
  pi,
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ AgentToolResult,
2
3
  ExtensionAPI,
3
4
  ExtensionContext,
4
5
  } from "@earendil-works/pi-coding-agent";
@@ -6,10 +7,8 @@ import type { NotesActivation } from "./activation.js";
6
7
  import type { NotesLifecycle } from "./lifecycle.js";
7
8
  import {
8
9
  GPT_NEW_CONTEXT_DESCRIPTION,
9
- GPT_NOTES_DESCRIPTION,
10
10
  HISTORY_USAGE,
11
11
  NEW_CONTEXT_DESCRIPTION,
12
- NOTES_DESCRIPTION,
13
12
  NOTES_USAGE,
14
13
  } from "./tool-contracts.js";
15
14
  import type { createTools } from "./tools.js";
@@ -20,25 +19,22 @@ import type { WindowCheckpoints } from "./window-checkpoint.js";
20
19
  export async function registerNotesToolIntegrations(
21
20
  pi: ExtensionAPI,
22
21
  lifecycle: NotesLifecycle,
22
+ activation: NotesActivation,
23
23
  tools: ReturnType<typeof createTools>,
24
- prepareTools: (ctx?: ExtensionContext) => void,
25
24
  ) {
26
25
  try {
27
26
  const { registerGptPromptMode } = await import(
28
27
  "@howaboua/pi-codex-conversion/prompt-mode"
29
28
  );
30
29
  const registration = registerGptPromptMode(pi, (active, ctx) => {
31
- prepareTools(ctx);
32
- for (const [name, normal, gpt] of [
33
- ["notes", NOTES_DESCRIPTION, GPT_NOTES_DESCRIPTION],
34
- ["new_context", NEW_CONTEXT_DESCRIPTION, GPT_NEW_CONTEXT_DESCRIPTION],
35
- ] as const) {
36
- const tool = tools.find((tool) => tool.name === name);
37
- const description = active ? gpt : normal;
38
- if (tool && tool.description !== description) {
39
- tool.description = description;
40
- pi.registerTool(tool);
41
- }
30
+ if (ctx) activation.refreshActivation(ctx);
31
+ const tool = tools.find((tool) => tool.name === "new_context");
32
+ const description = active
33
+ ? GPT_NEW_CONTEXT_DESCRIPTION
34
+ : NEW_CONTEXT_DESCRIPTION;
35
+ if (tool && tool.description !== description) {
36
+ tool.description = description;
37
+ pi.registerTool(tool);
42
38
  }
43
39
  return lifecycle.active ? tools : [];
44
40
  });
@@ -69,19 +65,11 @@ export async function registerNotesToolIntegrations(
69
65
  adaptToolForCodeMode(tool, {
70
66
  discovery: "help",
71
67
  usage: tool.name === "notes" ? NOTES_USAGE : HISTORY_USAGE,
72
- deferLoading: true,
68
+ deferLoading: tool.name !== "notes",
73
69
  opaqueResult: tool.name === "notes",
74
- resultValue(result) {
75
- const [part] = result.content;
76
- if (result.content.length === 1 && part?.type === "text") {
77
- try {
78
- return JSON.parse(part.text);
79
- } catch {
80
- return part.text;
81
- }
82
- }
83
- return { content: result.content };
84
- },
70
+ ...(tool.name === "history"
71
+ ? { resultValue: historyResultValue }
72
+ : {}),
85
73
  }),
86
74
  ),
87
75
  { isActive: () => lifecycle.active },
@@ -98,6 +86,18 @@ export async function registerNotesToolIntegrations(
98
86
  return refreshNested;
99
87
  }
100
88
 
89
+ function historyResultValue(result: AgentToolResult<unknown>): unknown {
90
+ const [part] = result.content;
91
+ if (result.content.length === 1 && part?.type === "text") {
92
+ try {
93
+ return JSON.parse(part.text);
94
+ } catch {
95
+ return part.text;
96
+ }
97
+ }
98
+ return { content: result.content };
99
+ }
100
+
101
101
  export async function registerNotesCompactionIntegration(
102
102
  pi: ExtensionAPI,
103
103
  activation: NotesActivation,
package/src/lifecycle.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  NOTES_RUN_ENTRY,
20
20
  } from "./fresh-notes.js";
21
21
  import { IdleAdmission } from "./idle-admission.js";
22
+ import type { ModelRoleHandoff } from "./model-roles.js";
22
23
  import { noteHints, sessionRef } from "./notes.js";
23
24
  import { RolloverRequests } from "./rollover.js";
24
25
  import type { IdleMinutes, NewWindowRequests } from "./settings.js";
@@ -59,7 +60,8 @@ export class NotesLifecycle {
59
60
  );
60
61
  this.requests = new RolloverRequests(
61
62
  this,
62
- (ctx, triggerTurn, trim) => this.openWindow(ctx, triggerTurn, trim),
63
+ (ctx, triggerTurn, trim, handoff) =>
64
+ this.openWindow(ctx, triggerTurn, trim, handoff),
63
65
  (message, options) => this.sendMessage(message, options),
64
66
  (ctx, instructions) => this.checkpoint.start(ctx, instructions),
65
67
  );
@@ -164,7 +166,11 @@ export class NotesLifecycle {
164
166
  runId,
165
167
  );
166
168
  }
167
- requestRollover(ctx: ExtensionContext, callId: string): boolean {
169
+ requestRollover(
170
+ ctx: ExtensionContext,
171
+ callId: string,
172
+ handoff?: ModelRoleHandoff,
173
+ ): boolean {
168
174
  if (this.newWindowRequests === "off")
169
175
  throw new Error(
170
176
  "New window requests are disabled. Continue in the current window.",
@@ -182,26 +188,35 @@ export class NotesLifecycle {
182
188
  throw new Error(
183
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.",
184
190
  );
185
- this.requests.schedule(ctx);
191
+ this.requests.schedule(ctx, handoff);
186
192
  return true;
187
193
  }
188
194
  private async openWindow(
189
195
  ctx: ExtensionContext,
190
196
  triggerTurn: boolean,
191
197
  trim: boolean,
198
+ handoff?: ModelRoleHandoff,
192
199
  ): Promise<void> {
193
200
  if (!ctx.isIdle())
194
201
  throw new Error("Wait for the current run to settle before rollover");
195
202
  const sessionId = ctx.sessionManager.getSessionId();
196
203
  const windowId = this.windows.current?.currentWindowId;
197
204
  if (trim) await this.prepareWindow?.(ctx);
198
- if (
199
- !ctx.isIdle() ||
200
- sessionId !== ctx.sessionManager.getSessionId() ||
201
- windowId !== this.windows.current?.currentWindowId ||
202
- !this.active
203
- )
204
- throw new Error("Session changed before rollover");
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
+ }
205
220
  const ids = this.windows.next();
206
221
  const hint = noteHints(this.store, ctx, this.agent(ctx));
207
222
  const message = windowMessage(
@@ -213,6 +228,7 @@ export class NotesLifecycle {
213
228
  this.gptPromptMode(),
214
229
  );
215
230
  this.windows.current = ids;
231
+ if (handoff) message.content = `${message.content}\n\nRole: ${handoff.id}`;
216
232
  if (triggerTurn)
217
233
  message.content = `${message.content}\n\n${this.gptPromptMode() ? "Saved notes→notes tool→resume task" : "Read your saved notes with the notes tool and resume the task."}`;
218
234
  this.sendMessage(message, { triggerTurn });
@@ -1,13 +1,8 @@
1
- import {
2
- existsSync,
3
- mkdirSync,
4
- readFileSync,
5
- renameSync,
6
- writeFileSync,
7
- } from "node:fs";
8
- import { dirname, join } from "node:path";
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
9
3
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
10
- export const THINKING_LEVELS = [
4
+
5
+ const THINKING_LEVELS = [
11
6
  "off",
12
7
  "minimal",
13
8
  "low",
@@ -16,7 +11,7 @@ export const THINKING_LEVELS = [
16
11
  "xhigh",
17
12
  "max",
18
13
  ] as const;
19
- export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
14
+ type ThinkingLevel = (typeof THINKING_LEVELS)[number];
20
15
 
21
16
  export interface ModelRole {
22
17
  id: string;
@@ -27,27 +22,24 @@ export interface ModelRole {
27
22
  }
28
23
 
29
24
  export interface RoleConfig {
30
- enabled: boolean;
31
25
  roles: ModelRole[];
32
26
  }
33
27
 
34
- function roleConfigPath(): string {
28
+ export function roleConfigPath(): string {
35
29
  return join(getAgentDir(), "notes-compaction", "model-roles.json");
36
30
  }
37
31
 
38
32
  export function readRoleConfig(path = roleConfigPath()): RoleConfig {
39
- if (!existsSync(path)) return { enabled: false, roles: [] };
33
+ if (!existsSync(path)) return { roles: [] };
40
34
  const value: unknown = JSON.parse(readFileSync(path, "utf8"));
41
35
  if (
42
36
  !value ||
43
37
  typeof value !== "object" ||
44
- !("enabled" in value) ||
45
- typeof value.enabled !== "boolean" ||
46
38
  !("roles" in value) ||
47
39
  !Array.isArray(value.roles)
48
40
  )
49
41
  throw new Error(
50
- "Model roles configuration must contain enabled and roles; repair it with /roles",
42
+ `Model roles configuration must contain a roles array. Edit ${path}; /roles shows the format`,
51
43
  );
52
44
  const ids = new Set<string>();
53
45
  const roles = value.roles.map((role: unknown): ModelRole => {
@@ -72,7 +64,7 @@ export function readRoleConfig(path = roleConfigPath()): RoleConfig {
72
64
  ids.has(role.id)
73
65
  )
74
66
  throw new Error(
75
- "Invalid or duplicate model role; repair model-roles.json or use /roles to replace roles",
67
+ `Invalid or duplicate model role. Edit ${path}; /roles shows the format`,
76
68
  );
77
69
  ids.add(role.id);
78
70
  return {
@@ -83,17 +75,5 @@ export function readRoleConfig(path = roleConfigPath()): RoleConfig {
83
75
  reasoning: role.reasoning as ThinkingLevel,
84
76
  };
85
77
  });
86
- return { enabled: value.enabled, roles };
87
- }
88
-
89
- export function writeRoleConfig(
90
- config: RoleConfig,
91
- path = roleConfigPath(),
92
- ): void {
93
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
94
- const temporary = `${path}.${process.pid}.tmp`;
95
- writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, {
96
- mode: 0o600,
97
- });
98
- renameSync(temporary, path);
78
+ return { roles };
99
79
  }
@@ -1,11 +1,7 @@
1
- import {
2
- type ExtensionContext,
3
- getSettingsListTheme,
4
- } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
2
  import {
6
3
  Key,
7
4
  matchesKey,
8
- SettingsList,
9
5
  truncateToWidth,
10
6
  wrapTextWithAnsi,
11
7
  } from "@earendil-works/pi-tui";
@@ -13,44 +9,64 @@ import type { ModelRole } from "./model-role-config.js";
13
9
 
14
10
  export function openModelRoleScreen(
15
11
  ctx: ExtensionContext,
16
- choices: string[],
17
12
  roles: ModelRole[],
13
+ configPath: string,
14
+ error?: string,
18
15
  ) {
19
- return ctx.ui.custom<string | undefined>((tui, theme, _kb, done) => {
20
- const list = new SettingsList(
21
- choices.map((choice) => ({
22
- id: choice,
23
- label: choice,
24
- currentValue: "select…",
25
- values: ["select…", "open…"],
26
- })),
27
- 8,
28
- getSettingsListTheme(),
29
- (id) => done(id),
30
- () => done(undefined),
31
- );
16
+ return ctx.ui.custom<"notes-tab" | undefined>((tui, theme, _kb, done) => {
17
+ let offset = 0;
18
+ let maxOffset = 0;
19
+ let pageSize = 1;
32
20
  return {
33
- render: (width: number) =>
34
- [
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 [
35
43
  ` ${theme.fg("dim", "Notes")} / ${theme.bold("Roles")}`,
36
44
  "",
37
- ...roles.flatMap((role) =>
38
- wrapTextWithAnsi(
39
- ` ${role.id}: ${role.provider}/${role.model} (${role.reasoning})\n ${role.description}`,
40
- width,
41
- ),
42
- ),
45
+ ...content
46
+ .slice(offset, offset + pageSize)
47
+ .map((line) => ` ${line}`),
43
48
  "",
44
- ...list.render(width),
45
- " Tab switch tab · ↑/↓ select · Enter change · Esc close",
46
- ].map((line) => truncateToWidth(line, width)),
47
- invalidate: () => list.invalidate(),
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: () => {},
48
53
  handleInput: (data: string) => {
49
54
  if (matchesKey(data, Key.tab) || matchesKey(data, Key.shift(Key.tab))) {
50
55
  done("notes-tab");
51
56
  return;
52
57
  }
53
- list.handleInput(data);
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));
54
70
  tui.requestRender();
55
71
  },
56
72
  };