返回 CodeWhale
commands.ts
根目录 / crates / engine / extension-host / src / shims / commands.ts
1 /**
2 * The `commands` service: slash commands a plugin contributes.
3 *
4 * Two audiences share one `register`:
5 *
6 * - **Codewhale plugins** write
7 * `ctx.commands.register({ name, description, argumentHint?, handler })`.
8 * - **DSH plugins** (`@deepseek-ai/dsh-commands`) write
9 * `ctx.commands.register({ name, description, input?: { hint }, handler })`
10 * and return `{ kind: 'success' | 'error', text }`. That surface is
11 * accepted as is.
12 *
13 * `register` returns an idempotent disposer, like `tools.register`; a
14 * registration is an effect of the calling plugin's fiber, so unloading the
15 * plugin removes it. The core admits or refuses each one (`registry/register`
16 * with `kind: 'command'`). A plugin command colliding with a built-in gets a
17 * plugin-specific name; unavailable names are refused with a reason.
18 *
19 * A handler is called only when the *user* runs the command, and it can only
20 * return an answer; it cannot call the model, a tool or approval. Results:
21 *
22 * - a string, or `{ kind: 'success', text? }`: shown to the user;
23 * - `{ kind: 'error', text }`: shown as a failure (a thrown error is too);
24 * - `{ kind: 'submit', prompt, text? }` (Codewhale only): `prompt` becomes the
25 * user's next message and runs through the normal turn, tool approval
26 * included; `text` is shown beside it.
27 *
28 * The invocation carries `args` (what follows the name, trimmed), `rawInput`
29 * (DSH's spelling: the text after the name including its leading separator,
30 * so `' hello'`), `commandId`, `signal` (aborted when the core cancels the
31 * call), an always-empty `attachments`, and the read-only strings `workspace`
32 * (where the user ran the command) and `dataDir` (the plugin's own writable
33 * directory). With an authoritative caller session, `agent` exposes its id
34 * and one text-only followup captured during this command and returned as
35 * Submit after successful completion. It is sealed on settlement or cancel.
36 * No general agent/session service is provided. Not provided: attachments (`input.attachments`
37 * is refused), `recordInput`/`definitionId` (accepted, ignored: Core owns
38 * command receipts), `list`/`find`/`execute`, and `sourceEventSeq`
39 * (accepted in a result, ignored).
40 */
41 import { Service } from '@deepseek-ai/cordis'
42 import type { CommandResultWire } from '../protocol.ts'
43 import { isJson } from '../json.ts'
44 import type { OwnedEntry, OwnerBase } from './owned.ts'
45
46 /** DSH's command grammar. The core enforces the same one. */
47 const COMMAND_NAME = /^[a-z][a-z0-9_-]*$/u
48 const NO_ATTACHMENTS: readonly never[] = Object.freeze([])
49
50 /** A registration, from this host's side. */
51 export interface LocalCommand<O extends OwnerBase = OwnerBase> extends OwnedEntry<O> {
52 definition: NormalizedCommand
53 }
54
55 export interface NormalizedCommand {
56 name: string
57 description: string
58 argumentHint?: string
59 handler: (invocation: CommandInvocation) => unknown
60 }
61
62 export interface CommandInvocation {
63 readonly commandId: string
64 /** What follows the command name, trimmed. */
65 readonly args: string
66 /** DSH spelling: what follows the name, with its leading separator. */
67 readonly rawInput: string
68 readonly attachments: readonly never[]
69 readonly signal: AbortSignal
70 /** The workspace the user ran the command in (absent if the core did not say). */
71 readonly workspace?: string
72 /** This plugin's own writable directory. */
73 readonly dataDir?: string
74 readonly sessionId?: string
75 readonly agentId?: string
76 readonly originTurnId?: string
77 readonly agent: Readonly<{
78 id: string
79 session: Readonly<{ id: string; header: Readonly<{ id: string; cwd?: string }> }>
80 followup(message: unknown): void
81 }>
82 }
83
84 /** Reject an invalid definition before it reaches the core, with a message that names the problem. */
85 export function normalizeCommand(definition: any): NormalizedCommand {
86 if (!definition || typeof definition !== 'object') throw new TypeError('command definition must be an object')
87 const { name } = definition
88 if (typeof name !== 'string' || !COMMAND_NAME.test(name)) {
89 throw new TypeError(`command name ${JSON.stringify(name)} must match ${String(COMMAND_NAME)}`)
90 }
91 if (typeof definition.description !== 'string' || definition.description.trim().length === 0) {
92 throw new TypeError(`command "${name}" needs a non-empty description`)
93 }
94 if (typeof definition.handler !== 'function') throw new TypeError(`command "${name}" handler must be a function`)
95 let hint: unknown = definition.argumentHint
96 const input: unknown = definition.input
97 if (input !== undefined) {
98 if (typeof input !== 'object' || input === null || typeof (input as any).hint !== 'string') {
99 throw new TypeError(`command "${name}" input hint must be a string`)
100 }
101 if ((input as any).attachments === true) {
102 throw new TypeError(`command "${name}": attachments are not supported by the Codewhale plugin host`)
103 }
104 hint ??= (input as any).hint
105 }
106 if (hint !== undefined && (typeof hint !== 'string' || hint.trim().length === 0)) {
107 throw new TypeError(`command "${name}" argument hint must be a non-empty string`)
108 }
109 return {
110 name,
111 description: definition.description,
112 ...(hint === undefined ? {} : { argumentHint: hint as string }),
113 handler: definition.handler,
114 }
115 }
116
117 /** What `registry/register` carries for a command. */
118 export function commandSpec(command: NormalizedCommand) {
119 return {
120 name: command.name,
121 description: command.description,
122 ...(command.argumentHint === undefined ? {} : { argument_hint: command.argumentHint }),
123 }
124 }
125
126 export function makeInvocation(
127 command: string,
128 args: string,
129 commandId: string,
130 signal: AbortSignal,
131 context: { workspace?: string; dataDir?: string; sessionId?: string; agentId?: string; originTurnId?: string } = {},
132 ) {
133 let open = !signal.aborted
134 let prompt: string | undefined
135 let failure: Error | undefined
136 const close = () => {
137 open = false
138 prompt = undefined
139 signal.removeEventListener('abort', close)
140 }
141 signal.addEventListener('abort', close, { once: true })
142 const reject: (reason: string) => never = (reason) => {
143 failure ??= new TypeError(`command "${command}" followup ${reason}`)
144 throw failure
145 }
146 const agent = context.sessionId?.trim() ? Object.freeze({
147 id: context.agentId ?? context.sessionId,
148 session: Object.freeze({
149 id: context.sessionId,
150 header: Object.freeze({
151 id: context.sessionId,
152 ...(context.workspace === undefined ? {} : { cwd: context.workspace }),
153 }),
154 }),
155 followup(message: unknown) {
156 if (!open || signal.aborted) reject('is unavailable after command settlement or cancellation')
157 if (failure) throw failure
158 if (prompt !== undefined) reject('accepts exactly one message per invocation')
159 if (!isJson(message) || message === null || Array.isArray(message) || typeof message !== 'object') {
160 reject('requires a lossless JSON user message')
161 }
162 if (Object.keys(message).some(key => !['id', 'role', 'content', 'source'].includes(key))
163 || typeof message.id !== 'string' || message.id.trim() === '' || message.id.length > 256
164 || message.role !== 'user') reject('requires only id, user role, content and source fields')
165 const source = message.source
166 if (!source || Array.isArray(source) || typeof source !== 'object'
167 || Object.keys(source).some(key => key !== 'kind') || typeof source.kind !== 'string'
168 || source.kind.trim() === '' || source.kind.length > 128) reject('requires a source with one bounded kind')
169 const content = message.content
170 if (!Array.isArray(content) || content.length !== 1) reject('requires exactly one text block')
171 const block = content[0]
172 if (!block || Array.isArray(block) || typeof block !== 'object'
173 || Object.keys(block).some(key => key !== 'type' && key !== 'text')
174 || block.type !== 'text' || typeof block.text !== 'string') reject('requires exactly one plain text block')
175 if (block.text.trim() === '' || Buffer.byteLength(block.text, 'utf8') > 128 * 1024) reject('text must be non-empty and at most 128 KiB')
176 prompt = block.text
177 },
178 }) : undefined
179 const invocation = Object.freeze(Object.defineProperty({
180 commandId,
181 args,
182 rawInput: args === '' ? '' : ` ${args}`,
183 attachments: NO_ATTACHMENTS,
184 signal,
185 ...context,
186 }, 'agent', { get() {
187 if (!agent) reject('requires an authoritative caller session')
188 return agent
189 } })) as CommandInvocation
190 return {
191 invocation,
192 close,
193 complete(value: unknown): CommandResultWire {
194 if (!open || signal.aborted) reject('is unavailable after command settlement or cancellation')
195 if (failure) throw failure
196 const result = normalizeResult(command, value)
197 if (prompt === undefined || result.kind === 'error') return result
198 if (result.kind === 'submit') reject('conflicts with an explicit Submit result')
199 return { kind: 'submit', prompt, ...(result.text === undefined ? {} : { text: result.text }) }
200 },
201 }
202 }
203
204 /** Validate and detach whatever a handler returned. */
205 export function normalizeResult(command: string, value: unknown): CommandResultWire {
206 if (value === undefined || value === null) return { kind: 'success' }
207 if (typeof value === 'string') return { kind: 'success', text: value }
208 if (typeof value !== 'object') throw new TypeError(`command "${command}" handler must return a result object or a string`)
209 const result = value as { kind?: unknown; text?: unknown; prompt?: unknown }
210 const text = result.text
211 if (text !== undefined && typeof text !== 'string') {
212 throw new TypeError(`command "${command}" result text must be a string when supplied`)
213 }
214 switch (result.kind) {
215 case 'success':
216 return text === undefined ? { kind: 'success' } : { kind: 'success', text }
217 case 'error':
218 if (typeof text !== 'string' || text.trim().length === 0) {
219 throw new TypeError(`command "${command}" error text must be a non-empty string`)
220 }
221 return { kind: 'error', text }
222 case 'submit':
223 if (typeof result.prompt !== 'string' || result.prompt.trim().length === 0) {
224 throw new TypeError(`command "${command}" submit prompt must be a non-empty string`)
225 }
226 return text === undefined ? { kind: 'submit', prompt: result.prompt } : { kind: 'submit', prompt: result.prompt, text }
227 default:
228 throw new TypeError(`command "${command}" returned unknown result kind ${JSON.stringify(result.kind)}`)
229 }
230 }
231
232 /** The host's side of the shim: how a `register` call becomes a core registration. */
233 export interface CommandsHost<O extends OwnerBase> {
234 ownerOf(ctx: any): O | undefined
235 addCommand(owner: O, command: NormalizedCommand): () => void
236 }
237
238 /**
239 * Build the `commands` service class for `host`. The class is frozen so one
240 * plugin cannot rewrite `register` for the others (the owner token is not a
241 * boundary between plugins that share the process; design §4.4).
242 */
243 export function defineCommandsService<O extends OwnerBase>(host: CommandsHost<O>) {
244 class CommandsShim extends Service {
245 constructor(ctx: any) {
246 super(ctx, 'commands')
247 }
248
249 /** `ctx.commands.register(definition)`: returns an idempotent disposer. */
250 register(definition: unknown): () => void {
251 const ctx: any = this.ctx
252 const owner = host.ownerOf(ctx)
253 if (!owner) throw new Error('commands.register called outside a plugin owner')
254 const command = normalizeCommand(definition)
255 return ctx.effect(() => host.addCommand(owner, command), `commands.register(${JSON.stringify(command.name)})`)
256 }
257 }
258 Object.freeze(CommandsShim.prototype)
259 return CommandsShim
260 }
261
261 lines TYPESCRIPT