Open History to see the last commit
1// The CLI catalog honors ignored/disabled skills and nested plugin skills that flat scans miss.
2import type { ServerProviderSkill } from "@t3tools/contracts";
3import type { GrokSettings } from "../settings.ts";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as ChildProcess from "effect/process/ChildProcess";
8import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
9import { resolveSpawnCommand } from "@t3tools/shared/shell";
10
11import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
12import { grokProbeEnvironment } from "./probeEnvironment.ts";
13
14const GROK_SKILLS_PROBE_TIMEOUT_MS = 4_000;
15// The composer's chip rule, anchored to the message start, so `$25` never names a skill.
16const LEADING_SKILL_MENTION = new RegExp(`^\\s*${SKILL_MENTION_PATTERN.source}`, "u");
17
18/** A message opening with a mention, such as `deploy` and ` ship it` for `$deploy ship it`. */
19export function leadingGrokSkillMention(
20 text: string,
21): { readonly name: string; readonly rest: string } | undefined {
22 const match = LEADING_SKILL_MENTION.exec(text);
23 if (match?.[2] === undefined) return undefined;
24 return { name: match[2], rest: text.slice(match[0].length) };
25}
26
27class GrokSkillsProbeError extends Schema.TaggedError<GrokSkillsProbeError>()(
28 "GrokSkillsProbeError",
29 {
30 stage: Schema.Literals(["spawn", "timeout", "exit", "decode"]),
31 cwd: Schema.optional(Schema.String),
32 exitCode: Schema.optional(Schema.Number),
33 cause: Schema.optional(Schema.Defect()),
34 },
35) {
36 override get message(): string {
37 const location = this.cwd === undefined ? "" : ` for '${this.cwd}'`;
38 const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
39 return `\`grok inspect --json\` failed during ${this.stage}${location}${exitCode}.`;
40 }
41}
42
43function decodeGrokInspectSkills(stdout: string): ReadonlyArray<ServerProviderSkill> | undefined {
44 let parsed: unknown;
45 try {
46 parsed = JSON.parse(stdout);
47 } catch {
48 return undefined;
49 }
50 if (typeof parsed !== "object" || parsed === null) {
51 return undefined;
52 }
53 const entries = (parsed as Record<string, unknown>).skills;
54 if (!Array.isArray(entries)) {
55 return undefined;
56 }
57
58 const skillsByName = new Map<string, ServerProviderSkill>();
59 for (const entry of entries) {
60 if (typeof entry !== "object" || entry === null) {
61 continue;
62 }
63 const record = entry as Record<string, unknown>;
64 const name = typeof record.name === "string" ? record.name.trim() : "";
65 const source =
66 typeof record.source === "object" && record.source !== null
67 ? (record.source as Record<string, unknown>)
68 : undefined;
69 const path = typeof source?.path === "string" ? source.path.trim() : "";
70 if (!name || !path) {
71 continue;
72 }
73 const scope = typeof source?.type === "string" ? source.type.trim() : "";
74 const description = typeof record.description === "string" ? record.description.trim() : "";
75 skillsByName.set(name, {
76 name,
77 path,
78 enabled: record.userInvocable !== false,
79 ...(scope ? { scope } : {}),
80 ...(description ? { description } : {}),
81 });
82 }
83
84 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
85}
86
87export const discoverGrokSkills = Effect.fn("discoverGrokSkills")(function* (
88 grokSettings: Pick<GrokSettings, "binaryPath">,
89 environment: NodeJS.ProcessEnv = process.env,
90 cwd?: string,
91) {
92 const command = grokSettings.binaryPath || "grok";
93 const probeEnvironment = grokProbeEnvironment(environment);
94 const inspectResult = yield* Effect.gen(function* () {
95 const spawnCommand = yield* resolveSpawnCommand(command, ["inspect", "--json"], {
96 env: probeEnvironment,
97 });
98 return yield* spawnAndCollect(
99 command,
100 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
101 ...(cwd ? { cwd } : {}),
102 env: probeEnvironment,
103 shell: spawnCommand.shell,
104 }),
105 );
106 }).pipe(
107 Effect.mapError(
108 (cause) =>
109 new GrokSkillsProbeError({
110 stage: "spawn",
111 ...(cwd ? { cwd } : {}),
112 cause,
113 }),
114 ),
115 Effect.timeoutOption(GROK_SKILLS_PROBE_TIMEOUT_MS),
116 );
117
118 if (Option.isNone(inspectResult)) {
119 return yield* new GrokSkillsProbeError({
120 stage: "timeout",
121 ...(cwd ? { cwd } : {}),
122 });
123 }
124 const output = inspectResult.value;
125 if (output.code !== 0) {
126 return yield* new GrokSkillsProbeError({
127 stage: "exit",
128 ...(cwd ? { cwd } : {}),
129 exitCode: output.code,
130 });
131 }
132 const skills = decodeGrokInspectSkills(output.stdout);
133 if (!skills) {
134 return yield* new GrokSkillsProbeError({
135 stage: "decode",
136 ...(cwd ? { cwd } : {}),
137 });
138 }
139 return skills;
140});