@lune_99/pi-subagent 0.1.0 → 0.2.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/src/auto-model.ts CHANGED
@@ -95,10 +95,12 @@ const TIER_QUESTION = {
95
95
  } satisfies ClassifierChoiceQuestion;
96
96
 
97
97
  const THINKING_INSTRUCTIONS =
98
- "Rate the least reasoning that the agent must do, before and between its steps, to complete " +
99
- "this task correctly. The options are thinking levels from least to most. Judge the " +
100
- "reasoning, not the amount of work: many files or steps need no more thinking, and a subtle " +
101
- "race condition in one function can need a lot.";
98
+ "Rate the reasoning that the agent must do, before and between its steps, to finish this " +
99
+ "task correctly and safely. Use the least level that is clearly enough, but raise it for " +
100
+ "work whose mistakes are hard to detect or whose correctness cannot be shown by running " +
101
+ "the result. The options are thinking levels from least to most. Judge the reasoning, not " +
102
+ "the amount of work: many files or steps need no more thinking, and a subtle race condition " +
103
+ "in one function can need a lot.";
102
104
 
103
105
  // A model-routing signal only: it never grants or blocks a tool, an approval or a permission.
104
106
  const RISK_QUESTION = {
@@ -139,29 +141,30 @@ const THINKING_CRITERIA = {
139
141
  low: "Brief planning over a few dependent steps, such as finding where a described change goes.",
140
142
  medium:
141
143
  "Plan several dependent steps and check the results along the way, such as tracing a " +
142
- "call path, fitting a change into existing code or debugging a failure that can be " +
143
- "reproduced.",
144
+ "call path, fitting a change into existing code or fixing a failure whose cause is " +
145
+ "stated.",
144
146
  high:
145
- "Weigh alternatives, form and test hypotheses, or reason about correctness, such as " +
146
- "finding a root cause or showing that a change is safe.",
147
+ "Investigate a failure that reproduces to find its cause, weigh a few approaches for a " +
148
+ "contained change, or confirm that a change meets its stated requirements.",
147
149
  xhigh:
148
- "Long chains of reasoning over many parts that affect each other, such as a concurrency " +
149
- "or state bug, a security review or a design with competing constraints.",
150
+ "Find the cause of a failure that does not reproduce, argue that a risky change is safe, " +
151
+ "or plan a change that spans unfamiliar components.",
150
152
  max:
151
- "The hardest reasoning, where a mistake is costly and every step needs checking, such as " +
152
- "showing that an algorithm is correct or finding a subtle data-loss bug across systems.",
153
+ "Reason about correctness that is hard to check, where a mistake is costly and easy to " +
154
+ "miss: subtle concurrency, state or data-loss defects, security or privacy boundaries, " +
155
+ "migrations or algorithms with invariants, or design trade-offs between constraints.",
153
156
  } satisfies Record<ThinkingLevel, string>;
154
157
 
155
158
  export interface AutoModelInput {
156
159
  ctx: ExtensionContext;
157
160
  settings: AutoModelSettings;
161
+ /** The effective subagent allowlist; uses the parent's scope when omitted. */
162
+ models?: readonly Model<Api>[];
158
163
  task: string;
159
164
  definition?: AgentDefinition;
160
165
  /** The selected task tools; undefined for the defaultTools selection. */
161
166
  tools?: readonly string[];
162
167
  isolation: Isolation;
163
- /** The call or the definition set the thinking level, so the rating must not. */
164
- thinkingSet: boolean;
165
168
  signal?: AbortSignal;
166
169
  }
167
170
 
@@ -174,7 +177,7 @@ export type AutoClassifier = Pick<
174
177
  export interface AutoModelResult {
175
178
  ref: ModelRef;
176
179
  choice: AutoModelChoice;
177
- /** From the thinking rating, when the start set no thinking level. */
180
+ /** The routed thinking level, including the only level a model supports. */
178
181
  thinking?: ThinkingLevel;
179
182
  }
180
183
 
@@ -182,9 +185,9 @@ export interface AutoModelResult {
182
185
  * Resolve `model: auto`. The classifier rates the task's tier and whether it is high risk; the
183
186
  * tier's model, or the next tier up that has one, runs it, and the main agent's model is the
184
187
  * ceiling. A high-risk task gets at least the floor tier's model, but keeps its rated tier, so the
185
- * difficulty and the risk stay apart. Unless the start set the
186
- * thinking, the classifier also rates it among the levels that Pi says the run's model supports:
187
- * in the same request when every model that the tier can lead to supports the same levels, else
188
+ * difficulty and the risk stay apart. The classifier also rates the thinking among the levels
189
+ * that Pi says the run's model supports: in the same request when every model that the tier can
190
+ * lead to supports the same levels, else
188
191
  * in a second request once the model is known. When the classifier fails, the run gets the main
189
192
  * agent's model and thinking, and the choice records why. A tier model outside the allowed set is
190
193
  * a settings error and fails the start.
@@ -196,11 +199,6 @@ export async function chooseAutoModel(input: AutoModelInput): Promise<AutoModelR
196
199
  return { ref: modelRef(mainModel(ctx)), choice: { by: "no-classifier" } };
197
200
  }
198
201
 
199
- // With no tier model, the rating could only set the thinking, and the start already did.
200
- if (input.thinkingSet && AUTO_TIERS.every((tier) => settings.tiers[tier] === null)) {
201
- return { ref: modelRef(mainModel(ctx)), choice: { by: "nothing-to-rate" } };
202
- }
203
-
204
202
  const classifierRef = formatModelRef(settings.classifier);
205
203
  const failed = (error: unknown): AutoModelResult => {
206
204
  // A cancelled start stops; any other failure leaves the run the main agent's settings.
@@ -218,7 +216,8 @@ export async function chooseAutoModel(input: AutoModelInput): Promise<AutoModelR
218
216
  };
219
217
  };
220
218
  // Undefined when the levels depend on the tier's model, so a second request asks for them.
221
- const levels = input.thinkingSet ? [] : sharedLevels(ctx, settings);
219
+ const models = input.models ?? allowedModels(ctx);
220
+ const levels = sharedLevels(ctx, settings, models);
222
221
  let classifier: ClassifierModel<ClassifierApi>;
223
222
  let tier: AutoRating<AutoTier>;
224
223
  let thinking: AutoRating<ThinkingLevel> | undefined;
@@ -250,7 +249,7 @@ export async function chooseAutoModel(input: AutoModelInput): Promise<AutoModelR
250
249
  const model =
251
250
  modelFrom === "main"
252
251
  ? mainModel(ctx)
253
- : tierModel(ctx, modelFrom, settings.tiers[modelFrom]!);
252
+ : tierModel(modelFrom, settings.tiers[modelFrom]!, models);
254
253
  const supported = getSupportedThinkingLevels(model);
255
254
 
256
255
  if (!levels && supported.length > 1) {
@@ -279,7 +278,7 @@ export async function chooseAutoModel(input: AutoModelInput): Promise<AutoModelR
279
278
  ...(thinking ? { thinking } : {}),
280
279
  risk,
281
280
  },
282
- ...(thinking ? { thinking: thinking.used } : {}),
281
+ thinking: thinking?.used ?? supported[0]!,
283
282
  };
284
283
  }
285
284
 
@@ -290,9 +289,9 @@ export async function chooseAutoModel(input: AutoModelInput): Promise<AutoModelR
290
289
  function sharedLevels(
291
290
  ctx: ExtensionContext,
292
291
  settings: AutoModelSettings,
292
+ allowed: readonly Model<Api>[],
293
293
  ): readonly ThinkingLevel[] | undefined {
294
- const allowed = allowedModels(ctx);
295
- // A model that the scope no longer allows fails the start if the tier leads to it.
294
+ // A model no longer in the allowed set fails the start if the tier leads to it.
296
295
  const models = AUTO_TIERS.flatMap((tier) => {
297
296
  const ref = settings.tiers[tier];
298
297
  const model = ref && allowed.find((each) => sameModel(each, ref));
@@ -310,10 +309,22 @@ function sharedLevels(
310
309
  }
311
310
 
312
311
  function thinkingQuestion(levels: readonly ThinkingLevel[]): ClassifierChoiceQuestion {
312
+ const top = levels.at(-1)!;
313
+
313
314
  return {
314
315
  type: "choice",
315
316
  instructions: THINKING_INSTRUCTIONS,
316
- criteria: Object.fromEntries(levels.map((level) => [level, THINKING_CRITERIA[level]])),
317
+ criteria: Object.fromEntries(
318
+ levels.map((level) => [
319
+ level,
320
+ // A model with fewer levels needs its top one to take the work that a higher level
321
+ // would rate, or a hard task falls to a lower level instead.
322
+ level === top && level !== "max"
323
+ ? `${THINKING_CRITERIA[level]} Also use this level for work that needs more ` +
324
+ "reasoning than this, because the run's model has no higher thinking level."
325
+ : THINKING_CRITERIA[level],
326
+ ]),
327
+ ),
317
328
  };
318
329
  }
319
330
 
@@ -331,8 +342,8 @@ async function findClassifier(
331
342
 
332
343
  if (!classifier) {
333
344
  throw new Error(
334
- `The auto classifier ${formatModelRef(ref)} is unavailable. Configure its provider in ` +
335
- "Pi, or select another classifier in the Subagents section of /lune-core-settings.",
345
+ `The classifier ${formatModelRef(ref)} is unavailable. Configure its provider in ` +
346
+ "Pi, or select another one in /lune-core-settings → Subagents → Classifier model.",
336
347
  );
337
348
  }
338
349
 
@@ -414,7 +425,7 @@ export function autoModelRequest(
414
425
  throw new Error(
415
426
  `The auto classifier ${formatModelRef(classifier)} has a context window of ` +
416
427
  `${classifier.contextWindow} tokens, too small for this task. Select a classifier ` +
417
- "with a larger window in the Subagents section of /lune-core-settings.",
428
+ "with a larger window in /lune-core-settings → Subagents → Classifier model.",
418
429
  );
419
430
  }
420
431
 
@@ -517,9 +528,8 @@ function mainModel(ctx: ExtensionContext): Model<Api> {
517
528
  return ctx.model;
518
529
  }
519
530
 
520
- /** A tier's model must still be one the parent allows; the scope can change after it was set. */
521
- function tierModel(ctx: ExtensionContext, tier: AutoTier, ref: ModelRef): Model<Api> {
522
- const allowed = allowedModels(ctx);
531
+ /** A tier's model must still be allowed; the selection can change after it was set. */
532
+ function tierModel(tier: AutoTier, ref: ModelRef, allowed: readonly Model<Api>[]): Model<Api> {
523
533
  const model = allowed.find((each) => sameModel(each, ref));
524
534
 
525
535
  if (!model) {
@@ -528,8 +538,7 @@ function tierModel(ctx: ExtensionContext, tier: AutoTier, ref: ModelRef): Model<
528
538
  throw new Error(
529
539
  `The ${tier} auto tier uses ${formatModelRef(ref)}, which is not in the allowed set` +
530
540
  (refs.length > 0 ? `: ${refs.join(", ")}.` : "; no models are available.") +
531
- " Select another model under Auto tiers in the Subagents section of " +
532
- "/lune-core-settings.",
541
+ " Select another model in /lune-core-settings → Subagents → Auto tiers.",
533
542
  );
534
543
  }
535
544
 
@@ -2,9 +2,10 @@ import { randomBytes } from "node:crypto";
2
2
  import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join } from "node:path";
4
4
 
5
- import { parseDocument } from "yaml";
5
+ import { isMap, isNode, isScalar, parseDocument } from "yaml";
6
6
 
7
7
  import { parseDefinition, type AgentDefinition } from "./definitions.ts";
8
+ import { AUTO_MODEL } from "./models.ts";
8
9
 
9
10
  /** The frontmatter fields the settings panel edits; the body stays as written. */
10
11
  export type DefinitionField = "name" | "description" | "model" | "thinking" | "tools" | "isolation";
@@ -104,6 +105,40 @@ export function setFrontmatterField(
104
105
  document.set(field, document.createNode([...value], { flow: true }));
105
106
  }
106
107
 
108
+ if (field === "model" && value === AUTO_MODEL) {
109
+ if (isMap(document.contents)) {
110
+ const items = document.contents.items;
111
+ const index = items.findIndex(
112
+ (item) => isScalar(item.key) && item.key.value === "thinking",
113
+ );
114
+ const removed = items[index];
115
+
116
+ if (removed) {
117
+ // Removing the override must not discard the user's notes attached to its nodes.
118
+ const comments = [removed.key, removed.value].flatMap((node) =>
119
+ isNode(node)
120
+ ? [node.commentBefore, node.comment].filter((comment) => comment != null)
121
+ : [],
122
+ );
123
+ const next = items[index + 1]?.key;
124
+
125
+ if (comments.length > 0) {
126
+ if (isNode(next)) {
127
+ next.commentBefore = [...comments, next.commentBefore]
128
+ .filter((comment) => comment != null)
129
+ .join("\n");
130
+ } else {
131
+ document.comment = [...comments, document.comment]
132
+ .filter((comment) => comment != null)
133
+ .join("\n");
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ document.delete("thinking");
140
+ }
141
+
107
142
  return `---\n${document.toString({ flowCollectionPadding: false }).trimEnd()}${normalized.slice(end)}`;
108
143
  }
109
144
 
@@ -217,6 +217,12 @@ export function parseDefinition(
217
217
  definition.thinking = oneOf(fields, "thinking", THINKING_LEVELS);
218
218
  }
219
219
 
220
+ if (definition.model === AUTO_MODEL && definition.thinking !== undefined) {
221
+ throw new Error(
222
+ "Model auto chooses both the model and thinking level; remove thinking from this definition.",
223
+ );
224
+ }
225
+
220
226
  if (fields.isolation !== undefined) {
221
227
  definition.isolation = oneOf(fields, "isolation", ISOLATION_MODES);
222
228
  }
@@ -7,6 +7,7 @@ import {
7
7
  type LuneDockSnapshot,
8
8
  } from "@lune_99/pi-lune-extensions-core/dock";
9
9
 
10
+ import { displayedStatus } from "../notify/notification-box.ts";
10
11
  import { fitRanked, type RankedPart } from "../render/text.ts";
11
12
  import type { RunManager } from "../run/run-manager.ts";
12
13
  import type { Run } from "../run/run.ts";
@@ -22,7 +23,6 @@ type DockStatus =
22
23
  | "blocked"
23
24
  | "failed"
24
25
  | "interrupted"
25
- | "unreported"
26
26
  | "done"
27
27
  | "idle";
28
28
 
@@ -36,7 +36,6 @@ const STATUS_RANKS: ReadonlyArray<readonly [DockStatus, number]> = [
36
36
  ["blocked", 9],
37
37
  ["failed", 10],
38
38
  ["interrupted", 5],
39
- ["unreported", 4],
40
39
  ["done", 3],
41
40
  ["idle", 2],
42
41
  ];
@@ -45,8 +44,8 @@ const LATEST_RANK = 1;
45
44
  const HINT_RANK = 0;
46
45
 
47
46
  /**
48
- * The Dock item of the runs on the current branch, and of runs on other branches whose ended turn
49
- * waits for that branch. Its lines count the runs by status and never cut a part: a narrow cell
47
+ * The Dock item of the runs on the current branch, and of runs on other branches that still work
48
+ * or whose ended turn waits for that branch. Its lines count the runs by status and never cut a part: a narrow cell
50
49
  * leaves out whole parts, then the title. A failed or blocked turn turns the marker red for a short
51
50
  * time, or until the user sees the run in the inspector; a later failure turns it red again.
52
51
  */
@@ -94,7 +93,10 @@ export class SubagentDockContribution {
94
93
  }
95
94
  }
96
95
 
97
- /** This branch's runs, and the runs of other branches whose ended turn waits for that branch. */
96
+ /**
97
+ * This branch's runs, and the runs of other branches that still work, such as runs kept running
98
+ * on a tree navigation, or whose ended turn waits for their branch.
99
+ */
98
100
  private runs(): { here: Run[]; elsewhere: Run[] } {
99
101
  const manager = this.manager;
100
102
 
@@ -104,7 +106,12 @@ export class SubagentDockContribution {
104
106
 
105
107
  const { here, elsewhere } = manager.runsByBranch();
106
108
 
107
- return { here, elsewhere: elsewhere.filter((run) => manager.hasDeferred(run)) };
109
+ return {
110
+ here,
111
+ elsewhere: elsewhere.filter(
112
+ (run) => run.state === "running" || manager.hasDeferred(run),
113
+ ),
114
+ };
108
115
  }
109
116
 
110
117
  private alarming(run: Run): boolean {
@@ -205,7 +212,7 @@ export class SubagentDockContribution {
205
212
  return latest
206
213
  ? [
207
214
  {
208
- text: theme.fg("muted", `latest: ${latest.name} ${dockStatus(latest)}`),
215
+ text: theme.fg("muted", `latest: ${latest.title} ${dockStatus(latest)}`),
209
216
  rank: LATEST_RANK,
210
217
  },
211
218
  ]
@@ -244,7 +251,10 @@ function dockStatus(run: Run): DockStatus {
244
251
  return run.state;
245
252
  }
246
253
 
247
- switch (run.lastTurn?.report?.status) {
254
+ switch (
255
+ run.lastTurn &&
256
+ displayedStatus(run.state, run.lastTurn.report?.status, run.lastTurn.cutShort)
257
+ ) {
248
258
  case "needs_input":
249
259
  return "needs input";
250
260
  case "blocked":
@@ -252,7 +262,7 @@ function dockStatus(run: Run): DockStatus {
252
262
  case "done":
253
263
  return "done";
254
264
  default:
255
- return run.lastTurn ? "unreported" : "idle";
265
+ return "idle";
256
266
  }
257
267
  }
258
268
 
package/src/index.ts CHANGED
@@ -94,6 +94,8 @@ export default function (pi: ExtensionAPI): void {
94
94
  projectTrusted: ctx.isProjectTrusted(),
95
95
  });
96
96
 
97
+ const view = await settings.view(ctx);
98
+
97
99
  manager = new RunManager({
98
100
  pi,
99
101
  ctx,
@@ -102,20 +104,44 @@ export default function (pi: ExtensionAPI): void {
102
104
  extensionTools,
103
105
  autoModelSettings: async (startCtx) =>
104
106
  autoModelSettings((await settings.view(startCtx)).snapshot()),
107
+ modelSelection: async (startCtx) =>
108
+ (await settings.view(startCtx)).get("allowedModels"),
109
+ autoOnly: async (startCtx) => (await settings.view(startCtx)).get("autoOnly"),
105
110
  });
106
111
  manager.restore();
107
112
  toolCatalog = addExtensionTools(catalog, extensionTools());
108
113
 
109
- // Built once per session: the declarations stay the same for every turn of it. Tools that
110
- // other extensions register later are missing from the list, but runs can still select them.
111
- for (const tool of createSubagentTools({
112
- manager,
113
- definitions,
114
- models: allowedModelRefs(ctx),
115
- catalog: toolCatalog,
116
- })) {
117
- pi.registerTool(tool);
118
- }
114
+ const runManager = manager;
115
+ const sessionCatalog = toolCatalog;
116
+ let registeredSchema: string | undefined;
117
+ const registerTools = (): void => {
118
+ const models = allowedModelRefs(ctx, view.get("allowedModels"));
119
+ const autoOnly = view.get("autoOnly");
120
+ const schema = JSON.stringify({ models, autoOnly });
121
+
122
+ if (schema === registeredSchema) {
123
+ return;
124
+ }
125
+
126
+ const tools = createSubagentTools({
127
+ manager: runManager,
128
+ definitions,
129
+ models,
130
+ autoOnly,
131
+ catalog: sessionCatalog,
132
+ });
133
+
134
+ // Only the allowlist and Auto mode only replace the start schema; other settings
135
+ // keep it stable.
136
+ for (const tool of registeredSchema ? tools.slice(0, 1) : tools) {
137
+ pi.registerTool(tool);
138
+ }
139
+
140
+ registeredSchema = schema;
141
+ };
142
+
143
+ registerTools();
144
+ resources.defer(view.subscribe(registerTools));
119
145
 
120
146
  roster = renderRoster(definitions);
121
147
  pi.events.emit(
@@ -1,6 +1,7 @@
1
1
  import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
2
2
  import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
3
 
4
+ import { displayedStatus } from "../notify/notification-box.ts";
4
5
  import { displayLines } from "../render/text.ts";
5
6
  import type { Run } from "../run/run.ts";
6
7
  import { formatDuration, formatTokens, startValueLines, workspaceLines } from "../tools/format.ts";
@@ -24,7 +25,7 @@ export function detailRows(run: Run, theme: Theme, width: number): string[] {
24
25
  };
25
26
 
26
27
  section("Run");
27
- line(`${run.name} (${run.id}) · ${run.state}${run.readOnly ? " · read-only" : ""}`);
28
+ line(`${run.title} (${run.id}) · ${run.state}${run.readOnly ? " · read-only" : ""}`);
28
29
  line(`File: ${run.file}`, "muted");
29
30
 
30
31
  if (run.readOnly) {
@@ -71,8 +72,13 @@ export function detailRows(run: Run, theme: Theme, width: number): string[] {
71
72
  const duration = Date.parse(turn.endedAt) - Date.parse(turn.startedAt);
72
73
 
73
74
  line(
74
- `${turn.state} · ${turn.report?.status ?? "unreported"}` +
75
- (Number.isFinite(duration) ? ` · ${formatDuration(duration)}` : ""),
75
+ [
76
+ turn.state,
77
+ displayedStatus(turn.state, turn.report?.status, turn.cutShort),
78
+ Number.isFinite(duration) ? formatDuration(duration) : undefined,
79
+ ]
80
+ .filter((part) => part !== undefined)
81
+ .join(" · "),
76
82
  );
77
83
 
78
84
  if (turn.stoppedBy) {