@ferris1225/pi-subagents 4.2.8 → 4.2.13

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/src/format.ts CHANGED
@@ -8,6 +8,7 @@ import type { AgentConfig } from "./agents.ts";
8
8
  import { runLabel, shrinkRunLabel } from "./monitor.ts";
9
9
  import { emptyUsage } from "./rpc-run.ts";
10
10
  import {
11
+ RESULT_LINE_MAX,
11
12
  getResultOutput,
12
13
  isFailedResult,
13
14
  truncateResultOutput,
@@ -93,7 +94,7 @@ export function formatCompletionBlock(
93
94
  const status = failed ? "failed" : "completed";
94
95
  const usage = formatUsage(result.usage);
95
96
  const output = getResultOutput(result);
96
- const { text, truncated } = truncateResultOutput(output, maxResultLines);
97
+ const { text, truncated, shownLines, totalLines, widthClipped } = truncateResultOutput(output, maxResultLines);
97
98
  const fallbackNote = result.modelFallbackFrom
98
99
  ? ` (selected model ${result.modelFallbackFrom} failed → main ${result.model ?? "dynamic default"})`
99
100
  : "";
@@ -142,11 +143,12 @@ export function formatCompletionBlock(
142
143
  const artifact = options.resultRoot
143
144
  ? writeResultArtifact(output, result.agent, options.resultRoot)
144
145
  : "(result root unavailable)";
145
- // State the loss (shown vs total) and condition the read: handing the
146
- // parent both a summary and a full-text entrance invites the same content
147
- // into its context twice.
148
- const totalLines = output.split("\n").length;
149
- lines.push("", `(${maxResultLines} of ${totalLines} lines shown; full result ${artifact} read only if these are insufficient)`);
146
+ // State the real loss and condition the read: handing the parent both a
147
+ // summary and a full-text entrance invites the same content twice.
148
+ const lineLoss = shownLines < totalLines ? `${shownLines} of ${totalLines} lines shown` : `${shownLines} line${shownLines === 1 ? "" : "s"} shown`;
149
+ const widthLoss = widthClipped ? `clipped to ${RESULT_LINE_MAX} characters` : undefined;
150
+ const loss = widthLoss ? `${lineLoss}, ${widthLoss}` : lineLoss;
151
+ lines.push("", `(${loss}; full result ${artifact} — read only if these are insufficient)`);
150
152
  }
151
153
  return lines.join("\n");
152
154
  }
package/src/models.ts CHANGED
@@ -1,203 +1,203 @@
1
- /*
2
- * Model routing, capability-aware thinking, and setup-picker helpers.
3
- *
4
- * Runtime has one explicit fallback only: a configured agent model hands
5
- * off directly to the current main-window model. Setup lists only currently
6
- * available models and derives thinking choices from Pi's model metadata.
7
- */
8
-
9
- import {
10
- clampThinkingLevel,
11
- getSupportedThinkingLevels,
12
- type Api,
13
- type Model,
14
- } from "@earendil-works/pi-ai";
15
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
- import { DEFAULT_THINKING_LEVEL, type ThinkingLevel } from "./config.ts";
17
-
18
- export type ModelContext = Pick<ExtensionContext, "model" | "modelRegistry"> &
19
- Partial<Pick<ExtensionContext, "scopedModels">>;
20
-
21
- export const CURRENT_MAIN_MODEL = "__current_main_model__";
22
-
23
- export interface ModelPickerItem {
24
- value: string;
25
- label: string;
26
- description?: string;
27
- }
28
-
29
- export type ModelListEntry = Pick<
30
- Model<Api>,
31
- "provider" | "id" | "name" | "input" | "reasoning" | "thinkingLevelMap"
32
- >;
33
-
34
- export interface ResolvedAgentModelRoute {
35
- /** Effective first candidate. Undefined means let Pi use its normal default. */
36
- primaryRef?: string;
37
- /** Current main-window model when it differs from the selection. */
38
- mainFallbackRef?: string;
39
- /** Runtime order, useful for status/tests. */
40
- candidateRefs: string[];
41
- /** Configured ref skipped because Pi does not currently report it available. */
42
- unavailableSelectedRef?: string;
43
- }
44
-
45
- export interface AgentModelRouteInput {
46
- selectedRef?: string;
47
- mainRef?: string;
48
- /** When supplied, a configured selection outside this live set is skipped. */
49
- availableRefs?: readonly string[];
50
- }
51
-
52
- function cleanModelRef(ref: string | undefined): string | undefined {
53
- const trimmed = ref?.trim();
54
- return trimmed || undefined;
55
- }
56
-
57
- export function modelRef(model: { provider: string; id: string }): string {
58
- return `${model.provider}/${model.id}`;
59
- }
60
-
61
- export function currentModelRef(ctx: Pick<ModelContext, "model">): string | undefined {
62
- return ctx.model ? modelRef(ctx.model) : undefined;
63
- }
64
-
65
- /**
66
- * Current authenticated registry models narrowed by the session scope. Scope
67
- * entries are a session snapshot, so they act only as a whitelist; the live
68
- * registry remains the source of truth for availability and model metadata.
69
- */
70
- export function availableModelsInScope(ctx: ModelContext): readonly Model<Api>[] {
71
- const models = ctx.modelRegistry.getAvailable();
72
- // scopedModels was added after the original Pi minimum. Treat a missing field
73
- // exactly like an empty scope and use the full live registry.
74
- const scopedModels = ctx.scopedModels ?? [];
75
- if (scopedModels.length === 0) return models;
76
- const scopedRefs = new Set(scopedModels.map((entry) => modelRef(entry.model)));
77
- return models.filter((model) => scopedRefs.has(modelRef(model)));
78
- }
79
-
80
- export function findModelByRef(
81
- models: readonly Model<Api>[],
82
- ref: string | undefined,
83
- ): Model<Api> | undefined {
84
- const normalized = cleanModelRef(ref);
85
- return normalized ? models.find((model) => modelRef(model) === normalized) : undefined;
86
- }
87
-
88
- /** Split persisted agent model overrides into the ones Pi still reports as
89
- * available and the stale ones. Stale refs are dropped at session start (with
90
- * a user notice) so the config never carries models that can no longer run. */
91
- export function filterUnavailableModelOverrides(
92
- agentModels: Record<string, string>,
93
- models: readonly Model<Api>[],
94
- ): { kept: Record<string, string>; dropped: Array<{ agent: string; ref: string }> } {
95
- const kept: Record<string, string> = {};
96
- const dropped: Array<{ agent: string; ref: string }> = [];
97
- for (const [agent, ref] of Object.entries(agentModels)) {
98
- if (findModelByRef(models, ref)) kept[agent] = ref;
99
- else dropped.push({ agent, ref });
100
- }
101
- return { kept, dropped };
102
- }
103
-
104
- /**
105
- * Resolve one agent's runtime route:
106
- *
107
- * configured selection -> current main-window model
108
- *
109
- * Without an override the current main model is primary, so an agent never
110
- * pins its own model. A configured selection that Pi no longer reports as
111
- * available is skipped immediately instead of spawning a doomed child.
112
- */
113
- export function resolveAgentModelRoute(input: AgentModelRouteInput): ResolvedAgentModelRoute {
114
- const selectedRef = cleanModelRef(input.selectedRef);
115
- const mainRef = cleanModelRef(input.mainRef);
116
- const available = input.availableRefs
117
- ? new Set(input.availableRefs.map((ref) => ref.trim()).filter(Boolean))
118
- : undefined;
119
- const selectedAvailable = !selectedRef || !available || available.has(selectedRef);
120
- const usableSelectedRef = selectedAvailable ? selectedRef : undefined;
121
- const primaryRef = usableSelectedRef ?? mainRef;
122
- const ordered = [primaryRef, usableSelectedRef && usableSelectedRef !== mainRef ? mainRef : undefined];
123
- const candidateRefs = [...new Set(ordered.filter((ref): ref is string => Boolean(ref)))];
124
- return {
125
- primaryRef,
126
- ...(candidateRefs[1] ? { mainFallbackRef: candidateRefs[1] } : {}),
127
- candidateRefs,
128
- ...(!selectedAvailable && selectedRef ? { unavailableSelectedRef: selectedRef } : {}),
129
- };
130
- }
131
-
132
- /** The exact levels Pi exposes for this model, including `off` when supported. */
133
- export function supportedThinkingLevels(model: Model<Api> | undefined): ThinkingLevel[] {
134
- return model ? (getSupportedThinkingLevels(model) as ThinkingLevel[]) : [];
135
- }
136
-
137
- /** Clamp an agent preference to the effective model's actual capability map. */
138
- export function resolveThinkingLevel(
139
- model: Model<Api> | undefined,
140
- preferred: ThinkingLevel = DEFAULT_THINKING_LEVEL,
141
- ): ThinkingLevel {
142
- return model ? (clampThinkingLevel(model, preferred) as ThinkingLevel) : preferred;
143
- }
144
-
145
- function modelCapabilities(model: ModelListEntry): string {
146
- const input = model.input.includes("image") ? "vision" : "text-only";
147
- const thinking = getSupportedThinkingLevels(model as Model<Api>).join("/");
148
- return `${input} · thinking: ${thinking}`;
149
- }
150
-
151
- /** Build one searchable list for agent model selection. Only models Pi
152
- * currently reports as available are supplied by setup. */
153
- export function buildModelPickerItems(options: {
154
- models: readonly ModelListEntry[];
155
- configuredRef?: string;
156
- mainRef?: string;
157
- }): ModelPickerItem[] {
158
- const configuredRef = cleanModelRef(options.configuredRef);
159
- const mainRef = cleanModelRef(options.mainRef);
160
- const byRef = new Map<string, ModelListEntry>();
161
- for (const model of options.models) {
162
- const ref = modelRef(model);
163
- if (!byRef.has(ref)) byRef.set(ref, model);
164
- }
165
-
166
- const refs = [...byRef.keys()]
167
- .sort((left, right) => {
168
- const leftRank = left === configuredRef ? 0 : left === mainRef ? 1 : 2;
169
- const rightRank = right === configuredRef ? 0 : right === mainRef ? 1 : 2;
170
- return leftRank - rightRank || left.localeCompare(right);
171
- });
172
-
173
- const dynamic: ModelPickerItem = {
174
- value: CURRENT_MAIN_MODEL,
175
- label: "Current main model (dynamic)",
176
- description: "Clear agent override; use the current main model dynamically",
177
- };
178
- const items: ModelPickerItem[] = [dynamic];
179
- for (const ref of refs) {
180
- const model = byRef.get(ref)!;
181
- const tags = [ref === configuredRef ? "configured" : "", ref === mainRef ? "current main" : ""]
182
- .filter(Boolean);
183
- const name = model.name.trim() && model.name !== model.id ? model.name.trim() : undefined;
184
- items.push({
185
- value: ref,
186
- label: ref,
187
- description: [name, modelCapabilities(model), ...tags].filter(Boolean).join(" · "),
188
- });
189
- }
190
- return items;
191
- }
192
-
193
- /** The dynamic choice removes the persisted per-agent override. */
194
- export function applyAgentModelChoice(
195
- current: Record<string, string>,
196
- agentName: string,
197
- choice: string,
198
- ): Record<string, string> {
199
- const next = { ...current };
200
- if (choice === CURRENT_MAIN_MODEL) delete next[agentName];
201
- else next[agentName] = choice.trim();
202
- return next;
203
- }
1
+ /*
2
+ * Model routing, capability-aware thinking, and setup-picker helpers.
3
+ *
4
+ * Runtime has one explicit fallback only: a configured agent model hands
5
+ * off directly to the current main-window model. Setup lists only currently
6
+ * available models and derives thinking choices from Pi's model metadata.
7
+ */
8
+
9
+ import {
10
+ clampThinkingLevel,
11
+ getSupportedThinkingLevels,
12
+ type Api,
13
+ type Model,
14
+ } from "@earendil-works/pi-ai";
15
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
+ import { DEFAULT_THINKING_LEVEL, type ThinkingLevel } from "./config.ts";
17
+
18
+ export type ModelContext = Pick<ExtensionContext, "model" | "modelRegistry"> &
19
+ Partial<Pick<ExtensionContext, "scopedModels">>;
20
+
21
+ export const CURRENT_MAIN_MODEL = "__current_main_model__";
22
+
23
+ export interface ModelPickerItem {
24
+ value: string;
25
+ label: string;
26
+ description?: string;
27
+ }
28
+
29
+ export type ModelListEntry = Pick<
30
+ Model<Api>,
31
+ "provider" | "id" | "name" | "input" | "reasoning" | "thinkingLevelMap"
32
+ >;
33
+
34
+ export interface ResolvedAgentModelRoute {
35
+ /** Effective first candidate. Undefined means let Pi use its normal default. */
36
+ primaryRef?: string;
37
+ /** Current main-window model when it differs from the selection. */
38
+ mainFallbackRef?: string;
39
+ /** Runtime order, useful for status/tests. */
40
+ candidateRefs: string[];
41
+ /** Configured ref skipped because Pi does not currently report it available. */
42
+ unavailableSelectedRef?: string;
43
+ }
44
+
45
+ export interface AgentModelRouteInput {
46
+ selectedRef?: string;
47
+ mainRef?: string;
48
+ /** When supplied, a configured selection outside this live set is skipped. */
49
+ availableRefs?: readonly string[];
50
+ }
51
+
52
+ function cleanModelRef(ref: string | undefined): string | undefined {
53
+ const trimmed = ref?.trim();
54
+ return trimmed || undefined;
55
+ }
56
+
57
+ export function modelRef(model: { provider: string; id: string }): string {
58
+ return `${model.provider}/${model.id}`;
59
+ }
60
+
61
+ export function currentModelRef(ctx: Pick<ModelContext, "model">): string | undefined {
62
+ return ctx.model ? modelRef(ctx.model) : undefined;
63
+ }
64
+
65
+ /**
66
+ * Current authenticated registry models narrowed by the session scope. Scope
67
+ * entries are a session snapshot, so they act only as a whitelist; the live
68
+ * registry remains the source of truth for availability and model metadata.
69
+ */
70
+ export function availableModelsInScope(ctx: ModelContext): readonly Model<Api>[] {
71
+ const models = ctx.modelRegistry.getAvailable();
72
+ // scopedModels was added after the original Pi minimum. Treat a missing field
73
+ // exactly like an empty scope and use the full live registry.
74
+ const scopedModels = ctx.scopedModels ?? [];
75
+ if (scopedModels.length === 0) return models;
76
+ const scopedRefs = new Set(scopedModels.map((entry) => modelRef(entry.model)));
77
+ return models.filter((model) => scopedRefs.has(modelRef(model)));
78
+ }
79
+
80
+ export function findModelByRef(
81
+ models: readonly Model<Api>[],
82
+ ref: string | undefined,
83
+ ): Model<Api> | undefined {
84
+ const normalized = cleanModelRef(ref);
85
+ return normalized ? models.find((model) => modelRef(model) === normalized) : undefined;
86
+ }
87
+
88
+ /** Split persisted agent model overrides into the ones Pi still reports as
89
+ * available and the stale ones. Stale refs are dropped at session start (with
90
+ * a user notice) so the config never carries models that can no longer run. */
91
+ export function filterUnavailableModelOverrides(
92
+ agentModels: Record<string, string>,
93
+ models: readonly Model<Api>[],
94
+ ): { kept: Record<string, string>; dropped: Array<{ agent: string; ref: string }> } {
95
+ const kept: Record<string, string> = {};
96
+ const dropped: Array<{ agent: string; ref: string }> = [];
97
+ for (const [agent, ref] of Object.entries(agentModels)) {
98
+ if (findModelByRef(models, ref)) kept[agent] = ref;
99
+ else dropped.push({ agent, ref });
100
+ }
101
+ return { kept, dropped };
102
+ }
103
+
104
+ /**
105
+ * Resolve one agent's runtime route:
106
+ *
107
+ * configured selection -> current main-window model
108
+ *
109
+ * Without an override the current main model is primary, so an agent never
110
+ * pins its own model. A configured selection that Pi no longer reports as
111
+ * available is skipped immediately instead of spawning a doomed child.
112
+ */
113
+ export function resolveAgentModelRoute(input: AgentModelRouteInput): ResolvedAgentModelRoute {
114
+ const selectedRef = cleanModelRef(input.selectedRef);
115
+ const mainRef = cleanModelRef(input.mainRef);
116
+ const available = input.availableRefs
117
+ ? new Set(input.availableRefs.map((ref) => ref.trim()).filter(Boolean))
118
+ : undefined;
119
+ const selectedAvailable = !selectedRef || !available || available.has(selectedRef);
120
+ const usableSelectedRef = selectedAvailable ? selectedRef : undefined;
121
+ const primaryRef = usableSelectedRef ?? mainRef;
122
+ const ordered = [primaryRef, usableSelectedRef && usableSelectedRef !== mainRef ? mainRef : undefined];
123
+ const candidateRefs = [...new Set(ordered.filter((ref): ref is string => Boolean(ref)))];
124
+ return {
125
+ primaryRef,
126
+ ...(candidateRefs[1] ? { mainFallbackRef: candidateRefs[1] } : {}),
127
+ candidateRefs,
128
+ ...(!selectedAvailable && selectedRef ? { unavailableSelectedRef: selectedRef } : {}),
129
+ };
130
+ }
131
+
132
+ /** The exact levels Pi exposes for this model, including `off` when supported. */
133
+ export function supportedThinkingLevels(model: Model<Api> | undefined): ThinkingLevel[] {
134
+ return model ? (getSupportedThinkingLevels(model) as ThinkingLevel[]) : [];
135
+ }
136
+
137
+ /** Clamp an agent preference to the effective model's actual capability map. */
138
+ export function resolveThinkingLevel(
139
+ model: Model<Api> | undefined,
140
+ preferred: ThinkingLevel = DEFAULT_THINKING_LEVEL,
141
+ ): ThinkingLevel {
142
+ return model ? (clampThinkingLevel(model, preferred) as ThinkingLevel) : preferred;
143
+ }
144
+
145
+ function modelCapabilities(model: ModelListEntry): string {
146
+ const input = model.input.includes("image") ? "vision" : "text-only";
147
+ const thinking = getSupportedThinkingLevels(model as Model<Api>).join("/");
148
+ return `${input} · thinking: ${thinking}`;
149
+ }
150
+
151
+ /** Build one searchable list for agent model selection. Only models Pi
152
+ * currently reports as available are supplied by setup. */
153
+ export function buildModelPickerItems(options: {
154
+ models: readonly ModelListEntry[];
155
+ configuredRef?: string;
156
+ mainRef?: string;
157
+ }): ModelPickerItem[] {
158
+ const configuredRef = cleanModelRef(options.configuredRef);
159
+ const mainRef = cleanModelRef(options.mainRef);
160
+ const byRef = new Map<string, ModelListEntry>();
161
+ for (const model of options.models) {
162
+ const ref = modelRef(model);
163
+ if (!byRef.has(ref)) byRef.set(ref, model);
164
+ }
165
+
166
+ const refs = [...byRef.keys()]
167
+ .sort((left, right) => {
168
+ const leftRank = left === configuredRef ? 0 : left === mainRef ? 1 : 2;
169
+ const rightRank = right === configuredRef ? 0 : right === mainRef ? 1 : 2;
170
+ return leftRank - rightRank || left.localeCompare(right);
171
+ });
172
+
173
+ const dynamic: ModelPickerItem = {
174
+ value: CURRENT_MAIN_MODEL,
175
+ label: "Current main model (dynamic)",
176
+ description: "Clear agent override; use the current main model dynamically",
177
+ };
178
+ const items: ModelPickerItem[] = [dynamic];
179
+ for (const ref of refs) {
180
+ const model = byRef.get(ref)!;
181
+ const tags = [ref === configuredRef ? "configured" : "", ref === mainRef ? "current main" : ""]
182
+ .filter(Boolean);
183
+ const name = model.name.trim() && model.name !== model.id ? model.name.trim() : undefined;
184
+ items.push({
185
+ value: ref,
186
+ label: ref,
187
+ description: [name, modelCapabilities(model), ...tags].filter(Boolean).join(" · "),
188
+ });
189
+ }
190
+ return items;
191
+ }
192
+
193
+ /** The dynamic choice removes the persisted per-agent override. */
194
+ export function applyAgentModelChoice(
195
+ current: Record<string, string>,
196
+ agentName: string,
197
+ choice: string,
198
+ ): Record<string, string> {
199
+ const next = { ...current };
200
+ if (choice === CURRENT_MAIN_MODEL) delete next[agentName];
201
+ else next[agentName] = choice.trim();
202
+ return next;
203
+ }
package/src/monitor.ts CHANGED
@@ -4,8 +4,9 @@
4
4
  *
5
5
  * The store notifies wait/status consumers on every mutation. Each run carries
6
6
  * timing information plus a concise activity string ("thinking",
7
- * "read src/index.ts", ...). Runs are removed after publication; tool results
8
- * and the finished-run registry are the durable user-facing records.
7
+ * "read src/index.ts", ...). Settled rows stay until the next beginTurn so the
8
+ * footer can count them beside live siblings; the widget ignores them. Tool
9
+ * results are the durable user-facing record.
9
10
  */
10
11
 
11
12
  import { stripVTControlCharacters } from "node:util";
package/src/prompt.ts CHANGED
@@ -35,6 +35,7 @@ export function buildDelegationDirective(
35
35
  "`executor`: brief it as the edit authorization. For cleanup, name the scope (uncommitted diff, Git range, directory) — every safe proven cut applies without per-item approval; finding no safe cut is a valid result. After a wide fan-out, pass the result-artifact paths to one executor and read its merged brief instead of every result yourself.",
36
36
  ]
37
37
  : []),
38
+ "A discovered defect is not a change: re-read the current code and confirm it is not a false positive before you edit or brief a writer to edit.",
38
39
  "Parallelize by default: map the todo list onto ONE `tasks` dispatch. One child owns one deliverable and its files; only genuinely dependent work waits for its prerequisite.",
39
40
  "Brief each child completely — goal, exact paths, constraints, expected output; it has no conversation memory and cannot delegate. Resume parked threads with `subagent_control resume`.",
40
41
  ];