@giladbarnea/pi-simple-team 1.0.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.
@@ -0,0 +1,72 @@
1
+ import * as childProcess from "node:child_process";
2
+
3
+ export interface TeammateModelSpec {
4
+ name: string;
5
+ model: string;
6
+ }
7
+
8
+ export type RunListModels = (modelPattern: string) => Promise<string>;
9
+
10
+ const thinkingSuffixes = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
11
+ const listModelsTimeoutMilliseconds = 15_000;
12
+
13
+ export function stripThinkingSuffix(model: string): string {
14
+ const suffixSeparatorIndex = model.lastIndexOf(":");
15
+ if (suffixSeparatorIndex === -1) return model;
16
+
17
+ const suffix = model.slice(suffixSeparatorIndex + 1);
18
+ if (!thinkingSuffixes.includes(suffix as (typeof thinkingSuffixes)[number])) return model;
19
+
20
+ return model.slice(0, suffixSeparatorIndex);
21
+ }
22
+
23
+ export const modelPatternForListModels = stripThinkingSuffix;
24
+
25
+ export function parseListModelsOutput(output: string): boolean {
26
+ const lines = output
27
+ .split("\n")
28
+ .map((line) => line.trim())
29
+ .filter(Boolean);
30
+ const headerIndex = lines.findIndex((line) => line.startsWith("provider ") && line.includes(" model"));
31
+ if (headerIndex === -1) return false;
32
+
33
+ return lines.slice(headerIndex + 1).some((line) => {
34
+ if (line.startsWith("No models matching ")) return false;
35
+ const columns = line.split(/\s+/);
36
+ return columns.length >= 2 && columns[0] !== "provider" && columns[1] !== "model";
37
+ });
38
+ }
39
+
40
+ export const hasListModelsMatch = parseListModelsOutput;
41
+
42
+ const runPiListModels: RunListModels = (modelPattern) => {
43
+ return new Promise((resolve, reject) => {
44
+ childProcess.execFile("pi", ["--list-models", modelPattern], { timeout: listModelsTimeoutMilliseconds, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
45
+ const output = `${stdout}${stderr}`;
46
+ if (!error) {
47
+ resolve(output);
48
+ return;
49
+ }
50
+
51
+ const details = output.trim() ? `\n${output.trim()}` : "";
52
+ reject(new Error(`pi --list-models ${JSON.stringify(modelPattern)} failed: ${error.message}${details}`));
53
+ });
54
+ });
55
+ };
56
+
57
+ async function validateTeammateModel(teammate: TeammateModelSpec, runListModels: RunListModels): Promise<void> {
58
+ const modelPattern = stripThinkingSuffix(teammate.model);
59
+ const output = await runListModels(modelPattern);
60
+ if (parseListModelsOutput(output)) return;
61
+
62
+ const details = output.trim() || "(no output)";
63
+ throw new Error(`No configured model matched ${JSON.stringify(teammate.model)} for teammate ${JSON.stringify(teammate.name)}. Checked ${JSON.stringify(modelPattern)} with pi --list-models:\n${details}`);
64
+ }
65
+
66
+ export async function validateTeammateModels(teammates: TeammateModelSpec[], runListModels: RunListModels = runPiListModels): Promise<void> {
67
+ const results = await Promise.allSettled(teammates.map((teammate) => validateTeammateModel(teammate, runListModels)));
68
+ const errors = results.flatMap((result) => (result.status === "rejected" ? [result.reason instanceof Error ? result.reason.message : String(result.reason)] : []));
69
+ if (errors.length === 0) return;
70
+
71
+ throw new Error(`Model preflight failed:\n${errors.map((error) => `- ${error}`).join("\n")}`);
72
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@giladbarnea/pi-simple-team",
3
+ "version": "1.0.0",
4
+ "description": "A flat, live team of Pi agents.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "pi-agent",
9
+ "pi-coding-agent",
10
+ "team",
11
+ "multi-agent"
12
+ ],
13
+ "author": "Gilad Barnea",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/giladbarnea/pi-simple-team.git"
18
+ },
19
+ "homepage": "https://github.com/giladbarnea/pi-simple-team",
20
+ "bugs": {
21
+ "url": "https://github.com/giladbarnea/pi-simple-team/issues"
22
+ },
23
+ "files": [
24
+ "*.ts",
25
+ "render-support",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "peerDependencies": {
30
+ "@earendil-works/pi-ai": "*",
31
+ "@earendil-works/pi-coding-agent": "*",
32
+ "@earendil-works/pi-tui": "*",
33
+ "typebox": "*"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "pi": {
39
+ "extensions": [
40
+ "./index.ts"
41
+ ]
42
+ }
43
+ }
@@ -0,0 +1,206 @@
1
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
+
3
+ import { rightMarginGuardEnabled } from "./settings.js";
4
+
5
+ export const ANSI_GREEN = "\x1b[32m";
6
+ export const ANSI_RED = "\x1b[31m";
7
+ export const ANSI_FG_RESET = "\x1b[39m";
8
+ export const ANSI_BG_RESET = "\x1b[49m";
9
+
10
+ export const ANSI_RE = /\x1b(?:\[[0-9;:]*m|\]133;[ABC]\x07|\]8;[^\x07\x1b]*(?:\x07|\x1b\\))/g;
11
+ export const ANSI_PRESENT_RE = /\x1b\[[0-9;]*m/;
12
+
13
+ export interface AnsiParts {
14
+ close: string;
15
+ open: string;
16
+ }
17
+
18
+ export function ansiRed(text: string): string {
19
+ return `${ANSI_RED}${text}${ANSI_FG_RESET}`;
20
+ }
21
+
22
+ export function ansiGreen(text: string): string {
23
+ return `${ANSI_GREEN}${text}${ANSI_FG_RESET}`;
24
+ }
25
+
26
+ export function stripAnsi(text: string): string {
27
+ return text.replace(ANSI_RE, "");
28
+ }
29
+
30
+ export function hasAnsi(text: string): boolean {
31
+ return ANSI_PRESENT_RE.test(text);
32
+ }
33
+
34
+ export function visibleLength(text: string): number {
35
+ return visibleWidth(text);
36
+ }
37
+
38
+ export function padVisible(text: string, width: number): string {
39
+ const missing = width - visibleLength(text);
40
+ return missing > 0 ? `${text}${" ".repeat(missing)}` : text;
41
+ }
42
+
43
+ export function truncateAnsi(text: string, width: number): string {
44
+ return truncateToWidth(text, Math.max(1, width), "");
45
+ }
46
+
47
+ export function stableRenderWidth(width: number, cwd?: string): number {
48
+ const safe = Math.max(1, Math.floor(width || 1));
49
+ return rightMarginGuardEnabled(cwd) && safe > 1 ? safe - 1 : safe;
50
+ }
51
+
52
+ export function terminalWidth(cwd?: string): number {
53
+ const raw = Number(process.stdout.columns || (process.stderr as any).columns || process.env.COLUMNS || 120);
54
+ const guarded = stableRenderWidth(raw, cwd);
55
+ return Math.max(40, guarded);
56
+ }
57
+
58
+ export function isBlankRenderLine(line: string | undefined): boolean {
59
+ return stripAnsi(line ?? "").trim().length === 0;
60
+ }
61
+
62
+ export function trimTrailingBlankLines(lines: string[]): string[] {
63
+ let end = lines.length - 1;
64
+ while (end >= 0 && isBlankRenderLine(lines[end])) end--;
65
+ return end < 0 ? [] : lines.slice(0, end + 1);
66
+ }
67
+
68
+ export function trimOuterBlankLines(lines: string[]): string[] {
69
+ let start = 0;
70
+ while (start < lines.length && isBlankRenderLine(lines[start])) start++;
71
+ let end = lines.length - 1;
72
+ while (end >= start && isBlankRenderLine(lines[end])) end--;
73
+ return start > end ? [] : lines.slice(start, end + 1);
74
+ }
75
+
76
+ const TRAILING_ANSI_RE = /(?:\x1b(?:\[[0-9;:]*m|\]133;[ABC]\x07))+$/;
77
+
78
+ export function trimTrailingWhitespaceBeforeAnsi(text: string): string {
79
+ const match = text.match(TRAILING_ANSI_RE);
80
+ if (!match) return text.trimEnd();
81
+ return `${text.slice(0, -match[0].length).trimEnd()}${match[0]}`;
82
+ }
83
+
84
+ export function isHorizontalRuleLine(line: string | undefined): boolean {
85
+ const stripped = stripAnsi(line ?? "").trim();
86
+ return stripped.length > 0 && /^[─━-]+$/.test(stripped);
87
+ }
88
+
89
+ export function trimOuterBlankLinesAroundRules(lines: string[]): string[] {
90
+ const trimmed = trimOuterBlankLines(lines);
91
+ if (trimmed.length < 3) return lines;
92
+ return isHorizontalRuleLine(trimmed[0]) && isHorizontalRuleLine(trimmed[trimmed.length - 1]) ? trimmed : lines;
93
+ }
94
+
95
+ export function isThinkingOnlyAssistantMessage(message: any): boolean {
96
+ const content = Array.isArray(message?.content) ? message.content : [];
97
+ let hasThinking = false;
98
+ for (const item of content) {
99
+ if (item?.type === "text" && typeof item.text === "string" && item.text.trim()) return false;
100
+ if (item?.type === "thinking" && typeof item.thinking === "string" && item.thinking.trim()) hasThinking = true;
101
+ }
102
+ return hasThinking;
103
+ }
104
+
105
+ export function trimThinkingOnlyAssistantLines(lines: string[]): string[] {
106
+ const trimmed = trimOuterBlankLines(lines).map((line) => line.trimEnd());
107
+ if (trimmed.length === 0) return lines;
108
+ const zoneStart = "\x1b]133;A\x07";
109
+ if (lines[0]?.includes(zoneStart) && !trimmed[0]?.includes(zoneStart)) trimmed[0] = `${zoneStart}${trimmed[0] ?? ""}`;
110
+ return trimmed;
111
+ }
112
+
113
+ export function ansiPartsFromStyled(styled: string): AnsiParts {
114
+ const marker = "\uE000";
115
+ const markerIndex = styled.indexOf(marker);
116
+ if (markerIndex < 0) return { open: "", close: "" };
117
+ return { open: styled.slice(0, markerIndex), close: styled.slice(markerIndex + marker.length) };
118
+ }
119
+
120
+ export function fgParts(theme: any, token: string): { open: string; close: string } {
121
+ const marker = "\uE000";
122
+ try {
123
+ const styled = theme.fg(token, marker);
124
+ const index = styled.indexOf(marker);
125
+ if (index < 0) return { open: "", close: "" };
126
+ return { open: styled.slice(0, index), close: styled.slice(index + marker.length) };
127
+ } catch {
128
+ return { open: "", close: "" };
129
+ }
130
+ }
131
+
132
+ export function applyBaseTextFg(line: string, theme: any): string {
133
+ let normalized = line;
134
+ for (const token of ["userMessageText", "text"]) {
135
+ const { open } = fgParts(theme, token);
136
+ if (open) normalized = normalized.split(open).join(ANSI_FG_RESET);
137
+ }
138
+ return `${ANSI_FG_RESET}${normalized.replace(/\x1b\[(?:0|39)m/g, (reset) => `${reset}${ANSI_FG_RESET}`)}${ANSI_FG_RESET}`;
139
+ }
140
+
141
+ export function ansiHasBackground(open: string): boolean {
142
+ for (const match of open.matchAll(/\x1b\[([0-9;:]*)m/g)) {
143
+ const params = match[1] || "0";
144
+ if (/(^|[;:])48([;:]|$)/.test(params)) return true;
145
+ if (/(^|[;:])(?:4[0-7]|10[0-7])([;:]|$)/.test(params)) return true;
146
+ }
147
+ return false;
148
+ }
149
+
150
+ export function sgrClearsBackground(code: string): boolean {
151
+ const match = code.match(/^\x1b\[([0-9;]*)m$/);
152
+ if (!match) return false;
153
+ const params = match[1] ? match[1].split(";").map((value) => Number.parseInt(value || "0", 10)) : [0];
154
+ return params.some((value) => value === 0 || value === 49);
155
+ }
156
+
157
+ export function stripSgrBackgroundParams(code: string): string {
158
+ const match = code.match(/^\x1b\[([0-9;:]*)m$/);
159
+ if (!match) return code;
160
+ const raw = match[1] ?? "";
161
+ if (!raw || raw.includes(":")) return code;
162
+ const params = raw.split(";");
163
+ const kept: string[] = [];
164
+ for (let index = 0; index < params.length; index++) {
165
+ const value = Number.parseInt(params[index] || "0", 10);
166
+ if (value === 48) {
167
+ const mode = Number.parseInt(params[index + 1] || "", 10);
168
+ if (mode === 5) {
169
+ index += 2;
170
+ continue;
171
+ }
172
+ if (mode === 2) {
173
+ index += 4;
174
+ continue;
175
+ }
176
+ }
177
+ if (value === 49 || (value >= 40 && value <= 47) || (value >= 100 && value <= 107)) continue;
178
+ kept.push(params[index] || "0");
179
+ }
180
+ return kept.length > 0 ? `\x1b[${kept.join(";")}m` : "";
181
+ }
182
+
183
+ export function stripLeadingBackgroundLayer(line: string): string {
184
+ let offset = 0;
185
+ let out = "";
186
+ const leadingAnsiRe = /\x1b(?:\[([0-9;:]*)m|\]133;[ABC]\x07)/y;
187
+ while (offset < line.length) {
188
+ leadingAnsiRe.lastIndex = offset;
189
+ const match = leadingAnsiRe.exec(line);
190
+ if (!match) break;
191
+ const code = match[0];
192
+ out += code.startsWith("\x1b[") ? stripSgrBackgroundParams(code) : code;
193
+ offset = leadingAnsiRe.lastIndex;
194
+ }
195
+ return `${out}${line.slice(offset)}`;
196
+ }
197
+
198
+ export function updateActiveAnsiStyle(code: string): string {
199
+ const match = code.match(/^\x1b\[([0-9;]*)m$/);
200
+ if (!match) return "";
201
+ const params = match[1] ? match[1].split(";").map((value) => Number.parseInt(value || "0", 10)) : [0];
202
+ if (params.some((value) => value === 0 || value === 39)) return "";
203
+ return code;
204
+ }
205
+
206
+ export { visibleWidth, wrapTextWithAnsi };
@@ -0,0 +1,157 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+
5
+ export type GlyphStyle = "unicode" | "ascii";
6
+ export type GlobalGlyphStyleOverride = "inherit" | GlyphStyle;
7
+
8
+ const LOCAL_CONFIG_ID = "@vanillagreen/pi-tool-renderer";
9
+ const GLOBAL_CONFIG_ID = "@vanillagreen/pi-tool-renderer";
10
+
11
+ function expandHome(input: string): string {
12
+ if (input === "~") return homedir();
13
+ if (input.startsWith("~/")) return join(homedir(), input.slice(2));
14
+ return input;
15
+ }
16
+
17
+ function projectSettingsPath(cwd: string): string {
18
+ let current = resolve(cwd);
19
+ while (true) {
20
+ const candidate = join(current, ".pi", "settings.json");
21
+ if (existsSync(candidate)) return candidate;
22
+ if (existsSync(join(current, ".pi")) || existsSync(join(current, ".git")) || existsSync(join(current, ".vstack-lock.json"))) return candidate;
23
+ const parent = dirname(current);
24
+ if (parent === current) return join(resolve(cwd), ".pi", "settings.json");
25
+ current = parent;
26
+ }
27
+ }
28
+
29
+ const PROJECT_TRUST_SYMBOL = Symbol.for("vstack.pi.project-trust");
30
+
31
+ interface ProjectTrustRegistry {
32
+ projectSettings?: Map<string, boolean>;
33
+ }
34
+
35
+ function projectTrustRegistry(): ProjectTrustRegistry {
36
+ const host = globalThis as unknown as Record<PropertyKey, ProjectTrustRegistry | undefined>;
37
+ const existing = host[PROJECT_TRUST_SYMBOL];
38
+ if (existing) return existing;
39
+ const created: ProjectTrustRegistry = {};
40
+ host[PROJECT_TRUST_SYMBOL] = created;
41
+ return created;
42
+ }
43
+
44
+ export function recordProjectTrust(ctx: { cwd?: string; isProjectTrusted?: () => boolean }): void {
45
+ if (!ctx.cwd) return;
46
+ let trusted = true;
47
+ try {
48
+ trusted = ctx.isProjectTrusted?.() === true;
49
+ } catch {
50
+ trusted = false;
51
+ }
52
+ const registry = projectTrustRegistry();
53
+ if (!registry.projectSettings) registry.projectSettings = new Map();
54
+ registry.projectSettings.set(projectSettingsPath(ctx.cwd), trusted);
55
+ }
56
+
57
+ function projectSettingsTrusted(settingsPath: string): boolean {
58
+ return projectTrustRegistry().projectSettings?.get(settingsPath) === true;
59
+ }
60
+
61
+
62
+ function piSettingsPaths(cwd = process.cwd()): string[] {
63
+ const userDir = resolve(expandHome(process.env.PI_CODING_AGENT_DIR?.trim() || "~/.pi/agent"));
64
+ const user = join(userDir, "settings.json");
65
+ const project = projectSettingsPath(cwd);
66
+ return projectSettingsTrusted(project) ? [user, project] : [user];
67
+ }
68
+
69
+ function readPackageConfig(packageId: string, cwd?: string): Record<string, unknown> {
70
+ const merged: Record<string, unknown> = {};
71
+ for (const settingsPath of piSettingsPaths(cwd)) {
72
+ if (!existsSync(settingsPath)) continue;
73
+ try {
74
+ const parsed = JSON.parse(readFileSync(settingsPath, "utf8"));
75
+ const config = parsed?.vstack?.extensionManager?.config?.[packageId];
76
+ if (config && typeof config === "object" && !Array.isArray(config)) Object.assign(merged, config);
77
+ } catch {
78
+ // Ignore malformed optional manager config.
79
+ }
80
+ }
81
+ return merged;
82
+ }
83
+
84
+ function asGlyphStyle(value: unknown): GlyphStyle | undefined {
85
+ return value === "unicode" || value === "ascii" ? value : undefined;
86
+ }
87
+
88
+ export function glyphStyle(cwd?: string): GlyphStyle {
89
+ const globalOverride = readPackageConfig(GLOBAL_CONFIG_ID, cwd).globalGlyphStyleOverride;
90
+ const forced = asGlyphStyle(globalOverride);
91
+ if (forced) return forced;
92
+ const local = readPackageConfig(LOCAL_CONFIG_ID, cwd);
93
+ return asGlyphStyle(local.glyphStyle) ?? asGlyphStyle(local.treeStyle) ?? "unicode";
94
+ }
95
+
96
+ export const GLYPHS = {
97
+ unicode: {
98
+ frame: { tl: "┏", tr: "┓", bl: "┗", br: "┛", h: "━", v: "┃" },
99
+ line: "─",
100
+ tree: { mid: "├─ ", last: "└─ ", stem: "│ ", blank: " " },
101
+ bullet: "● ",
102
+ emptyBullet: "○ ",
103
+ dot: " · ",
104
+ ok: "✓",
105
+ fail: "✗",
106
+ warn: "▲",
107
+ diamond: "◆",
108
+ prompt: "π",
109
+ ellipsis: "…",
110
+ arrow: "→",
111
+ codeBar: "▌",
112
+ },
113
+ ascii: {
114
+ frame: { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" },
115
+ line: "-",
116
+ tree: { mid: "|-- ", last: "`-- ", stem: "| ", blank: " " },
117
+ bullet: "* ",
118
+ emptyBullet: "o ",
119
+ dot: " - ",
120
+ ok: "+",
121
+ fail: "x",
122
+ warn: "!",
123
+ diamond: "*",
124
+ prompt: "pi",
125
+ ellipsis: "...",
126
+ arrow: "->",
127
+ codeBar: "|",
128
+ },
129
+ } as const;
130
+
131
+ export function glyphs(cwd?: string): (typeof GLYPHS)[GlyphStyle] {
132
+ return GLYPHS[glyphStyle(cwd)];
133
+ }
134
+
135
+ export function truncateIndicator(cwd?: string): string {
136
+ return glyphs(cwd).ellipsis;
137
+ }
138
+
139
+ export function truncateText(text: string, maxChars: number, cwd?: string): string {
140
+ if (text.length <= maxChars) return text;
141
+ const indicator = truncateIndicator(cwd);
142
+ return `${text.slice(0, Math.max(0, maxChars - indicator.length))}${indicator}`;
143
+ }
144
+
145
+ export function dot(cwd?: string): string {
146
+ return glyphs(cwd).dot;
147
+ }
148
+
149
+ export function treeGlyph(branch: "├" | "└" | "│", cwd?: string): string {
150
+ const tree = glyphs(cwd).tree;
151
+ if (branch === "│") return tree.stem;
152
+ return branch === "└" ? tree.last : tree.mid;
153
+ }
154
+
155
+ export function frameGlyphs(cwd?: string): (typeof GLYPHS)[GlyphStyle]["frame"] {
156
+ return glyphs(cwd).frame;
157
+ }
@@ -0,0 +1,174 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+
5
+ export const CONFIG_ID = "@vanillagreen/pi-tool-renderer";
6
+
7
+ export type VstackConfig = Record<string, unknown>;
8
+
9
+ function expandHome(input: string): string {
10
+ if (input === "~") return homedir();
11
+ if (input.startsWith("~/")) return join(homedir(), input.slice(2));
12
+ return input;
13
+ }
14
+
15
+ function projectSettingsPath(cwd: string): string {
16
+ let current = resolve(cwd);
17
+ while (true) {
18
+ const candidate = join(current, ".pi", "settings.json");
19
+ if (existsSync(candidate)) return candidate;
20
+ if (existsSync(join(current, ".pi")) || existsSync(join(current, ".git")) || existsSync(join(current, ".vstack-lock.json"))) return candidate;
21
+ const parent = dirname(current);
22
+ if (parent === current) return join(resolve(cwd), ".pi", "settings.json");
23
+ current = parent;
24
+ }
25
+ }
26
+
27
+ const PROJECT_TRUST_SYMBOL = Symbol.for("vstack.pi.project-trust");
28
+
29
+ interface ProjectTrustRegistry {
30
+ projectSettings?: Map<string, boolean>;
31
+ }
32
+
33
+ function projectTrustRegistry(): ProjectTrustRegistry {
34
+ const host = globalThis as unknown as Record<PropertyKey, ProjectTrustRegistry | undefined>;
35
+ const existing = host[PROJECT_TRUST_SYMBOL];
36
+ if (existing) return existing;
37
+ const created: ProjectTrustRegistry = {};
38
+ host[PROJECT_TRUST_SYMBOL] = created;
39
+ return created;
40
+ }
41
+
42
+ export function recordProjectTrust(ctx: { cwd?: string; isProjectTrusted?: () => boolean }): void {
43
+ if (!ctx.cwd) return;
44
+ let trusted = true;
45
+ try {
46
+ trusted = ctx.isProjectTrusted?.() === true;
47
+ } catch {
48
+ trusted = false;
49
+ }
50
+ const registry = projectTrustRegistry();
51
+ if (!registry.projectSettings) registry.projectSettings = new Map();
52
+ registry.projectSettings.set(projectSettingsPath(ctx.cwd), trusted);
53
+ }
54
+
55
+ function projectSettingsTrusted(settingsPath: string): boolean {
56
+ return projectTrustRegistry().projectSettings?.get(settingsPath) === true;
57
+ }
58
+
59
+
60
+ function piSettingsPaths(cwd = process.cwd()): string[] {
61
+ const userDir = resolve(expandHome(process.env.PI_CODING_AGENT_DIR?.trim() || "~/.pi/agent"));
62
+ const user = join(userDir, "settings.json");
63
+ const project = projectSettingsPath(cwd);
64
+ return projectSettingsTrusted(project) ? [user, project] : [user];
65
+ }
66
+
67
+ export function readVstackConfig(cwd?: string): VstackConfig {
68
+ const merged: VstackConfig = {};
69
+ for (const path of piSettingsPaths(cwd)) {
70
+ if (!existsSync(path)) continue;
71
+ try {
72
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
73
+ const config = parsed?.vstack?.extensionManager?.config?.[CONFIG_ID];
74
+ if (config && typeof config === "object" && !Array.isArray(config)) Object.assign(merged, config);
75
+ } catch {
76
+ // Ignore malformed optional manager config.
77
+ }
78
+ }
79
+ return merged;
80
+ }
81
+
82
+ export function settingNumber(key: string, fallback: number, cwd?: string): number {
83
+ const value = readVstackConfig(cwd)[key];
84
+ const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
85
+ return Number.isFinite(parsed) ? parsed : fallback;
86
+ }
87
+
88
+ export function settingBoolean(key: string, fallback: boolean, cwd?: string): boolean {
89
+ const value = readVstackConfig(cwd)[key];
90
+ return typeof value === "boolean" ? value : fallback;
91
+ }
92
+
93
+ export function settingString(key: string, fallback: string, cwd?: string): string {
94
+ const value = readVstackConfig(cwd)[key];
95
+ return typeof value === "string" ? value : fallback;
96
+ }
97
+
98
+ export function settingEnum<T extends string>(key: string, allowed: readonly T[], fallback: T, cwd?: string): T {
99
+ const value = readVstackConfig(cwd)[key];
100
+ return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;
101
+ }
102
+
103
+ export function rightMarginGuardEnabled(cwd?: string): boolean {
104
+ return settingBoolean("rightMarginGuard", true, cwd);
105
+ }
106
+
107
+ export function stackToolCalls(cwd?: string): boolean {
108
+ return settingBoolean("stackToolCalls", false, cwd);
109
+ }
110
+
111
+ export type StackChildDisplay = "rows" | "headline" | "anchor-list";
112
+
113
+ export function stackChildDisplay(cwd?: string): StackChildDisplay {
114
+ const value = readVstackConfig(cwd).stackChildDisplay;
115
+ if (value === "rows" || value === "headline" || value === "anchor-list") return value;
116
+ return settingBoolean("hideStackChildRows", false, cwd) ? "headline" : "rows";
117
+ }
118
+
119
+ export function stackShell(cwd?: string): { renderShell?: "self" } {
120
+ return stackToolCalls(cwd) ? { renderShell: "self" } : {};
121
+ }
122
+
123
+ export type ReadOutputMode = "hidden" | "summary" | "preview";
124
+ export type SearchOutputMode = "hidden" | "count" | "preview";
125
+ export type BashOutputMode = "hidden" | "summary" | "opencode" | "preview";
126
+ export type McpOutputMode = "hidden" | "summary" | "preview";
127
+
128
+ export function readOutputMode(cwd?: string): ReadOutputMode {
129
+ return settingEnum("readOutputMode", ["hidden", "summary", "preview"] as const, "preview", cwd);
130
+ }
131
+
132
+ export function searchOutputMode(cwd?: string): SearchOutputMode {
133
+ return settingEnum("searchOutputMode", ["hidden", "count", "preview"] as const, "preview", cwd);
134
+ }
135
+
136
+ export function bashOutputMode(cwd?: string): BashOutputMode {
137
+ return settingEnum("bashOutputMode", ["hidden", "summary", "opencode", "preview"] as const, "opencode", cwd);
138
+ }
139
+
140
+ export function bashLiveOutputDelayMs(cwd?: string): number {
141
+ return Math.max(0, Math.floor(settingNumber("bashLiveOutputDelayMs", 1000, cwd)));
142
+ }
143
+
144
+ export function bashLiveTailLines(cwd?: string): number {
145
+ return Math.max(1, Math.floor(settingNumber("bashLiveTailLines", 4, cwd)));
146
+ }
147
+
148
+ export function mcpOutputMode(cwd?: string): McpOutputMode {
149
+ return settingEnum("mcpOutputMode", ["hidden", "summary", "preview"] as const, "preview", cwd);
150
+ }
151
+
152
+ export type TreeStyle = "unicode" | "ascii";
153
+
154
+ export function treeStyle(cwd?: string): TreeStyle {
155
+ return settingEnum("treeStyle", ["unicode", "ascii"] as const, "unicode", cwd);
156
+ }
157
+
158
+ export function pendingStatusAnimation(cwd?: string): boolean {
159
+ return settingBoolean("pendingStatusAnimation", false, cwd);
160
+ }
161
+
162
+ export function diffBackgroundEnabled(cwd?: string): boolean {
163
+ return settingBoolean("diffBackgrounds", true, cwd);
164
+ }
165
+
166
+ export function bashDiffRenderingEnabled(cwd?: string): boolean {
167
+ return settingBoolean("renderBashDiffs", false, cwd);
168
+ }
169
+
170
+ export type ToolChromeMode = "off" | "transparent" | "outlines";
171
+
172
+ export function toolChromeMode(cwd?: string): ToolChromeMode {
173
+ return settingEnum("toolChrome", ["off", "transparent", "outlines"] as const, "outlines", cwd);
174
+ }