@howaboua/pi-subagent-review 0.2.12 → 0.2.14

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,174 @@
1
+ import type {
2
+ AssistantMessage,
3
+ Credential,
4
+ CredentialStore,
5
+ } from "@earendil-works/pi-ai";
6
+ import {
7
+ createAgentSession,
8
+ DefaultResourceLoader,
9
+ type ExtensionCommandContext,
10
+ getAgentDir,
11
+ ModelRuntime,
12
+ readStoredCredential,
13
+ SessionManager,
14
+ SettingsManager,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import type { ResolvedReviewConfig } from "./types.js";
17
+
18
+ const SUMMARY_SYSTEM_PROMPT =
19
+ "Summarize supplied conversation context for a separate code-review agent. Follow the user's summary format exactly and do not use tools.";
20
+
21
+ function summaryCredentialStore(
22
+ providerId: string,
23
+ credential: Credential | undefined,
24
+ ): CredentialStore {
25
+ const credentials = new Map<string, Credential>();
26
+ if (credential) credentials.set(providerId, credential);
27
+ return {
28
+ async read(id) {
29
+ return credentials.get(id);
30
+ },
31
+ async list() {
32
+ return [...credentials].map(([id, credential]) => ({
33
+ providerId: id,
34
+ type: credential.type,
35
+ }));
36
+ },
37
+ async modify(id, update) {
38
+ const current = credentials.get(id);
39
+ const next = await update(current);
40
+ if (next) credentials.set(id, next);
41
+ return next ?? current;
42
+ },
43
+ async delete(id) {
44
+ credentials.delete(id);
45
+ },
46
+ };
47
+ }
48
+
49
+ function lastAssistantMessage(
50
+ messages: readonly unknown[],
51
+ ): AssistantMessage | undefined {
52
+ for (let index = messages.length - 1; index >= 0; index--) {
53
+ const message = messages[index];
54
+ if (
55
+ message &&
56
+ typeof message === "object" &&
57
+ (message as { role?: unknown }).role === "assistant"
58
+ ) {
59
+ return message as AssistantMessage;
60
+ }
61
+ }
62
+ return undefined;
63
+ }
64
+
65
+ export async function completeSummary(
66
+ ctx: ExtensionCommandContext,
67
+ config: ResolvedReviewConfig,
68
+ prompt: string,
69
+ ): Promise<AssistantMessage> {
70
+ const signal = ctx.signal;
71
+ if (signal?.aborted) throw new Error("Summary model was aborted");
72
+
73
+ const parsed = config.summary.modelParsed;
74
+ const model = ctx.modelRegistry.find(parsed.provider, parsed.modelId);
75
+ if (!model)
76
+ throw new Error(`Summary model not found: ${config.summary.model}`);
77
+ const requestAuth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
78
+ if (!requestAuth.ok) throw new Error(requestAuth.error);
79
+ const persistedCredential = readStoredCredential(model.provider);
80
+ const storedCredential =
81
+ persistedCredential?.type === "oauth" &&
82
+ persistedCredential.access === requestAuth.apiKey
83
+ ? persistedCredential
84
+ : undefined;
85
+ const resolvedCredential =
86
+ requestAuth.apiKey || requestAuth.env
87
+ ? {
88
+ type: "api_key" as const,
89
+ ...(requestAuth.apiKey ? { key: requestAuth.apiKey } : {}),
90
+ ...(requestAuth.env ? { env: requestAuth.env } : {}),
91
+ }
92
+ : undefined;
93
+ const modelRuntime = await ModelRuntime.create({
94
+ credentials: summaryCredentialStore(
95
+ model.provider,
96
+ storedCredential ?? resolvedCredential,
97
+ ),
98
+ allowModelNetwork: false,
99
+ });
100
+ const registeredProvider = ctx.modelRegistry.getRegisteredProviderConfig(
101
+ model.provider,
102
+ );
103
+ if (registeredProvider || requestAuth.apiKey || requestAuth.headers) {
104
+ const { oauth, ...providerConfig } = registeredProvider ?? {};
105
+ modelRuntime.registerProvider(model.provider, {
106
+ ...providerConfig,
107
+ ...(storedCredential?.type !== "oauth" && requestAuth.apiKey
108
+ ? { apiKey: requestAuth.apiKey }
109
+ : {}),
110
+ headers: {
111
+ ...registeredProvider?.headers,
112
+ ...requestAuth.headers,
113
+ },
114
+ ...(storedCredential?.type === "oauth" && oauth ? { oauth } : {}),
115
+ });
116
+ }
117
+
118
+ const settingsManager = SettingsManager.inMemory({
119
+ compaction: { enabled: false },
120
+ });
121
+ const resourceLoader = new DefaultResourceLoader({
122
+ cwd: ctx.cwd,
123
+ agentDir: getAgentDir(),
124
+ settingsManager,
125
+ noExtensions: true,
126
+ noSkills: true,
127
+ noPromptTemplates: true,
128
+ noThemes: true,
129
+ noContextFiles: true,
130
+ systemPrompt: SUMMARY_SYSTEM_PROMPT,
131
+ });
132
+ await resourceLoader.reload();
133
+
134
+ const { session } = await createAgentSession({
135
+ cwd: ctx.cwd,
136
+ model,
137
+ thinkingLevel: config.summary.thinking,
138
+ modelRuntime,
139
+ noTools: "all",
140
+ resourceLoader,
141
+ sessionManager: SessionManager.inMemory(ctx.cwd),
142
+ settingsManager,
143
+ });
144
+ let abortPromise: Promise<void> | undefined;
145
+ const abortSummary = () => {
146
+ abortPromise ??= session.abort();
147
+ };
148
+ signal?.addEventListener("abort", abortSummary, { once: true });
149
+
150
+ try {
151
+ if (signal?.aborted) {
152
+ abortSummary();
153
+ throw new Error("Summary model was aborted");
154
+ }
155
+ await session.prompt(prompt, {
156
+ expandPromptTemplates: false,
157
+ source: "extension",
158
+ });
159
+ const response = lastAssistantMessage(session.messages);
160
+ if (!response)
161
+ throw new Error("Summary model returned no assistant message");
162
+ if (response.stopReason === "error") {
163
+ throw new Error(response.errorMessage || "Summary model failed");
164
+ }
165
+ if (response.stopReason === "aborted") {
166
+ throw new Error("Summary model was aborted");
167
+ }
168
+ return response;
169
+ } finally {
170
+ signal?.removeEventListener("abort", abortSummary);
171
+ await abortPromise;
172
+ session.dispose();
173
+ }
174
+ }
@@ -0,0 +1,128 @@
1
+ import {
2
+ type ExtensionAPI,
3
+ type ExtensionCommandContext,
4
+ generateBranchSummary,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import type { ResolvedSummaryConfig } from "./types.js";
7
+
8
+ interface TreeNavigationOptions {
9
+ summarize: true;
10
+ customInstructions?: string;
11
+ replaceInstructions?: boolean;
12
+ }
13
+
14
+ interface PendingSummary {
15
+ token: object;
16
+ targetId: string;
17
+ config: ResolvedSummaryConfig;
18
+ }
19
+
20
+ export type NavigateWithSummaryModel = (
21
+ ctx: ExtensionCommandContext,
22
+ targetId: string,
23
+ options: TreeNavigationOptions,
24
+ config: ResolvedSummaryConfig,
25
+ ) => ReturnType<ExtensionCommandContext["navigateTree"]>;
26
+
27
+ export function registerTreeSummaryModel(
28
+ pi: ExtensionAPI,
29
+ ): NavigateWithSummaryModel {
30
+ let pending: PendingSummary | undefined;
31
+
32
+ pi.on("session_before_tree", async (event, ctx) => {
33
+ const request = pending;
34
+ if (
35
+ !request ||
36
+ event.preparation.targetId !== request.targetId ||
37
+ !event.preparation.userWantsSummary
38
+ )
39
+ return;
40
+
41
+ const parsed = request.config.modelParsed;
42
+ const model = ctx.modelRegistry.find(parsed.provider, parsed.modelId);
43
+ const provider = model
44
+ ? ctx.modelRegistry.getProvider(model.provider)
45
+ : undefined;
46
+ if (!model || !provider) {
47
+ ctx.ui.notify(
48
+ `Configured summary model ${request.config.model} unavailable; falling back to the current session model.`,
49
+ "warning",
50
+ );
51
+ return;
52
+ }
53
+
54
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
55
+ if (!auth.ok) {
56
+ ctx.ui.notify(
57
+ `Configured summary model ${request.config.model} unavailable; falling back to the current session model.`,
58
+ "warning",
59
+ );
60
+ return;
61
+ }
62
+
63
+ try {
64
+ const result = await generateBranchSummary(
65
+ event.preparation.entriesToSummarize,
66
+ {
67
+ model,
68
+ signal: event.signal,
69
+ ...(auth.apiKey !== undefined ? { apiKey: auth.apiKey } : {}),
70
+ ...(auth.headers !== undefined ? { headers: auth.headers } : {}),
71
+ ...(auth.env !== undefined ? { env: auth.env } : {}),
72
+ ...(event.preparation.customInstructions !== undefined
73
+ ? { customInstructions: event.preparation.customInstructions }
74
+ : {}),
75
+ ...(event.preparation.replaceInstructions !== undefined
76
+ ? { replaceInstructions: event.preparation.replaceInstructions }
77
+ : {}),
78
+ streamFn: (requestModel, context, options) =>
79
+ provider.streamSimple(requestModel, context, {
80
+ ...options,
81
+ ...(requestModel.reasoning && request.config.thinking !== "off"
82
+ ? { reasoning: request.config.thinking }
83
+ : {}),
84
+ }),
85
+ },
86
+ );
87
+
88
+ if (result.aborted) return { cancel: true as const };
89
+ if (result.error || !result.summary) {
90
+ ctx.ui.notify(
91
+ `Configured summary model failed${result.error ? `: ${result.error}` : ""}; falling back to the current session model.`,
92
+ "warning",
93
+ );
94
+ return;
95
+ }
96
+
97
+ return {
98
+ summary: {
99
+ summary: result.summary,
100
+ details: {
101
+ readFiles: result.readFiles ?? [],
102
+ modifiedFiles: result.modifiedFiles ?? [],
103
+ },
104
+ ...(result.usage !== undefined ? { usage: result.usage } : {}),
105
+ },
106
+ };
107
+ } catch (error) {
108
+ if (event.signal.aborted) return { cancel: true as const };
109
+ ctx.ui.notify(
110
+ `Configured summary model failed: ${error instanceof Error ? error.message : String(error)}; falling back to the current session model.`,
111
+ "warning",
112
+ );
113
+ }
114
+ });
115
+
116
+ return async (ctx, targetId, options, config) => {
117
+ if (!config.enabled) return ctx.navigateTree(targetId, options);
118
+ if (pending) throw new Error("A tree summary is already in progress");
119
+
120
+ const token = {};
121
+ pending = { token, targetId, config };
122
+ try {
123
+ return await ctx.navigateTree(targetId, options);
124
+ } finally {
125
+ if (pending?.token === token) pending = undefined;
126
+ }
127
+ };
128
+ }
package/src/types.ts CHANGED
@@ -1,8 +1,11 @@
1
- import type { Message, ModelThinkingLevel } from "@earendil-works/pi-ai";
1
+ import type {
2
+ AssistantMessage,
3
+ ModelThinkingLevel,
4
+ } from "@earendil-works/pi-ai";
2
5
 
3
6
  export type ThinkingLevel = ModelThinkingLevel;
4
7
 
5
- export interface SummaryConfig {
8
+ interface SummaryConfig {
6
9
  enabled?: boolean;
7
10
  model?: string;
8
11
  thinking?: ThinkingLevel;
@@ -51,7 +54,7 @@ export interface ChildRunDetails {
51
54
  cwd: string;
52
55
  model: string;
53
56
  thinking?: ThinkingLevel;
54
- messages: Message[];
57
+ messages: AssistantMessage[];
55
58
  stderr: string;
56
59
  exitCode: number;
57
60
  stopReason?: string;