gsd-pi 0.3.0 → 0.3.3
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 +3 -1
- package/dist/cli.js +112 -5
- package/dist/loader.js +0 -0
- package/dist/resource-loader.d.ts +3 -3
- package/dist/resource-loader.js +10 -4
- package/dist/tool-bootstrap.d.ts +4 -0
- package/dist/tool-bootstrap.js +74 -0
- package/dist/wizard.js +15 -5
- package/package.json +6 -2
- package/patches/@mariozechner+pi-coding-agent+0.57.1.patch +48 -0
- package/patches/@mariozechner+pi-tui+0.57.1.patch +47 -0
- package/scripts/postinstall.js +8 -0
- package/src/resources/extensions/bg-shell/index.ts +57 -8
- package/src/resources/extensions/browser-tools/index.ts +80 -7
- package/src/resources/extensions/github/gh-api.ts +46 -30
- package/src/resources/extensions/gsd/auto.ts +188 -10
- package/src/resources/extensions/gsd/commands.ts +13 -6
- package/src/resources/extensions/gsd/doctor.ts +7 -0
- package/src/resources/extensions/gsd/guided-flow.ts +9 -6
- package/src/resources/extensions/gsd/index.ts +32 -2
- package/src/resources/extensions/gsd/prompts/discuss.md +73 -27
- package/src/resources/extensions/gsd/prompts/system.md +1 -1
- package/src/resources/extensions/gsd/prompts/worktree-merge.md +51 -17
- package/src/resources/extensions/gsd/tests/discuss-prompt.test.ts +38 -0
- package/src/resources/extensions/gsd/worktree-command.ts +219 -49
- package/src/resources/extensions/gsd/worktree-manager.ts +106 -16
- package/src/resources/extensions/mcporter/index.ts +410 -0
- package/src/resources/extensions/slash-commands/clear.ts +10 -0
- package/src/resources/extensions/slash-commands/index.ts +2 -2
- package/src/resources/extensions/voice/index.ts +176 -0
- package/src/resources/extensions/voice/speech-recognizer +0 -0
- package/src/resources/extensions/voice/speech-recognizer.swift +76 -0
- package/dist/modes/interactive/theme/dark.json +0 -85
- package/dist/modes/interactive/theme/light.json +0 -84
- package/dist/modes/interactive/theme/theme-schema.json +0 -335
- package/dist/modes/interactive/theme/theme.d.ts +0 -78
- package/dist/modes/interactive/theme/theme.d.ts.map +0 -1
- package/dist/modes/interactive/theme/theme.js +0 -949
- package/dist/modes/interactive/theme/theme.js.map +0 -1
- package/src/resources/extensions/slash-commands/gsd-run.ts +0 -34
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCPorter Extension — Lazy MCP server integration for pi
|
|
3
|
+
*
|
|
4
|
+
* Provides on-demand access to all MCP servers configured on the system
|
|
5
|
+
* (via Claude Desktop, Cursor, VS Code, mcporter config, etc.) without
|
|
6
|
+
* registering every tool upfront. This keeps token usage near-zero until
|
|
7
|
+
* the agent actually needs an MCP tool.
|
|
8
|
+
*
|
|
9
|
+
* Three tools:
|
|
10
|
+
* mcp_servers — List available MCP servers (cached after first call)
|
|
11
|
+
* mcp_discover — Get tool signatures for a specific server
|
|
12
|
+
* mcp_call — Call a tool on an MCP server
|
|
13
|
+
*
|
|
14
|
+
* Requirements:
|
|
15
|
+
* - mcporter installed globally: npm i -g mcporter
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
19
|
+
import {
|
|
20
|
+
truncateHead,
|
|
21
|
+
DEFAULT_MAX_BYTES,
|
|
22
|
+
DEFAULT_MAX_LINES,
|
|
23
|
+
formatSize,
|
|
24
|
+
} from "@mariozechner/pi-coding-agent";
|
|
25
|
+
import { Text } from "@mariozechner/pi-tui";
|
|
26
|
+
import { Type } from "@sinclair/typebox";
|
|
27
|
+
import { execFile, exec } from "node:child_process";
|
|
28
|
+
import { promisify } from "node:util";
|
|
29
|
+
|
|
30
|
+
const execFileAsync = promisify(execFile);
|
|
31
|
+
const execAsync = promisify(exec);
|
|
32
|
+
|
|
33
|
+
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
interface McpServer {
|
|
36
|
+
name: string;
|
|
37
|
+
status: string;
|
|
38
|
+
transport?: string;
|
|
39
|
+
tools: { name: string; description: string }[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface McpListResponse {
|
|
43
|
+
mode: string;
|
|
44
|
+
counts: { ok: number; auth: number; offline: number; http: number; error: number };
|
|
45
|
+
servers: McpServer[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface McpToolSchema {
|
|
49
|
+
name: string;
|
|
50
|
+
description: string;
|
|
51
|
+
inputSchema?: Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface McpServerDetail {
|
|
55
|
+
name: string;
|
|
56
|
+
status: string;
|
|
57
|
+
tools: McpToolSchema[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ─── Cache ────────────────────────────────────────────────────────────────────
|
|
61
|
+
|
|
62
|
+
let serverListCache: McpServer[] | null = null;
|
|
63
|
+
const serverDetailCache = new Map<string, McpServerDetail>();
|
|
64
|
+
|
|
65
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
66
|
+
|
|
67
|
+
async function runMcporter(
|
|
68
|
+
args: string[],
|
|
69
|
+
signal?: AbortSignal,
|
|
70
|
+
timeoutMs = 30000,
|
|
71
|
+
): Promise<string> {
|
|
72
|
+
// Use shell exec so PATH resolution works in all contexts
|
|
73
|
+
const escaped = args.map((a) => `'${a.replace(/'/g, "'\\''")}'`).join(" ");
|
|
74
|
+
const { stdout } = await execAsync(`mcporter ${escaped}`, {
|
|
75
|
+
timeout: timeoutMs,
|
|
76
|
+
maxBuffer: 1024 * 1024,
|
|
77
|
+
signal,
|
|
78
|
+
env: { ...process.env },
|
|
79
|
+
});
|
|
80
|
+
return stdout;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function getServerList(signal?: AbortSignal): Promise<McpServer[]> {
|
|
84
|
+
if (serverListCache) return serverListCache;
|
|
85
|
+
|
|
86
|
+
const raw = await runMcporter(["list", "--json"], signal, 60000);
|
|
87
|
+
let data: McpListResponse;
|
|
88
|
+
try {
|
|
89
|
+
data = JSON.parse(raw) as McpListResponse;
|
|
90
|
+
} catch (e) {
|
|
91
|
+
throw new Error(`Failed to parse mcporter output: ${raw.slice(0, 300)}`);
|
|
92
|
+
}
|
|
93
|
+
if (!Array.isArray(data.servers)) {
|
|
94
|
+
throw new Error(`Unexpected mcporter response shape: ${JSON.stringify(Object.keys(data))}`);
|
|
95
|
+
}
|
|
96
|
+
serverListCache = data.servers;
|
|
97
|
+
return serverListCache;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function getServerDetail(
|
|
101
|
+
serverName: string,
|
|
102
|
+
signal?: AbortSignal,
|
|
103
|
+
): Promise<McpServerDetail> {
|
|
104
|
+
if (serverDetailCache.has(serverName)) return serverDetailCache.get(serverName)!;
|
|
105
|
+
|
|
106
|
+
const raw = await runMcporter(["list", serverName, "--schema", "--json"], signal);
|
|
107
|
+
const data = JSON.parse(raw) as McpServerDetail;
|
|
108
|
+
serverDetailCache.set(serverName, data);
|
|
109
|
+
return data;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function formatServerList(servers: McpServer[]): string {
|
|
113
|
+
if (servers.length === 0) return "No MCP servers found.";
|
|
114
|
+
|
|
115
|
+
const lines: string[] = [`${servers.length} MCP servers available:\n`];
|
|
116
|
+
|
|
117
|
+
for (const s of servers) {
|
|
118
|
+
const tools = s.tools ?? [];
|
|
119
|
+
const status = s.status === "ok" ? "✓" : s.status === "auth" ? "🔑" : "✗";
|
|
120
|
+
lines.push(`${status} ${s.name} — ${tools.length} tools (${s.status})`);
|
|
121
|
+
for (const t of tools) {
|
|
122
|
+
lines.push(` ${t.name}: ${t.description?.slice(0, 100) ?? ""}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
lines.push("\nUse mcp_discover to see full tool schemas for a specific server.");
|
|
127
|
+
lines.push("Use mcp_call to invoke a tool: mcp_call(server, tool, args).");
|
|
128
|
+
return lines.join("\n");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function formatServerDetail(detail: McpServerDetail): string {
|
|
132
|
+
const lines: string[] = [`${detail.name} — ${detail.tools.length} tools:\n`];
|
|
133
|
+
|
|
134
|
+
for (const tool of detail.tools) {
|
|
135
|
+
lines.push(`## ${tool.name}`);
|
|
136
|
+
if (tool.description) lines.push(tool.description);
|
|
137
|
+
if (tool.inputSchema) {
|
|
138
|
+
lines.push("```json");
|
|
139
|
+
lines.push(JSON.stringify(tool.inputSchema, null, 2));
|
|
140
|
+
lines.push("```");
|
|
141
|
+
}
|
|
142
|
+
lines.push("");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
lines.push(`Call with: mcp_call(server="${detail.name}", tool="<tool_name>", args={...})`);
|
|
146
|
+
return lines.join("\n");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ─── Extension ────────────────────────────────────────────────────────────────
|
|
150
|
+
|
|
151
|
+
export default function (pi: ExtensionAPI) {
|
|
152
|
+
// ── mcp_servers ──────────────────────────────────────────────────────────
|
|
153
|
+
|
|
154
|
+
pi.registerTool({
|
|
155
|
+
name: "mcp_servers",
|
|
156
|
+
label: "MCP Servers",
|
|
157
|
+
description:
|
|
158
|
+
"List all available MCP servers discovered from your system (Claude Desktop, Cursor, VS Code, mcporter config). " +
|
|
159
|
+
"Shows server names, status, and tool counts. Use mcp_discover to get full tool schemas for a server.",
|
|
160
|
+
promptSnippet:
|
|
161
|
+
"List available MCP servers and their tools (lazy discovery via mcporter)",
|
|
162
|
+
promptGuidelines: [
|
|
163
|
+
"Call mcp_servers to see what MCP servers are available before trying to use one.",
|
|
164
|
+
"MCP servers provide external integrations (Twitter, Linear, Railway, etc.) via the Model Context Protocol.",
|
|
165
|
+
"After listing, use mcp_discover(server) to get tool schemas, then mcp_call(server, tool, args) to invoke.",
|
|
166
|
+
],
|
|
167
|
+
parameters: Type.Object({
|
|
168
|
+
refresh: Type.Optional(
|
|
169
|
+
Type.Boolean({ description: "Force refresh the server list (default: use cache)" }),
|
|
170
|
+
),
|
|
171
|
+
}),
|
|
172
|
+
|
|
173
|
+
async execute(_id, params, signal) {
|
|
174
|
+
if (params.refresh) serverListCache = null;
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
const servers = await getServerList(signal);
|
|
178
|
+
return {
|
|
179
|
+
content: [{ type: "text", text: formatServerList(servers) }],
|
|
180
|
+
details: {
|
|
181
|
+
serverCount: servers.length,
|
|
182
|
+
cached: !params.refresh && serverListCache !== null,
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
} catch (err: unknown) {
|
|
186
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
187
|
+
throw new Error(
|
|
188
|
+
`Failed to list MCP servers. Is mcporter installed? (npm i -g mcporter)\n${msg}`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
renderCall(args, theme) {
|
|
194
|
+
let text = theme.fg("toolTitle", theme.bold("mcp_servers"));
|
|
195
|
+
if (args.refresh) text += theme.fg("warning", " (refresh)");
|
|
196
|
+
return new Text(text, 0, 0);
|
|
197
|
+
},
|
|
198
|
+
|
|
199
|
+
renderResult(result, { isPartial }, theme) {
|
|
200
|
+
if (isPartial) return new Text(theme.fg("warning", "Discovering MCP servers..."), 0, 0);
|
|
201
|
+
const d = result.details as { serverCount: number } | undefined;
|
|
202
|
+
return new Text(
|
|
203
|
+
theme.fg("success", `${d?.serverCount ?? 0} servers found`),
|
|
204
|
+
0,
|
|
205
|
+
0,
|
|
206
|
+
);
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// ── mcp_discover ─────────────────────────────────────────────────────────
|
|
211
|
+
|
|
212
|
+
pi.registerTool({
|
|
213
|
+
name: "mcp_discover",
|
|
214
|
+
label: "MCP Discover",
|
|
215
|
+
description:
|
|
216
|
+
"Get detailed tool signatures and JSON schemas for a specific MCP server. " +
|
|
217
|
+
"Use this to understand what tools a server provides and what arguments they accept " +
|
|
218
|
+
"before calling them with mcp_call.",
|
|
219
|
+
promptSnippet:
|
|
220
|
+
"Get tool schemas for a specific MCP server before calling its tools",
|
|
221
|
+
promptGuidelines: [
|
|
222
|
+
"Call mcp_discover with a server name to see the full tool signatures before calling mcp_call.",
|
|
223
|
+
"The schemas show required and optional parameters with types and descriptions.",
|
|
224
|
+
],
|
|
225
|
+
parameters: Type.Object({
|
|
226
|
+
server: Type.String({
|
|
227
|
+
description:
|
|
228
|
+
"MCP server name (from mcp_servers output), e.g. 'railway', 'twitter-mcp', 'linear'",
|
|
229
|
+
}),
|
|
230
|
+
}),
|
|
231
|
+
|
|
232
|
+
async execute(_id, params, signal) {
|
|
233
|
+
try {
|
|
234
|
+
const detail = await getServerDetail(params.server, signal);
|
|
235
|
+
const text = formatServerDetail(detail);
|
|
236
|
+
|
|
237
|
+
// Truncation guard
|
|
238
|
+
const truncation = truncateHead(text, {
|
|
239
|
+
maxLines: DEFAULT_MAX_LINES,
|
|
240
|
+
maxBytes: DEFAULT_MAX_BYTES,
|
|
241
|
+
});
|
|
242
|
+
let finalText = truncation.content;
|
|
243
|
+
if (truncation.truncated) {
|
|
244
|
+
finalText +=
|
|
245
|
+
`\n\n[Truncated: ${truncation.outputLines}/${truncation.totalLines} lines ` +
|
|
246
|
+
`(${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)})]`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
content: [{ type: "text", text: finalText }],
|
|
251
|
+
details: {
|
|
252
|
+
server: params.server,
|
|
253
|
+
toolCount: detail.tools.length,
|
|
254
|
+
cached: serverDetailCache.has(params.server),
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
} catch (err: unknown) {
|
|
258
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
259
|
+
throw new Error(`Failed to discover tools for "${params.server}": ${msg}`);
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
renderCall(args, theme) {
|
|
264
|
+
let text = theme.fg("toolTitle", theme.bold("mcp_discover "));
|
|
265
|
+
text += theme.fg("accent", args.server);
|
|
266
|
+
return new Text(text, 0, 0);
|
|
267
|
+
},
|
|
268
|
+
|
|
269
|
+
renderResult(result, { isPartial }, theme) {
|
|
270
|
+
if (isPartial)
|
|
271
|
+
return new Text(theme.fg("warning", "Discovering tools..."), 0, 0);
|
|
272
|
+
const d = result.details as { server: string; toolCount: number } | undefined;
|
|
273
|
+
return new Text(
|
|
274
|
+
theme.fg("success", `${d?.toolCount ?? 0} tools`) +
|
|
275
|
+
theme.fg("dim", ` · ${d?.server}`),
|
|
276
|
+
0,
|
|
277
|
+
0,
|
|
278
|
+
);
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
// ── mcp_call ─────────────────────────────────────────────────────────────
|
|
283
|
+
|
|
284
|
+
pi.registerTool({
|
|
285
|
+
name: "mcp_call",
|
|
286
|
+
label: "MCP Call",
|
|
287
|
+
description:
|
|
288
|
+
"Call a tool on an MCP server. Provide the server name, tool name, and arguments. " +
|
|
289
|
+
"Use mcp_discover first to see available tools and their required arguments.",
|
|
290
|
+
promptSnippet: "Call a tool on an MCP server via mcporter",
|
|
291
|
+
promptGuidelines: [
|
|
292
|
+
"Always use mcp_discover first to understand the tool's parameters before calling mcp_call.",
|
|
293
|
+
"Arguments are passed as a JSON object matching the tool's input schema.",
|
|
294
|
+
],
|
|
295
|
+
parameters: Type.Object({
|
|
296
|
+
server: Type.String({
|
|
297
|
+
description: "MCP server name, e.g. 'railway', 'twitter-mcp'",
|
|
298
|
+
}),
|
|
299
|
+
tool: Type.String({
|
|
300
|
+
description: "Tool name on that server, e.g. 'railway_list_projects'",
|
|
301
|
+
}),
|
|
302
|
+
args: Type.Optional(
|
|
303
|
+
Type.Record(Type.String(), Type.Unknown(), {
|
|
304
|
+
description:
|
|
305
|
+
"Tool arguments as key-value pairs matching the tool's input schema",
|
|
306
|
+
}),
|
|
307
|
+
),
|
|
308
|
+
}),
|
|
309
|
+
|
|
310
|
+
async execute(_id, params, signal) {
|
|
311
|
+
// Build mcporter call command: mcporter call server.tool key:value ...
|
|
312
|
+
const callTarget = `${params.server}.${params.tool}`;
|
|
313
|
+
const cliArgs = ["call", callTarget, "--output", "raw"];
|
|
314
|
+
|
|
315
|
+
if (params.args && Object.keys(params.args).length > 0) {
|
|
316
|
+
for (const [key, value] of Object.entries(params.args)) {
|
|
317
|
+
const strVal =
|
|
318
|
+
typeof value === "string" ? value : JSON.stringify(value);
|
|
319
|
+
cliArgs.push(`${key}:${strVal}`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
try {
|
|
324
|
+
const raw = await runMcporter(cliArgs, signal, 60000);
|
|
325
|
+
|
|
326
|
+
// Truncation guard
|
|
327
|
+
const truncation = truncateHead(raw, {
|
|
328
|
+
maxLines: DEFAULT_MAX_LINES,
|
|
329
|
+
maxBytes: DEFAULT_MAX_BYTES,
|
|
330
|
+
});
|
|
331
|
+
let finalText = truncation.content;
|
|
332
|
+
if (truncation.truncated) {
|
|
333
|
+
finalText +=
|
|
334
|
+
`\n\n[Output truncated: ${truncation.outputLines}/${truncation.totalLines} lines ` +
|
|
335
|
+
`(${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)})]`;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return {
|
|
339
|
+
content: [{ type: "text", text: finalText }],
|
|
340
|
+
details: {
|
|
341
|
+
server: params.server,
|
|
342
|
+
tool: params.tool,
|
|
343
|
+
charCount: finalText.length,
|
|
344
|
+
truncated: truncation.truncated,
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
} catch (err: unknown) {
|
|
348
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
349
|
+
throw new Error(
|
|
350
|
+
`MCP call failed: ${params.server}.${params.tool}\n${msg}`,
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
},
|
|
354
|
+
|
|
355
|
+
renderCall(args, theme) {
|
|
356
|
+
let text = theme.fg("toolTitle", theme.bold("mcp_call "));
|
|
357
|
+
text += theme.fg("accent", `${args.server}.${args.tool}`);
|
|
358
|
+
if (args.args && Object.keys(args.args).length > 0) {
|
|
359
|
+
const preview = Object.entries(args.args)
|
|
360
|
+
.slice(0, 3)
|
|
361
|
+
.map(([k, v]) => {
|
|
362
|
+
const val = typeof v === "string" ? v : JSON.stringify(v);
|
|
363
|
+
return `${k}:${val.length > 30 ? val.slice(0, 30) + "…" : val}`;
|
|
364
|
+
})
|
|
365
|
+
.join(" ");
|
|
366
|
+
text += " " + theme.fg("muted", preview);
|
|
367
|
+
}
|
|
368
|
+
return new Text(text, 0, 0);
|
|
369
|
+
},
|
|
370
|
+
|
|
371
|
+
renderResult(result, { isPartial, expanded }, theme) {
|
|
372
|
+
if (isPartial) return new Text(theme.fg("warning", "Calling MCP tool..."), 0, 0);
|
|
373
|
+
|
|
374
|
+
const d = result.details as {
|
|
375
|
+
server: string;
|
|
376
|
+
tool: string;
|
|
377
|
+
charCount: number;
|
|
378
|
+
truncated: boolean;
|
|
379
|
+
} | undefined;
|
|
380
|
+
|
|
381
|
+
let text = theme.fg("success", `✓ ${d?.server}.${d?.tool}`);
|
|
382
|
+
text += theme.fg("dim", ` · ${(d?.charCount ?? 0).toLocaleString()} chars`);
|
|
383
|
+
if (d?.truncated) text += theme.fg("warning", " · truncated");
|
|
384
|
+
|
|
385
|
+
if (expanded) {
|
|
386
|
+
const content = result.content[0];
|
|
387
|
+
if (content?.type === "text") {
|
|
388
|
+
const preview = content.text.split("\n").slice(0, 15).join("\n");
|
|
389
|
+
text += "\n\n" + theme.fg("dim", preview);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
return new Text(text, 0, 0);
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
// ── Verify mcporter is available ─────────────────────────────────────────
|
|
398
|
+
|
|
399
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
400
|
+
try {
|
|
401
|
+
const ver = (await runMcporter(["--version"], undefined, 5000)).trim();
|
|
402
|
+
ctx.ui.notify(`MCPorter ${ver} ready`, "info");
|
|
403
|
+
} catch {
|
|
404
|
+
ctx.ui.notify(
|
|
405
|
+
"MCPorter not found. Install with: npm i -g mcporter",
|
|
406
|
+
"error",
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
export default function clearCommand(pi: ExtensionAPI) {
|
|
4
|
+
pi.registerCommand("clear", {
|
|
5
|
+
description: "Alias for /new — start a new session",
|
|
6
|
+
async handler(_args: string, ctx: ExtensionCommandContext) {
|
|
7
|
+
await ctx.newSession();
|
|
8
|
+
},
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -2,11 +2,11 @@ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
|
2
2
|
import createSlashCommand from "./create-slash-command.js";
|
|
3
3
|
import createExtension from "./create-extension.js";
|
|
4
4
|
import auditCommand from "./audit.js";
|
|
5
|
-
import
|
|
5
|
+
import clearCommand from "./clear.js";
|
|
6
6
|
|
|
7
7
|
export default function slashCommands(pi: ExtensionAPI) {
|
|
8
8
|
createSlashCommand(pi);
|
|
9
9
|
createExtension(pi);
|
|
10
10
|
auditCommand(pi);
|
|
11
|
-
|
|
11
|
+
clearCommand(pi);
|
|
12
12
|
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
2
|
+
import type { AssistantMessage } from "@mariozechner/pi-ai";
|
|
3
|
+
import { isKeyRelease, Key, matchesKey, truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
|
|
4
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
import * as readline from "node:readline";
|
|
7
|
+
|
|
8
|
+
const RECOGNIZER_BIN = path.join(__dirname, "speech-recognizer");
|
|
9
|
+
|
|
10
|
+
export default function (pi: ExtensionAPI) {
|
|
11
|
+
if (process.platform !== "darwin") return;
|
|
12
|
+
|
|
13
|
+
let active = false;
|
|
14
|
+
let recognizerProcess: ChildProcess | null = null;
|
|
15
|
+
let finalized = "";
|
|
16
|
+
let flashOn = true;
|
|
17
|
+
let flashTimer: ReturnType<typeof setInterval> | null = null;
|
|
18
|
+
let footerTui: { requestRender: () => void } | null = null;
|
|
19
|
+
|
|
20
|
+
function setVoiceFooter(ctx: ExtensionContext, on: boolean) {
|
|
21
|
+
if (!on) {
|
|
22
|
+
stopFlash();
|
|
23
|
+
ctx.ui.setFooter(undefined);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
flashOn = true;
|
|
28
|
+
flashTimer = setInterval(() => {
|
|
29
|
+
flashOn = !flashOn;
|
|
30
|
+
footerTui?.requestRender();
|
|
31
|
+
}, 500);
|
|
32
|
+
|
|
33
|
+
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
34
|
+
footerTui = tui;
|
|
35
|
+
const branchUnsub = footerData.onBranchChange(() => tui.requestRender());
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
dispose: branchUnsub,
|
|
39
|
+
invalidate() {},
|
|
40
|
+
render(width: number): string[] {
|
|
41
|
+
// --- Row 1: pwd (branch) ... ● transcribing ---
|
|
42
|
+
let pwd = process.cwd();
|
|
43
|
+
const home = process.env.HOME || process.env.USERPROFILE;
|
|
44
|
+
if (home && pwd.startsWith(home)) pwd = `~${pwd.slice(home.length)}`;
|
|
45
|
+
const branch = footerData.getGitBranch();
|
|
46
|
+
if (branch) pwd = `${pwd} (${branch})`;
|
|
47
|
+
|
|
48
|
+
const dot = flashOn ? theme.fg("error", "●") : theme.fg("dim", "●");
|
|
49
|
+
const voiceTag = `${dot} ${theme.fg("error", "transcribing")}`;
|
|
50
|
+
const voiceTagWidth = visibleWidth(voiceTag);
|
|
51
|
+
|
|
52
|
+
const maxPwdWidth = width - voiceTagWidth - 2;
|
|
53
|
+
const pwdStr = truncateToWidth(theme.fg("dim", pwd), maxPwdWidth, theme.fg("dim", "..."));
|
|
54
|
+
const pad1 = " ".repeat(Math.max(1, width - visibleWidth(pwdStr) - voiceTagWidth));
|
|
55
|
+
const row1 = truncateToWidth(pwdStr + pad1 + voiceTag, width);
|
|
56
|
+
|
|
57
|
+
// --- Row 2: stats ... model (replicate default) ---
|
|
58
|
+
let totalInput = 0, totalOutput = 0, totalCost = 0;
|
|
59
|
+
for (const entry of ctx.sessionManager.getEntries()) {
|
|
60
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
61
|
+
const m = entry.message as AssistantMessage;
|
|
62
|
+
totalInput += m.usage.input;
|
|
63
|
+
totalOutput += m.usage.output;
|
|
64
|
+
totalCost += m.usage.cost.total;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const fmt = (n: number) => n < 1000 ? `${n}` : n < 10000 ? `${(n / 1000).toFixed(1)}k` : `${Math.round(n / 1000)}k`;
|
|
69
|
+
const parts: string[] = [];
|
|
70
|
+
if (totalInput) parts.push(`↑${fmt(totalInput)}`);
|
|
71
|
+
if (totalOutput) parts.push(`↓${fmt(totalOutput)}`);
|
|
72
|
+
if (totalCost) parts.push(`$${totalCost.toFixed(3)}`);
|
|
73
|
+
|
|
74
|
+
const usage = ctx.getContextUsage();
|
|
75
|
+
const ctxPct = usage?.percent !== null && usage?.percent !== undefined ? `${usage.percent.toFixed(1)}%` : "?";
|
|
76
|
+
const ctxWin = usage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
|
|
77
|
+
parts.push(`${ctxPct}/${fmt(ctxWin)}`);
|
|
78
|
+
|
|
79
|
+
const statsLeft = theme.fg("dim", parts.join(" "));
|
|
80
|
+
const modelRight = theme.fg("dim", ctx.model?.id || "no-model");
|
|
81
|
+
const statsLeftW = visibleWidth(statsLeft);
|
|
82
|
+
const modelRightW = visibleWidth(modelRight);
|
|
83
|
+
const pad2 = " ".repeat(Math.max(2, width - statsLeftW - modelRightW));
|
|
84
|
+
const row2 = truncateToWidth(statsLeft + pad2 + modelRight, width);
|
|
85
|
+
|
|
86
|
+
return [row1, row2];
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function stopFlash() {
|
|
93
|
+
if (flashTimer) { clearInterval(flashTimer); flashTimer = null; }
|
|
94
|
+
footerTui = null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function toggleVoice(ctx: ExtensionContext) {
|
|
98
|
+
if (active) {
|
|
99
|
+
killRecognizer();
|
|
100
|
+
active = false;
|
|
101
|
+
setVoiceFooter(ctx, false);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
active = true;
|
|
106
|
+
finalized = "";
|
|
107
|
+
setVoiceFooter(ctx, true);
|
|
108
|
+
await runVoiceSession(ctx);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
pi.registerCommand("voice", {
|
|
112
|
+
description: "Toggle voice mode",
|
|
113
|
+
handler: async (_args, ctx) => toggleVoice(ctx),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
pi.registerShortcut("ctrl+alt+v", {
|
|
117
|
+
description: "Toggle voice mode",
|
|
118
|
+
handler: async (ctx) => toggleVoice(ctx),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
function killRecognizer() {
|
|
122
|
+
if (recognizerProcess) { recognizerProcess.kill("SIGTERM"); recognizerProcess = null; }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function startRecognizer(
|
|
126
|
+
onPartial: (text: string) => void,
|
|
127
|
+
onFinal: (text: string) => void,
|
|
128
|
+
onError: (msg: string) => void,
|
|
129
|
+
onReady: () => void,
|
|
130
|
+
) {
|
|
131
|
+
recognizerProcess = spawn(RECOGNIZER_BIN, [], { stdio: ["pipe", "pipe", "pipe"] });
|
|
132
|
+
const rl = readline.createInterface({ input: recognizerProcess.stdout! });
|
|
133
|
+
rl.on("line", (line: string) => {
|
|
134
|
+
if (line === "READY") { onReady(); return; }
|
|
135
|
+
if (line.startsWith("PARTIAL:")) onPartial(line.slice(8));
|
|
136
|
+
else if (line.startsWith("FINAL:")) onFinal(line.slice(6));
|
|
137
|
+
else if (line.startsWith("ERROR:")) onError(line.slice(6));
|
|
138
|
+
});
|
|
139
|
+
recognizerProcess.on("error", (err) => onError(err.message));
|
|
140
|
+
recognizerProcess.on("exit", () => { recognizerProcess = null; });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function runVoiceSession(ctx: ExtensionContext): Promise<void> {
|
|
144
|
+
return new Promise<void>((resolve) => {
|
|
145
|
+
startRecognizer(
|
|
146
|
+
(text) => {
|
|
147
|
+
const full = finalized + (finalized && text ? " " : "") + text;
|
|
148
|
+
ctx.ui.setEditorText(full);
|
|
149
|
+
},
|
|
150
|
+
(text) => {
|
|
151
|
+
finalized = (finalized ? finalized + " " : "") + text;
|
|
152
|
+
ctx.ui.setEditorText(finalized);
|
|
153
|
+
},
|
|
154
|
+
(msg) => ctx.ui.notify(`Voice: ${msg}`, "error"),
|
|
155
|
+
() => {},
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
ctx.ui.custom<void>(
|
|
159
|
+
(_tui, _theme, _kb, done) => ({
|
|
160
|
+
render(): string[] { return []; },
|
|
161
|
+
handleInput(data: string) {
|
|
162
|
+
if (isKeyRelease(data)) return;
|
|
163
|
+
if (matchesKey(data, Key.escape) || matchesKey(data, Key.enter)) {
|
|
164
|
+
killRecognizer();
|
|
165
|
+
active = false;
|
|
166
|
+
setVoiceFooter(ctx, false);
|
|
167
|
+
done();
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
invalidate() {},
|
|
171
|
+
}),
|
|
172
|
+
{ overlay: true, overlayOptions: { anchor: "bottom-center", width: "100%" } },
|
|
173
|
+
).then(() => resolve());
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Speech
|
|
3
|
+
import AVFoundation
|
|
4
|
+
|
|
5
|
+
// Unbuffered stdout
|
|
6
|
+
setbuf(stdout, nil)
|
|
7
|
+
|
|
8
|
+
guard SFSpeechRecognizer.authorizationStatus() == .authorized ||
|
|
9
|
+
SFSpeechRecognizer.authorizationStatus() == .notDetermined else {
|
|
10
|
+
print("ERROR:Speech recognition not authorized")
|
|
11
|
+
exit(1)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
SFSpeechRecognizer.requestAuthorization { status in
|
|
15
|
+
guard status == .authorized else {
|
|
16
|
+
print("ERROR:Speech recognition denied")
|
|
17
|
+
exit(1)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
|
|
22
|
+
guard recognizer.isAvailable else {
|
|
23
|
+
print("ERROR:Speech recognizer not available")
|
|
24
|
+
exit(1)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
let audioEngine = AVAudioEngine()
|
|
28
|
+
let request = SFSpeechAudioBufferRecognitionRequest()
|
|
29
|
+
request.shouldReportPartialResults = true
|
|
30
|
+
request.requiresOnDeviceRecognition = true
|
|
31
|
+
|
|
32
|
+
let node = audioEngine.inputNode
|
|
33
|
+
let format = node.outputFormat(forBus: 0)
|
|
34
|
+
|
|
35
|
+
node.installTap(onBus: 0, bufferSize: 1024, format: format) { buffer, _ in
|
|
36
|
+
request.append(buffer)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
audioEngine.prepare()
|
|
40
|
+
do {
|
|
41
|
+
try audioEngine.start()
|
|
42
|
+
print("READY")
|
|
43
|
+
} catch {
|
|
44
|
+
print("ERROR:Failed to start audio engine: \(error.localizedDescription)")
|
|
45
|
+
exit(1)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
var lastText = ""
|
|
49
|
+
|
|
50
|
+
recognizer.recognitionTask(with: request) { result, error in
|
|
51
|
+
if let result = result {
|
|
52
|
+
let text = result.bestTranscription.formattedString
|
|
53
|
+
if text != lastText {
|
|
54
|
+
lastText = text
|
|
55
|
+
let prefix = result.isFinal ? "FINAL" : "PARTIAL"
|
|
56
|
+
print("\(prefix):\(text)")
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if let error = error {
|
|
60
|
+
// Task finished errors are normal on kill
|
|
61
|
+
let nsError = error as NSError
|
|
62
|
+
if nsError.code != 216 { // kAFAssistantErrorDomain code for cancelled
|
|
63
|
+
print("ERROR:\(error.localizedDescription)")
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Handle SIGTERM/SIGINT gracefully
|
|
69
|
+
signal(SIGTERM) { _ in
|
|
70
|
+
exit(0)
|
|
71
|
+
}
|
|
72
|
+
signal(SIGINT) { _ in
|
|
73
|
+
exit(0)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
RunLoop.current.run()
|