@restranger/repi-advisor 0.0.0-stage → 0.0.1-1a48fc0
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 +89 -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/execute.ts
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SUBAGENTS_CONTRACT_ID,
|
|
3
|
+
type SubagentsService,
|
|
4
|
+
getService,
|
|
5
|
+
getSessionId,
|
|
6
|
+
modelKey,
|
|
7
|
+
resolveModel,
|
|
8
|
+
} from "@restranger/repi-lib";
|
|
9
|
+
import type { PiContext, PiExtensionAPI, PiModel } from "@restranger/repi-lib";
|
|
10
|
+
import {
|
|
11
|
+
type ContextMessageLike,
|
|
12
|
+
ensureUserTailForAdvisor,
|
|
13
|
+
stripInflightAdvisorCall,
|
|
14
|
+
stripToolDeclarations,
|
|
15
|
+
} from "./context.js";
|
|
16
|
+
import { getInventoryMessage } from "./inventory.js";
|
|
17
|
+
import {
|
|
18
|
+
ERR_ABORTED_DETAIL,
|
|
19
|
+
ERR_CALL_ABORTED,
|
|
20
|
+
ERR_EMPTY_RESPONSE,
|
|
21
|
+
ERR_EMPTY_RESPONSE_DETAIL,
|
|
22
|
+
ERR_NO_MODEL,
|
|
23
|
+
ERR_NO_MODEL_SELECTED,
|
|
24
|
+
ERR_UNKNOWN,
|
|
25
|
+
errCallFailed,
|
|
26
|
+
errCallThrew,
|
|
27
|
+
errMisconfigured,
|
|
28
|
+
errNoApiKey,
|
|
29
|
+
errNoApiKeyDetail,
|
|
30
|
+
msgConsulting,
|
|
31
|
+
msgConsultingFallback,
|
|
32
|
+
} from "./messages.js";
|
|
33
|
+
import { getRuntimeCompleteSimple, loadCompleteSimple, withHostRetry } from "./pi-compat.js";
|
|
34
|
+
import { ADVISOR_SYSTEM_PROMPT } from "./prompt.js";
|
|
35
|
+
import { getAdvisorEffort, getAdvisorFallbacks, getAdvisorModel } from "./state.js";
|
|
36
|
+
import type { AdvisorDetails, AdvisorUsage } from "./types.js";
|
|
37
|
+
|
|
38
|
+
export const advisorSessionId = (ctx: PiContext): string => {
|
|
39
|
+
const rawId = ctx.sessionManager?.getSessionId?.() ?? getSessionId(ctx, "default");
|
|
40
|
+
return `advisor-${rawId}`;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export interface AgentToolResult<T = unknown> {
|
|
44
|
+
content: Array<{ type: "text"; text: string }>;
|
|
45
|
+
details?: T;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type AgentToolUpdateCallback<T = unknown> = (update: AgentToolResult<T>) => void;
|
|
49
|
+
|
|
50
|
+
function advisorTextFromResponse(response: {
|
|
51
|
+
content: Array<{ type: string; text?: string; [key: string]: unknown }>;
|
|
52
|
+
}): string {
|
|
53
|
+
return response.content
|
|
54
|
+
.filter((c): c is { type: "text"; text: string } => c.type === "text" && typeof c.text === "string")
|
|
55
|
+
.map((c) => c.text)
|
|
56
|
+
.join("\n")
|
|
57
|
+
.trim();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function buildAdvisorResult(opts: {
|
|
61
|
+
text: string;
|
|
62
|
+
effort?: string;
|
|
63
|
+
advisorLabel?: string;
|
|
64
|
+
primaryModel?: string;
|
|
65
|
+
isFallback?: boolean;
|
|
66
|
+
attemptedModels?: readonly string[];
|
|
67
|
+
usage?: AdvisorUsage;
|
|
68
|
+
stopReason?: string;
|
|
69
|
+
errorMessage?: string;
|
|
70
|
+
}): AgentToolResult<AdvisorDetails> {
|
|
71
|
+
const details: AdvisorDetails = { effort: opts.effort };
|
|
72
|
+
if (opts.advisorLabel !== undefined) details.advisorModel = opts.advisorLabel;
|
|
73
|
+
if (opts.primaryModel !== undefined) details.primaryModel = opts.primaryModel;
|
|
74
|
+
if (opts.isFallback) details.isFallback = true;
|
|
75
|
+
if (opts.attemptedModels !== undefined) details.attemptedModels = opts.attemptedModels;
|
|
76
|
+
if (opts.usage !== undefined) details.usage = opts.usage;
|
|
77
|
+
if (opts.stopReason !== undefined) details.stopReason = opts.stopReason;
|
|
78
|
+
if (opts.errorMessage !== undefined) details.errorMessage = opts.errorMessage;
|
|
79
|
+
return { content: [{ type: "text", text: opts.text }], details };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function buildErrorResult(
|
|
83
|
+
advisorLabel: string | undefined,
|
|
84
|
+
effort: string | undefined,
|
|
85
|
+
userText: string,
|
|
86
|
+
errorMessage: string,
|
|
87
|
+
attemptedModels?: readonly string[],
|
|
88
|
+
): AgentToolResult<AdvisorDetails> {
|
|
89
|
+
return buildAdvisorResult({
|
|
90
|
+
text: userText,
|
|
91
|
+
effort,
|
|
92
|
+
advisorLabel,
|
|
93
|
+
errorMessage,
|
|
94
|
+
attemptedModels,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const PI_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Resolve session messages from Pi's sessionManager or context entries.
|
|
102
|
+
*/
|
|
103
|
+
async function resolveSessionMessages(ctx: PiContext): Promise<ContextMessageLike[]> {
|
|
104
|
+
try {
|
|
105
|
+
const { buildSessionContext, convertToLlm } = (await import(PI_AGENT_PACKAGE)) as {
|
|
106
|
+
buildSessionContext?: (entries: unknown[], leafId?: unknown) => { messages: unknown[] };
|
|
107
|
+
convertToLlm?: (messages: unknown[]) => ContextMessageLike[];
|
|
108
|
+
};
|
|
109
|
+
if (typeof buildSessionContext === "function" && typeof convertToLlm === "function" && ctx.sessionManager) {
|
|
110
|
+
const entries = [...(ctx.sessionManager.getEntries?.() ?? [])];
|
|
111
|
+
const leafId = ctx.sessionManager.getLeafId?.();
|
|
112
|
+
const { messages } = buildSessionContext(entries, leafId);
|
|
113
|
+
return convertToLlm(messages);
|
|
114
|
+
}
|
|
115
|
+
} catch {
|
|
116
|
+
// Fallback for mock environments
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const entries = ctx.sessionManager?.getEntries?.() ?? ctx.entries ?? [];
|
|
120
|
+
const extracted: ContextMessageLike[] = [];
|
|
121
|
+
for (const entry of entries) {
|
|
122
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
123
|
+
const rec = entry as Record<string, unknown>;
|
|
124
|
+
if (rec.type === "message" && typeof rec.message === "object" && rec.message !== null) {
|
|
125
|
+
extracted.push(rec.message as ContextMessageLike);
|
|
126
|
+
} else if (typeof rec.role === "string" && Array.isArray(rec.content)) {
|
|
127
|
+
extracted.push(rec as ContextMessageLike);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return extracted;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function executeAdvisor(
|
|
134
|
+
ctx: PiContext,
|
|
135
|
+
pi: PiExtensionAPI,
|
|
136
|
+
signal: AbortSignal | undefined,
|
|
137
|
+
onUpdate: AgentToolUpdateCallback<AdvisorDetails> | undefined,
|
|
138
|
+
): Promise<AgentToolResult<AdvisorDetails>> {
|
|
139
|
+
const effort = getAdvisorEffort();
|
|
140
|
+
const primaryAdvisor = getAdvisorModel();
|
|
141
|
+
if (!primaryAdvisor) {
|
|
142
|
+
return buildErrorResult(undefined, effort, ERR_NO_MODEL, ERR_NO_MODEL_SELECTED);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const primaryLabel = modelKey(primaryAdvisor);
|
|
146
|
+
const sessionId = getSessionId(ctx, "default");
|
|
147
|
+
const advisorSession = advisorSessionId(ctx);
|
|
148
|
+
|
|
149
|
+
// Subagents integration: query available subagents through the service seam
|
|
150
|
+
const subagentsService = getService<SubagentsService>(SUBAGENTS_CONTRACT_ID, sessionId);
|
|
151
|
+
const availableSubagents = subagentsService?.listAgents?.() ?? [];
|
|
152
|
+
|
|
153
|
+
// Retrieve conversation context and tools
|
|
154
|
+
const sessionMessages = await resolveSessionMessages(ctx);
|
|
155
|
+
const branchMessages = ensureUserTailForAdvisor(stripInflightAdvisorCall(stripToolDeclarations(sessionMessages)));
|
|
156
|
+
const allTools = typeof pi.getAllTools === "function" ? pi.getAllTools() : [];
|
|
157
|
+
const inventoryMessage = getInventoryMessage(allTools, availableSubagents);
|
|
158
|
+
const messages: ContextMessageLike[] = inventoryMessage ? [inventoryMessage, ...branchMessages] : branchMessages;
|
|
159
|
+
|
|
160
|
+
// Build the chain of candidate models: primary first, followed by configured fallback models
|
|
161
|
+
const fallbackKeys = getAdvisorFallbacks();
|
|
162
|
+
const candidateModels: Array<{ model: PiModel; isFallback: boolean }> = [
|
|
163
|
+
{ model: primaryAdvisor, isFallback: false },
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
for (const fallbackKey of fallbackKeys) {
|
|
167
|
+
const resolved = resolveModel<PiModel>(fallbackKey, ctx.modelRegistry);
|
|
168
|
+
if (resolved && modelKey(resolved).toLowerCase() !== primaryLabel.toLowerCase()) {
|
|
169
|
+
candidateModels.push({ model: resolved, isFallback: true });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const attempted: string[] = [];
|
|
174
|
+
let lastErrorMessage = ERR_UNKNOWN;
|
|
175
|
+
|
|
176
|
+
for (let index = 0; index < candidateModels.length; index++) {
|
|
177
|
+
const { model: currentModel, isFallback } = candidateModels[index];
|
|
178
|
+
const currentLabel = modelKey(currentModel);
|
|
179
|
+
attempted.push(currentLabel);
|
|
180
|
+
|
|
181
|
+
// Auth check for the current candidate model
|
|
182
|
+
const auth = ctx.modelRegistry?.getApiKeyAndHeaders
|
|
183
|
+
? await ctx.modelRegistry.getApiKeyAndHeaders(currentModel)
|
|
184
|
+
: { ok: true, apiKey: "dummy" };
|
|
185
|
+
|
|
186
|
+
if (!auth.ok) {
|
|
187
|
+
lastErrorMessage = auth.error ?? "Authentication failed";
|
|
188
|
+
if (index < candidateModels.length - 1) {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
return buildErrorResult(
|
|
192
|
+
currentLabel,
|
|
193
|
+
effort,
|
|
194
|
+
errMisconfigured(currentLabel, lastErrorMessage),
|
|
195
|
+
lastErrorMessage,
|
|
196
|
+
attempted,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const runtimeCompleteSimple = getRuntimeCompleteSimple(ctx.modelRegistry);
|
|
201
|
+
if (!auth.apiKey && !runtimeCompleteSimple) {
|
|
202
|
+
lastErrorMessage = errNoApiKeyDetail(currentModel.provider);
|
|
203
|
+
if (index < candidateModels.length - 1) {
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
return buildErrorResult(currentLabel, effort, errNoApiKey(currentLabel), lastErrorMessage, attempted);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (isFallback) {
|
|
210
|
+
onUpdate?.({
|
|
211
|
+
content: [{ type: "text", text: msgConsultingFallback(primaryLabel, currentLabel, effort) }],
|
|
212
|
+
details: {
|
|
213
|
+
advisorModel: currentLabel,
|
|
214
|
+
primaryModel: primaryLabel,
|
|
215
|
+
isFallback: true,
|
|
216
|
+
effort,
|
|
217
|
+
attemptedModels: attempted,
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
} else {
|
|
221
|
+
onUpdate?.({
|
|
222
|
+
content: [{ type: "text", text: msgConsulting(currentLabel, effort) }],
|
|
223
|
+
details: { advisorModel: currentLabel, effort, attemptedModels: attempted },
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
try {
|
|
228
|
+
const completeSimple = runtimeCompleteSimple ?? (await loadCompleteSimple());
|
|
229
|
+
const requestOptions = runtimeCompleteSimple
|
|
230
|
+
? { signal, reasoning: effort, sessionId: advisorSession }
|
|
231
|
+
: { apiKey: auth.apiKey, headers: auth.headers, signal, reasoning: effort, sessionId: advisorSession };
|
|
232
|
+
|
|
233
|
+
const callCandidate = (): Promise<{
|
|
234
|
+
content: Array<{ type: string; text?: string; [key: string]: unknown }>;
|
|
235
|
+
stopReason?: string;
|
|
236
|
+
errorMessage?: string;
|
|
237
|
+
usage?: AdvisorUsage;
|
|
238
|
+
}> =>
|
|
239
|
+
withHostRetry(
|
|
240
|
+
pi,
|
|
241
|
+
() =>
|
|
242
|
+
completeSimple(currentModel, { systemPrompt: ADVISOR_SYSTEM_PROMPT, messages, tools: [] }, requestOptions),
|
|
243
|
+
signal,
|
|
244
|
+
);
|
|
245
|
+
|
|
246
|
+
let response = await callCandidate();
|
|
247
|
+
|
|
248
|
+
if (response.stopReason === "aborted") {
|
|
249
|
+
return buildAdvisorResult({
|
|
250
|
+
text: ERR_CALL_ABORTED,
|
|
251
|
+
effort,
|
|
252
|
+
advisorLabel: currentLabel,
|
|
253
|
+
primaryModel: isFallback ? primaryLabel : undefined,
|
|
254
|
+
isFallback,
|
|
255
|
+
attemptedModels: attempted,
|
|
256
|
+
usage: response.usage,
|
|
257
|
+
stopReason: response.stopReason,
|
|
258
|
+
errorMessage: response.errorMessage ?? ERR_ABORTED_DETAIL,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (response.stopReason === "error") {
|
|
263
|
+
lastErrorMessage = response.errorMessage ?? ERR_UNKNOWN;
|
|
264
|
+
if (index < candidateModels.length - 1) {
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
return buildAdvisorResult({
|
|
268
|
+
text: errCallFailed(response.errorMessage),
|
|
269
|
+
effort,
|
|
270
|
+
advisorLabel: currentLabel,
|
|
271
|
+
primaryModel: isFallback ? primaryLabel : undefined,
|
|
272
|
+
isFallback,
|
|
273
|
+
attemptedModels: attempted,
|
|
274
|
+
usage: response.usage,
|
|
275
|
+
stopReason: response.stopReason,
|
|
276
|
+
errorMessage: response.errorMessage,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
let text = advisorTextFromResponse(response);
|
|
281
|
+
|
|
282
|
+
// Transient empty response gets one retry
|
|
283
|
+
if (!text) {
|
|
284
|
+
response = await callCandidate();
|
|
285
|
+
if (response.stopReason === "aborted") {
|
|
286
|
+
return buildAdvisorResult({
|
|
287
|
+
text: ERR_CALL_ABORTED,
|
|
288
|
+
effort,
|
|
289
|
+
advisorLabel: currentLabel,
|
|
290
|
+
primaryModel: isFallback ? primaryLabel : undefined,
|
|
291
|
+
isFallback,
|
|
292
|
+
attemptedModels: attempted,
|
|
293
|
+
usage: response.usage,
|
|
294
|
+
stopReason: response.stopReason,
|
|
295
|
+
errorMessage: response.errorMessage ?? ERR_ABORTED_DETAIL,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
if (response.stopReason === "error") {
|
|
299
|
+
lastErrorMessage = response.errorMessage ?? ERR_UNKNOWN;
|
|
300
|
+
if (index < candidateModels.length - 1) {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
return buildAdvisorResult({
|
|
304
|
+
text: errCallFailed(response.errorMessage),
|
|
305
|
+
effort,
|
|
306
|
+
advisorLabel: currentLabel,
|
|
307
|
+
primaryModel: isFallback ? primaryLabel : undefined,
|
|
308
|
+
isFallback,
|
|
309
|
+
attemptedModels: attempted,
|
|
310
|
+
usage: response.usage,
|
|
311
|
+
stopReason: response.stopReason,
|
|
312
|
+
errorMessage: response.errorMessage,
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
text = advisorTextFromResponse(response);
|
|
316
|
+
if (!text) {
|
|
317
|
+
lastErrorMessage = ERR_EMPTY_RESPONSE_DETAIL;
|
|
318
|
+
if (index < candidateModels.length - 1) {
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
return buildAdvisorResult({
|
|
322
|
+
text: ERR_EMPTY_RESPONSE,
|
|
323
|
+
effort,
|
|
324
|
+
advisorLabel: currentLabel,
|
|
325
|
+
primaryModel: isFallback ? primaryLabel : undefined,
|
|
326
|
+
isFallback,
|
|
327
|
+
attemptedModels: attempted,
|
|
328
|
+
usage: response.usage,
|
|
329
|
+
stopReason: response.stopReason,
|
|
330
|
+
errorMessage: ERR_EMPTY_RESPONSE_DETAIL,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return buildAdvisorResult({
|
|
336
|
+
text,
|
|
337
|
+
effort,
|
|
338
|
+
advisorLabel: currentLabel,
|
|
339
|
+
primaryModel: isFallback ? primaryLabel : undefined,
|
|
340
|
+
isFallback,
|
|
341
|
+
attemptedModels: attempted,
|
|
342
|
+
usage: response.usage,
|
|
343
|
+
stopReason: response.stopReason,
|
|
344
|
+
});
|
|
345
|
+
} catch (err) {
|
|
346
|
+
lastErrorMessage = err instanceof Error ? err.message : String(err);
|
|
347
|
+
if (index < candidateModels.length - 1) {
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
return buildErrorResult(currentLabel, effort, errCallThrew(lastErrorMessage), lastErrorMessage, attempted);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return buildErrorResult(primaryLabel, effort, errCallFailed(lastErrorMessage), lastErrorMessage, attempted);
|
|
355
|
+
}
|
package/src/handlers.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { PiContext, PiExtensionAPI, PiModel } from "@restranger/repi-lib";
|
|
2
|
+
import { modelKey } from "@restranger/repi-lib";
|
|
3
|
+
import { ADVISOR_TOOL_NAME, MSG_ADVISOR_DISABLED, msgAdvisorRestored } from "./messages.js";
|
|
4
|
+
import { isExecutorBlocked, isModelBlocked } from "./policy.js";
|
|
5
|
+
import { getAdvisorEffort, getAdvisorFallbacks, getAdvisorModel } from "./state.js";
|
|
6
|
+
|
|
7
|
+
interface ReconcileNotify {
|
|
8
|
+
disabled: string;
|
|
9
|
+
restored: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function reconcileAdvisorTool(
|
|
13
|
+
pi: PiExtensionAPI,
|
|
14
|
+
ctx: PiContext,
|
|
15
|
+
opts: { blocked: boolean; notify?: ReconcileNotify },
|
|
16
|
+
): void {
|
|
17
|
+
const active = typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [];
|
|
18
|
+
const hasTool = active.includes(ADVISOR_TOOL_NAME);
|
|
19
|
+
|
|
20
|
+
if (opts.blocked && hasTool) {
|
|
21
|
+
pi.setActiveTools?.(active.filter((n) => n !== ADVISOR_TOOL_NAME));
|
|
22
|
+
if (opts.notify && ctx.hasUI) {
|
|
23
|
+
ctx.ui.notify(opts.notify.disabled, "info");
|
|
24
|
+
}
|
|
25
|
+
} else if (!opts.blocked && !hasTool) {
|
|
26
|
+
pi.setActiveTools?.([...active, ADVISOR_TOOL_NAME]);
|
|
27
|
+
if (opts.notify && ctx.hasUI) {
|
|
28
|
+
ctx.ui.notify(opts.notify.restored, "info");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function registerAdvisorBeforeAgentStart(pi: PiExtensionAPI): void {
|
|
34
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
35
|
+
const blocked = !getAdvisorModel() || isExecutorBlocked(ctx, pi.getThinkingLevel?.());
|
|
36
|
+
reconcileAdvisorTool(pi, ctx, { blocked });
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function registerModelSelectHandler(pi: PiExtensionAPI): void {
|
|
41
|
+
pi.on("model_select", (event, ctx) => {
|
|
42
|
+
const ev = event as { source?: string; model?: PiModel };
|
|
43
|
+
if (ev.source === "restore") return;
|
|
44
|
+
|
|
45
|
+
const advisor = getAdvisorModel();
|
|
46
|
+
if (!advisor) return;
|
|
47
|
+
|
|
48
|
+
reconcileAdvisorTool(pi, ctx, {
|
|
49
|
+
blocked: isModelBlocked(ev.model, pi.getThinkingLevel?.()),
|
|
50
|
+
notify: {
|
|
51
|
+
disabled: ev.model ? `Advisor disabled for ${modelKey(ev.model)}` : MSG_ADVISOR_DISABLED,
|
|
52
|
+
restored: msgAdvisorRestored(modelKey(advisor), getAdvisorEffort(), getAdvisorFallbacks()),
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function registerThinkingLevelSelectHandler(pi: PiExtensionAPI): void {
|
|
59
|
+
pi.on("thinking_level_select", (event, ctx) => {
|
|
60
|
+
const ev = event as { level?: string };
|
|
61
|
+
const advisor = getAdvisorModel();
|
|
62
|
+
if (!advisor) return;
|
|
63
|
+
|
|
64
|
+
const model = ctx?.model;
|
|
65
|
+
reconcileAdvisorTool(pi, ctx, {
|
|
66
|
+
blocked: isModelBlocked(model, ev.level),
|
|
67
|
+
notify: {
|
|
68
|
+
disabled: model ? `Advisor disabled for ${modelKey(model)}` : MSG_ADVISOR_DISABLED,
|
|
69
|
+
restored: msgAdvisorRestored(modelKey(advisor), getAdvisorEffort(), getAdvisorFallbacks()),
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createAdvisorPlugin } from "./plugin.js";
|
|
2
|
+
|
|
3
|
+
export default createAdvisorPlugin();
|
|
4
|
+
|
|
5
|
+
export { createAdvisorPlugin } from "./plugin.js";
|
|
6
|
+
export { registerAdvisorCommand } from "./command.js";
|
|
7
|
+
export { openAdvisorMenu, AdvisorMenuView, getSupportedEffortLevels } from "./advisor-ui.js";
|
|
8
|
+
export { loadAdvisorConfig, saveAdvisorConfig } from "./config.js";
|
|
9
|
+
export { ensureUserTailForAdvisor, stripInflightAdvisorCall, stripToolDeclarations } from "./context.js";
|
|
10
|
+
export { executeAdvisor } from "./execute.js";
|
|
11
|
+
export {
|
|
12
|
+
reconcileAdvisorTool,
|
|
13
|
+
registerAdvisorBeforeAgentStart,
|
|
14
|
+
registerModelSelectHandler,
|
|
15
|
+
registerThinkingLevelSelectHandler,
|
|
16
|
+
} from "./handlers.js";
|
|
17
|
+
export { getInventoryMessage, stableStringify } from "./inventory.js";
|
|
18
|
+
export { ADVISOR_TOOL_NAME, TOOL_LABEL, EFFORT_ORDINAL, DEFAULT_EFFORT } from "./messages.js";
|
|
19
|
+
export { isExecutorBlocked, isModelBlocked, setDisabledForModels, getDisabledForModels } from "./policy.js";
|
|
20
|
+
export { registerAdvisorTool, DEFAULT_PROMPT_GUIDELINES, DEFAULT_PROMPT_SNIPPET } from "./register.js";
|
|
21
|
+
export { restoreAdvisorState, registerAdvisorSessionStart, __resetAdvisorAnnounced } from "./restore.js";
|
|
22
|
+
export {
|
|
23
|
+
getAdvisorEffort,
|
|
24
|
+
getAdvisorFallbacks,
|
|
25
|
+
getAdvisorModel,
|
|
26
|
+
setAdvisorEffort,
|
|
27
|
+
setAdvisorFallbacks,
|
|
28
|
+
setAdvisorModel,
|
|
29
|
+
clearAdvisorState,
|
|
30
|
+
} from "./state.js";
|
|
31
|
+
export type * from "./types.js";
|
package/src/inventory.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { PiToolInfo, SubagentSummary } from "@restranger/repi-lib";
|
|
2
|
+
import type { ContextMessageLike } from "./context.js";
|
|
3
|
+
|
|
4
|
+
const ADVISOR_STATE_KEY = Symbol.for("repi-advisor");
|
|
5
|
+
|
|
6
|
+
interface AdvisorRuntimeState {
|
|
7
|
+
inventorySignature?: string;
|
|
8
|
+
inventoryMessage?: ContextMessageLike;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function getAdvisorRuntimeState(): AdvisorRuntimeState {
|
|
12
|
+
const g = globalThis as unknown as { [k: symbol]: AdvisorRuntimeState | undefined };
|
|
13
|
+
let state = g[ADVISOR_STATE_KEY];
|
|
14
|
+
if (!state) {
|
|
15
|
+
state = {};
|
|
16
|
+
g[ADVISOR_STATE_KEY] = state;
|
|
17
|
+
}
|
|
18
|
+
return state;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function stableStringify(value: unknown): string {
|
|
22
|
+
if (value === null || typeof value !== "object") {
|
|
23
|
+
return JSON.stringify(value);
|
|
24
|
+
}
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
return `[${value.map((v) => (v === undefined ? "null" : stableStringify(v))).join(",")}]`;
|
|
27
|
+
}
|
|
28
|
+
const obj = value as Record<string, unknown>;
|
|
29
|
+
const entries: string[] = [];
|
|
30
|
+
for (const k of Object.keys(obj).sort()) {
|
|
31
|
+
const v = obj[k];
|
|
32
|
+
if (v === undefined) continue;
|
|
33
|
+
entries.push(`${JSON.stringify(k)}:${stableStringify(v)}`);
|
|
34
|
+
}
|
|
35
|
+
return `{${entries.join(",")}}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function buildInventoryBlock(tools: readonly PiToolInfo[]): string {
|
|
39
|
+
return tools
|
|
40
|
+
.map((t) => {
|
|
41
|
+
const params = t.parameters ? `\n\nParameters: ${stableStringify(t.parameters)}` : "";
|
|
42
|
+
return `### ${t.name}\n${t.description ?? ""}${params}`;
|
|
43
|
+
})
|
|
44
|
+
.join("\n\n---\n\n");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function buildSubagentsBlock(subagents: readonly SubagentSummary[]): string {
|
|
48
|
+
return subagents
|
|
49
|
+
.map((s) => {
|
|
50
|
+
const modelInfo = s.model ? ` (model: ${s.model})` : "";
|
|
51
|
+
return `- **${s.name}**${modelInfo}: ${s.description}`;
|
|
52
|
+
})
|
|
53
|
+
.join("\n");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function getInventoryMessage(
|
|
57
|
+
tools: readonly PiToolInfo[],
|
|
58
|
+
subagents?: readonly SubagentSummary[],
|
|
59
|
+
): ContextMessageLike | undefined {
|
|
60
|
+
if (tools.length === 0 && (!subagents || subagents.length === 0)) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const sortedTools = [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
65
|
+
const sortedSubagents = subagents
|
|
66
|
+
? [...subagents].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
67
|
+
: [];
|
|
68
|
+
|
|
69
|
+
const toolSig = sortedTools.map((t) => t.name).join("|");
|
|
70
|
+
const subSig = sortedSubagents.map((s) => `${s.name}:${s.model ?? ""}`).join("|");
|
|
71
|
+
const signature = `${toolSig}##${subSig}`;
|
|
72
|
+
|
|
73
|
+
const state = getAdvisorRuntimeState();
|
|
74
|
+
if (state.inventorySignature === signature && state.inventoryMessage) {
|
|
75
|
+
return state.inventoryMessage;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const sections: string[] = [];
|
|
79
|
+
|
|
80
|
+
if (sortedTools.length > 0) {
|
|
81
|
+
sections.push(`## Available Executor Tools\n\n${buildInventoryBlock(sortedTools)}`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (sortedSubagents.length > 0) {
|
|
85
|
+
sections.push(
|
|
86
|
+
`## Available Subagents\nThe executor can delegate tasks to isolated child sessions via the \`subagent\` tool:\n\n${buildSubagentsBlock(sortedSubagents)}`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const message: ContextMessageLike = {
|
|
91
|
+
role: "user",
|
|
92
|
+
content: [{ type: "text", text: sections.join("\n\n") }],
|
|
93
|
+
timestamp: Date.now(),
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
state.inventorySignature = signature;
|
|
97
|
+
state.inventoryMessage = message;
|
|
98
|
+
return message;
|
|
99
|
+
}
|
package/src/messages.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* messages — advisor vocabulary: tool identity, selector sentinels, effort
|
|
3
|
+
* levels, UI labels, and every user-facing string (static + parameterized).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// Tool identity
|
|
7
|
+
export const ADVISOR_TOOL_NAME = "advisor";
|
|
8
|
+
export const TOOL_LABEL = "Advisor";
|
|
9
|
+
|
|
10
|
+
// Selector sentinels
|
|
11
|
+
export const NO_ADVISOR_VALUE = "__no_advisor__";
|
|
12
|
+
export const OFF_VALUE = "__off__";
|
|
13
|
+
|
|
14
|
+
// Effort levels
|
|
15
|
+
export type GradedEffort = "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
16
|
+
export const EFFORT_ORDINAL: readonly GradedEffort[] = ["minimal", "low", "medium", "high", "xhigh", "max"];
|
|
17
|
+
export const DEFAULT_EFFORT: GradedEffort = "high";
|
|
18
|
+
export const RECOMMENDED_EFFORT_SUFFIX = " (recommended)";
|
|
19
|
+
|
|
20
|
+
// UI
|
|
21
|
+
export const CHECKMARK = " ✓";
|
|
22
|
+
|
|
23
|
+
// Messages (static)
|
|
24
|
+
export const MSG_ADVISOR_DISABLED = "Advisor disabled";
|
|
25
|
+
export const MSG_REQUIRES_INTERACTIVE = "/advisor requires interactive mode";
|
|
26
|
+
export const MSG_ADVISOR_NUDGE = "Please advise on the executor's situation above.";
|
|
27
|
+
export const MSG_EFFORT_NOT_SET = "Effort not set — advisor uses the model default";
|
|
28
|
+
export const MSG_PERSIST_FAILED = "Failed to save advisor selection — selection not persisted";
|
|
29
|
+
|
|
30
|
+
// Errors (static)
|
|
31
|
+
export const ERR_NO_MODEL = "No advisor model is configured. The user can enable one with the /advisor command.";
|
|
32
|
+
export const ERR_CALL_ABORTED = "Advisor call was cancelled before it completed.";
|
|
33
|
+
export const ERR_EMPTY_RESPONSE = "Advisor returned no text content.";
|
|
34
|
+
export const ERR_NO_MODEL_SELECTED = "no advisor model selected";
|
|
35
|
+
export const ERR_EMPTY_RESPONSE_DETAIL = "empty response";
|
|
36
|
+
export const ERR_ABORTED_DETAIL = "aborted";
|
|
37
|
+
export const ERR_UNKNOWN = "unknown error";
|
|
38
|
+
|
|
39
|
+
// Errors/messages (parameterized)
|
|
40
|
+
export const errMisconfigured = (label: string, err: string) => `Advisor (${label}) is misconfigured: ${err}`;
|
|
41
|
+
export const errNoApiKey = (label: string) => `Advisor (${label}) has no API key available.`;
|
|
42
|
+
export const errNoApiKeyDetail = (provider: string) => `no API key for ${provider}`;
|
|
43
|
+
export const errCallFailed = (err: string | undefined) => `Advisor call failed: ${err ?? ERR_UNKNOWN}`;
|
|
44
|
+
export const errCallThrew = (msg: string) => `Advisor call threw: ${msg}`;
|
|
45
|
+
export const errSelectionNotFound = (choice: string) => `Advisor selection not found: ${choice}`;
|
|
46
|
+
export const errModelUnavailable = (key: string) => `Previously configured advisor model ${key} is no longer available`;
|
|
47
|
+
export const msgAdvisorEnabled = (label: string, effort?: string, fallbacks?: readonly string[]) => {
|
|
48
|
+
const effortStr = effort ? `, ${effort}` : "";
|
|
49
|
+
const fallbackStr = fallbacks && fallbacks.length > 0 ? ` [fallback: ${fallbacks.join(", ")}]` : "";
|
|
50
|
+
return `Advisor: ${label}${effortStr}${fallbackStr}`;
|
|
51
|
+
};
|
|
52
|
+
export const msgAdvisorRestored = (label: string, effort?: string, fallbacks?: readonly string[]) => {
|
|
53
|
+
const effortStr = effort ? `, ${effort}` : "";
|
|
54
|
+
const fallbackStr = fallbacks && fallbacks.length > 0 ? ` [fallback: ${fallbacks.join(", ")}]` : "";
|
|
55
|
+
return `Advisor restored: ${label}${effortStr}${fallbackStr}`;
|
|
56
|
+
};
|
|
57
|
+
export const msgAdvisorRestoredInactive = (label: string, effort?: string) =>
|
|
58
|
+
`Advisor restored: ${label}${effort ? `, ${effort}` : ""} (inactive for current executor)`;
|
|
59
|
+
export const msgAdvisorEnabledInactive = (label: string, effort?: string) =>
|
|
60
|
+
`Advisor: ${label}${effort ? `, ${effort}` : ""} (inactive for current executor)`;
|
|
61
|
+
export const msgConsulting = (label: string, effort?: string) =>
|
|
62
|
+
`Consulting advisor (${label}${effort ? `, ${effort}` : ""})…`;
|
|
63
|
+
export const msgConsultingFallback = (primaryLabel: string, fallbackLabel: string, effort?: string) =>
|
|
64
|
+
`Advisor primary (${primaryLabel}) failed. Consulting fallback (${fallbackLabel}${effort ? `, ${effort}` : ""})…`;
|