@restranger/repi-advisor 0.0.0-stage → 0.0.1-44677f3
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 +88 -2
- package/package.json +44 -5
- package/src/advisor-ui.ts +1117 -0
- package/src/command.ts +169 -0
- package/src/config.ts +302 -0
- package/src/context.ts +62 -0
- package/src/execute.ts +355 -0
- package/src/handlers.ts +73 -0
- package/src/index.ts +31 -0
- package/src/inventory.ts +99 -0
- package/src/messages.ts +64 -0
- package/src/pi-compat.ts +90 -0
- package/src/plugin.ts +22 -0
- package/src/policy.ts +49 -0
- package/src/prompt.ts +16 -0
- package/src/register.ts +74 -0
- package/src/restore.ts +168 -0
- package/src/state.ts +36 -0
- package/src/types.ts +57 -0
package/src/command.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ArgumentChoice,
|
|
3
|
+
type PiContext,
|
|
4
|
+
type PiExtensionAPI,
|
|
5
|
+
type PiModel,
|
|
6
|
+
SUBAGENTS_CONTRACT_ID,
|
|
7
|
+
type SubagentsService,
|
|
8
|
+
completeArguments,
|
|
9
|
+
getService,
|
|
10
|
+
getSessionId,
|
|
11
|
+
modelKey,
|
|
12
|
+
resolveModel,
|
|
13
|
+
} from "@restranger/repi-lib";
|
|
14
|
+
import { openAdvisorMenu } from "./advisor-ui.js";
|
|
15
|
+
import { saveAdvisorConfig } from "./config.js";
|
|
16
|
+
import { reconcileAdvisorTool } from "./handlers.js";
|
|
17
|
+
import {
|
|
18
|
+
ADVISOR_TOOL_NAME,
|
|
19
|
+
EFFORT_ORDINAL,
|
|
20
|
+
type GradedEffort,
|
|
21
|
+
MSG_ADVISOR_DISABLED,
|
|
22
|
+
MSG_PERSIST_FAILED,
|
|
23
|
+
errModelUnavailable,
|
|
24
|
+
msgAdvisorEnabled,
|
|
25
|
+
msgAdvisorEnabledInactive,
|
|
26
|
+
} from "./messages.js";
|
|
27
|
+
import { isExecutorBlocked } from "./policy.js";
|
|
28
|
+
import {
|
|
29
|
+
clearAdvisorState,
|
|
30
|
+
getAdvisorEffort,
|
|
31
|
+
getAdvisorFallbacks,
|
|
32
|
+
getAdvisorModel,
|
|
33
|
+
setAdvisorEffort,
|
|
34
|
+
setAdvisorFallbacks,
|
|
35
|
+
setAdvisorModel,
|
|
36
|
+
} from "./state.js";
|
|
37
|
+
import type { AdvisorPluginOptions } from "./types.js";
|
|
38
|
+
|
|
39
|
+
const ADVISOR_ARGUMENTS: readonly ArgumentChoice[] = [
|
|
40
|
+
{ name: "menu", description: "Open the interactive advisor editor (default)" },
|
|
41
|
+
{ name: "status", description: "Show enabled state, current advisor, fallbacks and subagents integration" },
|
|
42
|
+
{ name: "list", description: "List available models that can act as advisor" },
|
|
43
|
+
{ name: "off", description: "Disable the advisor tool" },
|
|
44
|
+
{ name: "model", description: "Set the advisor model (e.g. /advisor model anthropic/claude-3-7-sonnet)" },
|
|
45
|
+
{ name: "effort", description: "Set the reasoning effort (e.g. /advisor effort high)" },
|
|
46
|
+
{ name: "fallback", description: "Configure comma-separated fallback models" },
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
export function registerAdvisorCommand(pi: PiExtensionAPI, options: AdvisorPluginOptions = {}): void {
|
|
50
|
+
pi.registerCommand("advisor", {
|
|
51
|
+
description: "Configure the reviewer model for the advisor-strategy pattern",
|
|
52
|
+
getArgumentCompletions: (prefix: string) => completeArguments(prefix, ADVISOR_ARGUMENTS),
|
|
53
|
+
handler: async (args, ctx) => {
|
|
54
|
+
const trimmed = (args ?? "").trim();
|
|
55
|
+
const sessionId = getSessionId(ctx, "default");
|
|
56
|
+
const cwd = options.cwd ?? ctx.cwd;
|
|
57
|
+
const workspaceTrusted = ctx.isProjectTrusted?.() === true;
|
|
58
|
+
const persistOptions = {
|
|
59
|
+
workspaceTrusted,
|
|
60
|
+
...(options.homeDir ? { homeDir: options.homeDir } : {}),
|
|
61
|
+
...(options.env ? { env: options.env } : {}),
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
if (trimmed === "off" || trimmed === "disable") {
|
|
65
|
+
if (!saveAdvisorConfig(cwd, { modelKey: null, effort: null }, persistOptions)) {
|
|
66
|
+
ctx.ui.notify(MSG_PERSIST_FAILED, "error");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
clearAdvisorState();
|
|
70
|
+
reconcileAdvisorTool(pi, ctx, { blocked: true });
|
|
71
|
+
ctx.ui.notify(MSG_ADVISOR_DISABLED, "info");
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (trimmed === "status") {
|
|
76
|
+
const current = getAdvisorModel();
|
|
77
|
+
const effort = getAdvisorEffort();
|
|
78
|
+
const fallbacks = getAdvisorFallbacks();
|
|
79
|
+
const blocked = isExecutorBlocked(ctx, pi.getThinkingLevel?.());
|
|
80
|
+
|
|
81
|
+
const subagentsService = getService<SubagentsService>(SUBAGENTS_CONTRACT_ID, sessionId);
|
|
82
|
+
const subagents = subagentsService?.listAgents?.() ?? [];
|
|
83
|
+
|
|
84
|
+
const lines = [
|
|
85
|
+
"Advisor Status:",
|
|
86
|
+
` Active Model: ${current ? modelKey(current) : "(none - disabled)"}`,
|
|
87
|
+
` Reasoning Effort: ${effort ?? "(model default)"}`,
|
|
88
|
+
` Fallback Chain: ${fallbacks.length > 0 ? fallbacks.join(" → ") : "(none)"}`,
|
|
89
|
+
` Tool Status: ${current ? (blocked ? "inactive (blocked for current executor model)" : "active") : "disabled"}`,
|
|
90
|
+
` Subagents Integration: ${subagents.length > 0 ? `${subagents.length} agents detected via service seam` : "inactive"}`,
|
|
91
|
+
];
|
|
92
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (trimmed === "list") {
|
|
97
|
+
const available = ctx.modelRegistry?.getAvailable?.();
|
|
98
|
+
const all = available && available.length > 0 ? available : (ctx.modelRegistry?.getAll?.() ?? []);
|
|
99
|
+
const listText = all.map((m) => ` ${m.provider}/${m.id}${m.reasoning ? " (reasoning)" : ""}`).join("\n");
|
|
100
|
+
ctx.ui.notify(`Available Models for Advisor:\n${listText || " (none)"}`, "info");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (trimmed.startsWith("model ")) {
|
|
105
|
+
const target = trimmed.slice(6).trim();
|
|
106
|
+
const picked = resolveModel<PiModel>(target, ctx.modelRegistry);
|
|
107
|
+
if (!picked) {
|
|
108
|
+
ctx.ui.notify(errModelUnavailable(target), "error");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const key = modelKey(picked);
|
|
112
|
+
if (!saveAdvisorConfig(cwd, { modelKey: key }, persistOptions)) {
|
|
113
|
+
ctx.ui.notify(MSG_PERSIST_FAILED, "error");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
setAdvisorModel(picked);
|
|
117
|
+
const blocked = isExecutorBlocked(ctx, pi.getThinkingLevel?.());
|
|
118
|
+
reconcileAdvisorTool(pi, ctx, { blocked });
|
|
119
|
+
ctx.ui.notify(
|
|
120
|
+
blocked
|
|
121
|
+
? msgAdvisorEnabledInactive(key, getAdvisorEffort())
|
|
122
|
+
: msgAdvisorEnabled(key, getAdvisorEffort(), getAdvisorFallbacks()),
|
|
123
|
+
"info",
|
|
124
|
+
);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (trimmed.startsWith("effort ")) {
|
|
129
|
+
const target = trimmed.slice(7).trim().toLowerCase();
|
|
130
|
+
if (!EFFORT_ORDINAL.includes(target as GradedEffort) && target !== "off") {
|
|
131
|
+
ctx.ui.notify(`Invalid effort "${target}". Valid: ${EFFORT_ORDINAL.join(", ")}, off`, "error");
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const effort = target === "off" ? null : (target as GradedEffort);
|
|
135
|
+
if (!saveAdvisorConfig(cwd, { effort }, persistOptions)) {
|
|
136
|
+
ctx.ui.notify(MSG_PERSIST_FAILED, "error");
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
setAdvisorEffort(effort ?? undefined);
|
|
140
|
+
ctx.ui.notify(`Advisor effort set to ${target}`, "info");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (trimmed.startsWith("fallback ")) {
|
|
145
|
+
const raw = trimmed.slice(9).trim();
|
|
146
|
+
const fallbacks = raw
|
|
147
|
+
.split(",")
|
|
148
|
+
.map((s) => s.trim())
|
|
149
|
+
.filter(Boolean);
|
|
150
|
+
if (!saveAdvisorConfig(cwd, { fallbackModels: fallbacks }, persistOptions)) {
|
|
151
|
+
ctx.ui.notify(MSG_PERSIST_FAILED, "error");
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
setAdvisorFallbacks(fallbacks);
|
|
155
|
+
ctx.ui.notify(`Advisor fallbacks updated: ${fallbacks.join(", ") || "(none)"}`, "info");
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Interactive TUI Menu
|
|
160
|
+
if (typeof ctx.ui?.custom === "function") {
|
|
161
|
+
await openAdvisorMenu(pi, ctx, options);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Non-interactive fallback
|
|
166
|
+
ctx.ui.notify("Use /advisor status, /advisor model <name>, /advisor effort <level>, or /advisor off", "info");
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { type PluginConfigLayer, type PluginDiagnostic, resolveConfigLayers } from "@restranger/repi-lib";
|
|
4
|
+
import { EFFORT_ORDINAL, type GradedEffort } from "./messages.js";
|
|
5
|
+
import type {
|
|
6
|
+
AdvisorConfig,
|
|
7
|
+
AdvisorConfigContext,
|
|
8
|
+
DisabledForModelsEntry,
|
|
9
|
+
GuidanceConfig,
|
|
10
|
+
LoadedAdvisorConfig,
|
|
11
|
+
} from "./types.js";
|
|
12
|
+
|
|
13
|
+
const CONFIG_NAME = "advisor.json";
|
|
14
|
+
|
|
15
|
+
export function resolveConfigPaths(context: AdvisorConfigContext): PluginConfigLayer[] {
|
|
16
|
+
return resolveConfigLayers({
|
|
17
|
+
cwd: context.cwd,
|
|
18
|
+
...(context.homeDir !== undefined ? { homeDir: context.homeDir } : {}),
|
|
19
|
+
...(context.env !== undefined ? { env: context.env } : {}),
|
|
20
|
+
...(context.workspaceTrusted !== undefined ? { workspaceTrusted: context.workspaceTrusted } : {}),
|
|
21
|
+
filename: CONFIG_NAME,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function validateDisabledForModels(value: unknown): DisabledForModelsEntry[] {
|
|
26
|
+
if (!Array.isArray(value)) return [];
|
|
27
|
+
return value.filter((entry): entry is DisabledForModelsEntry => {
|
|
28
|
+
if (typeof entry === "string") return entry.trim().length > 0;
|
|
29
|
+
if (typeof entry !== "object" || entry === null) return false;
|
|
30
|
+
const obj = entry as Record<string, unknown>;
|
|
31
|
+
if (typeof obj.model !== "string" || obj.model.trim().length === 0) return false;
|
|
32
|
+
if (obj.minEffort !== undefined && !EFFORT_ORDINAL.includes(obj.minEffort as GradedEffort)) {
|
|
33
|
+
console.warn(
|
|
34
|
+
`[repi-advisor] advisor.json: unknown minEffort "${String(obj.minEffort)}" — dropping entry for "${obj.model}"`,
|
|
35
|
+
);
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
return true;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function validateGuidance(value: unknown): GuidanceConfig {
|
|
43
|
+
if (typeof value !== "object" || value === null) return {};
|
|
44
|
+
const obj = value as Record<string, unknown>;
|
|
45
|
+
const result: { promptSnippet?: string; promptGuidelines?: string[] } = {};
|
|
46
|
+
if (typeof obj.promptSnippet === "string" && obj.promptSnippet.trim().length > 0) {
|
|
47
|
+
result.promptSnippet = obj.promptSnippet.trim();
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(obj.promptGuidelines)) {
|
|
50
|
+
result.promptGuidelines = obj.promptGuidelines
|
|
51
|
+
.filter((g): g is string => typeof g === "string" && g.trim().length > 0)
|
|
52
|
+
.map((g) => g.trim());
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function loadAdvisorConfig(context: AdvisorConfigContext): LoadedAdvisorConfig {
|
|
58
|
+
const diagnostics: PluginDiagnostic[] = [];
|
|
59
|
+
const configFiles: string[] = [];
|
|
60
|
+
let merged: AdvisorConfig = {};
|
|
61
|
+
|
|
62
|
+
for (const layer of resolveConfigPaths(context)) {
|
|
63
|
+
if (!safeExists(layer.path)) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
configFiles.push(layer.path);
|
|
67
|
+
const parsed = readConfigFile(layer, diagnostics);
|
|
68
|
+
if (!parsed) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
merged = mergeLayer(merged, parsed);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
config: merged,
|
|
77
|
+
configFiles,
|
|
78
|
+
diagnostics,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function readConfigFile(
|
|
83
|
+
layer: PluginConfigLayer,
|
|
84
|
+
diagnostics: PluginDiagnostic[],
|
|
85
|
+
): Record<string, unknown> | undefined {
|
|
86
|
+
let raw: string;
|
|
87
|
+
try {
|
|
88
|
+
raw = readFileSync(layer.path, "utf8");
|
|
89
|
+
} catch (err) {
|
|
90
|
+
diagnostics.push({
|
|
91
|
+
level: "error",
|
|
92
|
+
path: layer.path,
|
|
93
|
+
message: `Cannot read ${layer.source} config: ${errorMessage(err)}`,
|
|
94
|
+
});
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(raw.replace(/^\uFEFF/, "")) as unknown;
|
|
100
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
101
|
+
diagnostics.push({
|
|
102
|
+
level: "error",
|
|
103
|
+
path: layer.path,
|
|
104
|
+
message: `Invalid ${layer.source} config: expected a JSON object.`,
|
|
105
|
+
});
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
return parsed as Record<string, unknown>;
|
|
109
|
+
} catch (err) {
|
|
110
|
+
diagnostics.push({
|
|
111
|
+
level: "error",
|
|
112
|
+
path: layer.path,
|
|
113
|
+
message: `JSON syntax error in ${layer.source} config: ${errorMessage(err)}`,
|
|
114
|
+
});
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function mergeLayer(base: AdvisorConfig, patch: Record<string, unknown>): AdvisorConfig {
|
|
120
|
+
let modelKey = base.modelKey;
|
|
121
|
+
if (typeof patch.modelKey === "string" && patch.modelKey.trim().length > 0) {
|
|
122
|
+
modelKey = patch.modelKey.trim();
|
|
123
|
+
} else if (typeof patch.model === "string" && patch.model.trim().length > 0) {
|
|
124
|
+
modelKey = patch.model.trim();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let effort = base.effort;
|
|
128
|
+
if (typeof patch.effort === "string" && EFFORT_ORDINAL.includes(patch.effort as GradedEffort)) {
|
|
129
|
+
effort = patch.effort as GradedEffort;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
let fallbackModels = base.fallbackModels;
|
|
133
|
+
const rawFallbacks = patch.fallbackModels ?? patch.fallbacks ?? patch.fallback_models;
|
|
134
|
+
if (Array.isArray(rawFallbacks)) {
|
|
135
|
+
fallbackModels = rawFallbacks
|
|
136
|
+
.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0)
|
|
137
|
+
.map((entry) => entry.trim());
|
|
138
|
+
} else if (typeof rawFallbacks === "string") {
|
|
139
|
+
fallbackModels = rawFallbacks
|
|
140
|
+
.split(",")
|
|
141
|
+
.map((s) => s.trim())
|
|
142
|
+
.filter(Boolean);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let disabledForModels = base.disabledForModels;
|
|
146
|
+
if (patch.disabledForModels !== undefined) {
|
|
147
|
+
disabledForModels = validateDisabledForModels(patch.disabledForModels);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let guidance = base.guidance;
|
|
151
|
+
if (patch.guidance !== undefined) {
|
|
152
|
+
guidance = validateGuidance(patch.guidance);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
...base,
|
|
157
|
+
...(modelKey !== undefined ? { modelKey } : {}),
|
|
158
|
+
...(effort !== undefined ? { effort } : {}),
|
|
159
|
+
...(fallbackModels !== undefined ? { fallbackModels } : {}),
|
|
160
|
+
...(disabledForModels !== undefined ? { disabledForModels } : {}),
|
|
161
|
+
...(guidance !== undefined ? { guidance } : {}),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function safeExists(path: string): boolean {
|
|
166
|
+
try {
|
|
167
|
+
return existsSync(path);
|
|
168
|
+
} catch {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function errorMessage(error: unknown): string {
|
|
174
|
+
return error instanceof Error ? error.message : String(error);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function resolveProjectAdvisorConfigPath(cwd: string): string {
|
|
178
|
+
const directJson = join(resolve(cwd), ".pi", "extensions", "repi-advisor.json");
|
|
179
|
+
const extDir = join(resolve(cwd), ".pi", "extensions", "repi-advisor");
|
|
180
|
+
const inFolderConfig = join(extDir, "config.json");
|
|
181
|
+
const namedInExt = join(extDir, CONFIG_NAME);
|
|
182
|
+
const legacy = join(resolve(cwd), ".repi", CONFIG_NAME);
|
|
183
|
+
if (existsSync(directJson)) return directJson;
|
|
184
|
+
if (existsSync(inFolderConfig)) return inFolderConfig;
|
|
185
|
+
if (existsSync(namedInExt)) return namedInExt;
|
|
186
|
+
if (existsSync(legacy)) return legacy;
|
|
187
|
+
return directJson;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export interface SaveAdvisorConfigOptions {
|
|
191
|
+
/** `false` keeps the save away from the project layer; the user config is written instead. */
|
|
192
|
+
readonly workspaceTrusted?: boolean;
|
|
193
|
+
/** Defaults to `os.homedir()`; injectable for tests. */
|
|
194
|
+
readonly homeDir?: string;
|
|
195
|
+
/** Defaults to `process.env`; `XDG_CONFIG_HOME` and `PI_CODING_AGENT_DIR` are honored. */
|
|
196
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The file a save should update.
|
|
201
|
+
*
|
|
202
|
+
* A user-wide advisor is the common case: unless a trusted project already owns an advisor config,
|
|
203
|
+
* the save goes to `<agentDir>/extensions/repi-advisor.json`. In an untrusted workspace the project
|
|
204
|
+
* layer is never a target, so saving works instead of failing.
|
|
205
|
+
*/
|
|
206
|
+
function resolveSaveTarget(cwd: string, options: SaveAdvisorConfigOptions): string {
|
|
207
|
+
const layers = resolveConfigPaths({
|
|
208
|
+
cwd,
|
|
209
|
+
...(options.homeDir !== undefined ? { homeDir: options.homeDir } : {}),
|
|
210
|
+
...(options.env !== undefined ? { env: options.env } : {}),
|
|
211
|
+
...(options.workspaceTrusted !== undefined ? { workspaceTrusted: options.workspaceTrusted } : {}),
|
|
212
|
+
});
|
|
213
|
+
const userPath = layers.find((layer) => layer.source === "user")?.path;
|
|
214
|
+
if (!userPath) {
|
|
215
|
+
throw new Error("Cannot resolve the user advisor config path.");
|
|
216
|
+
}
|
|
217
|
+
if (options.workspaceTrusted === false) {
|
|
218
|
+
return userPath;
|
|
219
|
+
}
|
|
220
|
+
const projectPath = layers.find((layer) => layer.source === "project")?.path;
|
|
221
|
+
// Only update a project file that already exists. A fresh save goes to the user config, so the
|
|
222
|
+
// setting follows the user instead of being trapped in one checkout (and works before trust).
|
|
223
|
+
if (projectPath && safeExists(projectPath)) {
|
|
224
|
+
return projectPath;
|
|
225
|
+
}
|
|
226
|
+
return userPath;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function saveAdvisorConfig(
|
|
230
|
+
cwd: string,
|
|
231
|
+
patch: {
|
|
232
|
+
modelKey?: string | null;
|
|
233
|
+
effort?: GradedEffort | null;
|
|
234
|
+
fallbackModels?: readonly string[];
|
|
235
|
+
},
|
|
236
|
+
options: SaveAdvisorConfigOptions = {},
|
|
237
|
+
): boolean {
|
|
238
|
+
try {
|
|
239
|
+
const filePath = resolveSaveTarget(cwd, options);
|
|
240
|
+
const existing = readExistingObject(filePath);
|
|
241
|
+
|
|
242
|
+
const updated: Record<string, unknown> = {
|
|
243
|
+
...existing,
|
|
244
|
+
version: 1,
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
if (patch.modelKey !== undefined) {
|
|
248
|
+
updated.modelKey = patch.modelKey ?? undefined;
|
|
249
|
+
updated.model = undefined;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (patch.effort !== undefined) {
|
|
253
|
+
updated.effort = patch.effort ?? undefined;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (patch.fallbackModels !== undefined) {
|
|
257
|
+
updated.fallbackModels = [...patch.fallbackModels];
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
writeJsonAtomic(filePath, updated);
|
|
261
|
+
return true;
|
|
262
|
+
} catch {
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function readExistingObject(filePath: string): Record<string, unknown> {
|
|
268
|
+
let raw: string;
|
|
269
|
+
try {
|
|
270
|
+
raw = readFileSync(filePath, "utf8");
|
|
271
|
+
} catch (err) {
|
|
272
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
273
|
+
return {};
|
|
274
|
+
}
|
|
275
|
+
return {};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
try {
|
|
279
|
+
const parsed = JSON.parse(raw.replace(/^\uFEFF/, ""));
|
|
280
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
|
|
281
|
+
? (parsed as Record<string, unknown>)
|
|
282
|
+
: {};
|
|
283
|
+
} catch {
|
|
284
|
+
return {};
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function writeJsonAtomic(filePath: string, value: unknown): void {
|
|
289
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
290
|
+
const temp = join(dirname(filePath), `.${basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
|
|
291
|
+
try {
|
|
292
|
+
writeFileSync(temp, `${JSON.stringify(value, null, "\t")}\n`, { encoding: "utf8", mode: 0o600 });
|
|
293
|
+
renameSync(temp, filePath);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
try {
|
|
296
|
+
rmSync(temp, { force: true });
|
|
297
|
+
} catch {
|
|
298
|
+
// Best effort
|
|
299
|
+
}
|
|
300
|
+
throw err;
|
|
301
|
+
}
|
|
302
|
+
}
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ADVISOR_TOOL_NAME, MSG_ADVISOR_NUDGE } from "./messages.js";
|
|
2
|
+
|
|
3
|
+
export interface ContextMessageLike {
|
|
4
|
+
role?: string;
|
|
5
|
+
content?: unknown;
|
|
6
|
+
toolsAdded?: unknown;
|
|
7
|
+
toolsRemoved?: unknown;
|
|
8
|
+
timestamp?: number;
|
|
9
|
+
[key: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Strip the executor's in-flight advisor() toolCall from the tail assistant message.
|
|
14
|
+
*/
|
|
15
|
+
export function stripInflightAdvisorCall<T extends ContextMessageLike>(messages: readonly T[]): T[] {
|
|
16
|
+
if (messages.length === 0) return [...messages];
|
|
17
|
+
const last = messages[messages.length - 1];
|
|
18
|
+
if (!last || last.role !== "assistant" || !Array.isArray(last.content)) return [...messages];
|
|
19
|
+
|
|
20
|
+
const filtered = last.content.filter(
|
|
21
|
+
(c) =>
|
|
22
|
+
!(
|
|
23
|
+
typeof c === "object" &&
|
|
24
|
+
c !== null &&
|
|
25
|
+
(c as { type?: string }).type === "toolCall" &&
|
|
26
|
+
(c as { name?: string }).name === ADVISOR_TOOL_NAME
|
|
27
|
+
),
|
|
28
|
+
);
|
|
29
|
+
if (filtered.length === last.content.length) return [...messages];
|
|
30
|
+
if (filtered.length === 0) return messages.slice(0, -1);
|
|
31
|
+
return [...messages.slice(0, -1), { ...last, content: filtered }];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Guarantees that the forwarded conversation ends on a user turn.
|
|
36
|
+
*/
|
|
37
|
+
export function ensureUserTailForAdvisor<T extends ContextMessageLike>(messages: readonly T[]): T[] {
|
|
38
|
+
if (messages.length === 0) return [...messages];
|
|
39
|
+
const last = messages[messages.length - 1];
|
|
40
|
+
if (!last || last.role !== "assistant") return [...messages];
|
|
41
|
+
|
|
42
|
+
const nudge: ContextMessageLike = {
|
|
43
|
+
role: "user",
|
|
44
|
+
content: [{ type: "text", text: MSG_ADVISOR_NUDGE }],
|
|
45
|
+
timestamp: Date.now(),
|
|
46
|
+
};
|
|
47
|
+
return [...messages, nudge as T];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Drop tool declarations (toolsAdded / toolsRemoved) from system messages.
|
|
52
|
+
*/
|
|
53
|
+
export function stripToolDeclarations<T extends ContextMessageLike>(messages: readonly T[]): T[] {
|
|
54
|
+
if (!messages.some((m) => m.role === "system" && (m.toolsAdded || m.toolsRemoved))) {
|
|
55
|
+
return [...messages];
|
|
56
|
+
}
|
|
57
|
+
return messages.map((m) => {
|
|
58
|
+
if (m.role !== "system" || (!m.toolsAdded && !m.toolsRemoved)) return m;
|
|
59
|
+
const { toolsAdded: _added, toolsRemoved: _removed, ...rest } = m;
|
|
60
|
+
return rest as T;
|
|
61
|
+
});
|
|
62
|
+
}
|