pi-better-harness 0.35.2 → 0.36.0
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.
- package/README.md +14 -2
- package/extensions/shared-navigator-panels.ts +250 -0
- package/extensions/task-context/index.ts +4 -2
- package/node_modules/pi-better-background-tasks/package.json +1 -1
- package/node_modules/pi-better-background-tasks/src/index.ts +2 -0
- package/node_modules/pi-better-background-tasks/src/shared-navigator-panels.ts +250 -0
- package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +5 -5
- package/node_modules/pi-better-goal/package.json +1 -1
- package/node_modules/pi-better-goal/src/index.ts +5 -2
- package/node_modules/pi-better-goal/src/shared-navigator-panels.ts +250 -0
- package/node_modules/pi-better-subagents/agent-commands.ts +33 -0
- package/node_modules/pi-better-subagents/agent-inspection.ts +6 -0
- package/node_modules/pi-better-subagents/agent-session-settings.ts +42 -13
- package/node_modules/pi-better-subagents/catalog-preferences.ts +139 -0
- package/node_modules/pi-better-subagents/catalog-resolver.ts +3 -3
- package/node_modules/pi-better-subagents/catalog-store.ts +187 -1
- package/node_modules/pi-better-subagents/catalog-ui.ts +112 -15
- package/node_modules/pi-better-subagents/config.ts +1 -0
- package/node_modules/pi-better-subagents/docs/agent-catalog-lifecycle.md +14 -5
- package/node_modules/pi-better-subagents/docs/agent-catalog-operations.md +22 -2
- package/node_modules/pi-better-subagents/docs/agent-catalog.md +4 -2
- package/node_modules/pi-better-subagents/docs/usage.md +7 -1
- package/node_modules/pi-better-subagents/extensions.mjs +16 -2
- package/node_modules/pi-better-subagents/index.ts +2 -0
- package/node_modules/pi-better-subagents/package.json +1 -1
- package/node_modules/pi-better-subagents/roles/role.developer.md +3 -1
- package/node_modules/pi-better-subagents/shared-navigator-panels.ts +250 -0
- package/node_modules/pi-better-subagents/shared-navigator.ts +5 -5
- package/package.json +4 -4
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// Generated from packages/navigator/panels.ts. Do not edit directly.
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { Component, TUI } from "@earendil-works/pi-tui";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.js";
|
|
6
|
+
|
|
7
|
+
export const NAVIGATOR_PANEL_WIDGET_KEY = "background-work-list";
|
|
8
|
+
export const NAVIGATOR_ENTRY_TYPE = "pi-better-harness-navigator-panels";
|
|
9
|
+
export const NAVIGATOR_STICKY_SETTING_ID = "navigator-sticky";
|
|
10
|
+
type MouseEvent = { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean };
|
|
11
|
+
type PanelComponent = Component & { dispose?(): void; handleMouse?(event: MouseEvent): { handled: true; render: boolean } | undefined };
|
|
12
|
+
export type NavigatorPanelFactory = (tui: TUI, theme: Theme) => PanelComponent;
|
|
13
|
+
type Panel = { factory: NavigatorPanelFactory; component?: PanelComponent | undefined };
|
|
14
|
+
type Preference = { version: 1; sticky: boolean };
|
|
15
|
+
type Owner = { pi: ExtensionAPI; stop?: (() => void) | undefined };
|
|
16
|
+
type State = {
|
|
17
|
+
panels: Map<string, Panel>;
|
|
18
|
+
owners: Map<ExtensionAPI, Owner>;
|
|
19
|
+
ctx?: ExtensionContext | undefined;
|
|
20
|
+
ui?: ExtensionContext["ui"] | undefined;
|
|
21
|
+
pi?: ExtensionAPI | undefined;
|
|
22
|
+
sticky: boolean;
|
|
23
|
+
mounted: boolean;
|
|
24
|
+
tui?: TUI | undefined;
|
|
25
|
+
theme?: Theme | undefined;
|
|
26
|
+
anchor?: string | undefined;
|
|
27
|
+
pendingAnchor: boolean;
|
|
28
|
+
generation: number;
|
|
29
|
+
ranges: Array<{ start: number; end: number; component: PanelComponent }>;
|
|
30
|
+
control?: { id: string; label: string; values: string[]; get(): string; change(value: string, ctx: ExtensionContext): void } | undefined;
|
|
31
|
+
};
|
|
32
|
+
const KEY = Symbol.for("pi-better-harness.navigator-panels.state");
|
|
33
|
+
function state(): State {
|
|
34
|
+
const global = globalThis as typeof globalThis & { [KEY]?: State };
|
|
35
|
+
return global[KEY] ??= { panels: new Map(), owners: new Map(), sticky: true, mounted: false, pendingAnchor: false, generation: 0, ranges: [] };
|
|
36
|
+
}
|
|
37
|
+
function parsePreference(value: unknown): Preference {
|
|
38
|
+
if (value === undefined) return { version: 1, sticky: true };
|
|
39
|
+
const preference = value as Partial<Preference> | null;
|
|
40
|
+
if (!preference || preference.version !== 1 || typeof preference.sticky !== "boolean") {
|
|
41
|
+
throw new Error("Navigator preference must contain version 1 and a boolean sticky value.");
|
|
42
|
+
}
|
|
43
|
+
return { version: 1, sticky: preference.sticky };
|
|
44
|
+
}
|
|
45
|
+
function canScroll(pi: ExtensionAPI | undefined): boolean {
|
|
46
|
+
return typeof pi?.registerEntryRenderer === "function" && typeof pi?.appendEntry === "function";
|
|
47
|
+
}
|
|
48
|
+
function isTui(ctx: ExtensionContext | undefined): ctx is ExtensionContext {
|
|
49
|
+
return ctx?.mode === "tui" && ctx.hasUI && typeof ctx.ui?.setWidget === "function";
|
|
50
|
+
}
|
|
51
|
+
function disposePanels(s: State): void {
|
|
52
|
+
for (const panel of s.panels.values()) {
|
|
53
|
+
try { panel.component?.dispose?.(); } catch { /* stale UI cleanup is best effort */ }
|
|
54
|
+
panel.component = undefined;
|
|
55
|
+
}
|
|
56
|
+
s.ranges = [];
|
|
57
|
+
}
|
|
58
|
+
function orderedPanels(s: State): Panel[] {
|
|
59
|
+
const rank = (key: string) => key === "pi-better-goal" ? 0 : key === "pi-better-plan" ? 1 : 2;
|
|
60
|
+
return [...s.panels.entries()].sort(([a], [b]) => rank(a) - rank(b)).map(([, panel]) => panel);
|
|
61
|
+
}
|
|
62
|
+
function buildPanels(s: State): void {
|
|
63
|
+
if (!s.tui || !s.theme) return;
|
|
64
|
+
for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme);
|
|
65
|
+
}
|
|
66
|
+
function renderPanels(s: State, width: number): string[] {
|
|
67
|
+
buildPanels(s);
|
|
68
|
+
const lines: string[] = [];
|
|
69
|
+
s.ranges = [];
|
|
70
|
+
for (const panel of orderedPanels(s)) {
|
|
71
|
+
if (!panel.component) continue;
|
|
72
|
+
const rendered = panel.component.render(width);
|
|
73
|
+
s.ranges.push({ start: lines.length, end: lines.length + rendered.length, component: panel.component });
|
|
74
|
+
lines.push(...rendered);
|
|
75
|
+
}
|
|
76
|
+
return lines;
|
|
77
|
+
}
|
|
78
|
+
function mouse(s: State, event: MouseEvent) {
|
|
79
|
+
const range = s.ranges.find(range => event.y >= range.start && event.y < range.end);
|
|
80
|
+
return range?.component.handleMouse?.({ ...event, y: event.y - range.start });
|
|
81
|
+
}
|
|
82
|
+
function restoreAnchor(ctx: ExtensionContext): string | undefined {
|
|
83
|
+
let anchor: string | undefined;
|
|
84
|
+
for (const entry of ctx.sessionManager?.getBranch?.() ?? []) {
|
|
85
|
+
if (entry.type !== "custom" || entry.customType !== NAVIGATOR_ENTRY_TYPE) continue;
|
|
86
|
+
const data = entry.data as { version?: unknown; anchor?: unknown } | undefined;
|
|
87
|
+
if (data?.version === 1 && typeof data.anchor === "string") anchor = data.anchor;
|
|
88
|
+
}
|
|
89
|
+
return anchor;
|
|
90
|
+
}
|
|
91
|
+
function appendAnchor(s: State): void {
|
|
92
|
+
if (s.sticky || s.anchor || !canScroll(s.pi)) return;
|
|
93
|
+
const anchor = randomUUID();
|
|
94
|
+
s.anchor = anchor;
|
|
95
|
+
try { s.pi!.appendEntry(NAVIGATOR_ENTRY_TYPE, { version: 1, anchor }); }
|
|
96
|
+
catch (error) { s.anchor = undefined; throw error; }
|
|
97
|
+
}
|
|
98
|
+
function scheduleAnchor(s: State): void {
|
|
99
|
+
if (s.anchor || s.pendingAnchor || s.sticky) return;
|
|
100
|
+
s.pendingAnchor = true;
|
|
101
|
+
const generation = s.generation;
|
|
102
|
+
// Session writes cannot run inside a component render. Empty sessions stay untouched.
|
|
103
|
+
queueMicrotask(() => {
|
|
104
|
+
if (generation !== s.generation) return;
|
|
105
|
+
s.pendingAnchor = false;
|
|
106
|
+
if (!s.sticky && s.panels.size) appendAnchor(s);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
function clearHost(s: State): void {
|
|
110
|
+
s.generation++;
|
|
111
|
+
s.pendingAnchor = false;
|
|
112
|
+
try {
|
|
113
|
+
if (s.mounted && isTui(s.ctx)) s.ctx.ui.setWidget(NAVIGATOR_PANEL_WIDGET_KEY, undefined);
|
|
114
|
+
} catch { /* an old session context may already be detached */ }
|
|
115
|
+
disposePanels(s);
|
|
116
|
+
s.mounted = false;
|
|
117
|
+
s.tui = undefined;
|
|
118
|
+
s.theme = undefined;
|
|
119
|
+
}
|
|
120
|
+
function adoptContext(s: State, ctx: ExtensionContext): void {
|
|
121
|
+
if (s.ui && s.ui !== ctx.ui) {
|
|
122
|
+
clearHost(s);
|
|
123
|
+
s.panels.clear();
|
|
124
|
+
s.anchor = undefined;
|
|
125
|
+
}
|
|
126
|
+
s.ctx = ctx;
|
|
127
|
+
s.ui = ctx.ui;
|
|
128
|
+
}
|
|
129
|
+
function mountHost(s: State): void {
|
|
130
|
+
if (!isTui(s.ctx) || s.mounted || !s.panels.size) return;
|
|
131
|
+
s.mounted = true;
|
|
132
|
+
s.ctx.ui.setWidget(NAVIGATOR_PANEL_WIDGET_KEY, (tui, theme) => {
|
|
133
|
+
if (s.tui !== tui || s.theme !== theme) disposePanels(s);
|
|
134
|
+
s.tui = tui;
|
|
135
|
+
s.theme = theme;
|
|
136
|
+
buildPanels(s);
|
|
137
|
+
return {
|
|
138
|
+
render(width: number) {
|
|
139
|
+
const lines = renderPanels(s, width);
|
|
140
|
+
if (s.sticky) return lines;
|
|
141
|
+
if (lines.length) scheduleAnchor(s);
|
|
142
|
+
return [];
|
|
143
|
+
},
|
|
144
|
+
handleMouse: (event: MouseEvent) => s.sticky ? mouse(s, event) : undefined,
|
|
145
|
+
invalidate() {
|
|
146
|
+
for (const panel of s.panels.values()) panel.component?.invalidate();
|
|
147
|
+
},
|
|
148
|
+
dispose() { disposePanels(s); s.mounted = false; },
|
|
149
|
+
};
|
|
150
|
+
}, { placement: "aboveEditor" });
|
|
151
|
+
}
|
|
152
|
+
function changeSticky(value: string, ctx: ExtensionContext): void {
|
|
153
|
+
if (value !== "On" && value !== "Off") throw new Error("Sticky navigator expects On or Off.");
|
|
154
|
+
const s = state();
|
|
155
|
+
if (value === "Off" && !canScroll(s.pi)) {
|
|
156
|
+
throw new Error("Scrolling navigator requires a Pi version with registerEntryRenderer support.");
|
|
157
|
+
}
|
|
158
|
+
updateHarnessSetting("navigator", current => {
|
|
159
|
+
parsePreference(current);
|
|
160
|
+
return { version: 1, sticky: value === "On" };
|
|
161
|
+
});
|
|
162
|
+
adoptContext(s, ctx);
|
|
163
|
+
if (s.sticky && value === "Off") s.anchor = undefined;
|
|
164
|
+
s.sticky = value === "On";
|
|
165
|
+
refreshNavigatorPanels(ctx);
|
|
166
|
+
}
|
|
167
|
+
export function initializeNavigatorPanels(pi: ExtensionAPI): void {
|
|
168
|
+
const s = state();
|
|
169
|
+
if (s.owners.has(pi)) return;
|
|
170
|
+
s.pi = pi;
|
|
171
|
+
try { s.sticky = parsePreference(readHarnessSetting("navigator")).sticky; }
|
|
172
|
+
catch { s.sticky = true; }
|
|
173
|
+
if (!canScroll(pi)) s.sticky = true;
|
|
174
|
+
if (canScroll(pi)) pi.registerEntryRenderer(NAVIGATOR_ENTRY_TYPE, (entry) => {
|
|
175
|
+
const data = entry.data as { version?: number; anchor?: string } | undefined;
|
|
176
|
+
if (data?.version !== 1 || !data.anchor) return undefined;
|
|
177
|
+
// Pi reconstructs chat before session_start restores the visible branch.
|
|
178
|
+
// Keep the component mounted and resolve its active anchor at render time.
|
|
179
|
+
return {
|
|
180
|
+
render: width => !s.sticky && data.anchor === s.anchor ? renderPanels(s, width) : [],
|
|
181
|
+
handleMouse: event => !s.sticky && data.anchor === s.anchor ? mouse(s, event) : undefined,
|
|
182
|
+
invalidate() { for (const panel of s.panels.values()) panel.component?.invalidate(); },
|
|
183
|
+
} as PanelComponent;
|
|
184
|
+
});
|
|
185
|
+
s.control ??= {
|
|
186
|
+
id: NAVIGATOR_STICKY_SETTING_ID, label: "Sticky navigator", values: ["On", "Off"],
|
|
187
|
+
get: () => state().sticky ? "On" : "Off", change: changeSticky,
|
|
188
|
+
};
|
|
189
|
+
const owner: Owner = { pi };
|
|
190
|
+
s.owners.set(pi, owner);
|
|
191
|
+
// Use one stable contribution callback across vendored copies, but each owner
|
|
192
|
+
// cleans up its own event subscription when its extension is unloaded.
|
|
193
|
+
const register = () => pi.events?.emit?.("harness-settings:register", s.control);
|
|
194
|
+
owner.stop = pi.events?.on?.("harness-settings:request", register);
|
|
195
|
+
register();
|
|
196
|
+
pi.on("session_start", (_event, ctx) => {
|
|
197
|
+
adoptContext(s, ctx);
|
|
198
|
+
s.anchor = restoreAnchor(ctx);
|
|
199
|
+
});
|
|
200
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
201
|
+
adoptContext(s, ctx);
|
|
202
|
+
s.anchor = restoreAnchor(ctx);
|
|
203
|
+
refreshNavigatorPanels(ctx);
|
|
204
|
+
});
|
|
205
|
+
pi.on("session_shutdown", () => {
|
|
206
|
+
owner.stop?.();
|
|
207
|
+
s.owners.delete(pi);
|
|
208
|
+
if (s.owners.size) return;
|
|
209
|
+
clearHost(s);
|
|
210
|
+
s.panels.clear();
|
|
211
|
+
s.anchor = undefined;
|
|
212
|
+
s.ctx = undefined;
|
|
213
|
+
s.ui = undefined;
|
|
214
|
+
s.pi = undefined;
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
export function setNavigatorPanel(
|
|
218
|
+
ctx: ExtensionContext, key: string, content: NavigatorPanelFactory | undefined,
|
|
219
|
+
_options?: { placement?: "aboveEditor" | "belowEditor" },
|
|
220
|
+
): void {
|
|
221
|
+
const s = state();
|
|
222
|
+
if (!isTui(ctx)) return;
|
|
223
|
+
adoptContext(s, ctx);
|
|
224
|
+
s.panels.get(key)?.component?.dispose?.();
|
|
225
|
+
if (content) s.panels.set(key, { factory: content });
|
|
226
|
+
else s.panels.delete(key);
|
|
227
|
+
if (!s.panels.size) { clearHost(s); return; }
|
|
228
|
+
mountHost(s);
|
|
229
|
+
buildPanels(s);
|
|
230
|
+
s.tui?.requestRender?.();
|
|
231
|
+
}
|
|
232
|
+
export function refreshNavigatorPanels(ctx?: ExtensionContext): void {
|
|
233
|
+
const s = state();
|
|
234
|
+
if (ctx) adoptContext(s, ctx);
|
|
235
|
+
mountHost(s);
|
|
236
|
+
s.tui?.requestRender?.(true);
|
|
237
|
+
}
|
|
238
|
+
export function __resetNavigatorPanelsForTests(): void {
|
|
239
|
+
const s = state();
|
|
240
|
+
clearHost(s);
|
|
241
|
+
for (const owner of s.owners.values()) owner.stop?.();
|
|
242
|
+
s.owners.clear();
|
|
243
|
+
s.panels.clear();
|
|
244
|
+
s.pi = undefined;
|
|
245
|
+
s.ctx = undefined;
|
|
246
|
+
s.ui = undefined;
|
|
247
|
+
s.anchor = undefined;
|
|
248
|
+
s.sticky = true;
|
|
249
|
+
s.control = undefined;
|
|
250
|
+
}
|
|
@@ -31,6 +31,8 @@ import {
|
|
|
31
31
|
loadCatalog,
|
|
32
32
|
projectCatalogPaths,
|
|
33
33
|
refreshCatalog,
|
|
34
|
+
resetRuntimeToBundled,
|
|
35
|
+
resetUserDefinition,
|
|
34
36
|
saveDefinition,
|
|
35
37
|
userCatalogPaths,
|
|
36
38
|
type CatalogSnapshot,
|
|
@@ -758,6 +760,37 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
|
|
|
758
760
|
}
|
|
759
761
|
return { ok: saved.ok, message: saved.ok ? `Defaults saved (${saved.scope}): ${id}.` : saved.diagnostics.map((item) => item.message).join(" ") };
|
|
760
762
|
},
|
|
763
|
+
resetToBundled(entry) {
|
|
764
|
+
const source = entry.winningSource;
|
|
765
|
+
if (!source) return { ok: false, message: "The definition source is unavailable. Reopen its settings." };
|
|
766
|
+
const reset = resetRuntimeToBundled({ ...location(host, deps), id: entry.id, expectedPath: source.path, expectedDigest: source.contentDigest });
|
|
767
|
+
if (reset.ok) {
|
|
768
|
+
commandResult.wrote = true;
|
|
769
|
+
commandResult.path = reset.path;
|
|
770
|
+
commandResult.scope = "user";
|
|
771
|
+
try { deps.sessionSettings!.reset(entry.id); }
|
|
772
|
+
catch (error) {
|
|
773
|
+
return { ok: false, message: `Saved defaults reset for ${entry.id}, but current-session overrides remain active: ${error instanceof Error ? error.message : String(error)}. Retry Reset to bundled to clear them.` };
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
return { ok: reset.ok, message: reset.ok
|
|
777
|
+
? `Bundled model/effort restored: ${entry.id}. Role instructions unchanged.`
|
|
778
|
+
: reset.diagnostics.map(item => item.message).join(" ") };
|
|
779
|
+
},
|
|
780
|
+
resetDefinition(entry) {
|
|
781
|
+
if (entry.identity.scope === "bundled") return { ok: true, message: `Already using bundled instructions: ${entry.id}. Model/effort unchanged.` };
|
|
782
|
+
const source = entry.winningSource;
|
|
783
|
+
if (!source) return { ok: false, message: "The definition source is unavailable. Reopen its settings." };
|
|
784
|
+
const reset = resetUserDefinition({ ...location(host, deps), id: entry.id, expectedPath: source.path, expectedDigest: source.contentDigest });
|
|
785
|
+
if (reset.ok) {
|
|
786
|
+
commandResult.wrote = true;
|
|
787
|
+
commandResult.path = reset.path;
|
|
788
|
+
commandResult.scope = "user";
|
|
789
|
+
}
|
|
790
|
+
return { ok: reset.ok, message: reset.ok
|
|
791
|
+
? `Bundled instructions restored: ${entry.id}. Model/effort kept. Backup: ${reset.backupPath}.`
|
|
792
|
+
: reset.diagnostics.map(item => item.message).join(" ") };
|
|
793
|
+
},
|
|
761
794
|
} : undefined, () => viewportHeight), {
|
|
762
795
|
overlay: true,
|
|
763
796
|
overlayOptions: {
|
|
@@ -130,6 +130,7 @@ export interface OperationView {
|
|
|
130
130
|
winningSource?: { scope: string; path: string; contentDigest: string; id: string };
|
|
131
131
|
shadowed: { scope: string; path: string; contentDigest: string; reason: string }[];
|
|
132
132
|
instructionMode?: string;
|
|
133
|
+
preferenceSources?: Partial<Record<"model" | "effort", { scope: "user" | "project"; path: string; bundled?: boolean }>>;
|
|
133
134
|
instructions?: string;
|
|
134
135
|
fields?: { model: OperationField; effort: OperationField; tier: OperationField };
|
|
135
136
|
/** The definition's own default model and effort (role default, or the agent's override or inherited value). Null when neither is set. */
|
|
@@ -332,6 +333,11 @@ export function presentCatalogEntry(snapshot: CatalogSnapshot, id: string, enric
|
|
|
332
333
|
winningSource: inspection.winningSource,
|
|
333
334
|
shadowed: inspection.shadowed.map((item) => ({ ...item })),
|
|
334
335
|
instructionMode: inspection.instructionMode,
|
|
336
|
+
preferenceSources: Object.fromEntries((["model", "effort"] as const).flatMap(key => {
|
|
337
|
+
const owner = inspection.kind === "agent" && fields?.[key].inherited ? inspection.roleId : id;
|
|
338
|
+
const source = owner ? snapshot.preferenceSources?.[owner]?.[key] : undefined;
|
|
339
|
+
return source ? [[key, source]] : [];
|
|
340
|
+
})),
|
|
335
341
|
instructions: inspection.instructions,
|
|
336
342
|
fields,
|
|
337
343
|
defaults: definitionDefaults(fields),
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/** Branch-local catalog preferences. Null removes a definition's own value. */
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
2
4
|
import { EFFORT_LEVELS, type CatalogDefinition, type PortablePreferences, type ThinkingLevel } from "./catalog-schema.ts";
|
|
3
|
-
import { contentDigest,
|
|
5
|
+
import { contentDigest, projectCatalogPaths, userCatalogPaths, type CatalogSnapshot, type LoadCatalogInput, type SaveResult } from "./catalog-store.ts";
|
|
6
|
+
import { writeCatalogPreferences } from "./catalog-preferences.ts";
|
|
4
7
|
|
|
5
8
|
export const AGENT_SESSION_SETTINGS_ENTRY = "pi-better-subagents-agent-settings";
|
|
6
9
|
export type AgentSettingKey = "model" | "effort";
|
|
@@ -12,11 +15,16 @@ export interface AgentSessionSettings {
|
|
|
12
15
|
restore(ctx: AgentSessionContext): void;
|
|
13
16
|
snapshot(): AgentSessionOverrides;
|
|
14
17
|
change(id: string, key: AgentSettingKey, value: string | null): void;
|
|
18
|
+
reset(id: string): void;
|
|
15
19
|
clear(): void;
|
|
16
20
|
}
|
|
17
21
|
|
|
22
|
+
function validId(id: unknown): id is string {
|
|
23
|
+
return typeof id === "string" && /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id);
|
|
24
|
+
}
|
|
25
|
+
|
|
18
26
|
function valid(id: unknown, key: unknown, value: unknown): boolean {
|
|
19
|
-
return
|
|
27
|
+
return validId(id) &&
|
|
20
28
|
(key === "model" || key === "effort") && (value === null || typeof value === "string" &&
|
|
21
29
|
(key === "model" ? /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(value)
|
|
22
30
|
: (EFFORT_LEVELS as readonly string[]).includes(value)));
|
|
@@ -28,6 +36,11 @@ export function createAgentSessionSettings(pi: { appendEntry(customType: string,
|
|
|
28
36
|
const apply = (id: string, key: AgentSettingKey, value: string | null) => {
|
|
29
37
|
overrides = Object.freeze({ ...overrides, [id]: Object.freeze({ ...overrides[id], [key]: value }) });
|
|
30
38
|
};
|
|
39
|
+
const reset = (id: string) => {
|
|
40
|
+
const next = { ...overrides };
|
|
41
|
+
delete next[id];
|
|
42
|
+
overrides = Object.freeze(next);
|
|
43
|
+
};
|
|
31
44
|
return {
|
|
32
45
|
snapshot: () => overrides,
|
|
33
46
|
clear() { overrides = Object.freeze({}); },
|
|
@@ -38,8 +51,12 @@ export function createAgentSessionSettings(pi: { appendEntry(customType: string,
|
|
|
38
51
|
for (const entry of branch) {
|
|
39
52
|
if (!entry || entry.type !== "custom" || entry.customType !== AGENT_SESSION_SETTINGS_ENTRY) continue;
|
|
40
53
|
const data = entry.data;
|
|
41
|
-
if (data?.version !== 1
|
|
42
|
-
|
|
54
|
+
if (data?.version !== 1) continue;
|
|
55
|
+
if (data.kind === "reset") {
|
|
56
|
+
if (validId(data.id)) reset(data.id);
|
|
57
|
+
} else if (valid(data.id, data.key, data.value)) {
|
|
58
|
+
apply(data.id, data.key, data.value);
|
|
59
|
+
}
|
|
43
60
|
}
|
|
44
61
|
},
|
|
45
62
|
change(id, key, value) {
|
|
@@ -48,13 +65,19 @@ export function createAgentSessionSettings(pi: { appendEntry(customType: string,
|
|
|
48
65
|
pi.appendEntry(AGENT_SESSION_SETTINGS_ENTRY, { version: 1, id, key, value });
|
|
49
66
|
apply(id, key, value);
|
|
50
67
|
},
|
|
68
|
+
reset(id) {
|
|
69
|
+
if (!validId(id)) throw new Error("Choose a valid catalog id. Nothing changed.");
|
|
70
|
+
// Append first, just like changes: failed persistence leaves the session intact.
|
|
71
|
+
pi.appendEntry(AGENT_SESSION_SETTINGS_ENTRY, { version: 1, kind: "reset", id });
|
|
72
|
+
reset(id);
|
|
73
|
+
},
|
|
51
74
|
};
|
|
52
75
|
}
|
|
53
76
|
|
|
54
77
|
/** Copy only preferences; never repair or bypass a catalog validation failure. */
|
|
55
|
-
export function sessionPreferences(definition: CatalogDefinition, settings: AgentSessionOverrides = {}): PortablePreferences {
|
|
78
|
+
export function sessionPreferences(definition: CatalogDefinition, settings: AgentSessionOverrides = {}, saved: AgentSessionOverrides = {}): PortablePreferences {
|
|
56
79
|
const own = { ...(definition.kind === "role" ? definition.defaults : definition.overrides) };
|
|
57
|
-
const patch = settings[definition.id];
|
|
80
|
+
const patch = { ...saved[definition.id], ...settings[definition.id] };
|
|
58
81
|
for (const key of ["model", "effort"] as const) {
|
|
59
82
|
if (!patch || !Object.hasOwn(patch, key)) continue;
|
|
60
83
|
if (patch[key] === null) delete own[key];
|
|
@@ -74,16 +97,22 @@ export function withAgentSessionSettings(snapshot: CatalogSnapshot, settings?: A
|
|
|
74
97
|
return Object.freeze({ ...snapshot, digest, revision: digest, sessionSettings: Object.freeze(ordered) });
|
|
75
98
|
}
|
|
76
99
|
|
|
77
|
-
/** Save selected
|
|
100
|
+
/** Save selected preference edits without copying or rewriting Markdown definitions. */
|
|
78
101
|
export function saveAgentSessionDefaults(snapshot: CatalogSnapshot, id: string, settings: AgentSessionOverrides, location: LoadCatalogInput): SaveResult {
|
|
79
102
|
const entry = snapshot.roles.get(id) ?? snapshot.agents.get(id);
|
|
80
103
|
if (!entry?.definition || !entry.structurallyValid || entry.duplicate) {
|
|
81
104
|
return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: `Cannot save ${id}: repair the catalog definition first. Session edits are unchanged.`, blocking: true, structural: false }] };
|
|
82
105
|
}
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
106
|
+
const scope = entry.scope === "project" || Object.values(snapshot.preferenceSources?.[id] ?? {}).some(source => source.scope === "project") ? "project" : "user";
|
|
107
|
+
if (scope === "project" && !location.projectTrusted) {
|
|
108
|
+
return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: "Project catalog preferences require a trusted project. Nothing changed.", blocking: true, structural: false }] };
|
|
109
|
+
}
|
|
110
|
+
const root = scope === "project" ? projectCatalogPaths(location.cwd, location.projectConfigDirName).root : userCatalogPaths(location.userRoot).root;
|
|
111
|
+
try {
|
|
112
|
+
mkdirSync(dirname(root), { recursive: true, mode: 0o700 });
|
|
113
|
+
const saved = writeCatalogPreferences(root, id, current => ({ ...current, ...settings[id] }));
|
|
114
|
+
return { ok: true, path: saved.path, scope, diagnostics: [] };
|
|
115
|
+
} catch (error) {
|
|
116
|
+
return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: error instanceof Error ? error.message : String(error), blocking: true, structural: false }] };
|
|
117
|
+
}
|
|
89
118
|
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
|
|
6
|
+
|
|
7
|
+
export type CatalogPreference = Readonly<{ bundled?: true; model?: string | null; effort?: ThinkingLevel | null }>;
|
|
8
|
+
export type CatalogPreferences = Readonly<Record<string, CatalogPreference>>;
|
|
9
|
+
const ID = /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
|
|
10
|
+
const MODEL = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/;
|
|
11
|
+
|
|
12
|
+
function object(value: unknown, label: string): Record<string, unknown> {
|
|
13
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be a JSON object.`);
|
|
14
|
+
return value as Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function preferences(id: string, value: unknown): CatalogPreference {
|
|
18
|
+
if (typeof id !== "string" || !ID.test(id)) throw new Error(`Invalid catalog id ${JSON.stringify(id)}.`);
|
|
19
|
+
const record = object(value, `Preferences for ${id}`);
|
|
20
|
+
for (const [key, item] of Object.entries(record)) {
|
|
21
|
+
if (key !== "bundled" && key !== "model" && key !== "effort") throw new Error(`Unknown preference ${key} for ${id}.`);
|
|
22
|
+
if (key === "bundled" ? item !== true : item !== null && (typeof item !== "string" || (key === "model" ? !MODEL.test(item)
|
|
23
|
+
: !(THINKING_LEVELS as readonly string[]).includes(item)))) {
|
|
24
|
+
throw new Error(`Invalid ${key} preference for ${id}: ${JSON.stringify(item)}.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return Object.freeze({
|
|
28
|
+
...(Object.hasOwn(record, "bundled") ? { bundled: true as const } : {}),
|
|
29
|
+
...(Object.hasOwn(record, "model") ? { model: record.model as string | null } : {}),
|
|
30
|
+
...(Object.hasOwn(record, "effort") ? { effort: record.effort as ThinkingLevel | null } : {}),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function snapshot(values: CatalogPreferences): { settings: CatalogPreferences; digest: string } {
|
|
35
|
+
const settings = Object.freeze(Object.fromEntries(Object.keys(values).sort().map(id => [id, values[id]])));
|
|
36
|
+
return { settings, digest: createHash("sha256").update(JSON.stringify(settings)).digest("hex") };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function stat(path: string) {
|
|
40
|
+
try { return lstatSync(path); }
|
|
41
|
+
catch (error) {
|
|
42
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function checkRoot(root: string): boolean {
|
|
48
|
+
const info = stat(root);
|
|
49
|
+
if (!info) return false;
|
|
50
|
+
if (info.isSymbolicLink()) throw new Error(`Refusing symlink catalog directory ${root}.`);
|
|
51
|
+
if (!info.isDirectory()) throw new Error(`Catalog root ${root} must be a directory.`);
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function checkFile(path: string): boolean {
|
|
56
|
+
const info = stat(path);
|
|
57
|
+
if (!info) return false;
|
|
58
|
+
if (info.isSymbolicLink()) throw new Error(`Refusing symlink catalog settings file ${path}.`);
|
|
59
|
+
if (!info.isFile()) throw new Error(`Catalog settings ${path} must be a regular file.`);
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function readCatalogPreferences(root: string): { settings: CatalogPreferences; digest: string } {
|
|
64
|
+
root = resolve(root);
|
|
65
|
+
const path = join(root, "settings.json");
|
|
66
|
+
try {
|
|
67
|
+
if (!checkRoot(root) || !checkFile(path)) return snapshot({});
|
|
68
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
69
|
+
let data: Record<string, unknown>;
|
|
70
|
+
try {
|
|
71
|
+
if (!fstatSync(fd).isFile()) throw new Error("Settings must be a regular file.");
|
|
72
|
+
data = object(JSON.parse(readFileSync(fd, "utf8")), "Catalog settings");
|
|
73
|
+
} finally { closeSync(fd); }
|
|
74
|
+
if (data.version !== 1 || !Object.hasOwn(data, "defaults") ||
|
|
75
|
+
Object.keys(data).some(key => key !== "version" && key !== "defaults")) {
|
|
76
|
+
throw new Error("Expected only version: 1 and defaults in catalog settings.");
|
|
77
|
+
}
|
|
78
|
+
const settings = Object.fromEntries(Object.entries(object(data.defaults, "Catalog defaults"))
|
|
79
|
+
.map(([id, value]) => [id, preferences(id, value)]));
|
|
80
|
+
return snapshot(settings);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw new Error(`Cannot read catalog preferences at ${path}: ${(error as Error).message}`, { cause: error });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function acquire(path: string): () => void {
|
|
87
|
+
// Read-only catalog consumers (including the portable CLI) need no lock adapter.
|
|
88
|
+
const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
|
|
89
|
+
lockSync(path: string, options: { realpath: boolean }): () => void;
|
|
90
|
+
};
|
|
91
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
92
|
+
try { return lockfile.lockSync(path, { realpath: false }); }
|
|
93
|
+
catch (error) {
|
|
94
|
+
if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === 99) throw error;
|
|
95
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
throw new Error(`Cannot lock catalog settings at ${path}.`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Replace only this id's own preferences; null explicitly clears a definition value. */
|
|
102
|
+
export function writeCatalogPreferences(root: string, id: string, value: CatalogPreference | ((current: CatalogPreference) => CatalogPreference)): { path: string; settings: CatalogPreferences; digest: string } {
|
|
103
|
+
// Validate literal input before touching disk; updater callbacks run under the lock.
|
|
104
|
+
const selected = typeof value === "function" ? (preferences(id, {}), undefined) : preferences(id, value);
|
|
105
|
+
root = resolve(root);
|
|
106
|
+
const path = join(root, "settings.json");
|
|
107
|
+
let release: (() => void) | undefined;
|
|
108
|
+
let pending: string | undefined;
|
|
109
|
+
try {
|
|
110
|
+
if (!checkRoot(root)) {
|
|
111
|
+
// Do not create the caller's user/project configuration directories.
|
|
112
|
+
try { mkdirSync(root, { mode: 0o700 }); }
|
|
113
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
|
|
114
|
+
checkRoot(root);
|
|
115
|
+
}
|
|
116
|
+
checkFile(path);
|
|
117
|
+
release = acquire(path);
|
|
118
|
+
const settings = { ...readCatalogPreferences(root).settings };
|
|
119
|
+
const next = selected ?? preferences(id, (value as (current: CatalogPreference) => CatalogPreference)(settings[id] ?? Object.freeze({})));
|
|
120
|
+
if (Object.keys(next).length) settings[id] = next;
|
|
121
|
+
else delete settings[id];
|
|
122
|
+
const result = snapshot(settings);
|
|
123
|
+
pending = join(root, `.settings.json.${randomUUID()}.tmp`);
|
|
124
|
+
const fd = openSync(pending, "wx", 0o600);
|
|
125
|
+
try {
|
|
126
|
+
writeFileSync(fd, `${JSON.stringify({ version: 1, defaults: result.settings }, null, 2)}\n`);
|
|
127
|
+
fsyncSync(fd);
|
|
128
|
+
} finally { closeSync(fd); }
|
|
129
|
+
checkRoot(root);
|
|
130
|
+
checkFile(path);
|
|
131
|
+
renameSync(pending, path);
|
|
132
|
+
return { path, ...result };
|
|
133
|
+
} catch (error) {
|
|
134
|
+
throw new Error(`Cannot save catalog preferences at ${path}: ${(error as Error).message}`, { cause: error });
|
|
135
|
+
} finally {
|
|
136
|
+
try { if (pending) rmSync(pending, { force: true }); }
|
|
137
|
+
finally { release?.(); }
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -224,7 +224,7 @@ function resolveRole(snapshot: CatalogSnapshot, roleId: string): Resolution {
|
|
|
224
224
|
return blockedEntry(snapshot, entry, entry.diagnostics);
|
|
225
225
|
}
|
|
226
226
|
const definition = entry.definition;
|
|
227
|
-
const preferences = sessionPreferences(definition, snapshot.sessionSettings);
|
|
227
|
+
const preferences = sessionPreferences(definition, snapshot.sessionSettings, snapshot.savedSettings);
|
|
228
228
|
const launchable = entry.schemaLaunchable;
|
|
229
229
|
const diagnostics = launchable
|
|
230
230
|
? [...entry.diagnostics]
|
|
@@ -334,8 +334,8 @@ function baseEffective(
|
|
|
334
334
|
} | undefined,
|
|
335
335
|
): EffectiveDefinition {
|
|
336
336
|
const mode = agent.instructionMode;
|
|
337
|
-
const overrides = sessionPreferences(agent, snapshot.sessionSettings);
|
|
338
|
-
const defaults = inheritance ? sessionPreferences(inheritance.role, snapshot.sessionSettings) : {};
|
|
337
|
+
const overrides = sessionPreferences(agent, snapshot.sessionSettings, snapshot.savedSettings);
|
|
338
|
+
const defaults = inheritance ? sessionPreferences(inheritance.role, snapshot.sessionSettings, snapshot.savedSettings) : {};
|
|
339
339
|
const instructions = inheritance
|
|
340
340
|
? combineInstructions(inheritance.role.body, agent.body, mode)
|
|
341
341
|
: agent.body;
|