|
| 1 | +import { isMetricEnabled } from "../util.ts" |
| 2 | +import type { HandlerContext, PluginLogger } from "../types.ts" |
| 3 | + |
| 4 | +type SkillCommandInfo = { |
| 5 | + name: string |
| 6 | + description?: string |
| 7 | + agent?: string |
| 8 | + subtask?: boolean |
| 9 | +} |
| 10 | + |
| 11 | +type RawCommand = { |
| 12 | + name?: unknown |
| 13 | + source?: unknown |
| 14 | + description?: unknown |
| 15 | + agent?: unknown |
| 16 | + subtask?: unknown |
| 17 | +} |
| 18 | + |
| 19 | +type CommandListClient = { |
| 20 | + command?: { |
| 21 | + list(options?: { query?: { directory?: string; workspace?: string } }): Promise<{ data?: unknown; error?: unknown } | unknown> |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +type CommandExecuteInput = { |
| 26 | + command: string |
| 27 | + sessionID: string |
| 28 | + arguments: string |
| 29 | +} |
| 30 | + |
| 31 | +type SkillInvocationInput = { |
| 32 | + sessionID: string |
| 33 | + skillName: string |
| 34 | + invocationType: "command" | "tool" |
| 35 | + commandName?: string |
| 36 | + toolName?: string |
| 37 | + argumentsLength?: number |
| 38 | + description?: string |
| 39 | + agent?: string |
| 40 | + subtask?: boolean |
| 41 | +} |
| 42 | + |
| 43 | +type SkillCommandLookup = { |
| 44 | + ok: boolean |
| 45 | + commands: SkillCommandInfo[] |
| 46 | +} |
| 47 | + |
| 48 | +type ParsedSkillCommands = { |
| 49 | + sourceAware: boolean |
| 50 | + commands: SkillCommandInfo[] |
| 51 | +} |
| 52 | + |
| 53 | +function rawSkillCommand(command: RawCommand): SkillCommandInfo | undefined { |
| 54 | + if (command.source !== "skill" || typeof command.name !== "string") return undefined |
| 55 | + return { |
| 56 | + name: command.name, |
| 57 | + ...(typeof command.description === "string" ? { description: command.description } : {}), |
| 58 | + ...(typeof command.agent === "string" ? { agent: command.agent } : {}), |
| 59 | + ...(typeof command.subtask === "boolean" ? { subtask: command.subtask } : {}), |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +function commandsFromPayload(payload: unknown): ParsedSkillCommands { |
| 64 | + const data = payload && typeof payload === "object" && "data" in payload |
| 65 | + ? (payload as { data?: unknown }).data |
| 66 | + : payload |
| 67 | + const commands = data && typeof data === "object" && "data" in data |
| 68 | + ? (data as { data?: unknown }).data |
| 69 | + : data |
| 70 | + if (!Array.isArray(commands)) return { sourceAware: false, commands: [] } |
| 71 | + return { |
| 72 | + sourceAware: commands.length === 0 |
| 73 | + || commands.some((command) => command && typeof command === "object" && "source" in command), |
| 74 | + commands: commands |
| 75 | + .map((command) => rawSkillCommand(command as RawCommand)) |
| 76 | + .filter((command): command is SkillCommandInfo => !!command), |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +async function clientSkillCommands(client: CommandListClient, directory: string | undefined): Promise<SkillCommandLookup> { |
| 81 | + if (!client.command?.list) return { ok: false, commands: [] } |
| 82 | + const response = await client.command.list(directory ? { query: { directory } } : undefined) |
| 83 | + if (response && typeof response === "object" && "error" in response && (response as { error?: unknown }).error !== undefined) { |
| 84 | + return { ok: false, commands: [] } |
| 85 | + } |
| 86 | + const parsed = commandsFromPayload(response) |
| 87 | + return { ok: parsed.sourceAware, commands: parsed.commands } |
| 88 | +} |
| 89 | + |
| 90 | +async function rawSkillCommands(serverUrl: URL, directory: string | undefined, path: "/command" | "/api/command"): Promise<SkillCommandLookup> { |
| 91 | + const url = new URL(path, serverUrl) |
| 92 | + if (directory) { |
| 93 | + if (path === "/api/command") { |
| 94 | + url.searchParams.set("location[directory]", directory) |
| 95 | + } else { |
| 96 | + url.searchParams.set("directory", directory) |
| 97 | + } |
| 98 | + } |
| 99 | + const controller = new AbortController() |
| 100 | + const timeout = setTimeout(() => controller.abort(), 1_000) |
| 101 | + try { |
| 102 | + const response = await fetch(url, { signal: controller.signal }) |
| 103 | + if (!response.ok) return { ok: false, commands: [] } |
| 104 | + const parsed = commandsFromPayload(await response.json()) |
| 105 | + return { ok: parsed.sourceAware, commands: parsed.commands } |
| 106 | + } finally { |
| 107 | + clearTimeout(timeout) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +export function createSkillCommandResolver(input: { |
| 112 | + client: CommandListClient |
| 113 | + serverUrl: URL |
| 114 | + directory?: string |
| 115 | + log: PluginLogger |
| 116 | +}) { |
| 117 | + let lastRefresh = 0 |
| 118 | + let refreshPromise: Promise<void> | undefined |
| 119 | + const skillCommands = new Map<string, SkillCommandInfo>() |
| 120 | + |
| 121 | + const refresh = async (force = false) => { |
| 122 | + if (!force && Date.now() - lastRefresh < 30_000) return |
| 123 | + if (refreshPromise) return refreshPromise |
| 124 | + refreshPromise = (async () => { |
| 125 | + const next = new Map<string, SkillCommandInfo>() |
| 126 | + let catalogLoaded = false |
| 127 | + try { |
| 128 | + const lookup = await clientSkillCommands(input.client, input.directory) |
| 129 | + catalogLoaded = catalogLoaded || lookup.ok |
| 130 | + for (const command of lookup.commands) { |
| 131 | + next.set(command.name, command) |
| 132 | + } |
| 133 | + } catch (err) { |
| 134 | + await input.log("debug", "otel: command catalog lookup failed", { |
| 135 | + error: err instanceof Error ? err.message : String(err), |
| 136 | + }) |
| 137 | + } |
| 138 | + if (next.size === 0) { |
| 139 | + try { |
| 140 | + const lookup = await rawSkillCommands(input.serverUrl, input.directory, "/command") |
| 141 | + catalogLoaded = catalogLoaded || lookup.ok |
| 142 | + for (const command of lookup.commands) { |
| 143 | + next.set(command.name, command) |
| 144 | + } |
| 145 | + } catch (err) { |
| 146 | + await input.log("debug", "otel: raw command catalog lookup failed", { |
| 147 | + error: err instanceof Error ? err.message : String(err), |
| 148 | + }) |
| 149 | + } |
| 150 | + } |
| 151 | + if (next.size === 0) { |
| 152 | + try { |
| 153 | + const lookup = await rawSkillCommands(input.serverUrl, input.directory, "/api/command") |
| 154 | + catalogLoaded = catalogLoaded || lookup.ok |
| 155 | + for (const command of lookup.commands) { |
| 156 | + next.set(command.name, command) |
| 157 | + } |
| 158 | + } catch (err) { |
| 159 | + await input.log("debug", "otel: v2 command catalog lookup failed", { |
| 160 | + error: err instanceof Error ? err.message : String(err), |
| 161 | + }) |
| 162 | + } |
| 163 | + } |
| 164 | + if (!catalogLoaded) { |
| 165 | + await input.log("debug", "otel: skill command catalog refresh skipped") |
| 166 | + return |
| 167 | + } |
| 168 | + skillCommands.clear() |
| 169 | + for (const [name, command] of next) skillCommands.set(name, command) |
| 170 | + lastRefresh = Date.now() |
| 171 | + await input.log("debug", "otel: skill command catalog refreshed", { count: skillCommands.size }) |
| 172 | + })().finally(() => { |
| 173 | + refreshPromise = undefined |
| 174 | + }) |
| 175 | + return refreshPromise |
| 176 | + } |
| 177 | + |
| 178 | + return { |
| 179 | + refresh, |
| 180 | + resolve: async (command: string) => { |
| 181 | + let skill = skillCommands.get(command) |
| 182 | + if (skill) return skill |
| 183 | + await refresh(false) |
| 184 | + skill = skillCommands.get(command) |
| 185 | + return skill |
| 186 | + }, |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +function stringProp(input: Record<string, unknown>, key: string): string | undefined { |
| 191 | + const value = input[key] |
| 192 | + return typeof value === "string" && value.trim() ? value : undefined |
| 193 | +} |
| 194 | + |
| 195 | +/** Extracts a skill name from the native `skill` tool input without exposing raw input. */ |
| 196 | +export function skillNameFromToolInput(input: unknown): string { |
| 197 | + if (typeof input === "string" && input.trim()) return input |
| 198 | + if (!input || typeof input !== "object") return "unknown" |
| 199 | + const record = input as Record<string, unknown> |
| 200 | + const direct = stringProp(record, "skill") ?? stringProp(record, "skillName") ?? stringProp(record, "name") |
| 201 | + if (direct) return direct |
| 202 | + const skill = record.skill |
| 203 | + if (skill && typeof skill === "object") { |
| 204 | + return stringProp(skill as Record<string, unknown>, "name") ?? "unknown" |
| 205 | + } |
| 206 | + return "unknown" |
| 207 | +} |
| 208 | + |
| 209 | +/** Emits the shared skill usage metric and log event for command and native tool paths. */ |
| 210 | +export function recordSkillInvocation(input: SkillInvocationInput, ctx: HandlerContext) { |
| 211 | + const attrs = { |
| 212 | + ...ctx.commonAttrs, |
| 213 | + "session.id": input.sessionID, |
| 214 | + skill_name: input.skillName, |
| 215 | + invocation_type: input.invocationType, |
| 216 | + ...(input.commandName ? { command_name: input.commandName } : {}), |
| 217 | + ...(input.toolName ? { tool_name: input.toolName } : {}), |
| 218 | + ...(input.agent ? { agent: input.agent } : {}), |
| 219 | + ...(input.subtask !== undefined ? { subtask: input.subtask } : {}), |
| 220 | + } |
| 221 | + |
| 222 | + if (isMetricEnabled("skill.count", ctx)) { |
| 223 | + ctx.instruments.skillCounter.add(1, attrs) |
| 224 | + } |
| 225 | + |
| 226 | + ctx.emitLog({ |
| 227 | + severityNumber: ctx.logSeverity.info, |
| 228 | + severityText: "INFO", |
| 229 | + timestamp: Date.now(), |
| 230 | + observedTimestamp: Date.now(), |
| 231 | + body: "skill_invoked", |
| 232 | + attributes: { |
| 233 | + "event.name": "skill_invoked", |
| 234 | + ...attrs, |
| 235 | + ...(input.argumentsLength !== undefined ? { arguments_length: input.argumentsLength } : {}), |
| 236 | + ...(input.description ? { description: input.description } : {}), |
| 237 | + }, |
| 238 | + }) |
| 239 | + |
| 240 | + return ctx.log("info", "otel: skill_invoked", { |
| 241 | + sessionID: input.sessionID, |
| 242 | + skill_name: input.skillName, |
| 243 | + invocation_type: input.invocationType, |
| 244 | + ...(input.commandName ? { command_name: input.commandName } : {}), |
| 245 | + ...(input.toolName ? { tool_name: input.toolName } : {}), |
| 246 | + }) |
| 247 | +} |
| 248 | + |
| 249 | +export async function handleCommandExecuteBefore( |
| 250 | + input: CommandExecuteInput, |
| 251 | + ctx: HandlerContext, |
| 252 | + resolveSkillCommand: (command: string) => Promise<SkillCommandInfo | undefined>, |
| 253 | +) { |
| 254 | + const skill = await resolveSkillCommand(input.command) |
| 255 | + if (!skill) return |
| 256 | + |
| 257 | + return recordSkillInvocation({ |
| 258 | + sessionID: input.sessionID, |
| 259 | + skillName: skill.name, |
| 260 | + invocationType: "command", |
| 261 | + commandName: input.command, |
| 262 | + argumentsLength: input.arguments.length, |
| 263 | + ...(skill.description ? { description: skill.description } : {}), |
| 264 | + ...(skill.agent ? { agent: skill.agent } : {}), |
| 265 | + ...(skill.subtask !== undefined ? { subtask: skill.subtask } : {}), |
| 266 | + }, ctx) |
| 267 | +} |
0 commit comments