@cratis/pi 7.159.1 → 7.160.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.
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
5
|
* Agent discovery + format normalization for the Cratis subagent tool.
|
|
3
6
|
*
|
|
@@ -5,8 +8,8 @@
|
|
|
5
8
|
* surfaced to Pi through generated Pi-native adapters in `.pi/agents/*.md`. The canonical
|
|
6
9
|
* files use Claude/Copilot tool names such as `Read`/`Glob`/`Bash`; generated files use
|
|
7
10
|
* Pi's lowercase names. This loader also normalizes canonical, user and legacy files
|
|
8
|
-
* with the same tool-name map used by generation.
|
|
9
|
-
*
|
|
11
|
+
* with the same tool-name map used by generation. Model overrides, tiers and reviewer
|
|
12
|
+
* independence are retained for resolution against user configuration at dispatch.
|
|
10
13
|
*/
|
|
11
14
|
|
|
12
15
|
import * as fs from "node:fs";
|
|
@@ -32,6 +35,8 @@ export interface AgentConfig {
|
|
|
32
35
|
*/
|
|
33
36
|
toolsError?: string;
|
|
34
37
|
model?: string;
|
|
38
|
+
modelTier?: string;
|
|
39
|
+
reviewIndependence?: string;
|
|
35
40
|
systemPrompt: string;
|
|
36
41
|
source: "package" | "user" | "project";
|
|
37
42
|
filePath: string;
|
|
@@ -47,6 +52,8 @@ type AgentFrontmatter = {
|
|
|
47
52
|
description?: unknown;
|
|
48
53
|
tools?: unknown;
|
|
49
54
|
model?: unknown;
|
|
55
|
+
modelTier?: unknown;
|
|
56
|
+
reviewIndependence?: unknown;
|
|
50
57
|
};
|
|
51
58
|
|
|
52
59
|
/**
|
|
@@ -96,6 +103,8 @@ function loadAgentsFromDir(dir: string, source: "package" | "user" | "project"):
|
|
|
96
103
|
tools: normalizeTools(frontmatter.tools),
|
|
97
104
|
toolsError: toolsErrorFor(frontmatter.name, frontmatter.tools),
|
|
98
105
|
model: typeof frontmatter.model === "string" ? frontmatter.model.trim() : undefined,
|
|
106
|
+
modelTier: typeof frontmatter.modelTier === "string" ? frontmatter.modelTier.trim() : undefined,
|
|
107
|
+
reviewIndependence: typeof frontmatter.reviewIndependence === "string" ? frontmatter.reviewIndependence.trim() : undefined,
|
|
99
108
|
systemPrompt: body,
|
|
100
109
|
source,
|
|
101
110
|
filePath,
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
5
|
* Cratis Subagent tool for the Pi coding agent.
|
|
3
6
|
*
|
|
@@ -23,11 +26,12 @@ import * as fs from "node:fs";
|
|
|
23
26
|
import * as os from "node:os";
|
|
24
27
|
import * as path from "node:path";
|
|
25
28
|
import { fileURLToPath } from "node:url";
|
|
26
|
-
import { CONFIG_DIR_NAME, type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
29
|
+
import { CONFIG_DIR_NAME, type ExtensionAPI, type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
27
30
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
28
|
-
import { Type } from "typebox";
|
|
31
|
+
import { Type, type Static } from "typebox";
|
|
29
32
|
import { type AgentConfig, type AgentScope, discoverAgents } from "./agents.ts";
|
|
30
33
|
import { foreignDelegationTool, standDownNotice, SUBAGENT_TOOL_NAME } from "./delegation.ts";
|
|
34
|
+
import { readModelTierConfig, resolveModel, type ModelResolution, type ModelTierInputs } from "./modelTiers.ts";
|
|
31
35
|
|
|
32
36
|
const extensionPath = fileURLToPath(import.meta.url);
|
|
33
37
|
const isPackagedExtension = extensionPath.includes(`${path.sep}package${path.sep}corpus${path.sep}`);
|
|
@@ -43,6 +47,8 @@ interface SingleResult {
|
|
|
43
47
|
finalText: string;
|
|
44
48
|
stderr: string;
|
|
45
49
|
model?: string;
|
|
50
|
+
modelOutcome?: ModelResolution['outcome'];
|
|
51
|
+
modelNotice?: string;
|
|
46
52
|
stopReason?: string;
|
|
47
53
|
errorMessage?: string;
|
|
48
54
|
step?: number;
|
|
@@ -52,9 +58,10 @@ function isFailed(r: SingleResult): boolean {
|
|
|
52
58
|
return r.exitCode !== 0 || r.stopReason === "error" || r.stopReason === "aborted";
|
|
53
59
|
}
|
|
54
60
|
|
|
55
|
-
function resultOutput(r: SingleResult): string {
|
|
56
|
-
|
|
57
|
-
|
|
61
|
+
function resultOutput(r: SingleResult, results: SingleResult[] = [r]): string {
|
|
62
|
+
const output = isFailed(r) ? r.errorMessage || r.stderr || r.finalText || "(no output)" : r.finalText || "(no output)";
|
|
63
|
+
const notices = [...new Set(results.map(result => result.modelNotice).filter(Boolean))];
|
|
64
|
+
return [...notices, output].join("\n\n");
|
|
58
65
|
}
|
|
59
66
|
|
|
60
67
|
function capOutput(output: string): string {
|
|
@@ -76,9 +83,30 @@ function piInvocation(args: string[]): { command: string; args: string[] } {
|
|
|
76
83
|
return { command: "pi", args };
|
|
77
84
|
}
|
|
78
85
|
|
|
86
|
+
type OutputEvent = { type?: string; message?: { role?: string; content?: { type?: string; text?: string }[]; model?: string; stopReason?: string; errorMessage?: string } };
|
|
87
|
+
|
|
88
|
+
function assistantMessage(line: string): OutputEvent['message'] {
|
|
89
|
+
let event: OutputEvent;
|
|
90
|
+
try { event = JSON.parse(line); } catch { return undefined; }
|
|
91
|
+
if (event.type !== "message_end") return undefined;
|
|
92
|
+
return event.message?.role === "assistant" ? event.message : undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function updateAssistantResult(result: SingleResult, message: NonNullable<OutputEvent['message']>, onText?: (text: string) => void): void {
|
|
96
|
+
for (const part of message.content ?? []) {
|
|
97
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
98
|
+
result.finalText = part.text;
|
|
99
|
+
onText?.(part.text);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (!result.model && message.model) result.model = message.model;
|
|
103
|
+
if (message.stopReason) result.stopReason = message.stopReason;
|
|
104
|
+
if (message.errorMessage) result.errorMessage = message.errorMessage;
|
|
105
|
+
}
|
|
106
|
+
|
|
79
107
|
async function runSingleAgent(
|
|
80
108
|
defaultCwd: string,
|
|
81
|
-
dispatch: { model?: string; thinkingLevel?: string },
|
|
109
|
+
dispatch: Omit<ModelTierInputs, 'agent' | 'dispatchModel'> & { model?: string; thinkingLevel?: string; onNotice: (notice: string) => void },
|
|
82
110
|
agents: AgentConfig[],
|
|
83
111
|
agentName: string,
|
|
84
112
|
task: string,
|
|
@@ -115,11 +143,12 @@ async function runSingleAgent(
|
|
|
115
143
|
};
|
|
116
144
|
}
|
|
117
145
|
|
|
118
|
-
|
|
119
|
-
const model =
|
|
146
|
+
const resolution = resolveModel({ ...dispatch, agent, dispatchModel: dispatch.model });
|
|
147
|
+
const { model } = resolution;
|
|
148
|
+
if (resolution.notice) dispatch.onNotice(resolution.notice);
|
|
120
149
|
const args: string[] = ["--mode", "json", "-p", "--no-session"];
|
|
121
150
|
if (model) args.push("--model", model);
|
|
122
|
-
if (
|
|
151
|
+
if (resolution.thinkingInherited && dispatch.thinkingLevel) args.push("--thinking", dispatch.thinkingLevel);
|
|
123
152
|
if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
|
|
124
153
|
|
|
125
154
|
const result: SingleResult = {
|
|
@@ -130,6 +159,8 @@ async function runSingleAgent(
|
|
|
130
159
|
finalText: "",
|
|
131
160
|
stderr: "",
|
|
132
161
|
model,
|
|
162
|
+
modelOutcome: resolution.outcome,
|
|
163
|
+
modelNotice: resolution.notice,
|
|
133
164
|
step,
|
|
134
165
|
};
|
|
135
166
|
|
|
@@ -155,24 +186,8 @@ async function runSingleAgent(
|
|
|
155
186
|
let buffer = "";
|
|
156
187
|
const processLine = (line: string) => {
|
|
157
188
|
if (!line.trim()) return;
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
event = JSON.parse(line);
|
|
161
|
-
} catch {
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
if (event.type === "message_end" && event.message?.role === "assistant") {
|
|
165
|
-
const msg = event.message;
|
|
166
|
-
for (const part of msg.content ?? []) {
|
|
167
|
-
if (part.type === "text" && typeof part.text === "string") {
|
|
168
|
-
result.finalText = part.text;
|
|
169
|
-
onText?.(part.text);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
if (!result.model && msg.model) result.model = msg.model;
|
|
173
|
-
if (msg.stopReason) result.stopReason = msg.stopReason;
|
|
174
|
-
if (msg.errorMessage) result.errorMessage = msg.errorMessage;
|
|
175
|
-
}
|
|
189
|
+
const message = assistantMessage(line);
|
|
190
|
+
if (message) updateAssistantResult(result, message, onText);
|
|
176
191
|
};
|
|
177
192
|
proc.stdout.on("data", (data) => {
|
|
178
193
|
buffer += data.toString();
|
|
@@ -250,6 +265,91 @@ const SubagentParams = Type.Object({
|
|
|
250
265
|
cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
|
|
251
266
|
});
|
|
252
267
|
|
|
268
|
+
type AgentTask = Static<typeof TaskItem>;
|
|
269
|
+
type RunTask = (task: AgentTask, step?: number) => Promise<SingleResult>;
|
|
270
|
+
|
|
271
|
+
function modelDispatch(ctx: ExtensionContext) {
|
|
272
|
+
let modelNoticeShown = false;
|
|
273
|
+
return {
|
|
274
|
+
...readModelTierConfig(getAgentDir()),
|
|
275
|
+
model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
|
|
276
|
+
thinkingLevel: ctx.thinkingLevel,
|
|
277
|
+
available: ctx.modelRegistry.getAvailable().map(model => `${model.provider}/${model.id}`),
|
|
278
|
+
onNotice: (notice: string) => {
|
|
279
|
+
if (ctx.hasUI && !modelNoticeShown) {
|
|
280
|
+
modelNoticeShown = true;
|
|
281
|
+
ctx.ui.notify(notice, 'warning');
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function needsProjectConfirmation(params: Static<typeof SubagentParams>, ctx: ExtensionContext): boolean {
|
|
288
|
+
if (params.agentScope === 'user') return false;
|
|
289
|
+
return (params.confirmProjectAgents ?? false) && Boolean(ctx.hasUI);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function approveProjectAgents(params: Static<typeof SubagentParams>, ctx: ExtensionContext, discovery: ReturnType<typeof discoverAgents>): Promise<boolean> {
|
|
293
|
+
if (!needsProjectConfirmation(params, ctx)) return true;
|
|
294
|
+
const requested = new Set<string>();
|
|
295
|
+
for (const task of params.chain ?? []) requested.add(task.agent);
|
|
296
|
+
for (const task of params.tasks ?? []) requested.add(task.agent);
|
|
297
|
+
if (params.agent) requested.add(params.agent);
|
|
298
|
+
const projectRequested = Array.from(requested)
|
|
299
|
+
.map(name => discovery.agents.find(agent => agent.name === name))
|
|
300
|
+
.filter((agent): agent is AgentConfig => agent?.source === 'project');
|
|
301
|
+
if (projectRequested.length === 0) return true;
|
|
302
|
+
return ctx.ui.confirm(
|
|
303
|
+
"Run project-local agents?",
|
|
304
|
+
`Agents: ${projectRequested.map(agent => agent.name).join(", ")}\nSource: ${discovery.projectAgentsDir ?? "(unknown)"}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function exactlyOneMode(params: Static<typeof SubagentParams>): boolean {
|
|
309
|
+
const hasChain = (params.chain?.length ?? 0) > 0;
|
|
310
|
+
const hasTasks = (params.tasks?.length ?? 0) > 0;
|
|
311
|
+
const hasSingle = Boolean(params.agent && params.task);
|
|
312
|
+
return Number(hasChain) + Number(hasTasks) + Number(hasSingle) === 1;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function runChain(chain: AgentTask[], run: RunTask) {
|
|
316
|
+
const results: SingleResult[] = [];
|
|
317
|
+
let previous = "";
|
|
318
|
+
for (let i = 0; i < chain.length; i++) {
|
|
319
|
+
const stepDef = chain[i];
|
|
320
|
+
const task = stepDef.task.replace(/\{previous\}/g, previous);
|
|
321
|
+
const result = await run({ ...stepDef, task }, i + 1);
|
|
322
|
+
results.push(result);
|
|
323
|
+
if (isFailed(result)) {
|
|
324
|
+
return {
|
|
325
|
+
content: [{ type: "text" as const, text: `Chain stopped at step ${i + 1} (${stepDef.agent}): ${resultOutput(result, results)}` }],
|
|
326
|
+
details: { mode: "chain", results },
|
|
327
|
+
isError: true,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
previous = result.finalText;
|
|
331
|
+
}
|
|
332
|
+
return { content: [{ type: "text" as const, text: resultOutput(results[results.length - 1], results) }], details: { mode: "chain", results } };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function parallelSummary(result: SingleResult): string {
|
|
336
|
+
const reason = result.stopReason && result.stopReason !== "end" ? ` (${result.stopReason})` : "";
|
|
337
|
+
const status = isFailed(result) ? `failed${reason}` : "completed";
|
|
338
|
+
return `### [${result.agent}] ${status}\n\n${capOutput(resultOutput(result))}`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function runParallel(tasks: AgentTask[], run: RunTask) {
|
|
342
|
+
if (tasks.length > MAX_PARALLEL_TASKS) {
|
|
343
|
+
return { content: [{ type: "text" as const, text: `Too many parallel tasks (${tasks.length}). Max is ${MAX_PARALLEL_TASKS}.` }], details: {} };
|
|
344
|
+
}
|
|
345
|
+
const results = await mapLimit(tasks, MAX_CONCURRENCY, task => run(task));
|
|
346
|
+
const ok = results.filter(result => !isFailed(result)).length;
|
|
347
|
+
return {
|
|
348
|
+
content: [{ type: "text" as const, text: `Parallel: ${ok}/${results.length} succeeded\n\n${results.map(parallelSummary).join("\n\n---\n\n")}` }],
|
|
349
|
+
details: { mode: "parallel", results },
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
253
353
|
export default function (pi: ExtensionAPI) {
|
|
254
354
|
if (isPackagedExtension && fs.existsSync(path.join(process.cwd(), ".cratis", "ai.manifest.json"))) return;
|
|
255
355
|
// Discover once at registration so the tool description can name the valid agents — the model
|
|
@@ -295,16 +395,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
295
395
|
|
|
296
396
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
297
397
|
const agentScope: AgentScope = (params.agentScope as AgentScope) ?? "both";
|
|
298
|
-
const dispatch =
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
};
|
|
302
|
-
const { agents, projectAgentsDir } = discoverAgents(ctx.cwd, agentScope);
|
|
398
|
+
const dispatch = modelDispatch(ctx);
|
|
399
|
+
const discovery = discoverAgents(ctx.cwd, agentScope);
|
|
400
|
+
const { agents } = discovery;
|
|
303
401
|
|
|
304
|
-
|
|
305
|
-
const hasTasks = (params.tasks?.length ?? 0) > 0;
|
|
306
|
-
const hasSingle = Boolean(params.agent && params.task);
|
|
307
|
-
if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {
|
|
402
|
+
if (!exactlyOneMode(params)) {
|
|
308
403
|
const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
|
|
309
404
|
return {
|
|
310
405
|
content: [{ type: "text", text: `Provide exactly one mode (single, parallel, or chain).\nAvailable agents: ${available}` }],
|
|
@@ -313,68 +408,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
313
408
|
}
|
|
314
409
|
|
|
315
410
|
// Optional security gate for callers that want an extra confirmation for project agents.
|
|
316
|
-
if (
|
|
317
|
-
|
|
318
|
-
for (const s of params.chain ?? []) requested.add(s.agent);
|
|
319
|
-
for (const t of params.tasks ?? []) requested.add(t.agent);
|
|
320
|
-
if (params.agent) requested.add(params.agent);
|
|
321
|
-
const projectRequested = Array.from(requested)
|
|
322
|
-
.map((n) => agents.find((a) => a.name === n))
|
|
323
|
-
.filter((a): a is AgentConfig => a?.source === "project");
|
|
324
|
-
if (projectRequested.length > 0) {
|
|
325
|
-
const ok = await ctx.ui.confirm(
|
|
326
|
-
"Run project-local agents?",
|
|
327
|
-
`Agents: ${projectRequested.map((a) => a.name).join(", ")}\nSource: ${projectAgentsDir ?? "(unknown)"}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
|
|
328
|
-
);
|
|
329
|
-
if (!ok) return { content: [{ type: "text", text: "Canceled: project-local agents not approved." }], details: {} };
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// ── chain ──
|
|
334
|
-
if (params.chain && params.chain.length > 0) {
|
|
335
|
-
const results: SingleResult[] = [];
|
|
336
|
-
let previous = "";
|
|
337
|
-
for (let i = 0; i < params.chain.length; i++) {
|
|
338
|
-
const stepDef = params.chain[i];
|
|
339
|
-
const task = stepDef.task.replace(/\{previous\}/g, previous);
|
|
340
|
-
const r = await runSingleAgent(ctx.cwd, dispatch, agents, stepDef.agent, task, stepDef.cwd, i + 1, signal, undefined);
|
|
341
|
-
results.push(r);
|
|
342
|
-
if (isFailed(r)) {
|
|
343
|
-
return {
|
|
344
|
-
content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${stepDef.agent}): ${resultOutput(r)}` }],
|
|
345
|
-
details: { mode: "chain", results },
|
|
346
|
-
isError: true,
|
|
347
|
-
};
|
|
348
|
-
}
|
|
349
|
-
previous = r.finalText;
|
|
350
|
-
}
|
|
351
|
-
return {
|
|
352
|
-
content: [{ type: "text", text: resultOutput(results[results.length - 1]) }],
|
|
353
|
-
details: { mode: "chain", results },
|
|
354
|
-
};
|
|
411
|
+
if (!await approveProjectAgents(params, ctx, discovery)) {
|
|
412
|
+
return { content: [{ type: "text", text: "Canceled: project-local agents not approved." }], details: {} };
|
|
355
413
|
}
|
|
356
414
|
|
|
357
|
-
|
|
358
|
-
if (params.
|
|
359
|
-
|
|
360
|
-
return {
|
|
361
|
-
content: [{ type: "text", text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.` }],
|
|
362
|
-
details: {},
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
const results = await mapLimit(params.tasks, MAX_CONCURRENCY, (t) =>
|
|
366
|
-
runSingleAgent(ctx.cwd, dispatch, agents, t.agent, t.task, t.cwd, undefined, signal, undefined),
|
|
367
|
-
);
|
|
368
|
-
const ok = results.filter((r) => !isFailed(r)).length;
|
|
369
|
-
const summaries = results.map((r) => {
|
|
370
|
-
const status = isFailed(r) ? `failed${r.stopReason && r.stopReason !== "end" ? ` (${r.stopReason})` : ""}` : "completed";
|
|
371
|
-
return `### [${r.agent}] ${status}\n\n${capOutput(resultOutput(r))}`;
|
|
372
|
-
});
|
|
373
|
-
return {
|
|
374
|
-
content: [{ type: "text", text: `Parallel: ${ok}/${results.length} succeeded\n\n${summaries.join("\n\n---\n\n")}` }],
|
|
375
|
-
details: { mode: "parallel", results },
|
|
376
|
-
};
|
|
377
|
-
}
|
|
415
|
+
const run: RunTask = (task, step) => runSingleAgent(ctx.cwd, dispatch, agents, task.agent, task.task, task.cwd, step, signal, undefined);
|
|
416
|
+
if (params.chain && params.chain.length > 0) return runChain(params.chain, run);
|
|
417
|
+
if (params.tasks && params.tasks.length > 0) return runParallel(params.tasks, run);
|
|
378
418
|
|
|
379
419
|
// ── single ──
|
|
380
420
|
const r = await runSingleAgent(ctx.cwd, dispatch, agents, params.agent!, params.task!, params.cwd, undefined, signal, undefined);
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import * as fs from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
export interface ModelTierConfig {
|
|
8
|
+
schemaVersion: string;
|
|
9
|
+
tiers: Partial<Record<string, string | string[]>>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ModelTierInputs {
|
|
13
|
+
agent: { model?: string; modelTier?: string; reviewIndependence?: string };
|
|
14
|
+
dispatchModel?: string;
|
|
15
|
+
config?: ModelTierConfig;
|
|
16
|
+
available?: string[];
|
|
17
|
+
notice?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ModelResolution {
|
|
21
|
+
model?: string;
|
|
22
|
+
thinkingInherited: boolean;
|
|
23
|
+
outcome: 'explicit' | 'tier' | 'inherited' | 'single-provider';
|
|
24
|
+
notice?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const maximumConfigBytes = 65536;
|
|
28
|
+
const knownTiers = ['scoped', 'strongest', 'reviewer'];
|
|
29
|
+
|
|
30
|
+
function record(value: unknown): Record<string, unknown> {
|
|
31
|
+
if (Object.prototype.toString.call(value) !== '[object Object]') throw new Error('Expected an object');
|
|
32
|
+
return value as Record<string, unknown>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function providerOf(model?: string): string | undefined {
|
|
36
|
+
const separator = model?.indexOf('/') ?? -1;
|
|
37
|
+
return separator > 0 ? model!.slice(0, separator) : undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function configuredModel(value: unknown): string {
|
|
41
|
+
if (typeof value !== 'string') throw new Error('Expected a model string');
|
|
42
|
+
const model = value.trim();
|
|
43
|
+
if (!/^[^/\s]+\/[^\s]*[^/\s]$/.test(model)) throw new Error('Expected provider/id');
|
|
44
|
+
return model;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parseConfig(value: unknown): ModelTierConfig {
|
|
48
|
+
const parsed = record(value);
|
|
49
|
+
if (typeof parsed.schemaVersion !== 'string' || !/^1\.\d+$/.test(parsed.schemaVersion)) throw new Error('Unsupported schema');
|
|
50
|
+
const tiers = record(parsed.tiers);
|
|
51
|
+
const config: ModelTierConfig = { schemaVersion: parsed.schemaVersion, tiers: {} };
|
|
52
|
+
for (const tier of knownTiers) {
|
|
53
|
+
if (!(tier in tiers)) continue;
|
|
54
|
+
const candidates = tiers[tier];
|
|
55
|
+
config.tiers[tier] = Array.isArray(candidates) ? candidates.map(configuredModel) : configuredModel(candidates);
|
|
56
|
+
}
|
|
57
|
+
return config;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Read only user-owned configuration; malformed input must never prevent dispatch. */
|
|
61
|
+
export function readModelTierConfig(directory: string): { config?: ModelTierConfig; notice?: string } {
|
|
62
|
+
let descriptor: number | undefined;
|
|
63
|
+
try {
|
|
64
|
+
descriptor = fs.openSync(join(directory, 'cratis-models.json'), 'r');
|
|
65
|
+
const buffer = Buffer.alloc(maximumConfigBytes + 1);
|
|
66
|
+
const length = fs.readSync(descriptor, buffer, 0, buffer.length, 0);
|
|
67
|
+
if (length > maximumConfigBytes) throw new Error('Configuration too large');
|
|
68
|
+
return { config: parseConfig(JSON.parse(buffer.toString('utf8', 0, length))) };
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};
|
|
71
|
+
return { notice: 'Ignoring invalid cratis-models.json (expected schema 1.x tier mappings of provider/id; maximum 64 KiB).' };
|
|
72
|
+
} finally {
|
|
73
|
+
if (descriptor !== undefined) fs.closeSync(descriptor);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function candidatesFor({ agent, config, available }: ModelTierInputs): string[] {
|
|
78
|
+
const configured = agent.modelTier ? config?.tiers[agent.modelTier] : undefined;
|
|
79
|
+
const candidates = typeof configured === 'string' ? [configured] : configured ?? [];
|
|
80
|
+
return candidates.filter(model => available === undefined || available.includes(model));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function singleProvider(model: string | undefined): ModelResolution {
|
|
84
|
+
return {
|
|
85
|
+
model,
|
|
86
|
+
thinkingInherited: false,
|
|
87
|
+
outcome: 'single-provider',
|
|
88
|
+
notice: `single-provider: no different-provider model configured/available for reviewer tier; reviewing on ${model ?? '(session default)'} — not independent`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function differentProvider(model: string, dispatchModel?: string): boolean {
|
|
93
|
+
const authorProvider = providerOf(dispatchModel);
|
|
94
|
+
const candidateProvider = providerOf(model);
|
|
95
|
+
if (!authorProvider || !candidateProvider) return false;
|
|
96
|
+
return candidateProvider !== authorProvider;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function explicitModel(inputs: ModelTierInputs, model: string): ModelResolution {
|
|
100
|
+
if (inputs.agent.reviewIndependence === 'different-provider' && !differentProvider(model, inputs.dispatchModel)) return singleProvider(model);
|
|
101
|
+
return { model, thinkingInherited: false, outcome: 'explicit' };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function independentModel(inputs: ModelTierInputs, candidates: string[]): ModelResolution {
|
|
105
|
+
const model = candidates.find(candidate => differentProvider(candidate, inputs.dispatchModel));
|
|
106
|
+
return model ? { model, thinkingInherited: false, outcome: 'tier' } : singleProvider(candidates[0] ?? inputs.dispatchModel);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function chooseModel(inputs: ModelTierInputs): ModelResolution {
|
|
110
|
+
if (inputs.agent.model) return explicitModel(inputs, inputs.agent.model);
|
|
111
|
+
const candidates = candidatesFor(inputs);
|
|
112
|
+
if (inputs.agent.reviewIndependence === 'different-provider') return independentModel(inputs, candidates);
|
|
113
|
+
return candidates.length > 0
|
|
114
|
+
? { model: candidates[0], thinkingInherited: false, outcome: 'tier' }
|
|
115
|
+
: { model: inputs.dispatchModel, thinkingInherited: true, outcome: 'inherited' };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Resolve explicit overrides, then user tiers, then the dispatching session, without I/O. */
|
|
119
|
+
export function resolveModel(inputs: ModelTierInputs): ModelResolution {
|
|
120
|
+
const resolution = chooseModel(inputs);
|
|
121
|
+
if (inputs.notice) resolution.notice = [inputs.notice, resolution.notice].filter(Boolean).join('\n');
|
|
122
|
+
return resolution;
|
|
123
|
+
}
|