@rackrot/pi-council 0.0.0-stage → 0.0.1
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/README.md +100 -2
- package/package.json +34 -5
- package/src/config.ts +165 -0
- package/src/edit.ts +399 -0
- package/src/files.ts +19 -0
- package/src/index.ts +193 -0
- package/src/prompts.ts +31 -0
- package/src/run.ts +76 -0
- package/src/ui.ts +153 -0
- package/src/usage.ts +39 -0
package/README.md
CHANGED
|
@@ -1,3 +1,101 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rackrot/pi-council
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Two tools that let an agent consult other models. Both call models directly (no tools, no session history),
|
|
4
|
+
so the agent must send what the reviewer needs in `context` and `files`.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pi install npm:@rackrot/pi-council
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
- **`second_opinion`**: one model reviews a plan, diff or diagnosis. Uses your default model; the agent can
|
|
11
|
+
switch to one of the optional models when its `useWhen` fits.
|
|
12
|
+
- **`council`**: a preset's councillors (different models, optional role prompts) review in parallel, then a
|
|
13
|
+
synthesizer merges them into consensus, unique findings, disagreements and ranked actions. Modelled on
|
|
14
|
+
oh-my-opencode-slim's council. Councillors here have no codebase tools; pass `files`.
|
|
15
|
+
|
|
16
|
+
## Configure and prompt injection
|
|
17
|
+
|
|
18
|
+
`/council-config` opens a settings screen for both tools (Tab switches between global and project settings; type to search rows). It edits second_opinion's default model, options (model, id, use when, thinking), and the council's presets, councillors (model, thinking, role prompt), synthesizer and limits, and writes the same `council` settings shown below, then reloads pi. Fallback chains beyond the first model are edited in settings.json. `/council-config show` prints a summary.
|
|
19
|
+
|
|
20
|
+
Each tool's description carries its usage guidance, the default model and override options' `useWhen` text, or the preset rosters, and each adds a prompt snippet and guideline. These are fixed when pi loads the extension, so saving in the screen runs `/reload` for you; after editing settings.json by hand run `/reload` yourself. A disabled tool, or `council` with no presets, is not registered. Settings are still re-read on every call, so a model or prompt change takes effect even before the reload.
|
|
21
|
+
|
|
22
|
+
Models are `provider/model` strings of concrete models (not `alias/...` virtual models). Config goes under
|
|
23
|
+
`council` in `~/.pi/agent/settings.json` or `.pi/settings.json` (project overrides global per section).
|
|
24
|
+
Settings are re-read on every call; descriptions refresh on `/reload`.
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"council": {
|
|
29
|
+
"maxFileBytes": 100000,
|
|
30
|
+
"secondOpinion": {
|
|
31
|
+
"enabled": true,
|
|
32
|
+
"model": "openai/gpt-6.2-sol",
|
|
33
|
+
"thinking": "high",
|
|
34
|
+
"systemPrompt": "Extra guidance appended to the reviewer prompt.",
|
|
35
|
+
"maxTokens": 8000,
|
|
36
|
+
"timeoutSeconds": 300,
|
|
37
|
+
"models": [
|
|
38
|
+
{
|
|
39
|
+
"id": "claude",
|
|
40
|
+
"model": "anthropic/claude-opus-5",
|
|
41
|
+
"thinking": "high",
|
|
42
|
+
"useWhen": "Subtle design or correctness questions"
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"id": "fast",
|
|
46
|
+
"model": "google/gemini-3.8-flash",
|
|
47
|
+
"useWhen": "Quick sanity checks on small changes"
|
|
48
|
+
}
|
|
49
|
+
]
|
|
50
|
+
},
|
|
51
|
+
"council": {
|
|
52
|
+
"enabled": true,
|
|
53
|
+
"defaultPreset": "default",
|
|
54
|
+
"councillorPrompt": "Extra guidance for every councillor.",
|
|
55
|
+
"maxTokens": 8000,
|
|
56
|
+
"timeoutSeconds": 300,
|
|
57
|
+
"synthesizer": {
|
|
58
|
+
"enabled": true,
|
|
59
|
+
"model": ["anthropic/claude-opus-5", "openai/gpt-6.2-sol"],
|
|
60
|
+
"thinking": "high",
|
|
61
|
+
"prompt": "Extra guidance for the synthesizer."
|
|
62
|
+
},
|
|
63
|
+
"presets": {
|
|
64
|
+
"default": {
|
|
65
|
+
"useWhen": "General design or change review",
|
|
66
|
+
"councillors": {
|
|
67
|
+
"reviewer": {
|
|
68
|
+
"model": ["openai/gpt-6.2-sol", "openai/gpt-6.1-terra"],
|
|
69
|
+
"thinking": "high",
|
|
70
|
+
"prompt": "Focus on bugs, edge cases and failure modes."
|
|
71
|
+
},
|
|
72
|
+
"architect": {
|
|
73
|
+
"model": "google/gemini-4-hydrogen",
|
|
74
|
+
"prompt": "Focus on boundaries and long-term maintainability."
|
|
75
|
+
},
|
|
76
|
+
"skeptic": {
|
|
77
|
+
"model": "anthropic/claude-opus-5",
|
|
78
|
+
"prompt": "Challenge assumptions; look for what is missing."
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Reference
|
|
89
|
+
|
|
90
|
+
| Key | Default | Notes |
|
|
91
|
+
| ---------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------- |
|
|
92
|
+
| `secondOpinion.model` | session model | String or `{ model, thinking }`. |
|
|
93
|
+
| `secondOpinion.models[]` | none | `{ id?, model, thinking?, useWhen }`. The agent passes `id` (or the model string) as `model`; unknown values error. |
|
|
94
|
+
| `council.presets.<name>.councillors.<n>.model` | required | String, object, or array = fallback chain tried in order. |
|
|
95
|
+
| `council.presets.<name>.useWhen` | none | Shown to the agent so it can choose a preset. |
|
|
96
|
+
| `council.synthesizer.model` | session model | Same forms as councillor `model`. `enabled: false` returns raw answers for the agent to merge. |
|
|
97
|
+
| `thinking` | model default | `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. |
|
|
98
|
+
| `timeoutSeconds` | 300 | Per model call. |
|
|
99
|
+
|
|
100
|
+
If some councillors fail, the synthesizer works from the rest and the failures are listed. If every councillor fails the
|
|
101
|
+
tool errors. If the synthesizer fails, the raw councillor answers are returned.
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@rackrot/pi-council",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Second-opinion and multi-model council tools for pi",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension"
|
|
9
|
+
],
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test test/*.test.ts"
|
|
17
|
+
},
|
|
18
|
+
"pi": {
|
|
19
|
+
"extensions": [
|
|
20
|
+
"./src/index.ts"
|
|
21
|
+
]
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
25
|
+
"typebox": "*"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/rackrot/pi-tools.git",
|
|
33
|
+
"directory": "packages/council"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
|
|
5
|
+
export const THINKING = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
6
|
+
export type Thinking = (typeof THINKING)[number];
|
|
7
|
+
|
|
8
|
+
/** One model to call: `provider/model` plus optional thinking level. */
|
|
9
|
+
export interface ModelRef {
|
|
10
|
+
model: string;
|
|
11
|
+
thinking?: Thinking;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SecondOpinionOption extends ModelRef {
|
|
15
|
+
/** Name the agent passes as `model`. Defaults to the model string. */
|
|
16
|
+
id: string;
|
|
17
|
+
/** When the agent should pick this model over the default. Shown in the tool description. */
|
|
18
|
+
useWhen: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface SecondOpinionConfig {
|
|
22
|
+
enabled: boolean;
|
|
23
|
+
/** Default model; `undefined` falls back to the session's current model. */
|
|
24
|
+
default?: ModelRef;
|
|
25
|
+
options: SecondOpinionOption[];
|
|
26
|
+
systemPrompt?: string;
|
|
27
|
+
maxTokens?: number;
|
|
28
|
+
timeoutSeconds: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface Councillor {
|
|
32
|
+
/** Ordered fallback chain: the next entry is tried when one fails. */
|
|
33
|
+
chain: ModelRef[];
|
|
34
|
+
/** Role guidance appended to the councillor's system prompt. */
|
|
35
|
+
prompt?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface Preset {
|
|
39
|
+
useWhen?: string;
|
|
40
|
+
councillors: Record<string, Councillor>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CouncilConfig {
|
|
44
|
+
enabled: boolean;
|
|
45
|
+
defaultPreset: string;
|
|
46
|
+
presets: Record<string, Preset>;
|
|
47
|
+
synthesizer: {
|
|
48
|
+
/** false: return the raw councillor answers and let the calling agent synthesize. */
|
|
49
|
+
enabled: boolean;
|
|
50
|
+
chain: ModelRef[];
|
|
51
|
+
prompt?: string;
|
|
52
|
+
};
|
|
53
|
+
councillorPrompt?: string;
|
|
54
|
+
maxTokens?: number;
|
|
55
|
+
timeoutSeconds: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface Config {
|
|
59
|
+
secondOpinion: SecondOpinionConfig;
|
|
60
|
+
council: CouncilConfig;
|
|
61
|
+
/** Per-file cap when embedding `files`. */
|
|
62
|
+
maxFileBytes: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const DEFAULT_TIMEOUT = 300;
|
|
66
|
+
const DEFAULT_MAX_FILE_BYTES = 100_000;
|
|
67
|
+
|
|
68
|
+
const isObj = (v: unknown): v is Record<string, unknown> =>
|
|
69
|
+
!!v && typeof v === "object" && !Array.isArray(v);
|
|
70
|
+
const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
|
|
71
|
+
const num = (v: unknown) => (typeof v === "number" && v > 0 ? v : undefined);
|
|
72
|
+
const thinking = (v: unknown) => THINKING.find((t) => t === v);
|
|
73
|
+
|
|
74
|
+
/** Accepts `"provider/model"` or `{ model, thinking? }`. */
|
|
75
|
+
export function parseRef(v: unknown, inherit?: Thinking): ModelRef | undefined {
|
|
76
|
+
if (typeof v === "string") {
|
|
77
|
+
const model = str(v);
|
|
78
|
+
return model && model.includes("/") ? { model, thinking: inherit } : undefined;
|
|
79
|
+
}
|
|
80
|
+
if (!isObj(v)) return undefined;
|
|
81
|
+
const model = str(v.model ?? v.id);
|
|
82
|
+
if (!model?.includes("/")) return undefined;
|
|
83
|
+
return { model, thinking: thinking(v.thinking) ?? inherit };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Accepts a ref or an array of refs (fallback chain). `thinking` applies to entries without their own. */
|
|
87
|
+
export function parseChain(v: unknown, inherit?: Thinking): ModelRef[] {
|
|
88
|
+
const list = Array.isArray(v) ? v : v === undefined ? [] : [v];
|
|
89
|
+
return list.flatMap((e) => parseRef(e, inherit) ?? []);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function parseConfig(raw: unknown): Config {
|
|
93
|
+
const r = isObj(raw) ? raw : {};
|
|
94
|
+
const so = isObj(r.secondOpinion) ? r.secondOpinion : {};
|
|
95
|
+
const co = isObj(r.council) ? r.council : {};
|
|
96
|
+
|
|
97
|
+
const soThinking = thinking(so.thinking);
|
|
98
|
+
const options: SecondOpinionOption[] = [];
|
|
99
|
+
for (const o of Array.isArray(so.models) ? so.models : []) {
|
|
100
|
+
const ref = parseRef(o);
|
|
101
|
+
if (!ref || !isObj(o)) continue;
|
|
102
|
+
options.push({ ...ref, id: str(o.id) ?? ref.model, useWhen: str(o.useWhen) ?? "" });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const presets: Record<string, Preset> = {};
|
|
106
|
+
for (const [name, p] of Object.entries(isObj(co.presets) ? co.presets : {})) {
|
|
107
|
+
if (!isObj(p)) continue;
|
|
108
|
+
const councillors: Record<string, Councillor> = {};
|
|
109
|
+
for (const [cname, c] of Object.entries(isObj(p.councillors) ? p.councillors : {})) {
|
|
110
|
+
if (!isObj(c)) continue;
|
|
111
|
+
const chain = parseChain(c.model, thinking(c.thinking));
|
|
112
|
+
if (chain.length) councillors[cname] = { chain, prompt: str(c.prompt) };
|
|
113
|
+
}
|
|
114
|
+
if (Object.keys(councillors).length) presets[name] = { useWhen: str(p.useWhen), councillors };
|
|
115
|
+
}
|
|
116
|
+
const syn = isObj(co.synthesizer) ? co.synthesizer : {};
|
|
117
|
+
const defaultPreset = str(co.defaultPreset) ?? "default";
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
maxFileBytes: num(r.maxFileBytes) ?? DEFAULT_MAX_FILE_BYTES,
|
|
121
|
+
secondOpinion: {
|
|
122
|
+
enabled: so.enabled !== false,
|
|
123
|
+
default: parseRef(so.model, soThinking),
|
|
124
|
+
options,
|
|
125
|
+
systemPrompt: str(so.systemPrompt),
|
|
126
|
+
maxTokens: num(so.maxTokens),
|
|
127
|
+
timeoutSeconds: num(so.timeoutSeconds) ?? DEFAULT_TIMEOUT,
|
|
128
|
+
},
|
|
129
|
+
council: {
|
|
130
|
+
enabled: co.enabled !== false,
|
|
131
|
+
defaultPreset,
|
|
132
|
+
presets,
|
|
133
|
+
synthesizer: {
|
|
134
|
+
enabled: syn.enabled !== false,
|
|
135
|
+
chain: parseChain(syn.model, thinking(syn.thinking)),
|
|
136
|
+
prompt: str(syn.prompt),
|
|
137
|
+
},
|
|
138
|
+
councillorPrompt: str(co.councillorPrompt),
|
|
139
|
+
maxTokens: num(co.maxTokens),
|
|
140
|
+
timeoutSeconds: num(co.timeoutSeconds) ?? DEFAULT_TIMEOUT,
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function readJson(path: string): Record<string, unknown> {
|
|
146
|
+
if (!existsSync(path)) return {};
|
|
147
|
+
try {
|
|
148
|
+
return JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
|
|
149
|
+
} catch {
|
|
150
|
+
return {};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Merges the `council` settings key: project over global, per top-level section. */
|
|
155
|
+
export function loadConfig(cwd: string = process.cwd()): Config {
|
|
156
|
+
const g = readJson(join(getAgentDir(), "settings.json")).council;
|
|
157
|
+
const p = readJson(join(cwd, ".pi", "settings.json")).council;
|
|
158
|
+
const gg = isObj(g) ? g : {};
|
|
159
|
+
const pp = isObj(p) ? p : {};
|
|
160
|
+
const merged: Record<string, unknown> = { ...gg, ...pp };
|
|
161
|
+
for (const k of ["secondOpinion", "council"]) {
|
|
162
|
+
merged[k] = { ...(isObj(gg[k]) ? gg[k] : {}), ...(isObj(pp[k]) ? pp[k] : {}) };
|
|
163
|
+
}
|
|
164
|
+
return parseConfig(merged);
|
|
165
|
+
}
|
package/src/edit.ts
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { type Config, parseChain, THINKING } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
export type Obj = Record<string, unknown>;
|
|
6
|
+
|
|
7
|
+
export const UNSET = "unset";
|
|
8
|
+
const NONE = "(none)";
|
|
9
|
+
|
|
10
|
+
/** One editable line in the settings screen. `apply` mutates the raw `council` object of one settings file. */
|
|
11
|
+
export interface Row {
|
|
12
|
+
id: string;
|
|
13
|
+
label: string;
|
|
14
|
+
description: string;
|
|
15
|
+
current: string;
|
|
16
|
+
values?: string[];
|
|
17
|
+
/** Opens a model picker (`model`) or a text input (`text`) instead of cycling. */
|
|
18
|
+
submenu?: "model" | "text";
|
|
19
|
+
apply(council: Obj, value: string): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v);
|
|
23
|
+
|
|
24
|
+
function child(o: Obj, key: string): Obj {
|
|
25
|
+
if (!isObj(o[key])) o[key] = {};
|
|
26
|
+
return o[key] as Obj;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function put(o: Obj, key: string, v: unknown) {
|
|
30
|
+
if (v === undefined) delete o[key];
|
|
31
|
+
else o[key] = v;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Sets or clears the first model of a `model` field that may be a string, object or fallback chain. */
|
|
35
|
+
export function setFirstModel(o: Obj, key: string, value: string) {
|
|
36
|
+
const raw = o[key];
|
|
37
|
+
if (value === UNSET || value === NONE) {
|
|
38
|
+
if (Array.isArray(raw) && raw.length > 1) raw.shift();
|
|
39
|
+
else delete o[key];
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const swap = (e: unknown) => (isObj(e) ? { ...e, model: value } : value);
|
|
43
|
+
if (Array.isArray(raw)) raw[0] = swap(raw[0]);
|
|
44
|
+
else o[key] = swap(raw);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const firstModel = (raw: unknown) => parseChain(raw)[0]?.model;
|
|
48
|
+
|
|
49
|
+
function cycleValues(current: string, base: string[]): string[] {
|
|
50
|
+
return current === UNSET || base.includes(current) ? base : [...base, current];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const TIMEOUTS = ["60", "120", "300", "600", "900"];
|
|
54
|
+
const TOKENS = ["2000", "4000", "8000", "16000", "32000"];
|
|
55
|
+
|
|
56
|
+
/** Builds every row for one settings layer (`layer` is its raw `council` object); `eff` is the merged result. */
|
|
57
|
+
export function buildRows(layer: Obj, eff: Config): Row[] {
|
|
58
|
+
const rows: Row[] = [];
|
|
59
|
+
const so = isObj(layer.secondOpinion) ? layer.secondOpinion : {};
|
|
60
|
+
const co = isObj(layer.council) ? layer.council : {};
|
|
61
|
+
const syn = isObj(co.synthesizer) ? co.synthesizer : {};
|
|
62
|
+
|
|
63
|
+
const toggle = (
|
|
64
|
+
id: string,
|
|
65
|
+
label: string,
|
|
66
|
+
raw: unknown,
|
|
67
|
+
effective: boolean,
|
|
68
|
+
set: (c: Obj, v: boolean) => void,
|
|
69
|
+
) =>
|
|
70
|
+
rows.push({
|
|
71
|
+
id,
|
|
72
|
+
label,
|
|
73
|
+
description: `Effective: ${effective ? "on" : "off"}. Saving writes an explicit value to this scope.`,
|
|
74
|
+
current: typeof raw === "boolean" ? (raw ? "on" : "off") : effective ? "on" : "off",
|
|
75
|
+
values: ["on", "off"],
|
|
76
|
+
apply: (c, v) => set(c, v === "on"),
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const cycle = (
|
|
80
|
+
id: string,
|
|
81
|
+
label: string,
|
|
82
|
+
raw: unknown,
|
|
83
|
+
base: string[],
|
|
84
|
+
desc: string,
|
|
85
|
+
set: (c: Obj, v: string | undefined) => void,
|
|
86
|
+
) => {
|
|
87
|
+
const current = raw === undefined ? UNSET : String(raw);
|
|
88
|
+
rows.push({
|
|
89
|
+
id,
|
|
90
|
+
label,
|
|
91
|
+
description: `${desc} "${UNSET}" clears the value in this scope.`,
|
|
92
|
+
current,
|
|
93
|
+
values: cycleValues(current, [UNSET, ...base]),
|
|
94
|
+
apply: (c, v) => set(c, v === UNSET ? undefined : v),
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const text = (
|
|
99
|
+
id: string,
|
|
100
|
+
label: string,
|
|
101
|
+
raw: unknown,
|
|
102
|
+
desc: string,
|
|
103
|
+
set: (c: Obj, v: string | undefined) => void,
|
|
104
|
+
) =>
|
|
105
|
+
rows.push({
|
|
106
|
+
id,
|
|
107
|
+
label,
|
|
108
|
+
description: `${desc} Empty clears the value.`,
|
|
109
|
+
current:
|
|
110
|
+
typeof raw === "string" && raw ? (raw.length > 40 ? `${raw.slice(0, 37)}...` : raw) : UNSET,
|
|
111
|
+
submenu: "text",
|
|
112
|
+
apply: (c, v) => set(c, v.trim() || undefined),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const model = (
|
|
116
|
+
id: string,
|
|
117
|
+
label: string,
|
|
118
|
+
raw: unknown,
|
|
119
|
+
desc: string,
|
|
120
|
+
set: (c: Obj, v: string) => void,
|
|
121
|
+
) =>
|
|
122
|
+
rows.push({
|
|
123
|
+
id,
|
|
124
|
+
label,
|
|
125
|
+
description: desc,
|
|
126
|
+
current: firstModel(raw) ?? UNSET,
|
|
127
|
+
submenu: "model",
|
|
128
|
+
apply: (c, v) => set(c, v),
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const action = (id: string, label: string, desc: string, run: (c: Obj) => void) =>
|
|
132
|
+
rows.push({
|
|
133
|
+
id,
|
|
134
|
+
label,
|
|
135
|
+
description: desc,
|
|
136
|
+
current: "…",
|
|
137
|
+
values: ["…", "remove"],
|
|
138
|
+
apply: (c, v) => v === "remove" && run(c),
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
const thinking = (
|
|
142
|
+
id: string,
|
|
143
|
+
label: string,
|
|
144
|
+
raw: unknown,
|
|
145
|
+
set: (c: Obj, v: string | undefined) => void,
|
|
146
|
+
) => cycle(id, label, raw, [...THINKING], "Reasoning effort; unset uses the model default.", set);
|
|
147
|
+
|
|
148
|
+
// second_opinion
|
|
149
|
+
const sc = (c: Obj) => child(c, "secondOpinion");
|
|
150
|
+
toggle("so.enabled", "second_opinion · enabled", so.enabled, eff.secondOpinion.enabled, (c, v) =>
|
|
151
|
+
put(sc(c), "enabled", v),
|
|
152
|
+
);
|
|
153
|
+
model(
|
|
154
|
+
"so.model",
|
|
155
|
+
"second_opinion · default model",
|
|
156
|
+
so.model,
|
|
157
|
+
"Model used when the agent passes none. Unset uses the session's model.",
|
|
158
|
+
(c, v) => setFirstModel(sc(c), "model", v),
|
|
159
|
+
);
|
|
160
|
+
thinking("so.thinking", "second_opinion · thinking", so.thinking, (c, v) =>
|
|
161
|
+
put(sc(c), "thinking", v),
|
|
162
|
+
);
|
|
163
|
+
cycle(
|
|
164
|
+
"so.maxTokens",
|
|
165
|
+
"second_opinion · max tokens",
|
|
166
|
+
so.maxTokens,
|
|
167
|
+
TOKENS,
|
|
168
|
+
"Output cap per call.",
|
|
169
|
+
(c, v) => put(sc(c), "maxTokens", v && Number(v)),
|
|
170
|
+
);
|
|
171
|
+
cycle(
|
|
172
|
+
"so.timeout",
|
|
173
|
+
"second_opinion · timeout (s)",
|
|
174
|
+
so.timeoutSeconds,
|
|
175
|
+
TIMEOUTS,
|
|
176
|
+
`Per call. Effective: ${eff.secondOpinion.timeoutSeconds}.`,
|
|
177
|
+
(c, v) => put(sc(c), "timeoutSeconds", v && Number(v)),
|
|
178
|
+
);
|
|
179
|
+
text(
|
|
180
|
+
"so.prompt",
|
|
181
|
+
"second_opinion · extra prompt",
|
|
182
|
+
so.systemPrompt,
|
|
183
|
+
"Appended to the reviewer's system prompt.",
|
|
184
|
+
(c, v) => put(sc(c), "systemPrompt", v),
|
|
185
|
+
);
|
|
186
|
+
const opts = Array.isArray(so.models) ? so.models : [];
|
|
187
|
+
opts.forEach((entry, i) => {
|
|
188
|
+
const e = isObj(entry) ? entry : {};
|
|
189
|
+
const name = `option ${typeof e.id === "string" ? e.id : (firstModel(e) ?? i + 1)}`;
|
|
190
|
+
const at = (c: Obj) => {
|
|
191
|
+
const list = sc(c).models as unknown[];
|
|
192
|
+
if (!isObj(list[i])) list[i] = {};
|
|
193
|
+
return list[i] as Obj;
|
|
194
|
+
};
|
|
195
|
+
const p = `so.opt.${i}`;
|
|
196
|
+
model(`${p}.model`, ` ${name} · model`, e.model, "Model the agent can switch to.", (c, v) =>
|
|
197
|
+
setFirstModel(at(c), "model", v),
|
|
198
|
+
);
|
|
199
|
+
text(
|
|
200
|
+
`${p}.id`,
|
|
201
|
+
` ${name} · id`,
|
|
202
|
+
e.id,
|
|
203
|
+
"Name the agent passes as 'model'. Defaults to the model string.",
|
|
204
|
+
(c, v) => put(at(c), "id", v),
|
|
205
|
+
);
|
|
206
|
+
text(
|
|
207
|
+
`${p}.useWhen`,
|
|
208
|
+
` ${name} · use when`,
|
|
209
|
+
e.useWhen,
|
|
210
|
+
"Tells the agent when to pick this model over the default.",
|
|
211
|
+
(c, v) => put(at(c), "useWhen", v),
|
|
212
|
+
);
|
|
213
|
+
thinking(`${p}.thinking`, ` ${name} · thinking`, e.thinking, (c, v) =>
|
|
214
|
+
put(at(c), "thinking", v),
|
|
215
|
+
);
|
|
216
|
+
action(`${p}.remove`, ` ${name} · remove`, "Delete this option.", (c) =>
|
|
217
|
+
(sc(c).models as unknown[]).splice(i, 1),
|
|
218
|
+
);
|
|
219
|
+
});
|
|
220
|
+
rows.push({
|
|
221
|
+
id: "so.add",
|
|
222
|
+
label: "second_opinion · add option",
|
|
223
|
+
description: "Pick a model to add as an override option, then set its 'use when'.",
|
|
224
|
+
current: "pick…",
|
|
225
|
+
submenu: "model",
|
|
226
|
+
apply: (c, v) => {
|
|
227
|
+
const s = sc(c);
|
|
228
|
+
if (!Array.isArray(s.models)) s.models = [];
|
|
229
|
+
(s.models as unknown[]).push({ model: v, useWhen: "" });
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
// council
|
|
234
|
+
const cc = (c: Obj) => child(c, "council");
|
|
235
|
+
toggle("co.enabled", "council · enabled", co.enabled, eff.council.enabled, (c, v) =>
|
|
236
|
+
put(cc(c), "enabled", v),
|
|
237
|
+
);
|
|
238
|
+
cycle(
|
|
239
|
+
"co.default",
|
|
240
|
+
"council · default preset",
|
|
241
|
+
co.defaultPreset,
|
|
242
|
+
Object.keys(eff.council.presets),
|
|
243
|
+
`Effective: ${eff.council.defaultPreset}.`,
|
|
244
|
+
(c, v) => put(cc(c), "defaultPreset", v),
|
|
245
|
+
);
|
|
246
|
+
cycle(
|
|
247
|
+
"co.maxTokens",
|
|
248
|
+
"council · max tokens",
|
|
249
|
+
co.maxTokens,
|
|
250
|
+
TOKENS,
|
|
251
|
+
"Output cap per councillor and synthesizer call.",
|
|
252
|
+
(c, v) => put(cc(c), "maxTokens", v && Number(v)),
|
|
253
|
+
);
|
|
254
|
+
cycle(
|
|
255
|
+
"co.timeout",
|
|
256
|
+
"council · timeout (s)",
|
|
257
|
+
co.timeoutSeconds,
|
|
258
|
+
TIMEOUTS,
|
|
259
|
+
`Per call. Effective: ${eff.council.timeoutSeconds}.`,
|
|
260
|
+
(c, v) => put(cc(c), "timeoutSeconds", v && Number(v)),
|
|
261
|
+
);
|
|
262
|
+
text(
|
|
263
|
+
"co.prompt",
|
|
264
|
+
"council · councillor prompt",
|
|
265
|
+
co.councillorPrompt,
|
|
266
|
+
"Appended to every councillor's system prompt.",
|
|
267
|
+
(c, v) => put(cc(c), "councillorPrompt", v),
|
|
268
|
+
);
|
|
269
|
+
const sy = (c: Obj) => child(cc(c), "synthesizer");
|
|
270
|
+
toggle(
|
|
271
|
+
"syn.enabled",
|
|
272
|
+
"council · synthesizer enabled",
|
|
273
|
+
syn.enabled,
|
|
274
|
+
eff.council.synthesizer.enabled,
|
|
275
|
+
(c, v) => put(sy(c), "enabled", v),
|
|
276
|
+
);
|
|
277
|
+
model(
|
|
278
|
+
"syn.model",
|
|
279
|
+
"council · synthesizer model",
|
|
280
|
+
syn.model,
|
|
281
|
+
"Unset uses the session's model.",
|
|
282
|
+
(c, v) => setFirstModel(sy(c), "model", v),
|
|
283
|
+
);
|
|
284
|
+
thinking("syn.thinking", "council · synthesizer thinking", syn.thinking, (c, v) =>
|
|
285
|
+
put(sy(c), "thinking", v),
|
|
286
|
+
);
|
|
287
|
+
text(
|
|
288
|
+
"syn.prompt",
|
|
289
|
+
"council · synthesizer prompt",
|
|
290
|
+
syn.prompt,
|
|
291
|
+
"Appended to the synthesizer's system prompt.",
|
|
292
|
+
(c, v) => put(sy(c), "prompt", v),
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
const presets = isObj(co.presets) ? co.presets : {};
|
|
296
|
+
for (const [pn, praw] of Object.entries(presets)) {
|
|
297
|
+
const pr = isObj(praw) ? praw : {};
|
|
298
|
+
const pat = (c: Obj) => child(child(cc(c), "presets"), pn);
|
|
299
|
+
const pl = `preset ${pn}`;
|
|
300
|
+
text(
|
|
301
|
+
`pr.${pn}.useWhen`,
|
|
302
|
+
`${pl} · use when`,
|
|
303
|
+
pr.useWhen,
|
|
304
|
+
"Tells the agent when to pick this preset.",
|
|
305
|
+
(c, v) => put(pat(c), "useWhen", v),
|
|
306
|
+
);
|
|
307
|
+
rows.push({
|
|
308
|
+
id: `pr.${pn}.add`,
|
|
309
|
+
label: `${pl} · add councillor`,
|
|
310
|
+
description:
|
|
311
|
+
"Pick a model; the councillor is named after it. Rename by editing settings.json.",
|
|
312
|
+
current: "pick…",
|
|
313
|
+
submenu: "model",
|
|
314
|
+
apply: (c, v) => {
|
|
315
|
+
const list = child(pat(c), "councillors");
|
|
316
|
+
const base = v.slice(v.lastIndexOf("/") + 1);
|
|
317
|
+
let name = base;
|
|
318
|
+
for (let n = 2; name in list; n++) name = `${base}-${n}`;
|
|
319
|
+
list[name] = { model: v };
|
|
320
|
+
},
|
|
321
|
+
});
|
|
322
|
+
action(
|
|
323
|
+
`pr.${pn}.remove`,
|
|
324
|
+
`${pl} · remove`,
|
|
325
|
+
"Delete this preset.",
|
|
326
|
+
(c) => delete child(cc(c), "presets")[pn],
|
|
327
|
+
);
|
|
328
|
+
for (const [cn, craw] of Object.entries(isObj(pr.councillors) ? pr.councillors : {})) {
|
|
329
|
+
const cr = isObj(craw) ? craw : {};
|
|
330
|
+
const cat = (c: Obj) => child(child(pat(c), "councillors"), cn);
|
|
331
|
+
const cl = ` ${pn}/${cn}`;
|
|
332
|
+
model(
|
|
333
|
+
`pr.${pn}.${cn}.model`,
|
|
334
|
+
`${cl} · model`,
|
|
335
|
+
cr.model,
|
|
336
|
+
"First model of the chain; add fallbacks in settings.json.",
|
|
337
|
+
(c, v) => setFirstModel(cat(c), "model", v),
|
|
338
|
+
);
|
|
339
|
+
thinking(`pr.${pn}.${cn}.thinking`, `${cl} · thinking`, cr.thinking, (c, v) =>
|
|
340
|
+
put(cat(c), "thinking", v),
|
|
341
|
+
);
|
|
342
|
+
text(
|
|
343
|
+
`pr.${pn}.${cn}.prompt`,
|
|
344
|
+
`${cl} · role prompt`,
|
|
345
|
+
cr.prompt,
|
|
346
|
+
"Role guidance appended to this councillor's system prompt.",
|
|
347
|
+
(c, v) => put(cat(c), "prompt", v),
|
|
348
|
+
);
|
|
349
|
+
action(
|
|
350
|
+
`pr.${pn}.${cn}.remove`,
|
|
351
|
+
`${cl} · remove`,
|
|
352
|
+
"Delete this councillor.",
|
|
353
|
+
(c) => delete child(pat(c), "councillors")[cn],
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
rows.push({
|
|
358
|
+
id: "co.addPreset",
|
|
359
|
+
label: "council · add preset",
|
|
360
|
+
description: "Type a name, then add councillors to it.",
|
|
361
|
+
current: "name…",
|
|
362
|
+
submenu: "text",
|
|
363
|
+
apply: (c, v) => {
|
|
364
|
+
const name = v.trim();
|
|
365
|
+
if (name) child(child(cc(c), "presets"), name).councillors ??= {};
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
return rows;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function readData(path: string): { data: Obj; indent: string } {
|
|
372
|
+
if (!existsSync(path)) return { data: {}, indent: "\t" };
|
|
373
|
+
const text = readFileSync(path, "utf8");
|
|
374
|
+
if (!text.trim()) return { data: {}, indent: "\t" };
|
|
375
|
+
const data = JSON.parse(text) as unknown;
|
|
376
|
+
if (!isObj(data)) throw new Error(`${path} is not a JSON object`);
|
|
377
|
+
return { data, indent: /^\{\r?\n(\t| +)/.exec(text)?.[1] ?? "\t" };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** The raw `council` object of one settings file; `{}` when missing or unreadable. */
|
|
381
|
+
export function readLayer(path: string): Obj {
|
|
382
|
+
try {
|
|
383
|
+
const c = readData(path).data.council;
|
|
384
|
+
return isObj(c) ? c : {};
|
|
385
|
+
} catch {
|
|
386
|
+
return {};
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Applies `fn` to the file's `council` object and writes it back atomically, keeping other settings. */
|
|
391
|
+
export function saveLayer(path: string, fn: (council: Obj) => void) {
|
|
392
|
+
const { data, indent } = readData(path);
|
|
393
|
+
const council = child(data, "council");
|
|
394
|
+
fn(council);
|
|
395
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
396
|
+
const tmp = `${path}.tmp-${process.pid}`;
|
|
397
|
+
writeFileSync(tmp, `${JSON.stringify(data, null, indent)}\n`);
|
|
398
|
+
renameSync(tmp, path);
|
|
399
|
+
}
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Embeds the files as tagged blocks. Unreadable or oversized files are reported, never thrown. */
|
|
5
|
+
export function embedFiles(paths: string[] | undefined, cwd: string, maxBytes: number): string {
|
|
6
|
+
if (!paths?.length) return "";
|
|
7
|
+
return paths
|
|
8
|
+
.map((p) => {
|
|
9
|
+
try {
|
|
10
|
+
const buf = readFileSync(resolve(cwd, p));
|
|
11
|
+
const truncated = buf.length > maxBytes;
|
|
12
|
+
const text = buf.subarray(0, maxBytes).toString("utf8");
|
|
13
|
+
return `<file path="${p}"${truncated ? ` truncated="${maxBytes} of ${buf.length} bytes"` : ""}>\n${text}\n</file>`;
|
|
14
|
+
} catch (e) {
|
|
15
|
+
return `<file path="${p}" error="${(e as Error).message}" />`;
|
|
16
|
+
}
|
|
17
|
+
})
|
|
18
|
+
.join("\n\n");
|
|
19
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { loadConfig, type ModelRef } from "./config.ts";
|
|
4
|
+
import { embedFiles } from "./files.ts";
|
|
5
|
+
import {
|
|
6
|
+
COUNCILLOR_SYSTEM,
|
|
7
|
+
SECOND_OPINION_SYSTEM,
|
|
8
|
+
SYNTHESIZER_SYSTEM,
|
|
9
|
+
userPrompt,
|
|
10
|
+
withExtra,
|
|
11
|
+
} from "./prompts.ts";
|
|
12
|
+
import { callChain } from "./run.ts";
|
|
13
|
+
import { openSettings } from "./ui.ts";
|
|
14
|
+
import {
|
|
15
|
+
councilActive,
|
|
16
|
+
councilDescription,
|
|
17
|
+
secondOpinionActive,
|
|
18
|
+
secondOpinionDescription,
|
|
19
|
+
} from "./usage.ts";
|
|
20
|
+
|
|
21
|
+
const text = (t: string, details: Record<string, unknown> = {}) => ({
|
|
22
|
+
content: [{ type: "text" as const, text: t }],
|
|
23
|
+
details,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** The session's current model as a fallback when no model is configured. */
|
|
27
|
+
function sessionModel(ctx: ExtensionContext): ModelRef[] {
|
|
28
|
+
return ctx.model ? [{ model: `${ctx.model.provider}/${ctx.model.id}` }] : [];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const FILES_DESC =
|
|
32
|
+
"Paths (relative to cwd) of files to include verbatim. Prefer this over pasting code.";
|
|
33
|
+
const CONTEXT_DESC =
|
|
34
|
+
"Everything the reviewer needs: goal, constraints, what you tried, relevant findings. The reviewer sees nothing else from this session.";
|
|
35
|
+
|
|
36
|
+
export default function (pi: ExtensionAPI) {
|
|
37
|
+
const config = loadConfig();
|
|
38
|
+
|
|
39
|
+
pi.registerCommand("council-config", {
|
|
40
|
+
description: "Configure second_opinion and council. `show` prints the effective config.",
|
|
41
|
+
handler: async (args, ctx) => {
|
|
42
|
+
if (ctx.hasUI && args.trim() !== "show") {
|
|
43
|
+
if (await openSettings(ctx)) await ctx.reload();
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const cfg = loadConfig(ctx.cwd);
|
|
47
|
+
ctx.ui.notify(
|
|
48
|
+
`second_opinion: ${cfg.secondOpinion.enabled ? "on" : "off"}, default ${cfg.secondOpinion.default?.model ?? "session model"}, ${cfg.secondOpinion.options.length} options\ncouncil: ${cfg.council.enabled ? "on" : "off"}, presets ${Object.keys(cfg.council.presets).join(", ") || "none"}`,
|
|
49
|
+
"info",
|
|
50
|
+
);
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
if (secondOpinionActive(config))
|
|
55
|
+
pi.registerTool({
|
|
56
|
+
name: "second_opinion",
|
|
57
|
+
label: "Second Opinion",
|
|
58
|
+
description: secondOpinionDescription(config),
|
|
59
|
+
promptSnippet: "Get a second opinion from another model",
|
|
60
|
+
promptGuidelines: [
|
|
61
|
+
"Use second_opinion before committing to a non-trivial design or when unsure; give it full context since it sees nothing else.",
|
|
62
|
+
],
|
|
63
|
+
parameters: Type.Object({
|
|
64
|
+
question: Type.String({
|
|
65
|
+
description: "What you want a second opinion on, stated precisely.",
|
|
66
|
+
}),
|
|
67
|
+
context: Type.Optional(Type.String({ description: CONTEXT_DESC })),
|
|
68
|
+
files: Type.Optional(Type.Array(Type.String(), { description: FILES_DESC })),
|
|
69
|
+
model: Type.Optional(
|
|
70
|
+
Type.String({
|
|
71
|
+
description: "Option id or model from this tool's description. Omit for the default.",
|
|
72
|
+
}),
|
|
73
|
+
),
|
|
74
|
+
}),
|
|
75
|
+
async execute(_id, params, signal, _update, ctx) {
|
|
76
|
+
const fresh = loadConfig(ctx.cwd);
|
|
77
|
+
const s = fresh.secondOpinion;
|
|
78
|
+
let chain: ModelRef[];
|
|
79
|
+
if (params.model) {
|
|
80
|
+
const pick = s.options.find((o) => o.id === params.model || o.model === params.model);
|
|
81
|
+
if (!pick) {
|
|
82
|
+
const ids = s.options.map((o) => o.id).join(", ") || "(none configured)";
|
|
83
|
+
throw new Error(`Unknown model "${params.model}". Options: ${ids}`);
|
|
84
|
+
}
|
|
85
|
+
chain = [pick];
|
|
86
|
+
} else {
|
|
87
|
+
chain = s.default ? [s.default] : sessionModel(ctx);
|
|
88
|
+
}
|
|
89
|
+
const files = embedFiles(params.files, ctx.cwd, fresh.maxFileBytes);
|
|
90
|
+
const r = await callChain(ctx, chain, {
|
|
91
|
+
system: withExtra(SECOND_OPINION_SYSTEM, s.systemPrompt),
|
|
92
|
+
prompt: userPrompt(params.question, params.context, files),
|
|
93
|
+
maxTokens: s.maxTokens,
|
|
94
|
+
timeoutSeconds: s.timeoutSeconds,
|
|
95
|
+
signal,
|
|
96
|
+
});
|
|
97
|
+
return text(`Second opinion from ${r.ref.model}:\n\n${r.text}`, { model: r.ref.model });
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
if (councilActive(config))
|
|
102
|
+
pi.registerTool({
|
|
103
|
+
name: "council",
|
|
104
|
+
label: "Council",
|
|
105
|
+
description: councilDescription(config),
|
|
106
|
+
promptSnippet: "Have a council of models review a plan or change and report issues and gaps",
|
|
107
|
+
promptGuidelines: [
|
|
108
|
+
"Use council only for high-stakes or hard-to-reverse decisions and large reviews; prefer second_opinion otherwise.",
|
|
109
|
+
],
|
|
110
|
+
parameters: Type.Object({
|
|
111
|
+
question: Type.String({ description: "What the council should review or decide." }),
|
|
112
|
+
context: Type.Optional(Type.String({ description: CONTEXT_DESC })),
|
|
113
|
+
files: Type.Optional(Type.Array(Type.String(), { description: FILES_DESC })),
|
|
114
|
+
preset: Type.Optional(Type.String({ description: "Preset name. Omit for the default." })),
|
|
115
|
+
}),
|
|
116
|
+
async execute(_id, params, signal, update, ctx) {
|
|
117
|
+
const fresh = loadConfig(ctx.cwd);
|
|
118
|
+
const c = fresh.council;
|
|
119
|
+
const name = params.preset ?? c.defaultPreset;
|
|
120
|
+
const preset = c.presets[name];
|
|
121
|
+
if (!preset) {
|
|
122
|
+
throw new Error(
|
|
123
|
+
`Unknown preset "${name}". Presets: ${Object.keys(c.presets).join(", ")}`,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
const prompt = userPrompt(
|
|
127
|
+
params.question,
|
|
128
|
+
params.context,
|
|
129
|
+
embedFiles(params.files, ctx.cwd, fresh.maxFileBytes),
|
|
130
|
+
);
|
|
131
|
+
const names = Object.keys(preset.councillors);
|
|
132
|
+
update?.(text(`Council "${name}": asking ${names.join(", ")}...`));
|
|
133
|
+
|
|
134
|
+
const settled = await Promise.allSettled(
|
|
135
|
+
names.map((n) => {
|
|
136
|
+
const cl = preset.councillors[n];
|
|
137
|
+
return callChain(ctx, cl.chain, {
|
|
138
|
+
system: withExtra(withExtra(COUNCILLOR_SYSTEM, c.councillorPrompt), cl.prompt),
|
|
139
|
+
prompt,
|
|
140
|
+
maxTokens: c.maxTokens,
|
|
141
|
+
timeoutSeconds: c.timeoutSeconds,
|
|
142
|
+
signal,
|
|
143
|
+
});
|
|
144
|
+
}),
|
|
145
|
+
);
|
|
146
|
+
const answers = settled.map((s, i) => ({
|
|
147
|
+
name: names[i],
|
|
148
|
+
model: s.status === "fulfilled" ? s.value.ref.model : undefined,
|
|
149
|
+
text: s.status === "fulfilled" ? s.value.text : undefined,
|
|
150
|
+
error: s.status === "rejected" ? (s.reason as Error).message : undefined,
|
|
151
|
+
}));
|
|
152
|
+
const ok = answers.filter((a) => a.text);
|
|
153
|
+
if (!ok.length) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`All councillors failed:\n${answers.map((a) => `- ${a.name}: ${a.error}`).join("\n")}`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
const failed = answers.filter((a) => !a.text);
|
|
159
|
+
const failNote = failed.length
|
|
160
|
+
? `\n\nFailed councillors:\n${failed.map((a) => `- ${a.name}: ${a.error}`).join("\n")}`
|
|
161
|
+
: "";
|
|
162
|
+
const raw = ok.map((a) => `## ${a.name} (${a.model})\n\n${a.text}`).join("\n\n");
|
|
163
|
+
const details = {
|
|
164
|
+
preset: name,
|
|
165
|
+
councillors: answers.map((a) => ({ name: a.name, model: a.model, error: a.error })),
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
if (!c.synthesizer.enabled || ok.length === 1) {
|
|
169
|
+
return text(`Council "${name}" (unsynthesized):\n\n${raw}${failNote}`, details);
|
|
170
|
+
}
|
|
171
|
+
update?.(text(`Council "${name}": synthesizing ${ok.length} answers...`));
|
|
172
|
+
const synthChain = c.synthesizer.chain.length ? c.synthesizer.chain : sessionModel(ctx);
|
|
173
|
+
try {
|
|
174
|
+
const synth = await callChain(ctx, synthChain, {
|
|
175
|
+
system: withExtra(SYNTHESIZER_SYSTEM, c.synthesizer.prompt),
|
|
176
|
+
prompt: `${prompt}\n\n<councillor_answers>\n${raw}\n</councillor_answers>`,
|
|
177
|
+
maxTokens: c.maxTokens,
|
|
178
|
+
timeoutSeconds: c.timeoutSeconds,
|
|
179
|
+
signal,
|
|
180
|
+
});
|
|
181
|
+
return text(
|
|
182
|
+
`Council "${name}" synthesis (by ${synth.ref.model}; councillors: ${ok.map((a) => a.name).join(", ")}):\n\n${synth.text}${failNote}`,
|
|
183
|
+
details,
|
|
184
|
+
);
|
|
185
|
+
} catch (e) {
|
|
186
|
+
return text(
|
|
187
|
+
`Council "${name}": synthesizer failed (${(e as Error).message}); raw councillor answers follow.\n\n${raw}${failNote}`,
|
|
188
|
+
details,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
}
|
package/src/prompts.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const SECOND_OPINION_SYSTEM = `You are giving a second opinion to another AI coding agent that asked for it.
|
|
2
|
+
You see only what it sent you; you cannot run tools or see the repository beyond the attached files.
|
|
3
|
+
Be direct and concrete. Say where you agree, where you disagree and why, and what the agent may have missed.
|
|
4
|
+
Flag assumptions you had to make because context was missing. Do not pad the answer.`;
|
|
5
|
+
|
|
6
|
+
export const COUNCILLOR_SYSTEM = `You are one councillor on a review council. A calling agent sent you a question and context; other councillors with different models answer independently.
|
|
7
|
+
You cannot run tools; work from the question, context and attached files only.
|
|
8
|
+
Report concrete issues, gaps, risks and better alternatives. For each finding give: severity (high/medium/low), what is wrong or missing, evidence (file and line when attached), and a suggested fix.
|
|
9
|
+
End with a one-line verdict. Do not pad, and do not restate the question.`;
|
|
10
|
+
|
|
11
|
+
export const SYNTHESIZER_SYSTEM = `You are the synthesizer of a review council. Several councillors answered the same question independently.
|
|
12
|
+
Merge their answers into one report for the calling agent:
|
|
13
|
+
1. Consensus: findings several councillors raised (note how many).
|
|
14
|
+
2. Unique findings: raised by one councillor and plausible; name the councillor.
|
|
15
|
+
3. Disagreements: state each position and which you find stronger and why.
|
|
16
|
+
4. Recommended actions, ordered by severity.
|
|
17
|
+
Drop duplicates and findings that are clearly wrong or unsupported. If a councillor failed or returned nothing, say so briefly. Do not invent findings the councillors did not make.`;
|
|
18
|
+
|
|
19
|
+
export function userPrompt(question: string, context: string | undefined, files: string): string {
|
|
20
|
+
return [
|
|
21
|
+
`<question>\n${question}\n</question>`,
|
|
22
|
+
context ? `<context>\n${context}\n</context>` : "",
|
|
23
|
+
files,
|
|
24
|
+
]
|
|
25
|
+
.filter(Boolean)
|
|
26
|
+
.join("\n\n");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function withExtra(base: string, extra?: string): string {
|
|
30
|
+
return extra ? `${base}\n\n${extra}` : base;
|
|
31
|
+
}
|
package/src/run.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ModelRef } from "./config.ts";
|
|
3
|
+
|
|
4
|
+
export interface CallOptions {
|
|
5
|
+
system: string;
|
|
6
|
+
prompt: string;
|
|
7
|
+
maxTokens?: number;
|
|
8
|
+
timeoutSeconds: number;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface CallResult {
|
|
13
|
+
ref: ModelRef;
|
|
14
|
+
text: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Splits `provider/model`; the model id may itself contain slashes. */
|
|
18
|
+
export function splitModel(model: string): { provider: string; id: string } {
|
|
19
|
+
const i = model.indexOf("/");
|
|
20
|
+
return { provider: model.slice(0, i), id: model.slice(i + 1) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** One tool-less completion. Throws with a readable message on any failure. */
|
|
24
|
+
export async function callModel(
|
|
25
|
+
ctx: ExtensionContext,
|
|
26
|
+
ref: ModelRef,
|
|
27
|
+
o: CallOptions,
|
|
28
|
+
): Promise<CallResult> {
|
|
29
|
+
const { provider, id } = splitModel(ref.model);
|
|
30
|
+
const model = ctx.modelRegistry.find(provider, id);
|
|
31
|
+
if (!model) throw new Error(`model ${ref.model} not found`);
|
|
32
|
+
if (model.api === "pi-virtual") {
|
|
33
|
+
throw new Error(`${ref.model} is a virtual model (alias); use a concrete provider/model`);
|
|
34
|
+
}
|
|
35
|
+
const signal = AbortSignal.any([
|
|
36
|
+
AbortSignal.timeout(o.timeoutSeconds * 1000),
|
|
37
|
+
...(o.signal ? [o.signal] : []),
|
|
38
|
+
]);
|
|
39
|
+
const msg = await ctx.modelRegistry
|
|
40
|
+
.streamSimple(
|
|
41
|
+
model,
|
|
42
|
+
{
|
|
43
|
+
systemPrompt: o.system,
|
|
44
|
+
messages: [{ role: "user", content: o.prompt, timestamp: Date.now() }],
|
|
45
|
+
},
|
|
46
|
+
{ signal, maxTokens: o.maxTokens, reasoning: ref.thinking },
|
|
47
|
+
)
|
|
48
|
+
.result();
|
|
49
|
+
if (msg.stopReason === "error" || msg.stopReason === "aborted") {
|
|
50
|
+
throw new Error(msg.errorMessage ?? msg.stopReason);
|
|
51
|
+
}
|
|
52
|
+
const text = msg.content
|
|
53
|
+
.flatMap((c) => (c.type === "text" ? c.text : []))
|
|
54
|
+
.join("")
|
|
55
|
+
.trim();
|
|
56
|
+
if (!text) throw new Error("empty response");
|
|
57
|
+
return { ref, text };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Tries each ref in order; the error lists every failure. */
|
|
61
|
+
export async function callChain(
|
|
62
|
+
ctx: ExtensionContext,
|
|
63
|
+
chain: ModelRef[],
|
|
64
|
+
o: CallOptions,
|
|
65
|
+
): Promise<CallResult> {
|
|
66
|
+
const errors: string[] = [];
|
|
67
|
+
for (const ref of chain) {
|
|
68
|
+
try {
|
|
69
|
+
return await callModel(ctx, ref, o);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
if (o.signal?.aborted) throw e;
|
|
72
|
+
errors.push(`${ref.model}: ${(e as Error).message}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
throw new Error(errors.join("; ") || "no model configured");
|
|
76
|
+
}
|
package/src/ui.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
type ExtensionCommandContext,
|
|
4
|
+
getAgentDir,
|
|
5
|
+
getSelectListTheme,
|
|
6
|
+
getSettingsListTheme,
|
|
7
|
+
} from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import {
|
|
9
|
+
type Component,
|
|
10
|
+
Container,
|
|
11
|
+
Input,
|
|
12
|
+
SelectList,
|
|
13
|
+
type SettingItem,
|
|
14
|
+
SettingsList,
|
|
15
|
+
Text,
|
|
16
|
+
} from "@earendil-works/pi-tui";
|
|
17
|
+
import { loadConfig } from "./config.ts";
|
|
18
|
+
import { buildRows, type Row, readLayer, saveLayer, UNSET } from "./edit.ts";
|
|
19
|
+
|
|
20
|
+
type Scope = "global" | "project";
|
|
21
|
+
|
|
22
|
+
/** Filterable model list: type to narrow, arrows to move, enter to pick, escape to cancel. */
|
|
23
|
+
function modelPicker(models: string[], current: string, done: (v?: string) => void): Component {
|
|
24
|
+
const items = [UNSET, ...models].map((value) => ({
|
|
25
|
+
value,
|
|
26
|
+
label: value === UNSET ? "unset (use the session's model)" : value,
|
|
27
|
+
}));
|
|
28
|
+
const list = new SelectList(items, 12, getSelectListTheme());
|
|
29
|
+
list.setSelectedIndex(
|
|
30
|
+
Math.max(
|
|
31
|
+
0,
|
|
32
|
+
items.findIndex((i) => i.value === current),
|
|
33
|
+
),
|
|
34
|
+
);
|
|
35
|
+
list.onSelect = (i) => done(i.value);
|
|
36
|
+
list.onCancel = () => done();
|
|
37
|
+
const input = new Input({ prompt: "filter: " });
|
|
38
|
+
return {
|
|
39
|
+
render: (w) => [...input.render(w), ...list.render(w)],
|
|
40
|
+
invalidate: () => list.invalidate(),
|
|
41
|
+
handleInput: (data) => {
|
|
42
|
+
list.handleInput(data);
|
|
43
|
+
input.handleInput(data);
|
|
44
|
+
list.setFilter(input.getValue());
|
|
45
|
+
},
|
|
46
|
+
} as Component;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function textEditor(initial: string, done: (v?: string) => void): Component {
|
|
50
|
+
const input = new Input({ prompt: "> " });
|
|
51
|
+
input.setValue(initial);
|
|
52
|
+
input.onSubmit = (v) => done(v);
|
|
53
|
+
input.onEscape = () => done();
|
|
54
|
+
return input;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Opens the council settings screen. Resolves when the user closes it; true when anything was saved. */
|
|
58
|
+
export async function openSettings(ctx: ExtensionCommandContext): Promise<boolean> {
|
|
59
|
+
let dirty = false;
|
|
60
|
+
const cwd = ctx.cwd;
|
|
61
|
+
let scope: Scope = "global";
|
|
62
|
+
const pathOf = (s: Scope) =>
|
|
63
|
+
s === "global" ? join(getAgentDir(), "settings.json") : join(cwd, ".pi", "settings.json");
|
|
64
|
+
const models = [
|
|
65
|
+
...new Set(
|
|
66
|
+
ctx.modelRegistry
|
|
67
|
+
.getAvailable()
|
|
68
|
+
.filter((m) => m.api !== "pi-virtual")
|
|
69
|
+
.map((m) => `${m.provider}/${m.id}`),
|
|
70
|
+
),
|
|
71
|
+
].sort();
|
|
72
|
+
|
|
73
|
+
let rows: Row[] = [];
|
|
74
|
+
const rebuild = () => {
|
|
75
|
+
rows = buildRows(readLayer(pathOf(scope)), loadConfig(cwd));
|
|
76
|
+
};
|
|
77
|
+
const toItem = (r: Row): SettingItem => ({
|
|
78
|
+
id: r.id,
|
|
79
|
+
label: r.label,
|
|
80
|
+
description: r.description,
|
|
81
|
+
currentValue: r.current,
|
|
82
|
+
values: r.values,
|
|
83
|
+
submenu:
|
|
84
|
+
r.submenu === "model"
|
|
85
|
+
? (cur, done) => modelPicker(models, cur, done)
|
|
86
|
+
: r.submenu === "text"
|
|
87
|
+
? (cur, done) => textEditor(cur === UNSET || cur === "name…" ? "" : cur, done)
|
|
88
|
+
: undefined,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
await ctx.ui.custom<void>((tui, theme, kb, done) => {
|
|
92
|
+
const title = new Text("", 0, 0);
|
|
93
|
+
const file = new Text("", 0, 0);
|
|
94
|
+
const status = new Text("", 0, 0);
|
|
95
|
+
const header = new Container();
|
|
96
|
+
header.addChild(title);
|
|
97
|
+
header.addChild(file);
|
|
98
|
+
const tabKey = kb.getKeys("tui.input.tab")[0];
|
|
99
|
+
const renderHeader = () => {
|
|
100
|
+
title.setText(
|
|
101
|
+
`⚙ Council · Saving to: ${scope === "global" ? "Global" : "Project"}${tabKey ? theme.fg("muted", ` · ${tabKey} to switch`) : ""}`,
|
|
102
|
+
);
|
|
103
|
+
file.setText(theme.fg("muted", ` ${pathOf(scope)} · pi reloads on close to apply changes`));
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
let list: SettingsList;
|
|
107
|
+
const makeList = () => {
|
|
108
|
+
rebuild();
|
|
109
|
+
list = new SettingsList(
|
|
110
|
+
rows.map(toItem),
|
|
111
|
+
Math.max(5, Math.min(tui.terminal.rows - 10, rows.length)),
|
|
112
|
+
getSettingsListTheme(),
|
|
113
|
+
(id, next) => {
|
|
114
|
+
const row = rows.find((r) => r.id === id);
|
|
115
|
+
try {
|
|
116
|
+
if (row) {
|
|
117
|
+
saveLayer(pathOf(scope), (c) => row.apply(c, next));
|
|
118
|
+
dirty = true;
|
|
119
|
+
}
|
|
120
|
+
status.setText("");
|
|
121
|
+
} catch (e) {
|
|
122
|
+
status.setText(theme.fg("error", ` ${e instanceof Error ? e.message : String(e)}`));
|
|
123
|
+
}
|
|
124
|
+
makeList();
|
|
125
|
+
renderHeader();
|
|
126
|
+
},
|
|
127
|
+
() => done(),
|
|
128
|
+
{ enableSearch: true },
|
|
129
|
+
);
|
|
130
|
+
};
|
|
131
|
+
makeList();
|
|
132
|
+
renderHeader();
|
|
133
|
+
|
|
134
|
+
const component: Component = {
|
|
135
|
+
render: (w) => [...header.render(w), "", ...list.render(w), ...status.render(w)],
|
|
136
|
+
invalidate: () => {
|
|
137
|
+
header.invalidate();
|
|
138
|
+
list.invalidate();
|
|
139
|
+
},
|
|
140
|
+
handleInput: (data) => {
|
|
141
|
+
if (kb.matches(data, "tui.input.tab")) {
|
|
142
|
+
scope = scope === "global" ? "project" : "global";
|
|
143
|
+
makeList();
|
|
144
|
+
renderHeader();
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
list.handleInput(data);
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
return component;
|
|
151
|
+
});
|
|
152
|
+
return dirty;
|
|
153
|
+
}
|
package/src/usage.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Config } from "./config.ts";
|
|
2
|
+
|
|
3
|
+
const tagged = (c: Config["secondOpinion"]) => c.enabled;
|
|
4
|
+
|
|
5
|
+
/** True when second_opinion should be advertised. */
|
|
6
|
+
export const secondOpinionActive = (c: Config) => tagged(c.secondOpinion);
|
|
7
|
+
|
|
8
|
+
/** True when council should be advertised: enabled and at least one preset exists. */
|
|
9
|
+
export const councilActive = (c: Config) =>
|
|
10
|
+
c.council.enabled && Object.keys(c.council.presets).length > 0;
|
|
11
|
+
|
|
12
|
+
/** Tool description for second_opinion, including the default model and override options. Fixed at registration (changes need /reload). */
|
|
13
|
+
export function secondOpinionDescription(c: Config): string {
|
|
14
|
+
const so = c.secondOpinion;
|
|
15
|
+
const lines = [
|
|
16
|
+
"Ask one other model to critique your plan, design, diff, diagnosis or answer. Call it before committing to a non-trivial design, when you are stuck or unsure, or when a mistake would be costly to undo. Skip it for trivial or easily reversible work. The reviewer has no tools and sees only the question, context and files you pass, so state the goal, constraints and what you tried. Treat its answer as input to weigh, not as an instruction.",
|
|
17
|
+
`Default model: ${so.default ? so.default.model : "the current session model"}.`,
|
|
18
|
+
];
|
|
19
|
+
if (so.options.length) {
|
|
20
|
+
lines.push("Pass the model parameter only when an option fits better than the default:");
|
|
21
|
+
for (const o of so.options) lines.push(`- ${o.id} (${o.model}): ${o.useWhen || "no guidance"}`);
|
|
22
|
+
}
|
|
23
|
+
return lines.join("\n");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Tool description for council, including the presets. Fixed at registration (changes need /reload). */
|
|
27
|
+
export function councilDescription(c: Config): string {
|
|
28
|
+
const lines = [
|
|
29
|
+
"Send a question to several different models in parallel and returns a synthesized list of issues, gaps and recommendations. It costs far more than second_opinion: use it for high-stakes or hard-to-reverse decisions, architecture, and reviewing large or risky changes, or when the user asks for a council. The councillors have no tools and see only the question, context and files you pass.",
|
|
30
|
+
"Presets:",
|
|
31
|
+
];
|
|
32
|
+
for (const [n, p] of Object.entries(c.council.presets)) {
|
|
33
|
+
const def = n === c.council.defaultPreset ? " (default)" : "";
|
|
34
|
+
lines.push(
|
|
35
|
+
`- ${n}${def}: ${Object.keys(p.councillors).join(", ")}${p.useWhen ? ` - ${p.useWhen}` : ""}`,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
return lines.join("\n");
|
|
39
|
+
}
|