@howaboua/pi-notes-compaction 0.0.10 → 0.0.12

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.
@@ -14,7 +14,13 @@ import {
14
14
  sharedNotesUnavailable,
15
15
  } from "./shared-notes.js";
16
16
  import type { NotesStore } from "./store.js";
17
- import { queryArguments, queryHelp, result } from "./tool-contracts.js";
17
+ import {
18
+ prepareHistoryArguments,
19
+ prepareNotesArguments,
20
+ queryArguments,
21
+ queryHelp,
22
+ result,
23
+ } from "./tool-contracts.js";
18
24
 
19
25
  export function createQueryExecutor(
20
26
  pi: ExtensionAPI,
@@ -35,7 +41,8 @@ export function createQueryExecutor(
35
41
  signal: AbortSignal | undefined,
36
42
  ctx: ExtensionContext,
37
43
  ): Promise<AgentToolResult<unknown>> {
38
- const help = queryHelp("notes", input);
44
+ input = prepareNotesArguments(input, true);
45
+ const help = queryHelp("notes", input, false, lifecycle.gptPromptMode());
39
46
  if (help) return help;
40
47
  assertActive();
41
48
  const raw = queryArguments("notes", input);
@@ -127,6 +134,7 @@ export function createQueryExecutor(
127
134
  signal: AbortSignal | undefined,
128
135
  ctx: ExtensionContext,
129
136
  ): Promise<AgentToolResult<unknown>> {
137
+ input = prepareHistoryArguments(input);
130
138
  const help = queryHelp(
131
139
  "history",
132
140
  input,
@@ -0,0 +1,115 @@
1
+ import type { LookupQuery } from "./bridge.js";
2
+
3
+ const ACTIONS: Record<LookupQuery["namespace"], Record<string, string>> = {
4
+ notes: {
5
+ list_files_by_prefix: "list",
6
+ read_file: "read",
7
+ search_contents: "search",
8
+ append_to_file: "append",
9
+ write_file: "write",
10
+ },
11
+ history: { list_items: "list", read_item: "read", search_contents: "search" },
12
+ };
13
+ const HINTS = [
14
+ "limit",
15
+ "max_results",
16
+ "max_files",
17
+ "max_matches_per_file",
18
+ "file_order",
19
+ "file_order_by",
20
+ "recent_file_first",
21
+ "recent_first",
22
+ "limit_chars",
23
+ "max_chars_per_item",
24
+ ];
25
+ const PRESENTATION: Record<string, readonly string[]> = {
26
+ "notes:list": ["limit", "file_order", "file_order_by"],
27
+ "notes:search": ["limit", "max_matches_per_file", "recent_file_first"],
28
+ "notes:read": ["start_line", "stop_line"],
29
+ "history:list_windows": ["limit", "recent_first"],
30
+ "history:list": ["limit", "recent_first", "max_chars_per_item"],
31
+ "history:search": ["limit", "recent_first"],
32
+ "history:read": ["limit_chars", "offset_chars"],
33
+ };
34
+
35
+ function alias(params: Record<string, unknown>, from: string, to: string) {
36
+ if (!(from in params)) return;
37
+ if (to in params && params[to] !== params[from])
38
+ throw new Error(`Conflicting ${to} and ${from}; supply only ${to}`);
39
+ params[to] = params[from];
40
+ delete params[from];
41
+ }
42
+
43
+ /** Accept familiar spellings without adding competing names to discovery. */
44
+ export function normalizeQueryInput(
45
+ namespace: LookupQuery["namespace"],
46
+ input: unknown,
47
+ ): Record<string, unknown> {
48
+ if (input === undefined) return {};
49
+ if (typeof input === "string") {
50
+ try {
51
+ input = JSON.parse(input);
52
+ } catch {
53
+ throw new Error(
54
+ "Supply an action object or valid JSON object; use {} for help",
55
+ );
56
+ }
57
+ }
58
+ if (!input || typeof input !== "object" || Array.isArray(input))
59
+ throw new Error("Supply an action object; use {} for help");
60
+ const params = { ...input } as Record<string, unknown>;
61
+ const action =
62
+ ACTIONS[namespace][String(params["action"])] ?? params["action"];
63
+ if (action !== undefined) params["action"] = action;
64
+ if (namespace === "notes") {
65
+ if (action === "write" || action === "append")
66
+ alias(params, "content", "text");
67
+ if (action === "list" || action === "search") {
68
+ alias(params, "prefix", "path");
69
+ alias(params, "path_prefix", "path");
70
+ alias(params, "max_results", "limit");
71
+ alias(params, "max_files", "limit");
72
+ if (action === "search")
73
+ alias(params, "recent_first", "recent_file_first");
74
+ }
75
+ } else if (["list", "search", "list_windows"].includes(String(action))) {
76
+ alias(params, "max_results", "limit");
77
+ }
78
+ const used = PRESENTATION[`${namespace}:${String(action)}`] ?? [];
79
+ for (const hint of HINTS) if (!used.includes(hint)) delete params[hint];
80
+ return params;
81
+ }
82
+
83
+ /** Keep persisted sharing requests and backend endpoint names unchanged. */
84
+ export function internalQueryArguments(
85
+ namespace: LookupQuery["namespace"],
86
+ input: Record<string, unknown>,
87
+ ) {
88
+ const params = { ...input };
89
+ const action = params["action"];
90
+ params["action"] =
91
+ Object.entries(ACTIONS[namespace]).find(
92
+ ([, value]) => value === action,
93
+ )?.[0] ?? action;
94
+ if (namespace === "notes") {
95
+ if (action === "list" || action === "search") {
96
+ alias(params, "path", action === "list" ? "prefix" : "path_prefix");
97
+ alias(params, "limit", action === "list" ? "max_results" : "max_files");
98
+ }
99
+ }
100
+ return params;
101
+ }
102
+
103
+ export function isNoteWrite(input: unknown): boolean {
104
+ try {
105
+ if (typeof input === "string") input = JSON.parse(input);
106
+ if (!input || typeof input !== "object" || !("action" in input))
107
+ return false;
108
+ // Failed write attempts still invalidate freshness; do not validate their fields here.
109
+ return ["write", "append", "write_file", "append_to_file"].includes(
110
+ String(input.action),
111
+ );
112
+ } catch {
113
+ return false;
114
+ }
115
+ }
@@ -0,0 +1,103 @@
1
+ import { type Static, Type } from "typebox";
2
+ import { Check } from "typebox/value";
3
+ import type { SavedNotesSession } from "./saved-session.js";
4
+
5
+ const Agent = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
6
+ export const Identity = Type.Object({
7
+ protocol: Type.Literal(1),
8
+ sessionId: Type.String(),
9
+ threadId: Type.String(),
10
+ agentName: Agent,
11
+ storage: Type.Optional(
12
+ Type.Union([Type.Literal("session"), Type.Literal("remote")]),
13
+ ),
14
+ routing: Type.Optional(Type.Unknown()),
15
+ });
16
+ export const Member = Type.Object({
17
+ threadId: Type.String(),
18
+ sessionId: Type.String(),
19
+ agentName: Agent,
20
+ machine: Type.String(),
21
+ sessionFile: Type.String(),
22
+ });
23
+ export const Plan = Type.Object({
24
+ controllerSessionId: Type.String(),
25
+ targetSessionId: Type.String(),
26
+ context: Type.Optional(
27
+ Type.Object({
28
+ controller: Identity,
29
+ target: Identity,
30
+ alias: Agent,
31
+ controllerAlias: Agent,
32
+ controllerFile: Type.Optional(Type.String()),
33
+ controllerNotes: Type.Unknown(),
34
+ targetNotes: Type.Unknown(),
35
+ }),
36
+ ),
37
+ });
38
+ export const Route = Type.Object({
39
+ plan: Plan,
40
+ machine: Type.String(),
41
+ sessionFile: Type.String(),
42
+ phase: Type.Union([Type.Literal("pending"), Type.Literal("ready")]),
43
+ detached: Type.Optional(
44
+ Type.Object({ context: Type.Optional(Type.Unknown()) }),
45
+ ),
46
+ });
47
+ export const Detachment = Type.Object({
48
+ plan: Plan,
49
+ context: Type.Optional(Type.Unknown()),
50
+ });
51
+ export const Snapshot = Type.Object({
52
+ protocol: Type.Literal(1),
53
+ timestamp: Type.Number(),
54
+ files: Type.Array(
55
+ Type.Object({
56
+ path: Type.String(),
57
+ text: Type.String(),
58
+ createdAt: Type.Number(),
59
+ updatedAt: Type.Number(),
60
+ operation: Type.Union([
61
+ Type.Literal("local_append_overlay"),
62
+ Type.Literal("local_replacement"),
63
+ ]),
64
+ }),
65
+ ),
66
+ });
67
+ export const Parent = Type.Object({
68
+ transport: Type.Literal("shepherdr"),
69
+ parent: Type.String(),
70
+ });
71
+ export type Identity = Static<typeof Identity>;
72
+
73
+ /** Persisted sharing is session-scoped. Forks never inherit the source agent's address. */
74
+ export function savedNotesIdentity(
75
+ session: Pick<SavedNotesSession, "threadId" | "entries">,
76
+ ): Identity {
77
+ let found: Identity | undefined;
78
+ for (const entry of session.entries) {
79
+ if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
80
+ continue;
81
+ if (!Check(Identity, entry.data))
82
+ throw new Error("Invalid saved notes identity");
83
+ if (entry.data.threadId !== session.threadId) continue;
84
+ if (found) throw new Error("Conflicting saved notes identities");
85
+ found = entry.data;
86
+ }
87
+ return (
88
+ found ?? {
89
+ protocol: 1,
90
+ threadId: session.threadId,
91
+ sessionId: session.threadId,
92
+ agentName: "/root",
93
+ }
94
+ );
95
+ }
96
+
97
+ export function sameOwner(a: Identity, b: Identity): boolean {
98
+ return (
99
+ a.threadId === b.threadId &&
100
+ a.sessionId === b.sessionId &&
101
+ a.agentName === b.agentName
102
+ );
103
+ }
@@ -1,12 +1,15 @@
1
1
  import {
2
2
  type ExtensionContext,
3
+ getSelectListTheme,
3
4
  getSettingsListTheme,
4
5
  } from "@earendil-works/pi-coding-agent";
5
6
  import {
7
+ SelectList,
6
8
  SettingsList,
7
9
  truncateToWidth,
8
10
  wrapTextWithAnsi,
9
11
  } from "@earendil-works/pi-tui";
12
+ import type { SessionPruningInteraction } from "./session-pruning.js";
10
13
  import {
11
14
  CONVERSATION_DAYS,
12
15
  HISTORY_WINDOWS,
@@ -17,7 +20,7 @@ import {
17
20
  export interface SessionPruningSettings {
18
21
  get: () => SessionPruningPolicy;
19
22
  save: (policy: SessionPruningPolicy) => void;
20
- run: () => Promise<void>;
23
+ run: (interaction: SessionPruningInteraction) => Promise<void>;
21
24
  }
22
25
  const windowLabel = (value: number) =>
23
26
  value ? `Keep ${value} context windows` : "Off";
@@ -28,103 +31,174 @@ export async function openSessionPruningSettings(
28
31
  ctx: ExtensionContext,
29
32
  options: SessionPruningSettings,
30
33
  ): Promise<void> {
31
- while (true) {
32
- const action = await ctx.ui.custom<"close" | "run">(
33
- (tui, theme, _kb, done) => {
34
- const policy = options.get();
35
- const list = new SettingsList(
34
+ await ctx.ui.custom<void>((tui, theme, _kb, done) => {
35
+ type State =
36
+ | { kind: "idle" }
37
+ | { kind: "busy"; message: string }
38
+ | {
39
+ kind: "confirm";
40
+ title: string;
41
+ message: string;
42
+ choices: SelectList;
43
+ };
44
+ let state: State = { kind: "idle" };
45
+ const progress = (message: string) => {
46
+ state = { kind: "busy", message };
47
+ tui.requestRender();
48
+ };
49
+ const confirm: SessionPruningInteraction["confirm"] = (title, message) =>
50
+ new Promise((resolve) => {
51
+ const choices = new SelectList(
36
52
  [
37
- {
38
- id: "windows",
39
- label: "Full/tool history",
40
- currentValue: windowLabel(policy.windows),
41
- values: HISTORY_WINDOWS.map(windowLabel),
42
- description:
43
- "This session only. Outside retained windows, keep actual user messages (including attachments) and assistant prose, not tools or injected instructions. Off leaves full history intact.",
44
- },
45
- {
46
- id: "days",
47
- label: "Assistant & user messages",
48
- currentValue: ageLabel(policy.days),
49
- values: CONVERSATION_DAYS.map(ageLabel),
50
- description:
51
- "Expire conversation older than this limit, independently of full-history retention. The current context window and native active context are always protected.",
52
- },
53
- {
54
- id: "run",
55
- label: "Run now",
56
- currentValue: "select…",
57
- values: ["select…", "preview…"],
58
- description:
59
- "Preview and confirm irreversible pruning. Saved SQLite notes are never deleted. No archive or backup is kept.",
60
- },
53
+ { value: "no", label: "Cancel" },
54
+ { value: "yes", label: "Prune permanently" },
61
55
  ],
62
- 5,
63
- getSettingsListTheme(),
64
- (id, value) => {
65
- if (id === "run") {
66
- done("run");
67
- return;
68
- }
69
- const current = options.get();
70
- try {
71
- if (id === "windows") {
72
- const windows = HISTORY_WINDOWS.find(
73
- (item) => windowLabel(item) === value,
74
- );
75
- if (windows !== undefined)
76
- options.save({ ...current, windows });
77
- } else {
78
- const days = CONVERSATION_DAYS.find(
79
- (item) => ageLabel(item) === value,
80
- );
81
- if (days !== undefined) options.save({ ...current, days });
82
- }
83
- } catch (error) {
84
- list.updateValue(
85
- id,
86
- id === "windows"
87
- ? windowLabel(current.windows)
88
- : ageLabel(current.days),
89
- );
90
- ctx.ui.notify(
91
- `Could not save session pruning settings: ${String(error)}`,
92
- "error",
93
- );
94
- }
95
- tui.requestRender();
96
- },
97
- () => done("close"),
98
- { enableSearch: false },
56
+ 2,
57
+ getSelectListTheme(),
99
58
  );
100
- return {
101
- render: (width) => {
102
- const wrap = (text: string) =>
103
- wrapTextWithAnsi(text, Math.max(1, width - 2)).map(
104
- (line) => ` ${line}`,
105
- );
106
- return [
107
- theme.bold(" Session auto-pruning"),
108
- "",
109
- ...wrap(
110
- "Runs once after a new context window's first completed turn commits its checkpoint. Settings follow this session on resume; new and forked sessions start Off. Forks made before restarting can retain unpruned history.",
111
- ),
112
- "",
113
- ...wrap(RESTART_NOTICE),
114
- "",
115
- ...list.render(width),
116
- ...wrap("↑/↓ select · Enter/Space change · Esc back"),
117
- ].map((line) => truncateToWidth(line, width, ""));
118
- },
119
- invalidate: () => list.invalidate(),
120
- handleInput: (data) => {
121
- list.handleInput(data);
122
- tui.requestRender();
123
- },
59
+ const finish = (approved: boolean) => {
60
+ progress(
61
+ approved ? "Pruning session history…" : "Cancelling preview…",
62
+ );
63
+ resolve(approved);
124
64
  };
65
+ choices.onSelect = (item) => finish(item.value === "yes");
66
+ choices.onCancel = () => finish(false);
67
+ state = { kind: "confirm", title, message, choices };
68
+ tui.requestRender();
69
+ });
70
+ const run = async () => {
71
+ progress("Waiting for the current turn to finish…");
72
+ try {
73
+ await options.run({ progress, confirm });
74
+ } catch (error) {
75
+ ctx.ui.notify(
76
+ `Session pruning did not complete: ${String(error)}`,
77
+ "error",
78
+ );
79
+ } finally {
80
+ state = { kind: "idle" };
81
+ list.updateValue("run", "select…");
82
+ tui.requestRender();
83
+ }
84
+ };
85
+ const policy = options.get();
86
+ const list = new SettingsList(
87
+ [
88
+ {
89
+ id: "windows",
90
+ label: "Full/tool history",
91
+ currentValue: windowLabel(policy.windows),
92
+ values: HISTORY_WINDOWS.map(windowLabel),
93
+ description:
94
+ "This session only. Outside retained windows, keep actual user messages (including attachments) and assistant prose, not tools or injected instructions. Off leaves full history intact.",
95
+ },
96
+ {
97
+ id: "days",
98
+ label: "Assistant & user messages",
99
+ currentValue: ageLabel(policy.days),
100
+ values: CONVERSATION_DAYS.map(ageLabel),
101
+ description:
102
+ "Expire conversation older than this limit, independently of full-history retention. The current context window and native active context are always protected.",
103
+ },
104
+ {
105
+ id: "run",
106
+ label: "Run now",
107
+ currentValue: "select…",
108
+ values: ["select…", "preview…"],
109
+ description:
110
+ "Preview and confirm irreversible pruning. Saved SQLite notes are never deleted. No archive or backup is kept.",
111
+ },
112
+ ],
113
+ 5,
114
+ getSettingsListTheme(),
115
+ (id, value) => {
116
+ if (id === "run") {
117
+ void run();
118
+ return;
119
+ }
120
+ const current = options.get();
121
+ try {
122
+ if (id === "windows") {
123
+ const windows = HISTORY_WINDOWS.find(
124
+ (item) => windowLabel(item) === value,
125
+ );
126
+ if (windows !== undefined) options.save({ ...current, windows });
127
+ } else {
128
+ const days = CONVERSATION_DAYS.find(
129
+ (item) => ageLabel(item) === value,
130
+ );
131
+ if (days !== undefined) options.save({ ...current, days });
132
+ }
133
+ } catch (error) {
134
+ list.updateValue(
135
+ id,
136
+ id === "windows"
137
+ ? windowLabel(current.windows)
138
+ : ageLabel(current.days),
139
+ );
140
+ ctx.ui.notify(
141
+ `Could not save session pruning settings: ${String(error)}`,
142
+ "error",
143
+ );
144
+ }
145
+ tui.requestRender();
125
146
  },
147
+ () => done(),
148
+ { enableSearch: false },
126
149
  );
127
- if (action === "close") return;
128
- await options.run();
129
- }
150
+ return {
151
+ render: (width) => {
152
+ const wrap = (text: string) =>
153
+ wrapTextWithAnsi(text, Math.max(1, width - 2)).map(
154
+ (line) => ` ${line}`,
155
+ );
156
+ const rule = theme.fg("accent", "─".repeat(Math.max(0, width)));
157
+ return [
158
+ rule,
159
+ theme.bold(" Session auto-pruning"),
160
+ "",
161
+ ...wrap(
162
+ "Runs once after a new context window's first completed turn commits its checkpoint. Settings follow this session on resume; new and forked sessions start Off. Forks made before restarting can retain unpruned history.",
163
+ ),
164
+ "",
165
+ ...wrap(RESTART_NOTICE),
166
+ "",
167
+ ...(state.kind === "confirm"
168
+ ? [
169
+ ...wrap(theme.bold(state.title)),
170
+ ...wrap(state.message),
171
+ "",
172
+ ...state.choices.render(width),
173
+ ]
174
+ : list.render(width).slice(0, -2)),
175
+ "",
176
+ ...wrap(
177
+ state.kind === "busy"
178
+ ? state.message
179
+ : state.kind === "confirm"
180
+ ? "↑/↓ select · Enter confirm · Esc cancel"
181
+ : "↑/↓ select · Enter/Space change · Esc back",
182
+ ).map((line) =>
183
+ theme.fg(state.kind === "busy" ? "accent" : "dim", line),
184
+ ),
185
+ ...(state.kind === "busy"
186
+ ? wrap("Please wait; settings and closing are paused.").map(
187
+ (line) => theme.fg("dim", line),
188
+ )
189
+ : []),
190
+ rule,
191
+ ].map((line) => truncateToWidth(line, width, ""));
192
+ },
193
+ invalidate: () => {
194
+ list.invalidate();
195
+ if (state.kind === "confirm") state.choices.invalidate();
196
+ },
197
+ handleInput: (data) => {
198
+ if (state.kind === "idle") list.handleInput(data);
199
+ else if (state.kind === "confirm") state.choices.handleInput(data);
200
+ tui.requestRender();
201
+ },
202
+ };
203
+ });
130
204
  }
@@ -11,6 +11,11 @@ import { windowDetails } from "./windows.js";
11
11
 
12
12
  const bytes = (value: number) => `${(value / 1024 / 1024).toFixed(1)} MiB`;
13
13
 
14
+ export interface SessionPruningInteraction {
15
+ progress: (message: string) => void;
16
+ confirm: (title: string, message: string) => Promise<boolean>;
17
+ }
18
+
14
19
  export class SessionPruning {
15
20
  private running = false;
16
21
  private observed: string | undefined;
@@ -69,7 +74,11 @@ export class SessionPruning {
69
74
  });
70
75
  }
71
76
 
72
- async run(ctx: ExtensionContext, manual: boolean): Promise<void> {
77
+ async run(
78
+ ctx: ExtensionContext,
79
+ manual: boolean,
80
+ interaction?: SessionPruningInteraction,
81
+ ): Promise<void> {
73
82
  if (this.running) {
74
83
  if (manual) ctx.ui.notify("Session pruning is already running.", "info");
75
84
  return;
@@ -89,8 +98,10 @@ export class SessionPruning {
89
98
  );
90
99
  return;
91
100
  }
101
+ interaction?.progress("Preparing pruning preview…");
92
102
  const plan = await planSessionPruning(ctx.sessionManager, policy);
93
103
  if (!plan.changed) {
104
+ interaction?.progress("Cleaning ranked history…");
94
105
  await this.search.pruneSession(plan.sessionId, plan.path);
95
106
  if (manual)
96
107
  ctx.ui.notify(
@@ -101,7 +112,7 @@ export class SessionPruning {
101
112
  }
102
113
  if (
103
114
  manual &&
104
- !(await ctx.ui.confirm(
115
+ !(await (interaction?.confirm ?? ctx.ui.confirm)(
105
116
  "Prune this session's history?",
106
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}`,
107
118
  ))
@@ -113,6 +124,7 @@ export class SessionPruning {
113
124
  currentPolicy.days !== policy.days
114
125
  )
115
126
  throw new Error("Session pruning settings changed. Run now again.");
127
+ interaction?.progress("Pruning session history…");
116
128
  const result = await commitSessionPruning(this.pi, ctx, plan, () => {
117
129
  if (this.epoch !== epoch)
118
130
  throw new Error(
@@ -123,6 +135,7 @@ export class SessionPruning {
123
135
  throw new Error("Session pruning settings changed. Run now again.");
124
136
  });
125
137
  historyPruned = true;
138
+ interaction?.progress("Cleaning ranked history…");
126
139
  await this.search.pruneSession(plan.sessionId, plan.path);
127
140
  ctx.ui.notify(
128
141
  `Pruned session history: ${bytes(result.before)} → ${bytes(result.after)}. Saved notes unchanged. ${RESTART_NOTICE}`,
@@ -1,7 +1,11 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionCommandContext,
4
+ } from "@earendil-works/pi-coding-agent";
2
5
  import type { NotesActivation } from "./activation.js";
3
6
  import type { HistorySearch } from "./history-search.js";
4
7
  import type { NotesLifecycle } from "./lifecycle.js";
8
+ import type { createModelRoles } from "./model-roles.js";
5
9
  import { sessionRef } from "./notes.js";
6
10
  import type { SessionPruning } from "./session-pruning.js";
7
11
  import type { NotesSettings } from "./settings.js";
@@ -16,13 +20,17 @@ export function registerNotesSettingsCommand(
16
20
  search: HistorySearch,
17
21
  settingsPath: string,
18
22
  sessionPruning: SessionPruning,
23
+ roles: ReturnType<typeof createModelRoles>,
19
24
  ): void {
20
- pi.registerCommand("notes", {
21
- description: "Manage local notes and context rollover",
22
- handler: async (args, ctx) => {
23
- if (args.trim()) {
24
- ctx.ui.notify("Use /notes to open settings.", "info");
25
- return;
25
+ const open = async (
26
+ ctx: ExtensionCommandContext,
27
+ initial: "notes" | "roles",
28
+ ) => {
29
+ let tab = initial;
30
+ while (true) {
31
+ if (tab === "roles") {
32
+ if ((await roles.command("", ctx)) !== "notes") return;
33
+ tab = "notes";
26
34
  }
27
35
  if (!ctx.hasUI) {
28
36
  ctx.ui.notify("Notes settings require interactive Pi.", "warning");
@@ -44,7 +52,7 @@ export function registerNotesSettingsCommand(
44
52
  );
45
53
  };
46
54
  try {
47
- await openNotesSettings(ctx, {
55
+ const next = await openNotesSettings(ctx, {
48
56
  settings: () => activation.settings,
49
57
  save,
50
58
  settingsPath,
@@ -53,9 +61,9 @@ export function registerNotesSettingsCommand(
53
61
  get: () => store.pruningPolicy(ctx.sessionManager.getSessionId()),
54
62
  save: (value) =>
55
63
  store.setPruningPolicy(ctx.sessionManager.getSessionId(), value),
56
- run: async () => {
64
+ run: async (interaction) => {
57
65
  await ctx.waitForIdle();
58
- await sessionPruning.run(ctx, true);
66
+ await sessionPruning.run(ctx, true, interaction);
59
67
  },
60
68
  },
61
69
  status: () => {
@@ -69,9 +77,32 @@ export function registerNotesSettingsCommand(
69
77
  ];
70
78
  },
71
79
  });
80
+ if (next !== "roles") return;
81
+ tab = "roles";
72
82
  } catch (error) {
73
83
  ctx.ui.notify(`Notes settings failed: ${String(error)}`, "error");
84
+ return;
85
+ }
86
+ }
87
+ };
88
+ pi.registerCommand("notes", {
89
+ description: "Manage local notes and context rollover",
90
+ handler: async (args, ctx) => {
91
+ if (args.trim()) {
92
+ ctx.ui.notify("Use /notes to open settings.", "info");
93
+ return;
94
+ }
95
+ await open(ctx, "notes");
96
+ },
97
+ });
98
+ pi.registerCommand("roles", {
99
+ description: "Configure model roles and in-conversation handoffs",
100
+ handler: async (args, ctx) => {
101
+ if (args.trim()) {
102
+ await roles.command(args, ctx);
103
+ return;
74
104
  }
105
+ await open(ctx, "roles");
75
106
  },
76
107
  });
77
108
  }