|
| 1 | +import { SeverityNumber } from "@opentelemetry/api-logs" |
| 2 | +import { isMetricEnabled } from "../util.ts" |
| 3 | +import type { HandlerContext, PluginLogger } from "../types.ts" |
| 4 | + |
| 5 | +type SkillCommandInfo = { |
| 6 | + name: string |
| 7 | + description?: string |
| 8 | + agent?: string |
| 9 | + subtask?: boolean |
| 10 | +} |
| 11 | + |
| 12 | +type RawCommand = { |
| 13 | + name?: unknown |
| 14 | + source?: unknown |
| 15 | + description?: unknown |
| 16 | + agent?: unknown |
| 17 | + subtask?: unknown |
| 18 | +} |
| 19 | + |
| 20 | +type CommandListClient = { |
| 21 | + command?: { |
| 22 | + list(options?: { query?: { directory?: string; workspace?: string } }): Promise<{ data?: unknown; error?: unknown } | unknown> |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +type CommandExecuteInput = { |
| 27 | + command: string |
| 28 | + sessionID: string |
| 29 | + arguments: string |
| 30 | +} |
| 31 | + |
| 32 | +type SkillCommandLookup = { |
| 33 | + ok: boolean |
| 34 | + commands: SkillCommandInfo[] |
| 35 | +} |
| 36 | + |
| 37 | +function rawSkillCommand(command: RawCommand): SkillCommandInfo | undefined { |
| 38 | + if (command.source !== "skill" || typeof command.name !== "string") return undefined |
| 39 | + return { |
| 40 | + name: command.name, |
| 41 | + ...(typeof command.description === "string" ? { description: command.description } : {}), |
| 42 | + ...(typeof command.agent === "string" ? { agent: command.agent } : {}), |
| 43 | + ...(typeof command.subtask === "boolean" ? { subtask: command.subtask } : {}), |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +function commandsFromPayload(payload: unknown): SkillCommandInfo[] { |
| 48 | + const data = payload && typeof payload === "object" && "data" in payload |
| 49 | + ? (payload as { data?: unknown }).data |
| 50 | + : payload |
| 51 | + const commands = data && typeof data === "object" && "data" in data |
| 52 | + ? (data as { data?: unknown }).data |
| 53 | + : data |
| 54 | + if (!Array.isArray(commands)) return [] |
| 55 | + return commands |
| 56 | + .map((command) => rawSkillCommand(command as RawCommand)) |
| 57 | + .filter((command): command is SkillCommandInfo => !!command) |
| 58 | +} |
| 59 | + |
| 60 | +async function clientSkillCommands(client: CommandListClient, directory: string | undefined): Promise<SkillCommandLookup> { |
| 61 | + if (!client.command?.list) return { ok: false, commands: [] } |
| 62 | + const response = await client.command.list(directory ? { query: { directory } } : undefined) |
| 63 | + if (response && typeof response === "object" && "error" in response && (response as { error?: unknown }).error !== undefined) { |
| 64 | + return { ok: false, commands: [] } |
| 65 | + } |
| 66 | + return { ok: true, commands: commandsFromPayload(response) } |
| 67 | +} |
| 68 | + |
| 69 | +async function rawSkillCommands(serverUrl: URL, directory: string | undefined, path: "/command" | "/api/command"): Promise<SkillCommandLookup> { |
| 70 | + const url = new URL(path, serverUrl) |
| 71 | + if (directory) { |
| 72 | + if (path === "/api/command") { |
| 73 | + url.searchParams.set("location[directory]", directory) |
| 74 | + } else { |
| 75 | + url.searchParams.set("directory", directory) |
| 76 | + } |
| 77 | + } |
| 78 | + const controller = new AbortController() |
| 79 | + const timeout = setTimeout(() => controller.abort(), 1_000) |
| 80 | + try { |
| 81 | + const response = await fetch(url, { signal: controller.signal }) |
| 82 | + if (!response.ok) return { ok: false, commands: [] } |
| 83 | + return { ok: true, commands: commandsFromPayload(await response.json()) } |
| 84 | + } finally { |
| 85 | + clearTimeout(timeout) |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +export function createSkillCommandResolver(input: { |
| 90 | + client: CommandListClient |
| 91 | + serverUrl: URL |
| 92 | + directory?: string |
| 93 | + log: PluginLogger |
| 94 | +}) { |
| 95 | + let lastRefresh = 0 |
| 96 | + let refreshPromise: Promise<void> | undefined |
| 97 | + const skillCommands = new Map<string, SkillCommandInfo>() |
| 98 | + |
| 99 | + const refresh = async (force = false) => { |
| 100 | + if (!force && Date.now() - lastRefresh < 30_000) return |
| 101 | + if (refreshPromise) return refreshPromise |
| 102 | + refreshPromise = (async () => { |
| 103 | + const next = new Map<string, SkillCommandInfo>() |
| 104 | + let catalogLoaded = false |
| 105 | + try { |
| 106 | + const lookup = await clientSkillCommands(input.client, input.directory) |
| 107 | + catalogLoaded = catalogLoaded || lookup.ok |
| 108 | + for (const command of lookup.commands) { |
| 109 | + next.set(command.name, command) |
| 110 | + } |
| 111 | + } catch (err) { |
| 112 | + await input.log("debug", "otel: command catalog lookup failed", { |
| 113 | + error: err instanceof Error ? err.message : String(err), |
| 114 | + }) |
| 115 | + } |
| 116 | + if (next.size === 0) { |
| 117 | + try { |
| 118 | + const lookup = await rawSkillCommands(input.serverUrl, input.directory, "/command") |
| 119 | + catalogLoaded = catalogLoaded || lookup.ok |
| 120 | + for (const command of lookup.commands) { |
| 121 | + next.set(command.name, command) |
| 122 | + } |
| 123 | + } catch (err) { |
| 124 | + await input.log("debug", "otel: raw command catalog lookup failed", { |
| 125 | + error: err instanceof Error ? err.message : String(err), |
| 126 | + }) |
| 127 | + } |
| 128 | + } |
| 129 | + if (next.size === 0) { |
| 130 | + try { |
| 131 | + const lookup = await rawSkillCommands(input.serverUrl, input.directory, "/api/command") |
| 132 | + catalogLoaded = catalogLoaded || lookup.ok |
| 133 | + for (const command of lookup.commands) { |
| 134 | + next.set(command.name, command) |
| 135 | + } |
| 136 | + } catch (err) { |
| 137 | + await input.log("debug", "otel: v2 command catalog lookup failed", { |
| 138 | + error: err instanceof Error ? err.message : String(err), |
| 139 | + }) |
| 140 | + } |
| 141 | + } |
| 142 | + if (!catalogLoaded) { |
| 143 | + await input.log("debug", "otel: skill command catalog refresh skipped") |
| 144 | + return |
| 145 | + } |
| 146 | + skillCommands.clear() |
| 147 | + for (const [name, command] of next) skillCommands.set(name, command) |
| 148 | + lastRefresh = Date.now() |
| 149 | + await input.log("debug", "otel: skill command catalog refreshed", { count: skillCommands.size }) |
| 150 | + })().finally(() => { |
| 151 | + refreshPromise = undefined |
| 152 | + }) |
| 153 | + return refreshPromise |
| 154 | + } |
| 155 | + |
| 156 | + return { |
| 157 | + refresh, |
| 158 | + resolve: async (command: string) => { |
| 159 | + let skill = skillCommands.get(command) |
| 160 | + if (skill) return skill |
| 161 | + await refresh(false) |
| 162 | + skill = skillCommands.get(command) |
| 163 | + return skill |
| 164 | + }, |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +export async function handleCommandExecuteBefore( |
| 169 | + input: CommandExecuteInput, |
| 170 | + ctx: HandlerContext, |
| 171 | + resolveSkillCommand: (command: string) => Promise<SkillCommandInfo | undefined>, |
| 172 | +) { |
| 173 | + const skill = await resolveSkillCommand(input.command) |
| 174 | + if (!skill) return |
| 175 | + |
| 176 | + const attrs = { |
| 177 | + ...ctx.commonAttrs, |
| 178 | + "session.id": input.sessionID, |
| 179 | + skill_name: skill.name, |
| 180 | + command_name: input.command, |
| 181 | + ...(skill.agent ? { agent: skill.agent } : {}), |
| 182 | + ...(skill.subtask !== undefined ? { subtask: skill.subtask } : {}), |
| 183 | + } |
| 184 | + |
| 185 | + if (isMetricEnabled("skill.count", ctx)) { |
| 186 | + ctx.instruments.skillCounter.add(1, attrs) |
| 187 | + } |
| 188 | + |
| 189 | + ctx.emitLog({ |
| 190 | + severityNumber: SeverityNumber.INFO, |
| 191 | + severityText: "INFO", |
| 192 | + timestamp: Date.now(), |
| 193 | + observedTimestamp: Date.now(), |
| 194 | + body: "skill_invoked", |
| 195 | + attributes: { |
| 196 | + "event.name": "skill_invoked", |
| 197 | + ...attrs, |
| 198 | + arguments_length: input.arguments.length, |
| 199 | + ...(skill.description ? { description: skill.description } : {}), |
| 200 | + }, |
| 201 | + }) |
| 202 | + |
| 203 | + return ctx.log("info", "otel: skill_invoked", { |
| 204 | + sessionID: input.sessionID, |
| 205 | + skill_name: skill.name, |
| 206 | + command_name: input.command, |
| 207 | + }) |
| 208 | +} |
0 commit comments