@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.
@@ -0,0 +1,90 @@
1
+ import type { PiExtensionAPI } from "@restranger/repi-lib";
2
+
3
+ export interface CompleteSimpleRequestOptions {
4
+ apiKey?: string;
5
+ headers?: Record<string, string>;
6
+ signal?: AbortSignal;
7
+ reasoning?: string;
8
+ sessionId?: string;
9
+ }
10
+
11
+ export type CompleteSimpleFn = (
12
+ model: unknown,
13
+ context: { systemPrompt: string; messages: unknown[]; tools?: unknown[] },
14
+ options?: CompleteSimpleRequestOptions,
15
+ ) => Promise<{
16
+ content: Array<{ type: string; text?: string; [key: string]: unknown }>;
17
+ stopReason?: string;
18
+ errorMessage?: string;
19
+ usage?: {
20
+ inputTokens?: number;
21
+ outputTokens?: number;
22
+ cacheReadTokens?: number;
23
+ cacheWriteTokens?: number;
24
+ totalTokens?: number;
25
+ };
26
+ }>;
27
+
28
+ let testCompleteSimple: CompleteSimpleFn | undefined;
29
+
30
+ export function _setCompleteSimpleForTest(fn: CompleteSimpleFn | undefined): void {
31
+ testCompleteSimple = fn;
32
+ }
33
+
34
+ export function getRuntimeCompleteSimple(modelRegistry: unknown): CompleteSimpleFn | undefined {
35
+ if (testCompleteSimple) {
36
+ return testCompleteSimple;
37
+ }
38
+ try {
39
+ if (modelRegistry === null || typeof modelRegistry !== "object") return undefined;
40
+ const runtime = (modelRegistry as { runtime?: unknown }).runtime;
41
+ if (runtime === null || typeof runtime !== "object") return undefined;
42
+ const completeSimple = (runtime as { completeSimple?: unknown }).completeSimple;
43
+ return typeof completeSimple === "function" ? (completeSimple.bind(runtime) as CompleteSimpleFn) : undefined;
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
48
+
49
+ const PI_AI_COMPAT = "@earendil-works/pi-ai/compat";
50
+ const PI_AI_ROOT = "@earendil-works/pi-ai";
51
+ const PI_AGENT_ROOT = "@earendil-works/pi-coding-agent";
52
+
53
+ export async function loadCompleteSimple(): Promise<CompleteSimpleFn> {
54
+ if (testCompleteSimple) {
55
+ return testCompleteSimple;
56
+ }
57
+ let mod: { completeSimple?: CompleteSimpleFn };
58
+ try {
59
+ mod = (await import(PI_AI_COMPAT)) as { completeSimple?: CompleteSimpleFn };
60
+ } catch {
61
+ mod = (await import(PI_AI_ROOT)) as { completeSimple?: CompleteSimpleFn };
62
+ }
63
+ const completeSimple = mod.completeSimple;
64
+ if (typeof completeSimple !== "function") {
65
+ throw new Error("Host does not expose completeSimple");
66
+ }
67
+ return completeSimple;
68
+ }
69
+
70
+ export async function withHostRetry<T>(
71
+ pi: PiExtensionAPI,
72
+ call: () => Promise<T>,
73
+ signal: AbortSignal | undefined,
74
+ ): Promise<T> {
75
+ try {
76
+ const piAi = (await import(PI_AI_ROOT)) as {
77
+ retryAssistantCall?: (fn: () => Promise<T>, settings: unknown, signal?: AbortSignal) => Promise<T>;
78
+ };
79
+ const piAgent = (await import(PI_AGENT_ROOT)) as {
80
+ SettingsManager?: { inMemory(s: unknown): { getRetrySettings(): unknown } };
81
+ };
82
+ const settings = typeof pi.getSettings === "function" ? pi.getSettings() : undefined;
83
+ if (typeof piAi.retryAssistantCall === "function" && piAgent.SettingsManager && settings !== undefined) {
84
+ return await piAi.retryAssistantCall(call, piAgent.SettingsManager.inMemory(settings).getRetrySettings(), signal);
85
+ }
86
+ } catch {
87
+ // Ignore and run once
88
+ }
89
+ return call();
90
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { PiExtensionAPI } from "@restranger/repi-lib";
2
+ import { registerAdvisorCommand } from "./command.js";
3
+ import {
4
+ registerAdvisorBeforeAgentStart,
5
+ registerModelSelectHandler,
6
+ registerThinkingLevelSelectHandler,
7
+ } from "./handlers.js";
8
+ import { registerAdvisorTool } from "./register.js";
9
+ import { registerAdvisorSessionStart } from "./restore.js";
10
+ import type { AdvisorPluginOptions } from "./types.js";
11
+
12
+ export function createAdvisorPlugin(options: AdvisorPluginOptions = {}): (pi: unknown) => void {
13
+ return (host) => {
14
+ const pi = host as PiExtensionAPI;
15
+ registerAdvisorTool(pi, options);
16
+ registerAdvisorCommand(pi, options);
17
+ registerAdvisorBeforeAgentStart(pi);
18
+ registerModelSelectHandler(pi);
19
+ registerThinkingLevelSelectHandler(pi);
20
+ registerAdvisorSessionStart(pi, options);
21
+ };
22
+ }
package/src/policy.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { type PiContext, type PiModel, modelKey, parseModelKey } from "@restranger/repi-lib";
2
+ import { EFFORT_ORDINAL, type GradedEffort } from "./messages.js";
3
+ import type { DisabledForModelsEntry } from "./types.js";
4
+
5
+ let disabledForModelsCache: DisabledForModelsEntry[] = [];
6
+
7
+ export function setDisabledForModels(models: readonly DisabledForModelsEntry[]): void {
8
+ disabledForModelsCache = [...models];
9
+ }
10
+
11
+ export function getDisabledForModels(): readonly DisabledForModelsEntry[] {
12
+ return disabledForModelsCache;
13
+ }
14
+
15
+ /**
16
+ * Normalise a stored blocklist entry's model key to the canonical slash form.
17
+ */
18
+ function canonicalKey(entry: string): string {
19
+ const parsed = parseModelKey(entry);
20
+ return parsed ? `${parsed.provider}/${parsed.modelId}`.toLowerCase() : entry.toLowerCase();
21
+ }
22
+
23
+ /**
24
+ * True when `model` is on the disabledForModels blocklist at the executor's
25
+ * current thinking level. Fail-soft ranking contract: an executor level that
26
+ * is unset, "off", or unknown to EFFORT_ORDINAL yields indexOf −1, ranking
27
+ * below every minEffort threshold — such levels never block.
28
+ */
29
+ export function isModelBlocked(model: PiModel | undefined, thinkingLevel?: string): boolean {
30
+ if (!model) return false;
31
+ const key = modelKey(model).toLowerCase();
32
+ for (const entry of disabledForModelsCache) {
33
+ if (typeof entry === "string") {
34
+ if (canonicalKey(entry) === key) return true;
35
+ } else {
36
+ if (canonicalKey(entry.model) !== key) continue;
37
+ if (entry.minEffort === undefined) return true;
38
+ const thresholdOrdinal = EFFORT_ORDINAL.indexOf(entry.minEffort);
39
+ if (thresholdOrdinal === -1) continue;
40
+ const executorOrdinal = EFFORT_ORDINAL.indexOf(thinkingLevel as GradedEffort);
41
+ if (executorOrdinal >= thresholdOrdinal) return true;
42
+ }
43
+ }
44
+ return false;
45
+ }
46
+
47
+ export function isExecutorBlocked(ctx: PiContext | undefined, thinkingLevel?: string): boolean {
48
+ return isModelBlocked(ctx?.model, thinkingLevel);
49
+ }
package/src/prompt.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * prompt — the advisor system prompt.
3
+ * Grounded, directive instructions for the reviewer model in the advisor-strategy pattern.
4
+ */
5
+
6
+ export const ADVISOR_SYSTEM_PROMPT =
7
+ `You are an advisor model in an advisor-strategy pattern. An executor model is running a task end-to-end — calling tools, reading results, iterating toward a solution. When the executor hits a decision it cannot reasonably solve alone, it consults you for guidance. The executor's full tool inventory is prepended before the conversation so you can judge tool-choice correctness.
8
+
9
+ You read the shared conversation context and return ONE of:
10
+ - a plan (concrete next steps the executor should take),
11
+ - a correction (the executor is going down a wrong path — redirect it),
12
+ - a stop signal (the executor should halt and escalate to the user).
13
+
14
+ If declarative subagents are available in the executor's tool set, you may advise delegating specific tasks (exploration, planning, verification) to them.
15
+
16
+ You NEVER call tools. You NEVER produce user-facing output. Be concise, directive, and grounded in the shared context. Name files, functions, and line numbers where possible. No preamble, no apologies, no meta-commentary about being an advisor — just the guidance the executor needs.`.trim();
@@ -0,0 +1,74 @@
1
+ import type { PiContext, PiExtensionAPI } from "@restranger/repi-lib";
2
+ import { Type } from "@sinclair/typebox";
3
+ import { loadAdvisorConfig } from "./config.js";
4
+ import { executeAdvisor } from "./execute.js";
5
+ import { ADVISOR_TOOL_NAME, TOOL_LABEL } from "./messages.js";
6
+ import type { AdvisorPluginOptions } from "./types.js";
7
+
8
+ const AdvisorParams = Type.Object({});
9
+
10
+ const ADVISOR_DESCRIPTION =
11
+ "Escalate to a stronger reviewer model for guidance. When you need " +
12
+ "stronger judgment — a complex decision, an ambiguous failure, a problem " +
13
+ "you're circling without progress — escalate to the advisor model for " +
14
+ "guidance, then resume. Takes NO parameters — when you call advisor(), " +
15
+ "your entire conversation history is automatically forwarded. The advisor " +
16
+ "sees the task, every tool call you've made, every result you've seen.";
17
+
18
+ export const DEFAULT_PROMPT_SNIPPET =
19
+ "Escalate to a stronger reviewer model for guidance when stuck, before substantive work, or before declaring done";
20
+
21
+ export const DEFAULT_PROMPT_GUIDELINES: readonly string[] = [
22
+ "Call `advisor` BEFORE substantive work — before writing, before committing to an interpretation, before building on an assumption. Orientation (finding files, fetching a source, seeing what's there) is not substantive work; writing, editing, and declaring an answer are.",
23
+ "Also call `advisor` when you believe the task is complete. BEFORE this call, make your deliverable durable: write the file, save the result, commit the change.",
24
+ "Also call `advisor` when stuck — errors recurring, approach not converging, results that don't fit — or when considering a change of approach.",
25
+ "On tasks longer than a few steps, call `advisor` at least once before committing to an approach and once before declaring done.",
26
+ "Give the advisor's advice serious weight. If you follow a step and it fails empirically, adapt — but consider reconciling with the advisor before abandoning the plan.",
27
+ "If declarative subagents (e.g. `subagent` tool) are available, follow advisor suggestions to delegate specialized subtasks to them.",
28
+ "After each `advisor` result, put the advisor's key guidance into your next visible reply to the user before continuing — quote or paraphrase the plan, correction, or stop signal.",
29
+ ];
30
+
31
+ export function registerAdvisorTool(pi: PiExtensionAPI, options: AdvisorPluginOptions = {}): void {
32
+ const loaded = options.config
33
+ ? { config: options.config }
34
+ : loadAdvisorConfig({
35
+ cwd: options.cwd ?? process.cwd(),
36
+ ...(options.homeDir ? { homeDir: options.homeDir } : {}),
37
+ ...(options.env ? { env: options.env } : {}),
38
+ });
39
+
40
+ const guidance = loaded.config.guidance ?? {};
41
+
42
+ pi.registerTool({
43
+ name: ADVISOR_TOOL_NAME,
44
+ label: TOOL_LABEL,
45
+ description: ADVISOR_DESCRIPTION,
46
+ promptSnippet: guidance.promptSnippet ?? DEFAULT_PROMPT_SNIPPET,
47
+ promptGuidelines: guidance.promptGuidelines ?? DEFAULT_PROMPT_GUIDELINES,
48
+ parameters: AdvisorParams,
49
+ async execute(
50
+ _toolCallId: string,
51
+ _params: Record<string, unknown>,
52
+ signal?: AbortSignal,
53
+ onUpdate?: unknown,
54
+ ctx?: PiContext,
55
+ ) {
56
+ return executeAdvisor(ctx as PiContext, pi, signal, onUpdate as any);
57
+ },
58
+ });
59
+
60
+ const PI_AI_PACKAGE = "@earendil-works/pi-ai";
61
+ pi.on("session_shutdown", async (_event, _ctx) => {
62
+ try {
63
+ const { cleanupSessionResources } = (await import(PI_AI_PACKAGE)) as {
64
+ cleanupSessionResources?: (id: string) => void;
65
+ };
66
+ if (typeof cleanupSessionResources === "function" && _ctx) {
67
+ const id = (_ctx as { sessionManager?: { getSessionId(): string } }).sessionManager?.getSessionId?.();
68
+ if (id) cleanupSessionResources(`advisor-${id}`);
69
+ }
70
+ } catch {
71
+ // Best-effort cleanup
72
+ }
73
+ });
74
+ }
package/src/restore.ts ADDED
@@ -0,0 +1,168 @@
1
+ import {
2
+ ADVISOR_CONTRACT_ID,
3
+ type AdvisorService,
4
+ type PiContext,
5
+ type PiExtensionAPI,
6
+ type PiModel,
7
+ getSessionId,
8
+ modelKey,
9
+ parseModelKey,
10
+ publishService,
11
+ resolveModel,
12
+ } from "@restranger/repi-lib";
13
+ import { loadAdvisorConfig, saveAdvisorConfig } from "./config.js";
14
+ import { reconcileAdvisorTool } from "./handlers.js";
15
+ import {
16
+ ADVISOR_TOOL_NAME,
17
+ EFFORT_ORDINAL,
18
+ type GradedEffort,
19
+ errModelUnavailable,
20
+ msgAdvisorRestored,
21
+ msgAdvisorRestoredInactive,
22
+ } from "./messages.js";
23
+ import { isExecutorBlocked, setDisabledForModels } from "./policy.js";
24
+ import {
25
+ clearAdvisorState,
26
+ getAdvisorEffort,
27
+ getAdvisorFallbacks,
28
+ getAdvisorModel,
29
+ setAdvisorEffort,
30
+ setAdvisorFallbacks,
31
+ setAdvisorModel,
32
+ } from "./state.js";
33
+ import type { AdvisorPluginOptions } from "./types.js";
34
+
35
+ let restoreAnnounced = false;
36
+
37
+ export function __resetAdvisorAnnounced(): void {
38
+ restoreAnnounced = false;
39
+ }
40
+
41
+ export function restoreAdvisorState(ctx: PiContext, pi: PiExtensionAPI, options: AdvisorPluginOptions = {}): void {
42
+ const sessionId = getSessionId(ctx, "default");
43
+ const loaded = options.config
44
+ ? { config: options.config, configFiles: [], diagnostics: [] }
45
+ : loadAdvisorConfig({
46
+ cwd: options.cwd ?? ctx.cwd,
47
+ ...(options.homeDir ? { homeDir: options.homeDir } : {}),
48
+ ...(options.env ? { env: options.env } : {}),
49
+ workspaceTrusted: ctx.isProjectTrusted?.() === true,
50
+ });
51
+
52
+ const config = loaded.config;
53
+
54
+ if (config.disabledForModels) {
55
+ setDisabledForModels(config.disabledForModels);
56
+ }
57
+ if (config.fallbackModels) {
58
+ setAdvisorFallbacks(config.fallbackModels);
59
+ }
60
+
61
+ const deactivate = (): void => {
62
+ clearAdvisorState();
63
+ reconcileAdvisorTool(pi, ctx, { blocked: true });
64
+ };
65
+
66
+ // Register the AdvisorService on the service seam
67
+ const advisorService: AdvisorService = {
68
+ getAdvisor: () => {
69
+ const m = getAdvisorModel();
70
+ return {
71
+ model: m ? modelKey(m) : undefined,
72
+ effort: getAdvisorEffort(),
73
+ fallbackModels: getAdvisorFallbacks(),
74
+ isBlocked: isExecutorBlocked(ctx, pi.getThinkingLevel?.()),
75
+ };
76
+ },
77
+ setAdvisorModel: (key) => {
78
+ if (!key) {
79
+ setAdvisorModel(undefined);
80
+ reconcileAdvisorTool(pi, ctx, { blocked: true });
81
+ return;
82
+ }
83
+ const resolved = resolveModel<PiModel>(key, ctx.modelRegistry);
84
+ if (resolved) {
85
+ setAdvisorModel(resolved);
86
+ reconcileAdvisorTool(pi, ctx, { blocked: isExecutorBlocked(ctx, pi.getThinkingLevel?.()) });
87
+ }
88
+ },
89
+ setAdvisorEffort: (effort) => {
90
+ if (effort && EFFORT_ORDINAL.includes(effort as GradedEffort)) {
91
+ setAdvisorEffort(effort as GradedEffort);
92
+ } else {
93
+ setAdvisorEffort(undefined);
94
+ }
95
+ },
96
+ setAdvisorFallbackModels: (fallbacks) => {
97
+ setAdvisorFallbacks(fallbacks);
98
+ const cwd = options.cwd ?? ctx.cwd;
99
+ saveAdvisorConfig(
100
+ cwd,
101
+ { fallbackModels: fallbacks },
102
+ {
103
+ workspaceTrusted: ctx.isProjectTrusted?.() === true,
104
+ ...(options.homeDir ? { homeDir: options.homeDir } : {}),
105
+ ...(options.env ? { env: options.env } : {}),
106
+ },
107
+ );
108
+ },
109
+ };
110
+
111
+ publishService({
112
+ contract: ADVISOR_CONTRACT_ID,
113
+ sessionId,
114
+ owner: "@restranger/repi-advisor",
115
+ impl: advisorService,
116
+ });
117
+
118
+ if (!config.modelKey) {
119
+ deactivate();
120
+ return;
121
+ }
122
+
123
+ const parsed = parseModelKey(config.modelKey);
124
+ if (!parsed) {
125
+ deactivate();
126
+ return;
127
+ }
128
+
129
+ const notifyOnce = (msg: string, level: "info" | "warning" | "error"): void => {
130
+ if (!ctx.hasUI || restoreAnnounced) return;
131
+ ctx.ui.notify(msg, level);
132
+ restoreAnnounced = true;
133
+ };
134
+
135
+ const model = ctx.modelRegistry?.find?.(parsed.provider, parsed.modelId) as PiModel | undefined;
136
+ if (!model) {
137
+ deactivate();
138
+ notifyOnce(errModelUnavailable(config.modelKey), "warning");
139
+ return;
140
+ }
141
+
142
+ setAdvisorModel(model);
143
+
144
+ let effort = config.effort;
145
+ if (effort !== undefined && !EFFORT_ORDINAL.includes(effort)) {
146
+ effort = undefined;
147
+ }
148
+ setAdvisorEffort(effort);
149
+
150
+ if (isExecutorBlocked(ctx, pi.getThinkingLevel?.())) {
151
+ reconcileAdvisorTool(pi, ctx, { blocked: true });
152
+ notifyOnce(msgAdvisorRestoredInactive(modelKey(model), effort), "info");
153
+ return;
154
+ }
155
+
156
+ const active = typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [];
157
+ if (!active.includes(ADVISOR_TOOL_NAME)) {
158
+ pi.setActiveTools?.([...active, ADVISOR_TOOL_NAME]);
159
+ }
160
+
161
+ notifyOnce(msgAdvisorRestored(modelKey(model), effort, getAdvisorFallbacks()), "info");
162
+ }
163
+
164
+ export function registerAdvisorSessionStart(pi: PiExtensionAPI, options: AdvisorPluginOptions = {}): void {
165
+ pi.on("session_start", (_event, ctx) => {
166
+ restoreAdvisorState(ctx, pi, options);
167
+ });
168
+ }
package/src/state.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { PiModel } from "@restranger/repi-lib";
2
+ import type { GradedEffort } from "./messages.js";
3
+
4
+ let selectedAdvisor: PiModel | undefined;
5
+ let selectedAdvisorEffort: GradedEffort | undefined;
6
+ let selectedAdvisorFallbacks: readonly string[] = [];
7
+
8
+ export function getAdvisorModel(): PiModel | undefined {
9
+ return selectedAdvisor;
10
+ }
11
+
12
+ export function setAdvisorModel(model: PiModel | undefined): void {
13
+ selectedAdvisor = model;
14
+ }
15
+
16
+ export function getAdvisorEffort(): GradedEffort | undefined {
17
+ return selectedAdvisorEffort;
18
+ }
19
+
20
+ export function setAdvisorEffort(effort: GradedEffort | undefined): void {
21
+ selectedAdvisorEffort = effort;
22
+ }
23
+
24
+ export function getAdvisorFallbacks(): readonly string[] {
25
+ return selectedAdvisorFallbacks;
26
+ }
27
+
28
+ export function setAdvisorFallbacks(fallbacks: readonly string[] | undefined): void {
29
+ selectedAdvisorFallbacks = fallbacks ? [...fallbacks] : [];
30
+ }
31
+
32
+ export function clearAdvisorState(): void {
33
+ selectedAdvisor = undefined;
34
+ selectedAdvisorEffort = undefined;
35
+ selectedAdvisorFallbacks = [];
36
+ }
package/src/types.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { PluginDiagnostic } from "@restranger/repi-lib";
2
+ import type { GradedEffort } from "./messages.js";
3
+
4
+ export type DisabledForModelsEntry = string | { model: string; minEffort?: GradedEffort };
5
+
6
+ export interface GuidanceConfig {
7
+ readonly promptSnippet?: string;
8
+ readonly promptGuidelines?: readonly string[];
9
+ }
10
+
11
+ export interface AdvisorConfig {
12
+ readonly version?: number;
13
+ readonly modelKey?: string;
14
+ readonly effort?: GradedEffort;
15
+ readonly fallbackModels?: readonly string[];
16
+ readonly disabledForModels?: readonly DisabledForModelsEntry[];
17
+ readonly guidance?: GuidanceConfig;
18
+ }
19
+
20
+ export interface AdvisorConfigContext {
21
+ readonly cwd: string;
22
+ readonly homeDir?: string;
23
+ readonly env?: Readonly<Record<string, string | undefined>>;
24
+ readonly workspaceTrusted?: boolean;
25
+ }
26
+
27
+ export interface LoadedAdvisorConfig {
28
+ readonly config: AdvisorConfig;
29
+ readonly configFiles: readonly string[];
30
+ readonly diagnostics: readonly PluginDiagnostic[];
31
+ }
32
+
33
+ export interface AdvisorUsage {
34
+ readonly inputTokens?: number;
35
+ readonly outputTokens?: number;
36
+ readonly cacheReadTokens?: number;
37
+ readonly cacheWriteTokens?: number;
38
+ readonly totalTokens?: number;
39
+ }
40
+
41
+ export interface AdvisorDetails {
42
+ advisorModel?: string;
43
+ effort?: string;
44
+ primaryModel?: string;
45
+ isFallback?: boolean;
46
+ attemptedModels?: readonly string[];
47
+ usage?: AdvisorUsage;
48
+ stopReason?: string;
49
+ errorMessage?: string;
50
+ }
51
+
52
+ export interface AdvisorPluginOptions {
53
+ readonly cwd?: string;
54
+ readonly homeDir?: string;
55
+ readonly env?: Readonly<Record<string, string | undefined>>;
56
+ readonly config?: AdvisorConfig;
57
+ }