返回 CodeWhale
inspect.ts
根目录 / crates / engine / extension-host / src / dsh / inspect.ts
1 import { isJson } from '../json.ts'
2 import { assertSupportedJsonSchema, validateJsonSchemaValue } from './dsh-tools-compat.js'
3 import catalogData from './inspect-catalog.json' with { type: 'json' }
4
5 export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
6 export type InspectPlatform = 'host' | 'client'
7
8 export interface InspectMethod {
9 name: string
10 description: string
11 inputSchema: JsonValue
12 outputSchema: JsonValue
13 }
14
15 export interface InspectProviderView {
16 platform: InspectPlatform
17 id: string
18 description: string
19 methods: InspectMethod[]
20 }
21
22 export interface InstalledRow {
23 id: string
24 name: string
25 state: string
26 }
27
28 export interface ClientState {
29 connected: boolean
30 drawnSeats?: readonly string[]
31 }
32
33 export interface InspectSources {
34 tools?: (agent: unknown, signal: AbortSignal) => Promise<readonly JsonValue[]> | readonly JsonValue[]
35 installed?: (signal: AbortSignal) => Promise<readonly InstalledRow[]> | readonly InstalledRow[]
36 client?: () => ClientState
37 }
38
39 export interface CordisInspect {
40 list(): InspectProviderView[]
41 query(platform: string, provider: string, method: string, input: JsonValue | undefined, agent?: unknown, signal?: AbortSignal): Promise<JsonValue>
42 }
43
44 interface Provider {
45 platform: InspectPlatform
46 id: string
47 description: string
48 methods: InspectMethod[]
49 run(method: string, input: Record<string, JsonValue>, agent: unknown, signal: AbortSignal): Promise<any> | any
50 }
51
52 const catalog = catalogData as any
53 const EMPTY_INPUT: JsonValue = { type: 'object', properties: {}, additionalProperties: false }
54 const ANY_OUTPUT: JsonValue = { description: 'JSON data owned by this inspect provider.' }
55 const NO_CLIENT = 'No client is connected. Plugin screens are drawn by the desktop app; in a terminal nothing is drawn, so every slot reports drawn: false.'
56
57 const exactInput = (field: string, description: string): JsonValue => ({
58 type: 'object',
59 properties: { [field]: { type: 'string', description } },
60 additionalProperties: false,
61 })
62
63 const method = (name: string, description: string, inputSchema: JsonValue = EMPTY_INPUT, outputSchema: JsonValue = ANY_OUTPUT): InspectMethod =>
64 ({ name, description, inputSchema, outputSchema })
65
66 const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value))
67
68 function serviceView(service: any): JsonValue {
69 return {
70 key: service.key,
71 group: service.group,
72 summary: service.summary,
73 availability: service.availability,
74 availabilityText: service.availabilityText,
75 methods: service.methods,
76 }
77 }
78
79 function serviceProvider(): Provider {
80 return {
81 platform: 'host', id: 'Service',
82 description: 'The services this host gives plugins, with their methods, and the services a plugin may not provide. A name that is not listed does not exist here.',
83 methods: [method('listService', 'Without input: the directory of services with one-line summaries and method signatures. With service: that service\'s exact contract, with availability. These are services a plugin injects, not DSH\'s full catalogue.',
84 exactInput('service', 'Exact service key. Omit it for the directory.'))],
85 run(_name, input) {
86 const key = input.service
87 if (key === undefined) {
88 return {
89 services: catalog.host.services.map((s: any) => ({ key: s.key, group: s.group, summary: s.summary, availability: s.availability, signatures: s.methods.map((m: any) => m.signature) })),
90 refusedServices: catalog.host.refusedServices,
91 note: 'refusedServices are names a plugin may not provide: the Engine owns them. Service methods named by the host Event and Config providers are separate.',
92 targetDshVersion: catalog.targetDshVersion,
93 }
94 }
95 const found = catalog.host.services.find((s: any) => s.key === key)
96 if (!found) throw new Error(`Host service "${String(key)}" is not provided by this host. Call without service for the directory.`)
97 return { service: serviceView(found), targetDshVersion: catalog.targetDshVersion }
98 },
99 }
100 }
101
102 function eventProvider(): Provider {
103 return {
104 platform: 'host', id: 'Event',
105 description: 'The events a plugin may listen to in this host, and the ones the host refuses.',
106 methods: [method('listEvents', 'Without input: the directory of events with status supported or refused. With event: its exact contract.',
107 exactInput('event', 'Exact event name. Omit it for the directory.'))],
108 run(_name, input) {
109 const key = input.event
110 if (key === undefined) {
111 return {
112 events: catalog.host.events.map((e: any) => ({ name: e.name, status: e.status, summary: e.summary })),
113 note: catalog.host.cordisInternalEvents,
114 }
115 }
116 const found = catalog.host.events.find((e: any) => e.name === key)
117 if (!found) throw new Error(`Host event "${String(key)}" is not known to this host. Call without event for the directory.`)
118 return { event: found }
119 },
120 }
121 }
122
123 const CONFIG_INPUT: JsonValue = {
124 type: 'object',
125 properties: {
126 entry: { type: 'string', description: 'Exact entry id from the directory; returns that entry\'s Config schema.' },
127 name: { type: 'string', description: 'Exact package or plugin name; limits the directory to it.' },
128 offset: { type: 'integer', description: 'Zero-based directory offset; defaults to 0.' },
129 limit: { type: 'integer', description: 'Directory page size, from 1 to 100; defaults to 25.' },
130 },
131 additionalProperties: false,
132 }
133
134 function configProvider(sources: InspectSources): Provider {
135 return {
136 platform: 'host', id: 'Config',
137 description: 'Config a composition row may carry: the packages a row may name, each with the config it accepts, and the plugins installed on this host with their state.',
138 methods: [method('listConfigs', 'Without entry: a page of the directory (row packages first, then installed plugins) with total and nextOffset. With entry: one row package\'s exact JSON Schema, limits and a valid example. Installed plugins are listed with their state; their own config is not described here.', CONFIG_INPUT)],
139 async run(_name, input, _agent, signal) {
140 const rows: any[] = catalog.host.config.map((r: any) => ({ id: r.id, name: r.name, kind: 'row-package', status: 'schema', bridge: r.bridge, summary: r.summary }))
141 const installed = sources.installed ? await sources.installed(signal) : []
142 for (const row of installed) rows.push({ id: `plugin:${row.id}`, name: row.name, kind: 'installed-plugin', status: row.state })
143 if (input.entry !== undefined) {
144 const pkg = catalog.host.config.find((r: any) => r.id === input.entry)
145 if (pkg) return { entry: pkg.id, name: pkg.name, kind: 'row-package', bridge: pkg.bridge, summary: pkg.summary, limits: pkg.limits, example: pkg.example, ...pkg.hookEvents ? { hookEvents: pkg.hookEvents } : {}, schema: pkg.schema }
146 const live = rows.find((r) => r.id === input.entry)
147 if (live) return { entry: live.id, name: live.name, kind: live.kind, status: live.status, schema: null, note: 'An installed plugin\'s own Config is not described by this host.' }
148 throw new Error(`Host Config entry "${String(input.entry)}" is not listed. Call without entry for the directory.`)
149 }
150 const filtered = input.name === undefined ? rows : rows.filter((r) => r.name === input.name)
151 const offset = typeof input.offset === 'number' ? input.offset : 0
152 const limit = typeof input.limit === 'number' ? input.limit : 25
153 if (offset < 0 || limit < 1 || limit > 100) throw new Error('Host Config directory needs offset >= 0 and 1 <= limit <= 100')
154 const page = filtered.slice(offset, offset + limit)
155 const next = offset + page.length
156 return { entries: page, total: filtered.length, ...next < filtered.length ? { nextOffset: next } : {} }
157 },
158 }
159 }
160
161 function toolProvider(sources: InspectSources): Provider | undefined {
162 const source = sources.tools
163 if (!source) return undefined
164 return {
165 platform: 'host', id: 'Tool',
166 description: 'Tools visible to the requesting agent.',
167 methods: [method('listTools', 'Return the name of every tool currently callable by this agent.')],
168 async run(_name, _input, agent, signal) {
169 return { tools: [...await source(agent, signal)] }
170 },
171 }
172 }
173
174 const SUBTREE_INPUT = exactInput('root', 'Exact slot name to select. Omit it for every slot.')
175
176 function slotsProvider(sources: InspectSources): Provider {
177 return {
178 platform: 'client', id: 'Slots',
179 description: 'The DSH slot names this host accepts, the seat each maps to, and whether the connected client draws that seat.',
180 methods: [method('listSubTree', 'Return every slot with its seat and drawn state; with root, also that slot selected. Slots are static names here, not a live tree, and their props are not described by this host: a plugin registers on a slot, the Engine serves it on the mapped seat, and the client draws only the seats it places.', SUBTREE_INPUT)],
181 run(_name, input) {
182 const state = sources.client?.() ?? { connected: false }
183 const drawn = new Set(state.connected ? state.drawnSeats ?? catalog.client.seats.filter((s: any) => s.drawn).map((s: any) => s.seat) : [])
184 const slots = catalog.client.slots.map((s: any) => ({
185 type: 'slot', name: s.slot, seat: s.seat, supported: s.supported,
186 drawn: s.supported && drawn.has(s.seat),
187 ...s.reason ? { reason: s.reason } : {},
188 }))
189 const seats = catalog.client.seats.map((s: any) => ({ seat: s.seat, drawn: drawn.has(s.seat), where: s.where }))
190 const out: Record<string, JsonValue> = {
191 client: state.connected ? { connected: true } : { connected: false, message: NO_CLIENT },
192 seats, trees: slots, referencedTypes: [],
193 }
194 if (input.root !== undefined) {
195 const selected = slots.find((s: any) => s.name === input.root)
196 out.requestedRoot = { name: input.root, available: selected !== undefined }
197 if (selected) out.selected = selected
198 }
199 return out
200 },
201 }
202 }
203
204 function themeProvider(): Provider {
205 return {
206 platform: 'client', id: 'Theme',
207 description: 'What the plugin frame provides for theming.',
208 methods: [method('listTokens', 'Return the named tokens the frame provides (none), the colour schemes, and the theme calls a plugin has.')],
209 run() {
210 return { tokens: catalog.client.theme.tokens, colorSchemes: catalog.client.theme.colorSchemes, scheme: catalog.client.theme.scheme, api: catalog.client.theme.api, notes: catalog.client.theme.notes, referencedTypes: [] }
211 },
212 }
213 }
214
215 export function createCordisInspect(sources: InspectSources = {}): CordisInspect {
216 const providers: Provider[] = [serviceProvider(), eventProvider(), configProvider(sources), toolProvider(sources), slotsProvider(sources), themeProvider()]
217 .filter((p): p is Provider => p !== undefined)
218 for (const provider of providers) {
219 if (provider.id.trim() === '' || provider.description.trim() === '') throw new Error('Cordis inspect provider needs an id and a description')
220 for (const m of provider.methods) {
221 assertSupportedJsonSchema(m.inputSchema)
222 assertSupportedJsonSchema(m.outputSchema)
223 }
224 }
225 const label = (platform: InspectPlatform) => platform === 'host' ? 'Host' : 'Client'
226 return {
227 list() {
228 return providers.map((p) => ({ platform: p.platform, id: p.id, description: p.description, methods: copy(p.methods) }))
229 },
230 async query(platform, providerId, methodName, input, agent, signal = new AbortController().signal) {
231 if (platform !== 'host' && platform !== 'client') throw new Error(`Cordis inspect platform must be "host" or "client", not "${String(platform)}"`)
232 const provider = providers.find((p) => p.platform === platform && p.id === providerId)
233 if (!provider) throw new Error(`${label(platform)} Cordis inspect provider "${providerId}" is not registered`)
234 const found = provider.methods.find((m) => m.name === methodName)
235 if (!found) throw new Error(`Cordis inspect provider "${provider.id}" has no method "${methodName}"`)
236 const violations = validateJsonSchemaValue(found.inputSchema, input ?? {}, 'input') as string[]
237 if (violations.length > 0) throw new Error(`${label(platform)} Cordis inspect ${provider.id}.${found.name} rejected input: ${violations.join('; ')}`)
238 signal.throwIfAborted()
239 const data = await provider.run(methodName, (input ?? {}) as Record<string, JsonValue>, agent, signal)
240 signal.throwIfAborted()
241 if (!isJson(data)) throw new Error(`${label(platform)} Cordis inspect ${provider.id}.${found.name} returned a non-JSON value`)
242 return copy(data)
243 },
244 }
245 }
246
246 lines TYPESCRIPT