@lune_99/pi-subagent 0.0.0-stage → 0.1.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 (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +240 -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 +186 -0
  12. package/src/auto-model.ts +592 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +112 -0
  15. package/src/definitions.ts +324 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +318 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +168 -0
  20. package/src/inspector/details.ts +113 -0
  21. package/src/inspector/inspector.ts +653 -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 +54 -0
  27. package/src/notify/notification-box.ts +381 -0
  28. package/src/notify/notifier.ts +569 -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 +26 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +193 -0
  35. package/src/run/run-manager.ts +838 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +681 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +167 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +363 -0
  43. package/src/settings/panel.ts +179 -0
  44. package/src/settings/schema.ts +71 -0
  45. package/src/tools/format.ts +375 -0
  46. package/src/tools/subagent-tools.ts +467 -0
@@ -0,0 +1,592 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import {
3
+ getSupportedThinkingLevels,
4
+ type Api,
5
+ type ClassifierAnswer,
6
+ type ClassifierApi,
7
+ type ClassifierBoolQuestion,
8
+ type ClassifierChoiceQuestion,
9
+ type ClassifierContext,
10
+ type ClassifierModel,
11
+ type JsonObject,
12
+ type Model,
13
+ } from "@earendil-works/pi-ai";
14
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
15
+
16
+ import type { AgentDefinition } from "./definitions.ts";
17
+ import { allowedModels, formatModelRef, type ModelRef } from "./models.ts";
18
+ import {
19
+ AUTO_TIERS,
20
+ type AutoModelChoice,
21
+ type AutoRating,
22
+ type AutoRisk,
23
+ type AutoTier,
24
+ type Isolation,
25
+ } from "./run/types.ts";
26
+
27
+ /** The Lune settings that `model: auto` reads at each start. */
28
+ export interface AutoModelSettings {
29
+ /** Without a classifier, auto runs use the main agent's model and thinking. */
30
+ classifier: ModelRef | null;
31
+ /** The model of each tier; a task whose tier has none uses the next tier up that has one. */
32
+ tiers: Readonly<Record<AutoTier, ModelRef | null>>;
33
+ /** The lowest tier whose model a high-risk task may use; null leaves the model as rated. */
34
+ riskFloor: AutoTier | null;
35
+ /** The high-risk probability from which a task counts as high risk. */
36
+ riskThreshold: number;
37
+ }
38
+
39
+ export const DEFAULT_AUTO_MODEL_SETTINGS: AutoModelSettings = {
40
+ classifier: null,
41
+ tiers: { light: null, standard: null, complex: null, deep: null },
42
+ // A missed high-risk task costs more than a false alarm, so the default is below one half.
43
+ riskFloor: "deep",
44
+ riskThreshold: 0.4,
45
+ };
46
+
47
+ /** Below this confidence the classifier is unsure, and the run uses the next level up. */
48
+ const UNSURE_CONFIDENCE = 0.5;
49
+
50
+ // The classifier's window counts tokens of a tokenizer that the code does not know. A byte-level
51
+ // tokenizer gives each token at least one byte, so the request's UTF-8 bytes bound its tokens.
52
+
53
+ /** A rating needs the task's goal, not all of its text, and a shorter request is faster. */
54
+ const MAX_REQUEST_BYTES = 32_768;
55
+
56
+ /** Room in the window for the prompt that the classifier puts around the request, in tokens. */
57
+ const TEMPLATE_TOKENS = 512;
58
+
59
+ /** Less of the task and the instructions than this is too little to rate, so the start fails. */
60
+ const MIN_TEXT_BYTES = 1_024;
61
+
62
+ const EDIT_TOOLS = new Set(["edit", "write"]);
63
+ const COMMAND_TOOLS = new Set(["bash"]);
64
+
65
+ // The classifier knows nothing about models, so it rates the task and the code picks the model.
66
+ // Difficulty, reasoning and risk are separate questions; each criterion names traits that can be
67
+ // checked in the task and says what the option is not for.
68
+ const TIER_QUESTION = {
69
+ type: "choice",
70
+ instructions:
71
+ "Rate the least model capability that this delegated coding task needs: how hard the " +
72
+ "thinking is for the agent that will run it. The agent starts with only the task text, " +
73
+ "its role and its tools from the state. Judge the difficulty, not the risk, the number " +
74
+ "of files or steps, or the length of the text.",
75
+ criteria: {
76
+ light:
77
+ "Mechanical, deterministic work with almost no inference of its own: lookups, " +
78
+ "extraction, running given checks and reporting the results, or exactly specified " +
79
+ "edits, also across many files. Not for: changes that need judgment.",
80
+ standard:
81
+ "Routine features, local fixes, ordinary tests and local reviews, where the " +
82
+ "requirements and the acceptance criteria are clear and the path is known. Not for: " +
83
+ "unclear causes, open design choices, or work across components.",
84
+ complex:
85
+ "Multi-step analysis, work across components, a non-trivial implementation, or " +
86
+ "finding the cause of a failure that can be reproduced. The goal is clear, and the " +
87
+ "approach and the way to check it are stable. Not for: unknown causes or open " +
88
+ "trade-offs.",
89
+ deep:
90
+ "Uncertainty in the thinking: an unknown root cause, competing hypotheses, subtle " +
91
+ "concurrency or security defects, architectural trade-offs, complex invariants, or " +
92
+ "new solutions that need difficult judgment. Not for: work that is only large or has " +
93
+ "many steps.",
94
+ } satisfies Record<AutoTier, string>,
95
+ } satisfies ClassifierChoiceQuestion;
96
+
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.";
102
+
103
+ // A model-routing signal only: it never grants or blocks a tool, an approval or a permission.
104
+ const RISK_QUESTION = {
105
+ type: "bool",
106
+ instructions:
107
+ "Judge the task as the agent gets it, with normal, trusted execution and the intended use " +
108
+ "of its result. If the agent acts wrongly, writes wrong code, or gives a wrong conclusion " +
109
+ "that others rely on, can that seriously harm security, privacy, data integrity, money, " +
110
+ "production services or permission boundaries, or do other damage that is hard to undo? " +
111
+ "Weigh how far the harm reaches, where the work runs and how easily it is undone. Do not " +
112
+ "answer true only because of domain words, many files, much code, difficulty, or a worst " +
113
+ "case that is only possible in theory. Read-only work counts by what its result is used " +
114
+ "for. A missing detail is not by itself a risk.",
115
+ criteria: {
116
+ true:
117
+ "A mistake can do serious harm that is hard to undo. Examples: changes to " +
118
+ "authentication, authorization, credentials, keys or data isolation; a security audit " +
119
+ "that a release decision relies on; leaking, sending, deleting or opening access to " +
120
+ "personal data, keys or protected code; payment, balance, accounting, billing or tax " +
121
+ "logic; deployments, schema or data migrations, cloud permissions, network policies, " +
122
+ "backups or shared service configuration; deleting important data, rewriting history, " +
123
+ "or publishing what cannot be withdrawn.",
124
+ false:
125
+ "A mistake is found and undone at low cost. Examples: finding references or running " +
126
+ "existing tests and reporting the results; ordinary changes in a local sandbox or test " +
127
+ "code that can be rolled back and checked; renames, formatting or styles that do not " +
128
+ "change critical behavior, also in sensitive modules; local or experimental failures, " +
129
+ "even with an unknown cause; work that is only large, long or difficult.",
130
+ },
131
+ } satisfies ClassifierBoolQuestion;
132
+
133
+ /** Every Pi thinking level; a request offers only the levels that the run's model supports. */
134
+ const THINKING_CRITERIA = {
135
+ off:
136
+ "No reasoning: each step is stated or obvious, such as running a given command, reading " +
137
+ "named files or applying an exact edit.",
138
+ minimal: "A quick look before acting; the steps follow directly from the task.",
139
+ low: "Brief planning over a few dependent steps, such as finding where a described change goes.",
140
+ medium:
141
+ "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
+ 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
+ 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
+ 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
+ } satisfies Record<ThinkingLevel, string>;
154
+
155
+ export interface AutoModelInput {
156
+ ctx: ExtensionContext;
157
+ settings: AutoModelSettings;
158
+ task: string;
159
+ definition?: AgentDefinition;
160
+ /** The selected task tools; undefined for the defaultTools selection. */
161
+ tools?: readonly string[];
162
+ isolation: Isolation;
163
+ /** The call or the definition set the thinking level, so the rating must not. */
164
+ thinkingSet: boolean;
165
+ signal?: AbortSignal;
166
+ }
167
+
168
+ /** What the request size depends on. */
169
+ export type AutoClassifier = Pick<
170
+ ClassifierModel<ClassifierApi>,
171
+ "provider" | "id" | "api" | "contextWindow"
172
+ >;
173
+
174
+ export interface AutoModelResult {
175
+ ref: ModelRef;
176
+ choice: AutoModelChoice;
177
+ /** From the thinking rating, when the start set no thinking level. */
178
+ thinking?: ThinkingLevel;
179
+ }
180
+
181
+ /**
182
+ * Resolve `model: auto`. The classifier rates the task's tier and whether it is high risk; the
183
+ * tier's model, or the next tier up that has one, runs it, and the main agent's model is the
184
+ * 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
+ * in a second request once the model is known. When the classifier fails, the run gets the main
189
+ * agent's model and thinking, and the choice records why. A tier model outside the allowed set is
190
+ * a settings error and fails the start.
191
+ */
192
+ export async function chooseAutoModel(input: AutoModelInput): Promise<AutoModelResult> {
193
+ const { ctx, settings, signal } = input;
194
+
195
+ if (!settings.classifier) {
196
+ return { ref: modelRef(mainModel(ctx)), choice: { by: "no-classifier" } };
197
+ }
198
+
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
+ const classifierRef = formatModelRef(settings.classifier);
205
+ const failed = (error: unknown): AutoModelResult => {
206
+ // A cancelled start stops; any other failure leaves the run the main agent's settings.
207
+ if (signal?.aborted) {
208
+ throw error;
209
+ }
210
+
211
+ return {
212
+ ref: modelRef(mainModel(ctx)),
213
+ choice: {
214
+ by: "classifier-failed",
215
+ classifier: classifierRef,
216
+ error: error instanceof Error ? error.message : String(error),
217
+ },
218
+ };
219
+ };
220
+ // 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);
222
+ let classifier: ClassifierModel<ClassifierApi>;
223
+ let tier: AutoRating<AutoTier>;
224
+ let thinking: AutoRating<ThinkingLevel> | undefined;
225
+ let risk: AutoRisk;
226
+
227
+ try {
228
+ classifier = await findClassifier(input, settings.classifier);
229
+
230
+ const answers = await classifyTask(input, classifier, {
231
+ tier: TIER_QUESTION,
232
+ risk: RISK_QUESTION,
233
+ ...(levels && levels.length > 1 ? { thinking: thinkingQuestion(levels) } : {}),
234
+ });
235
+
236
+ tier = rating(answers.tier, AUTO_TIERS, `${classifierRef} gave no valid tier`);
237
+ risk = riskRating(answers.risk, tier.used, settings, `${classifierRef} gave no valid risk`);
238
+ thinking =
239
+ levels && levels.length > 1
240
+ ? rating(answers.thinking, levels, `${classifierRef} gave no valid thinking level`)
241
+ : undefined;
242
+ } catch (error) {
243
+ return failed(error);
244
+ }
245
+
246
+ const modelFrom =
247
+ AUTO_TIERS.slice(AUTO_TIERS.indexOf(risk.floor ?? tier.used)).find(
248
+ (level) => settings.tiers[level] !== null,
249
+ ) ?? "main";
250
+ const model =
251
+ modelFrom === "main"
252
+ ? mainModel(ctx)
253
+ : tierModel(ctx, modelFrom, settings.tiers[modelFrom]!);
254
+ const supported = getSupportedThinkingLevels(model);
255
+
256
+ if (!levels && supported.length > 1) {
257
+ try {
258
+ const answers = await classifyTask(input, classifier, {
259
+ thinking: thinkingQuestion(supported),
260
+ });
261
+
262
+ thinking = rating(
263
+ answers.thinking,
264
+ supported,
265
+ `${classifierRef} gave no valid thinking level`,
266
+ );
267
+ } catch (error) {
268
+ return failed(error);
269
+ }
270
+ }
271
+
272
+ return {
273
+ ref: modelRef(model),
274
+ choice: {
275
+ by: "rating",
276
+ classifier: classifierRef,
277
+ tier,
278
+ modelFrom,
279
+ ...(thinking ? { thinking } : {}),
280
+ risk,
281
+ },
282
+ ...(thinking ? { thinking: thinking.used } : {}),
283
+ };
284
+ }
285
+
286
+ /**
287
+ * The thinking levels that every model the tier can lead to supports, or undefined when they
288
+ * differ. The main agent's model is one of those models while the deep tier has none.
289
+ */
290
+ function sharedLevels(
291
+ ctx: ExtensionContext,
292
+ settings: AutoModelSettings,
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.
296
+ const models = AUTO_TIERS.flatMap((tier) => {
297
+ const ref = settings.tiers[tier];
298
+ const model = ref && allowed.find((each) => sameModel(each, ref));
299
+
300
+ return model ? [model] : [];
301
+ });
302
+
303
+ if (settings.tiers.deep === null && ctx.model) {
304
+ models.push(ctx.model);
305
+ }
306
+
307
+ const [first, ...rest] = models.map((model) => getSupportedThinkingLevels(model));
308
+
309
+ return first && rest.every((levels) => levels.join() === first.join()) ? first : undefined;
310
+ }
311
+
312
+ function thinkingQuestion(levels: readonly ThinkingLevel[]): ClassifierChoiceQuestion {
313
+ return {
314
+ type: "choice",
315
+ instructions: THINKING_INSTRUCTIONS,
316
+ criteria: Object.fromEntries(levels.map((level) => [level, THINKING_CRITERIA[level]])),
317
+ };
318
+ }
319
+
320
+ async function findClassifier(
321
+ input: AutoModelInput,
322
+ ref: ModelRef,
323
+ ): Promise<ClassifierModel<ClassifierApi>> {
324
+ const { ctx, signal } = input;
325
+
326
+ signal?.throwIfAborted();
327
+
328
+ const classifier = (
329
+ await ctx.modelRegistry.getAvailableOfType("classifier", undefined, { signal })
330
+ ).find((model) => sameModel(model, ref));
331
+
332
+ if (!classifier) {
333
+ 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.",
336
+ );
337
+ }
338
+
339
+ return classifier;
340
+ }
341
+
342
+ /** One classifier request about the task; it throws when the classifier fails. */
343
+ async function classifyTask(
344
+ input: AutoModelInput,
345
+ classifier: ClassifierModel<ClassifierApi>,
346
+ questions: Record<string, ClassifierChoiceQuestion | ClassifierBoolQuestion>,
347
+ ): Promise<Record<string, ClassifierAnswer>> {
348
+ const { ctx, signal } = input;
349
+ const result = await ctx.modelRegistry.classify(
350
+ classifier,
351
+ autoModelRequest(input, classifier, questions),
352
+ { signal },
353
+ );
354
+
355
+ signal?.throwIfAborted();
356
+
357
+ if (result.stopReason !== "stop") {
358
+ throw new Error(
359
+ `The auto classifier ${formatModelRef(classifier)} failed: ` +
360
+ `${result.errorMessage ?? result.stopReason}.`,
361
+ );
362
+ }
363
+
364
+ return result.answers;
365
+ }
366
+
367
+ /**
368
+ * The task, the agent's role and what its tools allow; no model names, which the code maps. When
369
+ * the task and the agent's instructions do not fit the classifier, both are shortened, and the
370
+ * instructions get at most a quarter of the room unless the task leaves more.
371
+ */
372
+ export function autoModelRequest(
373
+ input: Pick<AutoModelInput, "task" | "definition" | "tools" | "isolation">,
374
+ classifier: AutoClassifier,
375
+ questions: Record<string, ClassifierChoiceQuestion | ClassifierBoolQuestion>,
376
+ ): ClassifierContext {
377
+ const state: JsonObject = { task: "" };
378
+ const instructions = input.definition?.body ?? "";
379
+ const agent = input.definition && {
380
+ name: input.definition.name,
381
+ description: input.definition.description,
382
+ instructions: "",
383
+ };
384
+
385
+ if (agent) {
386
+ state.agent = agent;
387
+ }
388
+
389
+ if (input.tools) {
390
+ state.access = access(input.tools);
391
+ state.tools = [...input.tools];
392
+ } else {
393
+ state.tools = "the default tool selection";
394
+ }
395
+
396
+ state.workspace =
397
+ input.isolation === "worktree" ? "its own Git worktree" : "the user's working directory";
398
+
399
+ const request = { state, questions };
400
+ const room = requestLimit(classifier) - Buffer.byteLength(JSON.stringify(request));
401
+ const taskBytes = textBytes(input.task);
402
+
403
+ if (taskBytes + textBytes(instructions) <= room) {
404
+ state.task = input.task;
405
+
406
+ if (agent) {
407
+ agent.instructions = instructions;
408
+ }
409
+
410
+ return request;
411
+ }
412
+
413
+ if (room < MIN_TEXT_BYTES) {
414
+ throw new Error(
415
+ `The auto classifier ${formatModelRef(classifier)} has a context window of ` +
416
+ `${classifier.contextWindow} tokens, too small for this task. Select a classifier ` +
417
+ "with a larger window in the Subagents section of /lune-core-settings.",
418
+ );
419
+ }
420
+
421
+ const shortInstructions = shorten(
422
+ instructions,
423
+ Math.max(Math.floor(room / 4), room - taskBytes),
424
+ );
425
+
426
+ state.task = shorten(input.task, room - textBytes(shortInstructions));
427
+
428
+ if (agent) {
429
+ agent.instructions = shortInstructions;
430
+ }
431
+
432
+ return request;
433
+ }
434
+
435
+ /** The most bytes the request may have for the classifier's window. */
436
+ function requestLimit(classifier: AutoClassifier): number {
437
+ // Pi's llama.cpp classifier shows the state and the questions twice in its prompt.
438
+ const copies = classifier.api === "llama-cpp-classify" ? 2 : 1;
439
+
440
+ return Math.min(
441
+ MAX_REQUEST_BYTES,
442
+ Math.floor((classifier.contextWindow - TEMPLATE_TOKENS) / copies),
443
+ );
444
+ }
445
+
446
+ function access(tools: readonly string[]): string {
447
+ const edits = tools.some((tool) => EDIT_TOOLS.has(tool));
448
+ const commands = tools.some((tool) => COMMAND_TOOLS.has(tool));
449
+
450
+ return edits && commands
451
+ ? "can edit files and run commands"
452
+ : edits
453
+ ? "can edit files"
454
+ : commands
455
+ ? "can run commands"
456
+ : "read-only";
457
+ }
458
+
459
+ /** The high-risk answer, and the floor when it raises the tier that the model comes from. */
460
+ function riskRating(
461
+ answer: ClassifierAnswer | undefined,
462
+ tier: AutoTier,
463
+ settings: AutoModelSettings,
464
+ invalid: string,
465
+ ): AutoRisk {
466
+ if (answer?.type !== "bool" || !Number.isFinite(answer.probability)) {
467
+ throw new Error(`The auto classifier ${invalid}.`);
468
+ }
469
+
470
+ const high = answer.probability >= settings.riskThreshold;
471
+ const floor = settings.riskFloor;
472
+
473
+ return {
474
+ probability: answer.probability,
475
+ threshold: settings.riskThreshold,
476
+ high,
477
+ ...(high && floor && AUTO_TIERS.indexOf(floor) > AUTO_TIERS.indexOf(tier) ? { floor } : {}),
478
+ };
479
+ }
480
+
481
+ /** One rating; an unsure answer moves up one level, since too little costs more than too much. */
482
+ function rating<T extends string>(
483
+ answer: ClassifierAnswer | undefined,
484
+ levels: readonly T[],
485
+ invalid: string,
486
+ ): AutoRating<T> {
487
+ if (answer?.type !== "choice" || !levels.includes(answer.choice as T)) {
488
+ throw new Error(`The auto classifier ${invalid}.`);
489
+ }
490
+
491
+ const rated = answer.choice as T;
492
+
493
+ return {
494
+ rated,
495
+ used:
496
+ answer.confidence < UNSURE_CONFIDENCE
497
+ ? levels[Math.min(levels.indexOf(rated) + 1, levels.length - 1)]!
498
+ : rated,
499
+ confidence: answer.confidence,
500
+ probabilities: Object.fromEntries(
501
+ levels.flatMap((level) => {
502
+ const probability = answer.probabilities[level];
503
+
504
+ return typeof probability === "number" && Number.isFinite(probability)
505
+ ? [[level, probability]]
506
+ : [];
507
+ }),
508
+ ) as Partial<Record<T, number>>,
509
+ };
510
+ }
511
+
512
+ function mainModel(ctx: ExtensionContext): Model<Api> {
513
+ if (!ctx.model) {
514
+ throw new Error("The main agent has no current model for the auto run to use.");
515
+ }
516
+
517
+ return ctx.model;
518
+ }
519
+
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);
523
+ const model = allowed.find((each) => sameModel(each, ref));
524
+
525
+ if (!model) {
526
+ const refs = allowed.map((each) => formatModelRef(each));
527
+
528
+ throw new Error(
529
+ `The ${tier} auto tier uses ${formatModelRef(ref)}, which is not in the allowed set` +
530
+ (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.",
533
+ );
534
+ }
535
+
536
+ return model;
537
+ }
538
+
539
+ function sameModel(model: ModelRef, ref: ModelRef): boolean {
540
+ return model.provider === ref.provider && model.id === ref.id;
541
+ }
542
+
543
+ function modelRef(model: ModelRef): ModelRef {
544
+ return { provider: model.provider, id: model.id };
545
+ }
546
+
547
+ /** The UTF-8 bytes of `text` in a JSON string, escapes included. */
548
+ function textBytes(text: string): number {
549
+ return Buffer.byteLength(JSON.stringify(text)) - 2;
550
+ }
551
+
552
+ /**
553
+ * `text` in at most `maxBytes`: its start and its end, which usually state the goal and what to
554
+ * deliver, around a note of how much was left out.
555
+ */
556
+ function shorten(text: string, maxBytes: number): string {
557
+ if (textBytes(text) <= maxBytes) {
558
+ return text;
559
+ }
560
+
561
+ const chars = [...text];
562
+ // The note's count is less than the text's length, so the note takes at most this room.
563
+ const room = maxBytes - textBytes(omitted(chars.length));
564
+ const startCount = fitting(chars, Math.floor((room * 3) / 4));
565
+ const start = chars.slice(0, startCount).join("");
566
+ const rest = chars.slice(startCount);
567
+ const endCount = fitting(rest.toReversed(), room - textBytes(start));
568
+
569
+ return start + omitted(rest.length - endCount) + rest.slice(rest.length - endCount).join("");
570
+ }
571
+
572
+ function omitted(count: number): string {
573
+ return `\n[${count} characters not shown]\n`;
574
+ }
575
+
576
+ /** How many of `chars`, from the first, fit in `maxBytes`. */
577
+ function fitting(chars: readonly string[], maxBytes: number): number {
578
+ let bytes = 0;
579
+ let count = 0;
580
+
581
+ for (const char of chars) {
582
+ bytes += textBytes(char);
583
+
584
+ if (bytes > maxBytes) {
585
+ break;
586
+ }
587
+
588
+ count++;
589
+ }
590
+
591
+ return count;
592
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,111 @@
1
+ import {
2
+ createBashToolDefinition,
3
+ createCodemodeExtension,
4
+ createEditToolDefinition,
5
+ createFindToolDefinition,
6
+ createGrepToolDefinition,
7
+ createLsToolDefinition,
8
+ createMcpExtension,
9
+ createPowerShellToolDefinition,
10
+ createReadToolDefinition,
11
+ createToolSearchExtension,
12
+ createWriteToolDefinition,
13
+ DefaultResourceLoader,
14
+ type InlineExtension,
15
+ } from "@earendil-works/pi-coding-agent";
16
+
17
+ import type { ExtensionTool } from "./extension-tools.ts";
18
+
19
+ export interface CatalogTool {
20
+ name: string;
21
+ description: string;
22
+ source: "native" | "builtin" | "extension";
23
+ }
24
+
25
+ export interface ToolCatalog {
26
+ tools: CatalogTool[];
27
+ /** Load errors of the built-in extensions; their tools are then missing from `tools`. */
28
+ errors: string[];
29
+ }
30
+
31
+ /** The extensions every run loads; a run loads others only for the extension tools it selects. */
32
+ export function runExtensionFactories(): InlineExtension[] {
33
+ return [createCodemodeExtension(), createToolSearchExtension(), createMcpExtension()];
34
+ }
35
+
36
+ /**
37
+ * The tools every run can select, read from Pi's own definitions rather than a hardcoded list or
38
+ * the parent's tools: a parent extension that replaces `bash` does not replace the run's native one.
39
+ *
40
+ * MCP tools are missing: they register only once a run's servers connect, which happens in the run.
41
+ */
42
+ export async function loadToolCatalog(cwd: string, agentDir: string): Promise<ToolCatalog> {
43
+ const native = [
44
+ createReadToolDefinition(cwd),
45
+ createBashToolDefinition(cwd),
46
+ createEditToolDefinition(cwd),
47
+ createWriteToolDefinition(cwd),
48
+ createGrepToolDefinition(cwd),
49
+ createFindToolDefinition(cwd),
50
+ createLsToolDefinition(cwd),
51
+ createPowerShellToolDefinition(cwd),
52
+ ];
53
+ const tools: CatalogTool[] = native.map((definition) => ({
54
+ name: definition.name,
55
+ description: definition.description,
56
+ source: "native",
57
+ }));
58
+
59
+ // Loading the factories registers their tools without a session_start, so no MCP server starts.
60
+ const loader = new DefaultResourceLoader({
61
+ cwd,
62
+ agentDir,
63
+ noExtensions: true,
64
+ noSkills: true,
65
+ noPromptTemplates: true,
66
+ noThemes: true,
67
+ noContextFiles: true,
68
+ extensionFactories: runExtensionFactories(),
69
+ });
70
+
71
+ await loader.reload({ resolveProjectTrust: async () => false });
72
+
73
+ const result = loader.getExtensions();
74
+
75
+ for (const extension of result.extensions) {
76
+ for (const tool of extension.tools.values()) {
77
+ if (!tools.some((known) => known.name === tool.definition.name)) {
78
+ tools.push({
79
+ name: tool.definition.name,
80
+ description: tool.definition.description,
81
+ source: "builtin",
82
+ });
83
+ }
84
+ }
85
+ }
86
+
87
+ return {
88
+ tools,
89
+ errors: result.errors.map((error) => `${error.path}: ${error.error}`),
90
+ };
91
+ }
92
+
93
+ /** The catalog with the extension tools that runs can load. */
94
+ export function addExtensionTools(
95
+ catalog: ToolCatalog,
96
+ extensionTools: readonly ExtensionTool[],
97
+ ): ToolCatalog {
98
+ return {
99
+ ...catalog,
100
+ tools: [
101
+ ...catalog.tools,
102
+ ...extensionTools.map(
103
+ (tool): CatalogTool => ({
104
+ name: tool.name,
105
+ description: tool.description,
106
+ source: "extension",
107
+ }),
108
+ ),
109
+ ],
110
+ };
111
+ }