pi-finder-subagent 1.0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # pi-finder
2
+
3
+ Read-only codebase scout subagent package for [pi](https://github.com/badlogic/pi-mono).
4
+
5
+ ## Installation
6
+
7
+ From npm (after publish):
8
+
9
+ ```bash
10
+ pi install npm:pi-finder-subagent
11
+ ```
12
+
13
+ From git:
14
+
15
+ ```bash
16
+ pi install git:github.com/default-anton/pi-finder
17
+ ```
18
+
19
+ Or run without installing:
20
+
21
+ ```bash
22
+ pi -e npm:pi-finder-subagent
23
+ # or
24
+ pi -e git:github.com/default-anton/pi-finder
25
+ ```
26
+
27
+ ## What it does
28
+
29
+ - Registers a `finder` tool.
30
+ - Runs a dedicated subagent session with strict turn budget enforcement.
31
+ - Uses only `bash` + `read` in the subagent.
32
+ - Enforces read-only scouting behavior (rg/fd/ls + targeted reads).
33
+ - Returns structured Markdown output (`Summary`, `Locations`, optional `Evidence`/`Searched`/`Next steps`).
34
+ - Selects subagent model dynamically using shared package `pi-subagent-model-selection`.
35
+ - Emits compact selection diagnostics (`authMode`, `authSource`, `reason`) in tool details.
36
+
37
+ ## Tool interface
38
+
39
+ ```ts
40
+ finder({
41
+ query: string,
42
+ })
43
+ ```
44
+
45
+ ## Model selection policy
46
+
47
+ Finder delegates model selection to `pi-subagent-model-selection`, which uses the same policy as pi-librarian:
48
+
49
+ - OAuth mode:
50
+ 1. `google-antigravity/gemini-3-flash`
51
+ 2. fallback strategy
52
+ - API-key mode:
53
+ 1. `google-vertex` Gemini 3 Flash (`gemini-3-flash*`)
54
+ 2. `google` Gemini 3 Flash (`gemini-3-flash*`)
55
+ 3. fallback strategy
56
+
57
+ Fallback strategy:
58
+ 1. Gemini 3 Flash on current provider
59
+ 2. Claude Haiku 4.5 on current provider
60
+ 3. Current model with `thinkingLevel: low`
61
+
62
+ ## Development
63
+
64
+ ```bash
65
+ npm run test:model-selection
66
+ npm run pack:check
67
+ ```
68
+
69
+ ## License
70
+
71
+ Apache-2.0
@@ -0,0 +1,142 @@
1
+ import events from "node:events";
2
+
3
+ import { Type } from "@sinclair/typebox";
4
+
5
+ export const DEFAULT_MAX_TURNS = 10;
6
+ export const MAX_TOOL_CALLS_TO_KEEP = 80;
7
+
8
+ const DEFAULT_EVENTTARGET_MAX_LISTENERS = 100;
9
+ const EVENTTARGET_MAX_LISTENERS_STATE_KEY = Symbol.for("pi.eventTargetMaxListenersState");
10
+
11
+ type EventTargetMaxListenersState = { depth: number; savedDefault?: number };
12
+
13
+ export type FinderStatus = "running" | "done" | "error" | "aborted";
14
+
15
+ export type ToolCall = {
16
+ id: string;
17
+ name: string;
18
+ args: unknown;
19
+ startedAt: number;
20
+ endedAt?: number;
21
+ isError?: boolean;
22
+ };
23
+
24
+ export interface FinderRunDetails {
25
+ status: FinderStatus;
26
+ query: string;
27
+ turns: number;
28
+ toolCalls: ToolCall[];
29
+ summaryText?: string;
30
+ error?: string;
31
+ startedAt: number;
32
+ endedAt?: number;
33
+ }
34
+
35
+ export interface SubagentSelectionInfo {
36
+ authMode: "oauth" | "api-key";
37
+ authSource: "runtime" | "api_key" | "oauth" | "env" | "fallback" | "none";
38
+ reason: string;
39
+ }
40
+
41
+ export interface FinderDetails {
42
+ status: FinderStatus;
43
+ workspace?: string;
44
+ subagentProvider?: string;
45
+ subagentModelId?: string;
46
+ subagentSelection?: SubagentSelectionInfo;
47
+ runs: FinderRunDetails[];
48
+ }
49
+
50
+ export const FinderParams = Type.Object({
51
+ query: Type.String({
52
+ description: [
53
+ "Describe what to find in the codebase. Include: (1) specific goal, (2) keywords/identifiers to search, (3) desired output type (paths, line ranges, directory structure), (4) what counts as 'found'.",
54
+ "Finder uses rg/fd/ls and read — do not request grep or find.",
55
+ "Example: 'Find where user authentication is implemented. Look for functions named login, auth, or authenticate. Return paths with line ranges for the main entry point and token handling. Search in src/auth and src/api directories.'",
56
+ ].join("\n"),
57
+ }),
58
+ });
59
+
60
+ function getEventTargetMaxListenersState(): EventTargetMaxListenersState {
61
+ const g = globalThis as any;
62
+ if (!g[EVENTTARGET_MAX_LISTENERS_STATE_KEY]) g[EVENTTARGET_MAX_LISTENERS_STATE_KEY] = { depth: 0 };
63
+ return g[EVENTTARGET_MAX_LISTENERS_STATE_KEY] as EventTargetMaxListenersState;
64
+ }
65
+
66
+ export function bumpDefaultEventTargetMaxListeners(): () => void {
67
+ const state = getEventTargetMaxListenersState();
68
+
69
+ const raw = process.env.PI_EVENTTARGET_MAX_LISTENERS ?? process.env.PI_ABORT_MAX_LISTENERS;
70
+ const desired = raw !== undefined ? Number(raw) : DEFAULT_EVENTTARGET_MAX_LISTENERS;
71
+ if (!Number.isFinite(desired) || desired < 0) return () => { };
72
+
73
+ if (state.depth === 0) state.savedDefault = events.defaultMaxListeners;
74
+ state.depth += 1;
75
+
76
+ if (events.defaultMaxListeners < desired) events.setMaxListeners(desired);
77
+
78
+ return () => {
79
+ state.depth = Math.max(0, state.depth - 1);
80
+ if (state.depth !== 0) return;
81
+ if (state.savedDefault === undefined) return;
82
+
83
+ events.setMaxListeners(state.savedDefault);
84
+ state.savedDefault = undefined;
85
+ };
86
+ }
87
+
88
+ export function shorten(text: string, max: number): string {
89
+ if (text.length <= max) return text;
90
+ return `${text.slice(0, max)}…`;
91
+ }
92
+
93
+ export function getLastAssistantText(messages: any[]): string {
94
+ for (let i = messages.length - 1; i >= 0; i--) {
95
+ const msg = messages[i];
96
+ if (msg?.role !== "assistant") continue;
97
+ const parts = msg.content;
98
+ if (!Array.isArray(parts)) continue;
99
+
100
+ const blocks: string[] = [];
101
+ for (const part of parts) {
102
+ if (part?.type === "text" && typeof part.text === "string") blocks.push(part.text);
103
+ }
104
+
105
+ if (blocks.length > 0) return blocks.join("");
106
+ }
107
+ return "";
108
+ }
109
+
110
+ export function computeOverallStatus(runs: FinderRunDetails[]): FinderStatus {
111
+ if (runs.some((r) => r.status === "running")) return "running";
112
+ if (runs.some((r) => r.status === "error")) return "error";
113
+ if (runs.every((r) => r.status === "aborted")) return "aborted";
114
+ return "done";
115
+ }
116
+
117
+ export function renderCombinedMarkdown(runs: FinderRunDetails[]): string {
118
+ const r = runs[0];
119
+ return (r.summaryText ?? (r.status === "running" ? "(searching...)" : "(no output)")).trim();
120
+ }
121
+
122
+ export function formatToolCall(call: ToolCall): string {
123
+ const args = call.args && typeof call.args === "object" ? (call.args as Record<string, any>) : undefined;
124
+
125
+ if (call.name === "read") {
126
+ const p = typeof args?.path === "string" ? args.path : "";
127
+ const offset = typeof args?.offset === "number" ? args.offset : undefined;
128
+ const limit = typeof args?.limit === "number" ? args.limit : undefined;
129
+ const range = offset || limit ? `:${offset ?? 1}${limit ? `-${(offset ?? 1) + limit - 1}` : ""}` : "";
130
+ return `read ${p}${range}`;
131
+ }
132
+
133
+ if (call.name === "bash") {
134
+ const command = typeof args?.command === "string" ? args.command : "";
135
+ const timeout = typeof args?.timeout === "number" ? args.timeout : undefined;
136
+ const normalized = command.replace(/\s+/g, " ").trim();
137
+ const suffix = timeout ? ` (timeout ${timeout}s)` : "";
138
+ return `bash ${shorten(normalized, 120)}${suffix}`.trimEnd();
139
+ }
140
+
141
+ return call.name;
142
+ }
@@ -0,0 +1,46 @@
1
+ export function buildFinderSystemPrompt(maxTurns: number): string {
2
+ return `You are Finder, an evidence-first repository scout.
3
+ You operate in a read-only environment and may only use the provided tools (bash/read).
4
+
5
+ Use bash for repository scouting (e.g., rg, fd, ls). Never use grep (use rg) or find (use fd).
6
+ Use read to open specific file ranges for line-level citations.
7
+
8
+ Turn budget: at most ${maxTurns} turns total (hard cap).
9
+ Tool use is disabled on the final turn; reserve final turn for synthesis.
10
+
11
+ Non-negotiable constraints:
12
+ - Do not modify files, propose patches, or refactor.
13
+ - No side effects: do not run commands that modify files or repository state.
14
+ - Do not guess. Every claim must be backed by tool output.
15
+ - Keep snippets short (about 5-15 lines).
16
+
17
+ How to work:
18
+ 1) Translate the query into a concrete search checklist.
19
+ 2) Search broadly with bash using rg + fd, then narrow.
20
+ 3) Use read with offset+limit for line-level evidence.
21
+ 4) Stop as soon as evidence is sufficient.
22
+
23
+ Citations:
24
+ - For file-content claims, cite path:lineStart-lineEnd from explicit read ranges.
25
+ - For path-only claims, cite paths from bash outputs.
26
+
27
+ Output format (Markdown, exact order):
28
+ ## Summary
29
+ (1-3 sentences)
30
+ ## Locations
31
+ - \`path\` or \`path:lineStart-lineEnd\` — what is here and why it matters
32
+ ## Evidence (optional)
33
+ (snippets, each preceded by a citation)
34
+ ## Searched (only if incomplete / not found)
35
+ (patterns and directories tried)
36
+ ## Next steps (optional)
37
+ (what to check next if ambiguous)`.trim();
38
+ }
39
+
40
+ export function buildFinderUserPrompt(query: string): string {
41
+ return `Task: locate and cite exact code locations that answer the query.
42
+ Follow the system instructions for tools, citations, and output format.
43
+
44
+ Query:
45
+ ${query.trim()}`.trim();
46
+ }
@@ -0,0 +1,403 @@
1
+ import type { ExtensionAPI, ExtensionContext, ExtensionFactory } from "@mariozechner/pi-coding-agent";
2
+ import {
3
+ DefaultResourceLoader,
4
+ SessionManager,
5
+ createAgentSession,
6
+ createBashTool,
7
+ createReadTool,
8
+ getMarkdownTheme,
9
+ } from "@mariozechner/pi-coding-agent";
10
+ import { Container, Markdown, Spacer, Text } from "@mariozechner/pi-tui";
11
+ import { getSmallModelFromProvider } from "pi-subagent-model-selection";
12
+
13
+ import {
14
+ DEFAULT_MAX_TURNS,
15
+ FinderParams,
16
+ MAX_TOOL_CALLS_TO_KEEP,
17
+ bumpDefaultEventTargetMaxListeners,
18
+ computeOverallStatus,
19
+ formatToolCall,
20
+ getLastAssistantText,
21
+ renderCombinedMarkdown,
22
+ shorten,
23
+ type FinderDetails,
24
+ type FinderRunDetails,
25
+ } from "./finder-core";
26
+ import { buildFinderSystemPrompt, buildFinderUserPrompt } from "./finder-prompts.md.ts";
27
+
28
+ function createTurnBudgetExtension(maxTurns: number): ExtensionFactory {
29
+ return (pi) => {
30
+ let turnIndex = 0;
31
+
32
+ pi.on("turn_start", async (event) => {
33
+ turnIndex = event.turnIndex;
34
+ });
35
+
36
+ pi.on("tool_call", async () => {
37
+ if (turnIndex < maxTurns - 1) return undefined;
38
+
39
+ const humanTurn = Math.min(turnIndex + 1, maxTurns);
40
+ return {
41
+ block: true,
42
+ reason: `Tool use is disabled on the final turn (turn ${humanTurn}/${maxTurns}). Provide your final answer now without calling tools.`,
43
+ };
44
+ });
45
+
46
+ pi.on("tool_result", async (event) => {
47
+ const remainingAfter = Math.max(0, maxTurns - (turnIndex + 1));
48
+ const humanTurn = Math.min(turnIndex + 1, maxTurns);
49
+ const budgetLine = `[turn budget] turn ${humanTurn}/${maxTurns}; remaining after this turn: ${remainingAfter}`;
50
+
51
+ return {
52
+ content: [...(event.content ?? []), { type: "text", text: `\n\n${budgetLine}` }],
53
+ };
54
+ });
55
+ };
56
+ }
57
+
58
+ export default function finderExtension(pi: ExtensionAPI) {
59
+ pi.registerTool({
60
+ name: "finder",
61
+ label: "Finder",
62
+ description:
63
+ "Read-only codebase scout: searches repositories using rg/fd/ls and read, returns structured Markdown with Summary, Locations (path:lineStart-lineEnd), Evidence, and Searched sections.",
64
+ parameters: FinderParams,
65
+
66
+ async execute(_toolCallId, params, signal, onUpdate, ctx: ExtensionContext) {
67
+ const restoreMaxListeners = bumpDefaultEventTargetMaxListeners();
68
+ let abortListenerAdded = false;
69
+ let onAbort: (() => void) | undefined;
70
+ try {
71
+ const maxTurns = DEFAULT_MAX_TURNS;
72
+ const query = typeof (params as any).query === "string" ? ((params as any).query as string).trim() : "";
73
+
74
+ if (!query) {
75
+ const error = "Invalid parameters: expected `query` to be a non-empty string.";
76
+ return {
77
+ content: [{ type: "text", text: error }],
78
+ details: { status: "error", runs: [] } satisfies FinderDetails,
79
+ isError: true,
80
+ };
81
+ }
82
+
83
+ const runs: FinderRunDetails[] = [
84
+ {
85
+ status: "running",
86
+ query,
87
+ turns: 0,
88
+ toolCalls: [],
89
+ startedAt: Date.now(),
90
+ },
91
+ ];
92
+
93
+ const modelRegistry = ctx.modelRegistry;
94
+ const subModelSelection = getSmallModelFromProvider(modelRegistry, ctx.model);
95
+
96
+ if (!subModelSelection) {
97
+ const error = "No models available. Configure credentials (e.g. /login or auth.json) and try again.";
98
+ runs[0].status = "error";
99
+ runs[0].error = error;
100
+ runs[0].summaryText = error;
101
+ runs[0].endedAt = Date.now();
102
+ return {
103
+ content: [{ type: "text", text: error }],
104
+ details: {
105
+ status: "error",
106
+ workspace: ctx.cwd,
107
+ runs,
108
+ } satisfies FinderDetails,
109
+ isError: true,
110
+ };
111
+ }
112
+
113
+ const subModel = subModelSelection.model;
114
+ const subagentThinkingLevel = subModelSelection.thinkingLevel;
115
+ const subagentSelection = {
116
+ authMode: subModelSelection.authMode,
117
+ authSource: subModelSelection.authSource,
118
+ reason: subModelSelection.reason,
119
+ } as const;
120
+
121
+ let lastUpdate = 0;
122
+ const emitAll = (force = false) => {
123
+ const now = Date.now();
124
+ if (!force && now - lastUpdate < 120) return;
125
+ lastUpdate = now;
126
+
127
+ const status = computeOverallStatus(runs);
128
+ const text = renderCombinedMarkdown(runs);
129
+
130
+ onUpdate?.({
131
+ content: [{ type: "text", text }],
132
+ details: {
133
+ status,
134
+ workspace: ctx.cwd,
135
+ subagentProvider: subModel.provider,
136
+ subagentModelId: subModel.id,
137
+ subagentSelection,
138
+ runs,
139
+ } satisfies FinderDetails,
140
+ });
141
+ };
142
+
143
+ emitAll(true);
144
+
145
+ const systemPrompt = buildFinderSystemPrompt(maxTurns);
146
+
147
+ let toolAborted = false;
148
+ const activeSessions = new Set<{ abort: () => Promise<void> }>();
149
+
150
+ const markAllAborted = () => {
151
+ for (const run of runs) {
152
+ if (run.status !== "running") continue;
153
+ run.status = "aborted";
154
+ run.summaryText = run.summaryText ?? "Aborted";
155
+ run.endedAt = Date.now();
156
+ }
157
+ };
158
+
159
+ const abortAll = async () => {
160
+ if (toolAborted) return;
161
+ toolAborted = true;
162
+ markAllAborted();
163
+ emitAll(true);
164
+ await Promise.allSettled([...activeSessions].map((session) => session.abort()));
165
+ };
166
+
167
+ onAbort = () => void abortAll();
168
+
169
+ if (signal?.aborted) {
170
+ await abortAll();
171
+ const status = computeOverallStatus(runs);
172
+ const text = renderCombinedMarkdown(runs);
173
+ return {
174
+ content: [{ type: "text", text }],
175
+ details: {
176
+ status,
177
+ workspace: ctx.cwd,
178
+ runs,
179
+ subagentProvider: subModel.provider,
180
+ subagentModelId: subModel.id,
181
+ subagentSelection,
182
+ } satisfies FinderDetails,
183
+ isError: status === "error",
184
+ };
185
+ }
186
+
187
+ if (signal) {
188
+ signal.addEventListener("abort", onAbort);
189
+ abortListenerAdded = true;
190
+ }
191
+
192
+ const wasAborted = () => toolAborted || signal?.aborted;
193
+ const run = runs[0];
194
+
195
+ let session: any;
196
+ let unsubscribe: (() => void) | undefined;
197
+
198
+ try {
199
+ const resourceLoader = new DefaultResourceLoader({
200
+ noExtensions: true,
201
+ additionalExtensionPaths: ["npm:pi-subdir-context"],
202
+ noSkills: true,
203
+ noPromptTemplates: true,
204
+ noThemes: true,
205
+ extensionFactories: [createTurnBudgetExtension(maxTurns)],
206
+ systemPromptOverride: () => systemPrompt,
207
+ skillsOverride: () => ({ skills: [], diagnostics: [] }),
208
+ });
209
+ await resourceLoader.reload();
210
+
211
+ run.status = "running";
212
+ run.turns = 0;
213
+ run.toolCalls = [];
214
+ run.startedAt = Date.now();
215
+ run.endedAt = undefined;
216
+ run.error = undefined;
217
+ run.summaryText = undefined;
218
+
219
+ const { session: createdSession } = await createAgentSession({
220
+ cwd: ctx.cwd,
221
+ modelRegistry,
222
+ resourceLoader,
223
+ sessionManager: SessionManager.inMemory(ctx.cwd),
224
+ model: subModel,
225
+ thinkingLevel: subagentThinkingLevel,
226
+ tools: [createReadTool(ctx.cwd), createBashTool(ctx.cwd)],
227
+ });
228
+
229
+ session = createdSession;
230
+ activeSessions.add(session as any);
231
+
232
+ unsubscribe = session.subscribe((event) => {
233
+ switch (event.type) {
234
+ case "turn_end": {
235
+ run.turns += 1;
236
+ emitAll();
237
+ break;
238
+ }
239
+ case "tool_execution_start": {
240
+ run.toolCalls.push({
241
+ id: event.toolCallId,
242
+ name: event.toolName,
243
+ args: event.args,
244
+ startedAt: Date.now(),
245
+ });
246
+ if (run.toolCalls.length > MAX_TOOL_CALLS_TO_KEEP) {
247
+ run.toolCalls.splice(0, run.toolCalls.length - MAX_TOOL_CALLS_TO_KEEP);
248
+ }
249
+ emitAll(true);
250
+ break;
251
+ }
252
+ case "tool_execution_end": {
253
+ const call = run.toolCalls.find((c) => c.id === event.toolCallId);
254
+ if (call) {
255
+ call.endedAt = Date.now();
256
+ call.isError = event.isError;
257
+ }
258
+ emitAll(true);
259
+ break;
260
+ }
261
+ }
262
+ });
263
+
264
+ await session.prompt(buildFinderUserPrompt(query), {
265
+ expandPromptTemplates: false,
266
+ });
267
+ run.summaryText = getLastAssistantText(session.state.messages as any[]).trim();
268
+ if (!run.summaryText) run.summaryText = wasAborted() ? "Aborted" : "(no output)";
269
+ run.status = wasAborted() ? "aborted" : "done";
270
+ run.endedAt = Date.now();
271
+ emitAll(true);
272
+ } catch (error) {
273
+ const message = wasAborted() ? "Aborted" : error instanceof Error ? error.message : String(error);
274
+ run.status = wasAborted() ? "aborted" : "error";
275
+ run.error = wasAborted() ? undefined : message;
276
+ run.summaryText = message;
277
+ run.endedAt = Date.now();
278
+ emitAll(true);
279
+ } finally {
280
+ if (session) activeSessions.delete(session as any);
281
+ unsubscribe?.();
282
+ session?.dispose();
283
+ }
284
+
285
+ const status = computeOverallStatus(runs);
286
+ const text = renderCombinedMarkdown(runs);
287
+
288
+ return {
289
+ content: [{ type: "text", text }],
290
+ details: {
291
+ status,
292
+ workspace: ctx.cwd,
293
+ runs,
294
+ subagentProvider: subModel.provider,
295
+ subagentModelId: subModel.id,
296
+ subagentSelection,
297
+ } satisfies FinderDetails,
298
+ isError: status === "error",
299
+ };
300
+ } finally {
301
+ if (signal && abortListenerAdded && onAbort) signal.removeEventListener("abort", onAbort);
302
+ restoreMaxListeners();
303
+ }
304
+ },
305
+
306
+ renderCall(args, theme) {
307
+ const query = typeof (args as any)?.query === "string" ? ((args as any).query as string).trim() : "";
308
+ const preview = shorten(query.replace(/\s+/g, " ").trim(), 70);
309
+
310
+ const title = theme.fg("toolTitle", theme.bold("finder"));
311
+ const text = title + (preview ? `\n${theme.fg("muted", preview)}` : "");
312
+ return new Text(text, 0, 0);
313
+ },
314
+
315
+ renderResult(result, { expanded, isPartial }, theme) {
316
+ const details = result.details as FinderDetails | undefined;
317
+ if (!details) {
318
+ const text = result.content[0];
319
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
320
+ }
321
+
322
+ const status = isPartial ? "running" : details.status;
323
+ const icon =
324
+ status === "done"
325
+ ? theme.fg("success", "✓")
326
+ : status === "error"
327
+ ? theme.fg("error", "✗")
328
+ : status === "aborted"
329
+ ? theme.fg("warning", "◼")
330
+ : theme.fg("warning", "⏳");
331
+
332
+ const run = details.runs[0];
333
+ const totalToolCalls = run?.toolCalls.length ?? 0;
334
+ const totalTurns = run?.turns ?? 0;
335
+
336
+ const selectionSummary = details.subagentSelection
337
+ ? `${details.subagentSelection.authMode}/${details.subagentSelection.authSource}`
338
+ : "?/?";
339
+
340
+ const header =
341
+ icon +
342
+ " " +
343
+ theme.fg("toolTitle", theme.bold("finder ")) +
344
+ theme.fg(
345
+ "dim",
346
+ `${details.subagentProvider ?? "?"}/${details.subagentModelId ?? "?"} • ${selectionSummary} • ${totalTurns} turns • ${totalToolCalls} tool call${totalToolCalls === 1 ? "" : "s"}`,
347
+ );
348
+
349
+ const workspaceLine = details.workspace
350
+ ? `${theme.fg("muted", "workspace: ")}${theme.fg("toolOutput", details.workspace)}`
351
+ : theme.fg("muted", "workspace: (none)");
352
+
353
+ const selectionReasonLine = details.subagentSelection
354
+ ? `${theme.fg("muted", "selection: ")}${theme.fg("toolOutput", details.subagentSelection.reason)}`
355
+ : undefined;
356
+
357
+ let toolsText = "";
358
+ if (run && run.toolCalls.length > 0) {
359
+ const calls = expanded ? run.toolCalls : run.toolCalls.slice(-6);
360
+ const lines: string[] = [theme.fg("muted", "Tools:")];
361
+ for (const call of calls) {
362
+ const callIcon = call.isError ? theme.fg("error", "✗") : theme.fg("dim", "→");
363
+ lines.push(`${callIcon} ${theme.fg("toolOutput", formatToolCall(call))}`);
364
+ }
365
+ if (!expanded && run.toolCalls.length > 6) lines.push(theme.fg("muted", "(Ctrl+O to expand)"));
366
+ toolsText = lines.join("\n");
367
+ }
368
+
369
+ if (status === "running") {
370
+ let text = `${header}\n${workspaceLine}`;
371
+ if (expanded && selectionReasonLine) text += `\n${selectionReasonLine}`;
372
+ if (toolsText) text += `\n\n${toolsText}`;
373
+ text += `\n\n${theme.fg("muted", "Searching codebase…")}`;
374
+ return new Text(text, 0, 0);
375
+ }
376
+
377
+ const mdTheme = getMarkdownTheme();
378
+ const combined =
379
+ (result.content[0]?.type === "text" ? result.content[0].text : renderCombinedMarkdown(details.runs)).trim() ||
380
+ "(no output)";
381
+
382
+ if (!expanded) {
383
+ const previewLines = combined.split("\n").slice(0, 18).join("\n");
384
+ let text = `${header}\n${workspaceLine}\n\n${theme.fg("toolOutput", previewLines)}`;
385
+ if (combined.split("\n").length > 18) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
386
+ if (toolsText) text += `\n\n${toolsText}`;
387
+ return new Text(text, 0, 0);
388
+ }
389
+
390
+ const container = new Container();
391
+ container.addChild(new Text(header, 0, 0));
392
+ container.addChild(new Text(workspaceLine, 0, 0));
393
+ if (selectionReasonLine) container.addChild(new Text(selectionReasonLine, 0, 0));
394
+ if (toolsText) {
395
+ container.addChild(new Spacer(1));
396
+ container.addChild(new Text(toolsText, 0, 0));
397
+ }
398
+ container.addChild(new Spacer(1));
399
+ container.addChild(new Markdown(combined, 0, 0, mdTheme));
400
+ return container;
401
+ },
402
+ });
403
+ }
@@ -0,0 +1,68 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import type { AuthSource } from "pi-subagent-model-selection";
5
+ import { getSmallModelFromProvider } from "pi-subagent-model-selection";
6
+
7
+ type Model = { provider: string; id: string };
8
+
9
+ type RegistryOptions = {
10
+ authSource?: AuthSource;
11
+ usingOAuth?: boolean;
12
+ };
13
+
14
+ function makeRegistry(models: Model[], options: RegistryOptions = {}) {
15
+ return {
16
+ getAvailable() {
17
+ return models;
18
+ },
19
+ getAuthSource() {
20
+ return options.authSource ?? "none";
21
+ },
22
+ isUsingOAuth() {
23
+ return options.usingOAuth ?? false;
24
+ },
25
+ };
26
+ }
27
+
28
+ test("oauth mode selects antigravity gemini flash", () => {
29
+ const selected = getSmallModelFromProvider(
30
+ makeRegistry([{ provider: "google-antigravity", id: "gemini-3-flash" }], { authSource: "oauth", usingOAuth: true }),
31
+ { provider: "openai", id: "gpt-5.1-codex" },
32
+ );
33
+
34
+ assert.ok(selected);
35
+ assert.equal(selected.model.provider, "google-antigravity");
36
+ assert.equal(selected.authMode, "oauth");
37
+ assert.equal(selected.authSource, "oauth");
38
+ });
39
+
40
+ test("api-key mode prefers vertex gemini flash", () => {
41
+ const selected = getSmallModelFromProvider(
42
+ makeRegistry(
43
+ [
44
+ { provider: "google-vertex", id: "gemini-3-flash-preview" },
45
+ { provider: "google", id: "gemini-3-flash" },
46
+ ],
47
+ { authSource: "api_key" },
48
+ ),
49
+ { provider: "anthropic", id: "claude-opus-4-6" },
50
+ );
51
+
52
+ assert.ok(selected);
53
+ assert.equal(selected.model.provider, "google-vertex");
54
+ assert.equal(selected.authMode, "api-key");
55
+ assert.equal(selected.authSource, "api_key");
56
+ });
57
+
58
+ test("falls back to current model if no preferred small models exist", () => {
59
+ const selected = getSmallModelFromProvider(
60
+ makeRegistry([{ provider: "openai", id: "gpt-5.1-codex" }], { authSource: "runtime" }),
61
+ { provider: "openai", id: "gpt-5.1-codex" },
62
+ );
63
+
64
+ assert.ok(selected);
65
+ assert.equal(selected.model.provider, "openai");
66
+ assert.equal(selected.model.id, "gpt-5.1-codex");
67
+ assert.equal(selected.thinkingLevel, "low");
68
+ });
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "pi-finder-subagent",
3
+ "version": "1.0.0",
4
+ "description": "Read-only codebase scout subagent package for pi coding agent",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "pi-extension",
9
+ "finder",
10
+ "subagent",
11
+ "code-search"
12
+ ],
13
+ "license": "Apache-2.0",
14
+ "author": "Anton Kuzmenko",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/default-anton/pi-finder.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/default-anton/pi-finder/issues"
21
+ },
22
+ "homepage": "https://github.com/default-anton/pi-finder#readme",
23
+ "pi": {
24
+ "extensions": [
25
+ "./extensions/index.ts"
26
+ ]
27
+ },
28
+ "scripts": {
29
+ "test:model-selection": "node --test extensions/model-selection.test.ts",
30
+ "pack:check": "npm pack --dry-run",
31
+ "prepublishOnly": "npm run test:model-selection"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "peerDependencies": {
37
+ "@mariozechner/pi-coding-agent": "*",
38
+ "@mariozechner/pi-tui": "*",
39
+ "@sinclair/typebox": "*"
40
+ },
41
+ "dependencies": {
42
+ "pi-subagent-model-selection": "^0.1.1"
43
+ },
44
+ "files": [
45
+ "extensions/",
46
+ "README.md",
47
+ "LICENSE"
48
+ ]
49
+ }