@lune_99/pi-subagent 0.0.0-stage → 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.
Files changed (47) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/LICENSE +21 -0
  3. package/README.md +185 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +264 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +190 -0
  12. package/src/auto-model.ts +601 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +147 -0
  15. package/src/definitions.ts +330 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +328 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +194 -0
  20. package/src/inspector/details.ts +119 -0
  21. package/src/inspector/inspector.ts +677 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +69 -0
  27. package/src/notify/notification-box.ts +408 -0
  28. package/src/notify/notifier.ts +586 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +31 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +194 -0
  35. package/src/run/run-manager.ts +935 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +773 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +175 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +376 -0
  43. package/src/settings/panel.ts +221 -0
  44. package/src/settings/schema.ts +75 -0
  45. package/src/settings/thinking-choices.ts +92 -0
  46. package/src/tools/format.ts +397 -0
  47. package/src/tools/subagent-tools.ts +355 -0
@@ -0,0 +1,92 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import { getSupportedThinkingLevels, type Api, type Model } from "@earendil-works/pi-ai";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import type { SettingsChoice, SettingsChoiceSource } from "@lune_99/pi-lune-extensions-core/panel";
5
+ import type { DeepReadonly } from "@lune_99/pi-lune-extensions-core/settings";
6
+
7
+ import { AUTO_MODEL, allowedModels, formatModelRef } from "../models.ts";
8
+ import type { SubagentSettings } from "./schema.ts";
9
+
10
+ export function defaultThinkingChoice(
11
+ model: string | undefined,
12
+ values: DeepReadonly<SubagentSettings>,
13
+ ): SettingsChoice<ThinkingLevel | null> {
14
+ return model === AUTO_MODEL && values.autoClassifier
15
+ ? {
16
+ value: null,
17
+ label: "Automatic thinking",
18
+ description:
19
+ "Leave thinking out: the classifier chooses a supported level for each task. " +
20
+ "If classification fails, runs use the main agent's thinking.",
21
+ }
22
+ : {
23
+ value: null,
24
+ label: "Main agent's thinking",
25
+ description:
26
+ "Leave thinking out: runs use the main agent's level within model limits.",
27
+ };
28
+ }
29
+
30
+ export function thinkingChoices(
31
+ model: string | undefined,
32
+ values: DeepReadonly<SubagentSettings>,
33
+ current?: ThinkingLevel,
34
+ ): SettingsChoiceSource<ThinkingLevel | null> {
35
+ return {
36
+ load: ({ context }) => {
37
+ const fallback = defaultThinkingChoice(model, values);
38
+
39
+ if (model === AUTO_MODEL) {
40
+ return [fallback];
41
+ }
42
+
43
+ const levels = getSupportedThinkingLevels(thinkingModel(context, model, values));
44
+
45
+ return [
46
+ fallback,
47
+ ...levels.map((level) => ({ value: level, label: level })),
48
+ ...(current !== undefined && !levels.includes(current)
49
+ ? [
50
+ {
51
+ value: current,
52
+ label: `${current} · saved, unsupported`,
53
+ disabled:
54
+ "This saved level is not supported by the current model selection. " +
55
+ "Choose another level or remove the override.",
56
+ },
57
+ ]
58
+ : []),
59
+ ];
60
+ },
61
+ };
62
+ }
63
+
64
+ function thinkingModel(
65
+ context: ExtensionContext,
66
+ model: string | undefined,
67
+ values: DeepReadonly<SubagentSettings>,
68
+ ): Model<Api> {
69
+ const allowed = (): Model<Api>[] => allowedModels(context, values.allowedModels);
70
+ const selected = (ref: string, models: readonly Model<Api>[]): Model<Api> => {
71
+ const found = models.find((each) => formatModelRef(each) === ref);
72
+
73
+ if (!found) {
74
+ throw new Error(
75
+ `The model ${ref} is unavailable or not in the subagent allowed set. ` +
76
+ "Select an available model before choosing thinking.",
77
+ );
78
+ }
79
+
80
+ return found;
81
+ };
82
+
83
+ if (model !== undefined && model !== AUTO_MODEL) {
84
+ return selected(model, allowed());
85
+ }
86
+
87
+ if (!context.model) {
88
+ throw new Error("The main agent has no current model for thinking choices.");
89
+ }
90
+
91
+ return context.model;
92
+ }
@@ -0,0 +1,397 @@
1
+ import { userMessageHeading } from "../run/guide.ts";
2
+ import type { Run } from "../run/run.ts";
3
+ import type { AutoRating, AutoRisk, RunSnapshot, RunUsage, TurnRecord } from "../run/types.ts";
4
+
5
+ /** How much of a summary or task a run list shows; one run shows all of it. */
6
+ const PREVIEW_CHARS = 200;
7
+ const DIAGNOSTICS_SHOWN = 5;
8
+
9
+ /** The workspace lines `subagent_start` and `subagent_status` return. */
10
+ export function workspaceLines(run: Run): string[] {
11
+ const snapshot = run.snapshot;
12
+
13
+ if (!snapshot) {
14
+ return [];
15
+ }
16
+
17
+ const lines = [`Isolation: ${snapshot.isolation}`, `Working directory: ${snapshot.cwd}`];
18
+
19
+ if (snapshot.worktree) {
20
+ lines.push(
21
+ `Worktree: ${snapshot.worktree.path}`,
22
+ `Base commit: ${snapshot.worktree.baseCommit}`,
23
+ );
24
+ }
25
+
26
+ return lines;
27
+ }
28
+
29
+ /** The start values and where each came from. */
30
+ export function startValueLines(run: Run): string[] {
31
+ const snapshot = run.snapshot;
32
+
33
+ if (!snapshot) {
34
+ return [];
35
+ }
36
+
37
+ return [
38
+ `Agent: ${snapshot.definition ? snapshot.definition.name : "inline"}`,
39
+ `Model: ${snapshot.model} (${modelOrigin(snapshot)})`,
40
+ `Thinking: ${snapshot.thinking} (${thinkingOrigin(snapshot)})`,
41
+ `Tools: ${snapshot.tools.join(", ")} (from ${snapshot.sources.tools})`,
42
+ ];
43
+ }
44
+
45
+ function modelOrigin(snapshot: RunSnapshot): string {
46
+ const auto = snapshot.autoModel;
47
+
48
+ if (!auto) {
49
+ return `from ${snapshot.sources.model}`;
50
+ }
51
+
52
+ const origin = `auto from ${snapshot.sources.model}`;
53
+
54
+ switch (auto.by) {
55
+ case "rating": {
56
+ const { tier, modelFrom, risk } = auto;
57
+ const lowest = risk?.floor ?? tier.used;
58
+ const model =
59
+ modelFrom === lowest
60
+ ? `the ${lowest} tier's model`
61
+ : modelFrom === "main"
62
+ ? `no tier from ${lowest} up has a model, so the main agent's model`
63
+ : `the ${lowest} tier has no model, so the ${modelFrom} tier's model`;
64
+
65
+ return (
66
+ `${origin}: the classifier ${auto.classifier} rated the task ${ratingText(tier)}` +
67
+ (risk ? `, ${riskText(risk)}` : "") +
68
+ `; ${model}`
69
+ );
70
+ }
71
+ case "no-classifier":
72
+ return `${origin}: no classifier is selected, so the main agent's model`;
73
+ case "nothing-to-rate":
74
+ return `${origin}: no auto tier has a model and the thinking is set, so the main agent's model`;
75
+ case "classifier-failed":
76
+ return `${origin}: the main agent's model. ${auto.error}`;
77
+ default:
78
+ // A run that an earlier version started records its auto choice in another form.
79
+ return origin;
80
+ }
81
+ }
82
+
83
+ function thinkingOrigin(snapshot: RunSnapshot): string {
84
+ const auto = snapshot.autoModel;
85
+
86
+ return snapshot.sources.thinking === "auto" && auto?.by === "rating" && auto.thinking
87
+ ? `auto: the classifier rated the thinking ${ratingText(auto.thinking)}`
88
+ : `from ${snapshot.sources.thinking}`;
89
+ }
90
+
91
+ /** `complex (71%)`, and the level used instead when the classifier was unsure. */
92
+ export function ratingText(rating: AutoRating<string>): string {
93
+ const share = rating.probabilities[rating.rated];
94
+
95
+ return (
96
+ rating.rated +
97
+ (share === undefined ? "" : ` (${formatPercent(share)})`) +
98
+ (rating.used === rating.rated
99
+ ? ""
100
+ : `, unsure at ${formatPercent(rating.confidence)} confidence, so ${rating.used}`)
101
+ );
102
+ }
103
+
104
+ /** `high risk (72%), so at least the deep tier`, or `not high risk (12%)`. */
105
+ export function riskText(risk: AutoRisk): string {
106
+ return risk.high
107
+ ? `high risk (${formatPercent(risk.probability)})` +
108
+ (risk.floor ? `, so at least the ${risk.floor} tier` : "")
109
+ : `not high risk (${formatPercent(risk.probability)})`;
110
+ }
111
+
112
+ export function formatStarted(run: Run): string {
113
+ return [
114
+ startedHeading(run),
115
+ ...titleLines(run),
116
+ ...startValueLines(run),
117
+ ...workspaceLines(run),
118
+ "The run works in the background. A message arrives when its turn ends.",
119
+ ].join("\n");
120
+ }
121
+
122
+ /** One run in full: everything `subagent_status` knows, the last turn's whole report included. */
123
+ export function formatRunStatus(run: Run): string {
124
+ const lines = [heading(run), ...titleLines(run)];
125
+
126
+ if (run.loadError) {
127
+ lines.push(`The run file could not be read: ${run.loadError}`);
128
+
129
+ return lines.join("\n");
130
+ }
131
+
132
+ lines.push(...startValueLines(run), ...workspaceLines(run));
133
+ lines.push(`Turns: ${run.turns}`, `Usage: ${formatUsage(run.usage)}`);
134
+ lines.push(...runningLines(run));
135
+ lines.push(...diagnosticLines(run));
136
+ lines.push(...currentUserLines(run, false));
137
+ lines.push("", "Task:", run.snapshot?.task ?? "");
138
+
139
+ if (run.lastTurn) {
140
+ lines.push("", ...turnLines(run.lastTurn, false));
141
+ }
142
+
143
+ return lines.join("\n");
144
+ }
145
+
146
+ /** The runs of the current branch, one block each, with previews instead of whole reports. */
147
+ export function formatRunList(runs: readonly Run[], elsewhere: number): string {
148
+ const blocks = runs.map((run) => {
149
+ if (run.loadError) {
150
+ return [heading(run), `The run file could not be read: ${run.loadError}`].join("\n");
151
+ }
152
+
153
+ return [
154
+ heading(run),
155
+ ...titleLines(run),
156
+ ...startValueLines(run).slice(0, 1),
157
+ ...workspaceLines(run),
158
+ `Turns: ${run.turns} · Usage: ${formatUsage(run.usage)}`,
159
+ ...runningLines(run),
160
+ ...currentUserLines(run, true),
161
+ ...diagnosticLines(run),
162
+ ...(run.lastTurn ? turnLines(run.lastTurn, true) : []),
163
+ ].join("\n");
164
+ });
165
+ const notes: string[] = [];
166
+
167
+ if (runs.length === 0) {
168
+ notes.push("No subagent runs on the current branch.");
169
+ } else {
170
+ notes.push("Call subagent_status with a runId for a run's whole report.");
171
+ }
172
+
173
+ if (elsewhere > 0) {
174
+ notes.push(
175
+ `${elsewhere} run${elsewhere === 1 ? " belongs" : "s belong"} to other branches and ` +
176
+ `${elsewhere === 1 ? "is" : "are"} not listed.`,
177
+ );
178
+ }
179
+
180
+ return [...blocks, notes.join(" ")].join("\n\n");
181
+ }
182
+
183
+ export function formatUsage(usage: RunUsage): string {
184
+ return [
185
+ `${formatTokens(usage.input)} input`,
186
+ `${formatTokens(usage.output)} output`,
187
+ `${formatTokens(usage.cacheRead)} cache read`,
188
+ `${formatTokens(usage.cacheWrite)} cache write`,
189
+ `$${usage.cost.toFixed(3)}`,
190
+ ].join(" · ");
191
+ }
192
+
193
+ export function formatTokens(count: number): string {
194
+ if (count < 1000) {
195
+ return String(count);
196
+ }
197
+
198
+ if (count < 1_000_000) {
199
+ return `${(count / 1000).toFixed(1)}k`;
200
+ }
201
+
202
+ return `${(count / 1_000_000).toFixed(1)}M`;
203
+ }
204
+
205
+ /** `4.2s` / `1m 4s` / `1h 2m`. */
206
+ export function formatDuration(ms: number): string {
207
+ const seconds = ms / 1000;
208
+
209
+ if (seconds < 60) {
210
+ return `${seconds.toFixed(1)}s`;
211
+ }
212
+
213
+ const totalSeconds = Math.floor(seconds);
214
+ const minutes = Math.floor(totalSeconds / 60);
215
+
216
+ if (minutes < 60) {
217
+ return `${minutes}m ${totalSeconds % 60}s`;
218
+ }
219
+
220
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
221
+ }
222
+
223
+ /** `82%`: a value from 0 to 1 as a whole percentage. */
224
+ export function formatPercent(value: number): string {
225
+ return `${Math.round(value * 100)}%`;
226
+ }
227
+
228
+ function heading(run: Run): string {
229
+ return `Run ${run.id}: ${run.state}${run.readOnly ? ", read-only" : ""}`;
230
+ }
231
+
232
+ function startedHeading(run: Run): string {
233
+ return `Started run ${run.id}: ${run.state}.`;
234
+ }
235
+
236
+ /** The user-facing title stays out of the handle position, so it cannot be read as a run ID. */
237
+ function titleLines(run: Run): string[] {
238
+ const title = run.snapshot?.title;
239
+
240
+ return title === undefined ? [] : [`Title: ${title}`];
241
+ }
242
+
243
+ function runningLines(run: Run): string[] {
244
+ if (run.state !== "running") {
245
+ return [];
246
+ }
247
+
248
+ const started = run.turnStartedAt;
249
+ const lines = [
250
+ started
251
+ ? `Turn running for ${formatDuration(Date.now() - Date.parse(started))}`
252
+ : "Turn running",
253
+ ];
254
+
255
+ if (run.activity) {
256
+ lines.push(run.activity);
257
+ }
258
+
259
+ return lines;
260
+ }
261
+
262
+ /** What the user wrote during the turn in progress, which no notice has carried yet. */
263
+ function currentUserLines(run: Run, preview: boolean): string[] {
264
+ const messages = run.turnUserMessages;
265
+
266
+ if (messages.length === 0) {
267
+ return [];
268
+ }
269
+
270
+ const lines = [
271
+ "The user wrote to the run during this turn.",
272
+ ...userMessageLines(messages, preview),
273
+ ];
274
+
275
+ return preview ? lines : ["", ...lines];
276
+ }
277
+
278
+ /** Every message in full, each after a blank line, or the last one as a preview. */
279
+ function userMessageLines(messages: readonly string[], preview: boolean): string[] {
280
+ if (!preview) {
281
+ return messages.flatMap((text, index) => [
282
+ "",
283
+ userMessageHeading(index, messages.length),
284
+ text,
285
+ ]);
286
+ }
287
+
288
+ const last = messages.at(-1);
289
+
290
+ if (last === undefined) {
291
+ return [];
292
+ }
293
+
294
+ return [
295
+ messages.length === 1
296
+ ? `User message: ${clip(last)}`
297
+ : `User messages: ${messages.length}, the last: ${clip(last)}`,
298
+ ];
299
+ }
300
+
301
+ function diagnosticLines(run: Run): string[] {
302
+ const shown = run.diagnostics
303
+ .filter((diagnostic) => diagnostic.level !== "info")
304
+ .slice(-DIAGNOSTICS_SHOWN);
305
+
306
+ if (shown.length === 0) {
307
+ return [];
308
+ }
309
+
310
+ return [
311
+ "Diagnostics:",
312
+ ...shown.map((diagnostic) => ` ${diagnostic.level}: ${diagnostic.message}`),
313
+ ];
314
+ }
315
+
316
+ function turnLines(turn: TurnRecord, preview: boolean): string[] {
317
+ const duration = Date.parse(turn.endedAt) - Date.parse(turn.startedAt);
318
+ const lines = [
319
+ `Last turn: ${turn.state}, ended ${turn.endedAt}` +
320
+ (Number.isFinite(duration) ? ` after ${formatDuration(duration)}` : ""),
321
+ ];
322
+
323
+ if (turn.stoppedBy) {
324
+ lines.push(`Stopped by: ${turn.stoppedBy}`);
325
+ }
326
+
327
+ if (turn.userWrote) {
328
+ const messages = turn.userMessages ?? [];
329
+
330
+ lines.push(
331
+ "The user wrote to the run during that turn.",
332
+ ...userMessageLines(messages, preview),
333
+ );
334
+
335
+ if (!preview && messages.length > 0) {
336
+ lines.push("");
337
+ }
338
+ }
339
+
340
+ if (turn.error) {
341
+ lines.push(`Error: ${turn.error}`);
342
+ }
343
+
344
+ for (const earlier of turn.earlierReports ?? []) {
345
+ lines.push(`Earlier report in that turn, replaced by a later one: ${earlier.status}`);
346
+
347
+ if (preview) {
348
+ continue;
349
+ }
350
+
351
+ if (earlier.reason) {
352
+ lines.push(`Reason: ${earlier.reason}`);
353
+ }
354
+
355
+ if (earlier.question) {
356
+ lines.push(`Question: ${earlier.question}`);
357
+ }
358
+
359
+ lines.push("Summary:", earlier.summary, "");
360
+ }
361
+
362
+ if (turn.report) {
363
+ lines.push(`Report: ${turn.report.status}`);
364
+
365
+ if (turn.report.reason) {
366
+ lines.push(`Reason: ${turn.report.reason}`);
367
+ }
368
+
369
+ if (turn.report.question) {
370
+ lines.push(`Question: ${turn.report.question}`);
371
+ }
372
+
373
+ lines.push(preview ? `Summary: ${clip(turn.report.summary)}` : "Summary:");
374
+
375
+ if (!preview) {
376
+ lines.push(turn.report.summary);
377
+ }
378
+ } else {
379
+ const message = turn.unreportedMessage ?? "";
380
+
381
+ lines.push("No task status: the turn ended without a report.");
382
+
383
+ if (preview) {
384
+ lines.push(`Last message: ${message === "" ? "none" : clip(message)}`);
385
+ } else {
386
+ lines.push(message === "" ? "The run left no message." : "Last message:", message);
387
+ }
388
+ }
389
+
390
+ return lines;
391
+ }
392
+
393
+ function clip(text: string): string {
394
+ const line = text.replace(/\s+/g, " ").trim();
395
+
396
+ return line.length > PREVIEW_CHARS ? `${line.slice(0, PREVIEW_CHARS)}…` : line;
397
+ }