repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(ultra): add model tiers

05eb805a840c56a72949dfb8199e4eabc1ae4fe3

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (7)

+189 / −22 text lines

Diff layout

extensions/ultra/README.md

Modified

+24 / −7 text lines

5757`<cwd>/settings.json` (later overriding earlier), with the runtime settings
5858manager on top.
60| Key | Default | Meaning |
61| -------------------------- | -------- | ----------------------------------------------- |
62| `ultra.enabled` | `true` | When false, the tool + command refuse to run. |
63| `ultra.concurrency` | `5` | Max concurrent sub-agents in a `fanout` phase. |
64| `ultra.maxRetries` | `2` | Schema-validation retries per step. |
65| `ultra.defaultTimeoutMs` | `180000` | Per-step timeout when a step omits `timeoutMs`. |
66| `ultra.subagentExtensions` | `"all"` | Load host extensions into sub-agents, or not. |
60| Key | Default | Meaning |
61| -------------------------- | -------- | -------------------------------------------------- |
62| `ultra.enabled` | `true` | When false, the tool + command refuse to run. |
63| `ultra.concurrency` | `5` | Max concurrent sub-agents in a `fanout` phase. |
64| `ultra.maxRetries` | `2` | Schema-validation retries per step. |
65| `ultra.defaultTimeoutMs` | `180000` | Per-step timeout when a step omits `timeoutMs`. |
66| `ultra.subagentExtensions` | `"all"` | Load host extensions into sub-agents, or not. |
67| `ultra.modelTiers` | `{}` | Optional `small` / `medium` / `big` model aliases. |
69`ultra.modelTiers` maps workflow step `model` values of `small`, `medium`, or `big` to concrete model refs.
70Unset tiers fall back to the session model.
71A tier value may end with a thinking suffix (`:off`, `:minimal`, `:low`, `:medium`, `:high`, `:xhigh`), used when the step omits `thinkingLevel`.
73```json
74{
75 "ultra": {
76 "modelTiers": {
77 "small": "openai/gpt-5-mini:low",
78 "medium": "anthropic/claude-sonnet-4:medium",
79 "big": "openai/gpt-5.1:xhigh"
80 }
81 }
82}
83```
6885`ultra.subagentExtensions` (`"all"` | `"none"`, default `"all"`) controls whether
6986workflow sub-agents load the host's extensions. With `"all"`, a step can grant any

extensions/ultra/__tests__/runner.test.ts

Modified

+60 / −0 text lines

277277 expect(seen[1].at(-1)?.content).toContain("schema validation failed");
278278 });
280 it("resolves configured model tier aliases before completeFn auth", async () => {
281 const completeFn = vi.fn(
282 async (): Promise<CompleteResponse> => ({ text: '{ "verdict": "ok" }' }),
283 );
284 const resolveModel = vi.fn((m?: string) => ({ id: m ?? "host" }));
285 const drivers = makeDrivers({ completeFn, resolveModel });
287 await runStep(
288 { ...toollessStep, model: "small" },
289 makeCtx(),
290 drivers,
291 baseOpts({ modelTiers: { small: "openai/gpt-5-mini:low" } }),
292 );
294 expect(resolveModel).toHaveBeenCalledWith("openai/gpt-5-mini");
295 });
297 it("unconfigured model tiers fall back to the session model", async () => {
298 const completeFn = vi.fn(
299 async (): Promise<CompleteResponse> => ({ text: '{ "verdict": "ok" }' }),
300 );
301 const resolveModel = vi.fn((m?: string) => ({ id: m ?? "host" }));
302 const drivers = makeDrivers({ completeFn, resolveModel });
304 await runStep(
305 { ...toollessStep, model: "small" },
306 makeCtx(),
307 drivers,
308 baseOpts(),
309 );
311 expect(resolveModel).toHaveBeenCalledWith(undefined);
312 });
280314 it("drops before calling completeFn when auth is unavailable", async () => {
281315 const completeFn = vi.fn(
282316 async (): Promise<CompleteResponse> => ({ text: "{}" }),
667701 }
668702 });
704 it("applies a tier thinking suffix to tool-using sessions unless the step overrides it", async () => {
705 const harness = makeSessionHarness({
706 drive: happyDrive({ verdict: "tiered" }),
707 });
708 const drivers = makeDrivers({ sessionFactory: harness.factory });
710 await runStep(
711 { ...toolStep, model: "small" },
712 makeCtx(),
713 drivers,
714 baseOpts({ modelTiers: { small: "openai/gpt-5-mini:low" } }),
715 );
716 expect(harness.captured.args?.thinkingLevel).toBe("low");
718 const overrideHarness = makeSessionHarness({
719 drive: happyDrive({ verdict: "override" }),
720 });
721 await runStep(
722 { ...toolStep, model: "small", thinkingLevel: "high" },
723 makeCtx(),
724 makeDrivers({ sessionFactory: overrideHarness.factory }),
725 baseOpts({ modelTiers: { small: "openai/gpt-5-mini:low" } }),
726 );
727 expect(overrideHarness.captured.args?.thinkingLevel).toBe("high");
728 });
670730 it("routes a tool-using call through runStep and returns its result", async () => {
671731 const harness = makeSessionHarness({
672732 drive: happyDrive({ verdict: "routed" }),

extensions/ultra/__tests__/settings.test.ts

Modified

+27 / −2 text lines

1414 maxRetries: 2,
1515 defaultTimeoutMs: 180000,
1616 subagentExtensions: "all",
17 modelTiers: {},
1718 });
1819 });
1920});
6162 maxRetries: 1,
6263 enabled: false,
6364 defaultTimeoutMs: 5000,
65 modelTiers: {
66 small: "openai/gpt-5-mini:low",
67 medium: "anthropic/claude-sonnet-4",
68 big: "openai/gpt-5.1:xhigh",
69 bogus: "ignored",
70 },
6471 },
6572 }),
6673 ).toEqual({
6875 concurrency: 8,
6976 maxRetries: 1,
7077 defaultTimeoutMs: 5000,
78 modelTiers: {
79 small: "openai/gpt-5-mini:low",
80 medium: "anthropic/claude-sonnet-4",
81 big: "openai/gpt-5.1:xhigh",
82 },
7183 });
7284 });
7486 it("ignores wrong-typed values and unknown keys", () => {
7587 expect(
76 pickUltra({ ultra: { concurrency: "8", maxRetries: 2, bogus: 1 } }),
88 pickUltra({
89 ultra: {
90 concurrency: "8",
91 maxRetries: 2,
92 bogus: 1,
93 modelTiers: { small: 7, extra: "ignored" },
94 },
95 }),
7796 ).toEqual({
7897 maxRetries: 2,
98 modelTiers: {},
7999 });
80100 });
90110describe("mergeUltraSettings", () => {
91111 it("folds partials over the defaults, later winning", () => {
92112 expect(
93 mergeUltraSettings({ concurrency: 3 }, { concurrency: 9, maxRetries: 4 }),
113 mergeUltraSettings(
114 { concurrency: 3, modelTiers: { small: "openai/gpt-5-mini" } },
115 { concurrency: 9, maxRetries: 4, modelTiers: { big: "openai/gpt-5" } },
116 ),
94117 ).toEqual({
95118 enabled: true,
96119 concurrency: 9,
97120 maxRetries: 4,
98121 defaultTimeoutMs: 180000,
99122 subagentExtensions: "all",
123 modelTiers: { big: "openai/gpt-5" },
100124 });
101125 });
122146 maxRetries: 9,
123147 defaultTimeoutMs: 180000,
124148 subagentExtensions: "all",
149 modelTiers: {},
125150 });
126151 });

extensions/ultra/index.ts

Modified

+1 / −0 text lines

133133 maxRetries: cfg.maxRetries,
134134 defaultTimeoutMs: cfg.defaultTimeoutMs,
135135 schemas: spec.schemas,
136 modelTiers: cfg.modelTiers,
136137 };
137138 return makeStepRunner(drivers, ctxLike, baseOpts);
138139 };

extensions/ultra/runner.ts

Modified

+46 / −5 text lines

3535 mapSessionEvent,
3636 type UltraProgressEvent,
3737} from "./progress.ts";
38import type { ModelTiers } from "./settings.ts";
3839import { compileSchema, type Step, type ThinkingLevel } from "./spec.ts";
4041// ---------------------------------------------------------------------------
152153 defaultTimeoutMs: number;
153154 /** Named schemas (`spec.schemas`) for resolving a `step.schema` string ref. */
154155 schemas?: Record<string, object>;
156 /** Optional local aliases used by step.model: small|medium|big. */
157 modelTiers?: ModelTiers;
155158 /** Optional extra system-prompt text for the tool-less path. */
156159 systemPrompt?: string;
224227 return ref;
230function isModelTierName(value: string): value is keyof ModelTiers {
231 return value === "small" || value === "medium" || value === "big";
232}
234function splitTierSpec(spec: string): {
235 model: string;
236 thinkingLevel?: ThinkingLevel;
237} {
238 const match = spec.match(/^(.*):(off|minimal|low|medium|high|xhigh)$/);
239 if (!match) return { model: spec };
240 return { model: match[1], thinkingLevel: match[2] as ThinkingLevel };
241}
243function resolveModelTier(step: Step, tiers: ModelTiers | undefined): Step {
244 if (!step.model || !isModelTierName(step.model)) return step;
245 const tier = tiers?.[step.model];
246 if (!tier) {
247 const { model: _model, ...withoutModel } = step;
248 return withoutModel;
249 }
250 const resolved = splitTierSpec(tier);
251 return {
252 ...step,
253 model: resolved.model,
254 thinkingLevel: step.thinkingLevel ?? resolved.thinkingLevel,
255 };
256}
227258/** Strip a leading ```json (or ```) fence and a trailing ``` fence (angel's behavior). */
228259function stripFences(raw: string): string {
229260 const FENCE_OPEN = /^\s*`{3}(?:json)?\s*\n?/i;
328359 drivers: StepDrivers,
329360 opts: RunStepOptions,
330361): Promise<RunStepResult> {
331 const schemaObj = resolveStepSchema(step, opts);
362 const resolvedStep = resolveModelTier(step, opts.modelTiers);
363 const schemaObj = resolveStepSchema(resolvedStep, opts);
332364 const validator = schemaObj
333365 ? (compileSchema(schemaObj) as CompiledValidator)
334366 : undefined;
335 const timeoutMs = step.timeoutMs ?? opts.defaultTimeoutMs;
336 const usesTools = Array.isArray(step.tools) && step.tools.length > 0;
367 const timeoutMs = resolvedStep.timeoutMs ?? opts.defaultTimeoutMs;
368 const usesTools =
369 Array.isArray(resolvedStep.tools) && resolvedStep.tools.length > 0;
338371 return usesTools
339 ? runToolStep(step, ctxLike, drivers, opts, schemaObj, validator, timeoutMs)
340 : runCompleteStep(step, drivers, opts, validator, timeoutMs);
372 ? runToolStep(
373 resolvedStep,
374 ctxLike,
375 drivers,
376 opts,
377 schemaObj,
378 validator,
379 timeoutMs,
380 )
381 : runCompleteStep(resolvedStep, drivers, opts, validator, timeoutMs);
343384// ---- tool-less path -------------------------------------------------------

extensions/ultra/settings.ts

Modified

+19 / −0 text lines

33// Reads the `ultra.*` block from Pi settings via runtime `settingsManager`.
55/** Resolved `ultra` configuration (design §Settings). */
6export type ModelTierName = "small" | "medium" | "big";
7export type ModelTiers = Partial<Record<ModelTierName, string>>;
8
69export interface UltraSettings {
710 /** When false, the tool + command refuse to run. */
811 enabled: boolean;
1619 * (`"all"`, default) or keep sub-agents isolated to core tools (`"none"`).
1720 * The `step.tools` allowlist still gates which tools are actually active. */
1821 subagentExtensions: "none" | "all";
22 /** Optional local aliases used by step.model: small|medium|big. */
23 modelTiers: ModelTiers;
2126/** Documented defaults (design §Settings table). */
2530 maxRetries: 2,
2631 defaultTimeoutMs: 180000,
2732 subagentExtensions: "all",
33 modelTiers: {},
2834};
3036function isPlainObject(v: unknown): v is Record<string, unknown> {
3137 return v !== null && typeof v === "object" && !Array.isArray(v);
40function pickModelTiers(raw: unknown): ModelTiers | undefined {
41 if (!isPlainObject(raw)) return undefined;
42 const out: ModelTiers = {};
43 for (const name of ["small", "medium", "big"] as const) {
44 const value = raw[name];
45 if (typeof value === "string") out[name] = value;
46 }
47 return out;
48}
3450/**
3551 * Extract the `ultra` block from a parsed settings object, keeping only known
3652 * keys with the correct primitive type. A missing/non-object block, wrong-typed
4965 out.defaultTimeoutMs = ultra.defaultTimeoutMs;
5066 if (ultra.subagentExtensions === "none" || ultra.subagentExtensions === "all")
5167 out.subagentExtensions = ultra.subagentExtensions;
68 const modelTiers = pickModelTiers(ultra.modelTiers);
69 if (modelTiers) out.modelTiers = modelTiers;
5270 return out;
7290 p.subagentExtensions === "none" || p.subagentExtensions === "all"
7391 ? p.subagentExtensions
7492 : into.subagentExtensions,
93 modelTiers: isPlainObject(p.modelTiers) ? p.modelTiers : into.modelTiers,
7594 }),
7695 { ...ULTRA_DEFAULTS },
7796 );

extensions/ultra/skills/authoring-workflows/references/spec-format.md

Modified

+12 / −8 text lines

4747## Steps
49| Field | Required | Type | Meaning |
50| --------------- | -------- | --------------------- | ----------------------------------------------------------------- |
51| `prompt` | yes | string | The agent instruction. Interpolates `{...}` tokens (see below). |
52| `tools` | no | string[] | Tool allowlist. Omit for a tool-less completion (pure reasoning). |
53| `model` | no | string | `provider/id` override; defaults to the session model. |
54| `thinkingLevel` | no | off…xhigh | Reasoning budget for this step. |
55| `schema` | no | string \| JSON Schema | A `schemas` name, or an inline schema. Forces structured output. |
56| `timeoutMs` | no | number | Per-agent timeout. |
49| Field | Required | Type | Meaning |
50| --------------- | -------- | --------------------- | ------------------------------------------------------------------------------------------------- |
51| `prompt` | yes | string | The agent instruction. Interpolates `{...}` tokens (see below). |
52| `tools` | no | string[] | Tool allowlist. Omit for a tool-less completion (pure reasoning). |
53| `model` | no | string | `provider/id` override, or configured tier `small`/`medium`/`big`; defaults to the session model. |
54| `thinkingLevel` | no | off…xhigh | Reasoning budget for this step. |
55| `schema` | no | string \| JSON Schema | A `schemas` name, or an inline schema. Forces structured output. |
56| `timeoutMs` | no | number | Per-agent timeout. |
5858A string `schema` is a **name reference** and must resolve in the spec's
5959`schemas` map, or validation fails.
61Configured model tiers live in Pi settings under `ultra.modelTiers`.
62If a step sets `model` to `small`, `medium`, or `big`, ultra resolves it through that map; an unset tier falls back to the session model.
63Tier values may include a thinking suffix like `openai/gpt-5-mini:low`, used only when the step omits `thinkingLevel`.
6165## Interpolation grammar
6367A closed mini-syntax — not an expression evaluator, no `eval`. Tokens