Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PiCommands.ts

153 lines6.0 KB

1import { type ServerProviderSkill, type ServerProviderSlashCommand } from "@t3tools/contracts";
2import * as Predicate from "effect/Predicate";
3​
4// Pi RPC get_commands omits TUI builtins. T3 handles these explicitly.
5export const PI_COMPACT_SLASH_COMMAND: ServerProviderSlashCommand = {
6 name: "compact",
7 description: "Summarize the conversation and reduce context usage",
8 input: { hint: "Optional instructions" },
9 argumentMode: "optional",
10};
11​
12export interface PiCompactCommand {
13 readonly customInstructions?: string;
15​
16export function parsePiCompactCommand(text: string): PiCompactCommand | null {
17 const trimmed = text.trim();
18 if (trimmed === "/compact") return {};
19 if (!trimmed.startsWith("/compact")) return null;
20 const rest = trimmed.slice("/compact".length);
21 if (rest.length === 0) return {};
22 if (!/^\s/.test(rest)) return null;
23 const customInstructions = rest.trim();
24 return customInstructions.length === 0 ? {} : { customInstructions };
26​
27export function withPiBuiltinSlashCommands(
28 commands: ReadonlyArray<ServerProviderSlashCommand>,
29): ReadonlyArray<ServerProviderSlashCommand> {
30 const builtins = [
31 PI_COMPACT_SLASH_COMMAND,
32 { name: "copy", description: "Copy the last assistant response", argumentMode: "none" },
33 {
34 name: "export",
35 description: "Download the Pi session as HTML",
36 input: { hint: "Optional HTML path on the server" },
37 argumentMode: "optional",
38 },
39 {
40 name: "share",
41 description: "Share the Pi session through an unlisted GitHub gist",
42 argumentMode: "none",
43 },
44 ] satisfies ReadonlyArray<ServerProviderSlashCommand>;
45 const names = new Set(builtins.map((command) => command.name));
46 return [...builtins, ...commands.filter((command) => !names.has(command.name))];
48​
49export interface PiDiscoveredCommands {
50 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
51 readonly skills: ReadonlyArray<ServerProviderSkill>;
53​
54function normalizePiSkillScope(scope: string | undefined): string | undefined {
55 if (scope === undefined) return undefined;
56 const normalized = scope.trim().toLowerCase();
57 if (normalized === "global" || normalized === "personal") return "user";
58 if (normalized === "workspace" || normalized === "local") return "project";
59 return scope;
61​
62/** Maps Pi's `get_commands` payload to T3's shared command and skill surfaces. */
63export function parsePiDiscoveredCommands(data: unknown): PiDiscoveredCommands {
64 const commands = recordField(data, "commands");
65 if (!Array.isArray(commands)) return { slashCommands: [], skills: [] };
66 const slashCommands: Array<ServerProviderSlashCommand> = [];
67 const skills: Array<ServerProviderSkill> = [];
68 for (const command of commands) {
69 const commandName = recordString(command, "name");
70 if (commandName === undefined || commandName.length === 0) continue;
71 const description = recordString(command, "description");
72 if (recordString(command, "source") === "skill") {
73 const name = commandName.startsWith("skill:")
74 ? commandName.slice("skill:".length)
75 : commandName;
76 if (name.length === 0) continue;
77 const sourceInfo = recordField(command, "sourceInfo");
78 const commandInterface = recordField(command, "interface");
79 const path =
80 recordString(sourceInfo, "path") ?? recordString(command, "path") ?? `pi:skill:${name}`;
81 const scope = normalizePiSkillScope(
82 recordString(sourceInfo, "scope") ?? recordString(command, "location"),
83 );
84 const displayName =
85 recordString(command, "displayName") ??
86 recordString(sourceInfo, "displayName") ??
87 recordString(commandInterface, "displayName");
88 const shortDescription =
89 recordString(command, "shortDescription") ??
90 recordString(sourceInfo, "shortDescription") ??
91 recordString(commandInterface, "shortDescription");
92 skills.push({
93 name,
94 path,
95 enabled: true,
96 ...(description === undefined ? {} : { description }),
97 ...(scope === undefined ? {} : { scope }),
98 ...(displayName === undefined ? {} : { displayName }),
99 ...(shortDescription === undefined ? {} : { shortDescription }),
100 });
101 continue;
102 }
103 slashCommands.push({
104 name: commandName,
105 ...(description === undefined ? {} : { description }),
106 });
107 }
108 return { slashCommands, skills };
110​
111/**
112 * Pi expands skills only through leading `/skill:name` commands. T3 stores
113 * skill chips as `$name`, so hoist every known `$skill` to that native
114 * command position while preserving the rest of the user's prompt.
115 */
116export function expandPiSkillReference(text: string, skillNames: ReadonlySet<string>): string {
117 const references = /(^|\s)\$([^\s]+)(?=\s|$)/g;
118 const found: Array<{ name: string; start: number; end: number }> = [];
119 for (const match of text.matchAll(references)) {
120 const name = match[2];
121 if (name === undefined || !skillNames.has(name) || match.index === undefined) continue;
122 const tokenStart = match.index + (match[1]?.length ?? 0);
123 found.push({ name, start: tokenStart, end: tokenStart + name.length + 1 });
124 }
125 if (found.length === 0) return text;
126​
127 const orderedNames: string[] = [];
128 const seen = new Set<string>();
129 for (const token of found) {
130 if (seen.has(token.name)) continue;
131 seen.add(token.name);
132 orderedNames.push(token.name);
133 }
134​
135 let body = text;
136 for (let index = found.length - 1; index >= 0; index -= 1) {
137 const token = found[index];
138 if (token === undefined) continue;
139 body = `${body.slice(0, token.start)}${body.slice(token.end)}`;
140 }
141 body = body.trim();
142 const prefix = orderedNames.map((name) => `/skill:${name}`).join(" ");
143 return body.length === 0 ? prefix : `${prefix} ${body}`;
145​
146function recordField(input: unknown, key: string): unknown {
147 return Predicate.isObject(input) ? input[key] : undefined;
149​
150function recordString(input: unknown, key: string): string | undefined {
151 const value = recordField(input, key);
152 return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;