返回 CodeWhale
agents.ts
根目录 / crates / engine / extension-host / src / dsh / agents.ts
1 import { Service } from '@deepseek-ai/cordis'
2 import { ErrorCode } from '../protocol.ts'
3 import { RpcError } from '../rpc.ts'
4 import { PERSONA_PREFIX_SECTION } from './dsh-message-compat.js'
5 import type { AdapterHost, DshAdapter } from './adapters.ts'
6
7 export const HOST_PROMPT_QUEUE = Symbol.for('dsh.subagent.queuePrompt')
8 export const HOST_PROMPT_DELIVER = Symbol.for('dsh.subagent.deliverPrompt')
9
10 const SPAWN_PROVIDER = Object.freeze({
11 name: 'spawn',
12 inheritsParentContext: false,
13 capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true, depthLimit: true }),
14 })
15 const FORK_PROVIDER = Object.freeze({
16 name: 'fork',
17 inheritsParentContext: true,
18 capabilities: Object.freeze({ persona: true, toolFilter: true, agentOptions: true, depthLimit: true }),
19 })
20 const PERSONA_ORDER = 0
21
22 function plain(value: unknown, allowed: string[], what: string): Record<string, unknown> {
23 if (value === null || typeof value !== 'object' || Array.isArray(value)
24 || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, `expected a plain ${what} object`)
25 const result: Record<string, unknown> = Object.create(null)
26 for (const key of Reflect.ownKeys(value)) {
27 const descriptor = Object.getOwnPropertyDescriptor(value, key)!
28 if (typeof key !== 'string' || !allowed.includes(key) || !('value' in descriptor)) throw new RpcError(ErrorCode.NotAvailable, `unsupported ${what} property ${String(key)}`)
29 if (descriptor.value !== undefined) result[key] = descriptor.value
30 }
31 return result
32 }
33
34 function promptText(content: unknown): string {
35 if (typeof content === 'string') {
36 if (content.trim().length === 0) throw new RpcError(ErrorCode.InvalidParams, 'prompt must be non-empty text')
37 return content
38 }
39 if (!Array.isArray(content) || content.length === 0) throw new RpcError(ErrorCode.InvalidParams, 'prompt must be a non-empty content array')
40 return content.map((block: unknown) => {
41 const item = plain(block, ['type', 'text'], 'prompt block')
42 if (item.type !== 'text' || typeof item.text !== 'string') throw new RpcError(ErrorCode.NotAvailable, 'only text prompt blocks are supported')
43 return item.text
44 }).join('')
45 }
46
47 function checkChildId(childId: unknown): string {
48 if (typeof childId !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(childId)) {
49 throw new RpcError(ErrorCode.InvalidParams, 'childId must be 1-128 letters, digits, or _.:-')
50 }
51 return childId
52 }
53
54 async function deliverSubagentPrompt(
55 host: AdapterHost,
56 ctx: unknown,
57 parent: unknown,
58 childId: unknown,
59 content: unknown,
60 mode: 'queue' | 'steer' | 'followup' | 'message',
61 signal?: unknown,
62 ): Promise<string> {
63 const owner = host.ownerOf(ctx)
64 const id = checkChildId(childId)
65 const prompt = promptText(content)
66 if (signal !== undefined && !(signal instanceof AbortSignal)) {
67 throw new RpcError(ErrorCode.InvalidParams, 'signal must be an AbortSignal')
68 }
69 const invocation = host.liveInvocation(ctx)
70 if (!invocation || invocation.agent === undefined || (parent !== undefined && parent !== invocation.agent)) {
71 throw new RpcError(ErrorCode.NotAvailable, 'subagent delivery requires the exact live calling agent as parent')
72 }
73 if (invocation.owner !== owner) throw new RpcError(ErrorCode.NotAvailable, 'subagents service owner is no longer current')
74 if (invocation.delegated || invocation.subagentTicket === undefined) {
75 throw new RpcError(ErrorCode.NotAvailable, 'child delivery is only available to a root tool invocation')
76 }
77 const combined = signal === undefined ? invocation.signal : AbortSignal.any([invocation.signal, signal])
78 combined.throwIfAborted()
79 const receipt = await host.rpc.request<any>('subagent/prompt', {
80 owner: invocation.owner.ref,
81 ticket: invocation.subagentTicket,
82 child_id: id,
83 prompt,
84 mode,
85 }, combined)
86 if (receipt === null || typeof receipt !== 'object' || typeof receipt.message_id !== 'string') {
87 throw new RpcError(ErrorCode.Internal, 'invalid subagent prompt receipt')
88 }
89 return receipt.message_id
90 }
91
92 export function createBundledSubagentsView(host: AdapterHost, base: any, ctx: any): Record<PropertyKey, unknown> {
93 return {
94 getProvider(name: unknown) {
95 return base.getProvider(name)
96 },
97 listProviders() {
98 return base.listProviders()
99 },
100 startActivation(request: any) {
101 return base.startActivation.call({ ctx }, request)
102 },
103 async followup(parent: unknown, childId: unknown, content: unknown, options?: { signal?: AbortSignal }) {
104 return deliverSubagentPrompt(host, ctx, parent, childId, content, 'followup', options?.signal)
105 },
106 async sendMessage(sender: unknown, targetId: unknown, content: unknown, options?: { signal?: AbortSignal }) {
107 return deliverSubagentPrompt(host, ctx, sender, targetId, content, 'message', options?.signal)
108 },
109 async [HOST_PROMPT_QUEUE](parent: unknown, childId: unknown, content: unknown, _source: unknown, signal?: AbortSignal) {
110 return deliverSubagentPrompt(host, ctx, parent, childId, content, 'queue', signal)
111 },
112 async [HOST_PROMPT_DELIVER](parent: unknown, childId: unknown, content: unknown, _source: unknown, signal?: AbortSignal, delivery?: unknown) {
113 const mode = delivery === 'steer' ? 'steer' : 'queue'
114 return deliverSubagentPrompt(host, ctx, parent, childId, content, mode, signal)
115 },
116 registerContinuableSetup(setup: (childCtx: any) => () => void) {
117 const owner = host.ownerOf(ctx)
118 if (!owner) throw new RpcError(ErrorCode.NotAvailable, 'registerContinuableSetup requires an active plugin owner')
119 return ctx.on('agent/created', (payload: any) => {
120 const agent = payload?.agent
121 if (!agent?.ctx) return undefined
122 const childCtx = Object.create(agent.ctx, {
123 agent: { value: agent, enumerable: true },
124 })
125 return setup(childCtx)
126 })
127 },
128 async drainChildren(parent: unknown, ids: unknown) {
129 const owner = host.ownerOf(ctx)
130 const invocation = host.liveInvocation(ctx)
131 if (!invocation || invocation.agent === undefined || (parent !== undefined && parent !== invocation.agent)) {
132 throw new RpcError(ErrorCode.NotAvailable, 'drainChildren requires the exact live calling agent as parent')
133 }
134 if (invocation.owner !== owner) throw new RpcError(ErrorCode.NotAvailable, 'subagents service owner is no longer current')
135 if (invocation.delegated || invocation.subagentTicket === undefined) {
136 throw new RpcError(ErrorCode.NotAvailable, 'drainChildren is only available to a root tool invocation')
137 }
138 if (!Array.isArray(ids)) throw new RpcError(ErrorCode.InvalidParams, 'ids must be an array')
139 for (const rawId of ids) {
140 const childId = checkChildId(rawId)
141 await host.rpc.request('subagent/dispose', {
142 owner: invocation.owner.ref,
143 ticket: invocation.subagentTicket,
144 child_id: childId,
145 }, invocation.signal)
146 }
147 },
148 drainContinuableChildren(this: any, parent: unknown, ids: unknown) {
149 return this.drainChildren(parent, ids)
150 },
151 }
152 }
153
154 function defineSubagents(host: AdapterHost): new (ctx: any) => Service {
155 class SubagentsShim extends Service {
156 constructor(ctx: any) { super(ctx, 'subagents') }
157 getProvider(name: unknown) {
158 if (name === 'spawn') return SPAWN_PROVIDER
159 if (name === 'fork') return FORK_PROVIDER
160 return undefined
161 }
162 listProviders() { return Object.freeze(['spawn', 'fork']) }
163 async startActivation(request: any) {
164 const owner = host.ownerOf(this.ctx)
165 const input = plain(request, ['provider', 'label', 'childId', 'request', 'signal', 'delivery'], 'activation')
166 if (input.provider !== 'spawn' && input.provider !== 'fork') throw new RpcError(ErrorCode.NotAvailable, 'only the spawn and fork providers are available')
167 const spawn = plain(input.request, ['parent', 'prompt', 'agentOptions'], 'spawn request')
168 const options = spawn.agentOptions === undefined ? {} : plain(spawn.agentOptions, ['model'], 'agentOptions')
169 if (options.model !== undefined && typeof options.model !== 'string') throw new RpcError(ErrorCode.InvalidParams, 'agentOptions.model must be a string')
170 const delivery = input.delivery === undefined ? 'parent' : input.delivery
171 if (delivery !== 'caller' && delivery !== 'parent') throw new RpcError(ErrorCode.InvalidParams, 'delivery must be caller or parent')
172 const childId = checkChildId(input.childId)
173 const prompt = promptText(spawn.prompt)
174 if (input.signal !== undefined && !(input.signal instanceof AbortSignal)) throw new RpcError(ErrorCode.InvalidParams, 'signal must be an AbortSignal')
175 const invocation = host.liveInvocation(this.ctx)
176 if (!invocation || invocation.agent === undefined || spawn.parent !== invocation.agent) {
177 throw new RpcError(ErrorCode.NotAvailable, 'startActivation requires the exact live calling agent as parent')
178 }
179 if (invocation.owner !== owner) throw new RpcError(ErrorCode.NotAvailable, 'subagents service owner is no longer current')
180 if (invocation.delegated || invocation.subagentTicket === undefined) throw new RpcError(ErrorCode.NotAvailable, 'child agents are only available to a root tool invocation')
181 const signal = input.signal === undefined ? invocation.signal : AbortSignal.any([invocation.signal, input.signal as AbortSignal])
182 signal.throwIfAborted()
183 let persona: string | undefined
184 const denied = new Set<string>()
185 let open = true
186 const sealed = () => { if (!open) throw new RpcError(ErrorCode.NotAvailable, 'the child creation window has closed') }
187 const child = Object.freeze({
188 id: childId,
189 ctx: Object.freeze({
190 systemPrompt: Object.freeze({
191 getSectionOrder(name: unknown) {
192 sealed()
193 if (name !== 'DEPLOYMENT_PERSONA_PREFIX') throw new RpcError(ErrorCode.NotAvailable, 'only the deployment persona slot is available')
194 return PERSONA_ORDER
195 },
196 section(section: unknown) {
197 sealed()
198 const value = plain(section, ['name', 'order', 'text'], 'system prompt section')
199 if (value.name !== PERSONA_PREFIX_SECTION || value.order !== PERSONA_ORDER || typeof value.text !== 'string') {
200 throw new RpcError(ErrorCode.NotAvailable, 'only the child deployment persona section is supported')
201 }
202 if (persona !== undefined) throw new RpcError(ErrorCode.InvalidParams, 'the child persona is already set')
203 if (Buffer.byteLength(value.text) > 32 * 1024) throw new RpcError(ErrorCode.InvalidParams, 'child persona exceeds 32768 bytes')
204 persona = value.text
205 return () => undefined
206 },
207 }),
208 tools: Object.freeze({
209 restrict(filter: unknown) {
210 sealed()
211 const value = plain(filter, ['deny'], 'tool filter')
212 if (!Array.isArray(value.deny) || value.deny.some(name => typeof name !== 'string' || name === '')) throw new RpcError(ErrorCode.InvalidParams, 'deny must be a list of tool names')
213 for (const name of value.deny as string[]) denied.add(name)
214 return () => undefined
215 },
216 guard() {
217 sealed()
218 throw new RpcError(ErrorCode.NotAvailable, 'child tools.guard is not supported; use child.ctx.tools.restrict({ deny }) or root ctx.tools.guard')
219 },
220 }),
221 }),
222 })
223 const listeners = (((this.ctx as any).root?.events?._hooks?.['agent/created']) ?? [])
224 .filter((hook: any) => !hook.global && hook.ctx !== undefined && host.ownerOf(hook.ctx) === owner)
225 .map((hook: any) => hook.callback)
226 try {
227 await Promise.all(listeners.map(async (callback: Function) => callback({ agent: child })))
228 } finally {
229 open = false
230 }
231 signal.throwIfAborted()
232 const call = invocation
233 const rpc = (method: string, params: Record<string, unknown>, abort: AbortSignal) =>
234 host.rpc.request<any>(method, { owner: call.owner.ref, ticket: call.subagentTicket, child_id: childId, ...params }, abort)
235 const started = await rpc('subagent/start', {
236 prompt,
237 ...(options.model === undefined ? {} : { model: options.model }),
238 ...(persona === undefined ? {} : { persona }),
239 denied_tools: [...denied],
240 delivery,
241 }, signal)
242 if (started === null || typeof started !== 'object' || started.child_id !== childId || typeof started.message_id !== 'string') {
243 throw new RpcError(ErrorCode.Internal, 'invalid child activation receipt')
244 }
245 let result: Promise<unknown> | undefined
246 let disposed: Promise<void> | undefined
247 return Object.freeze({
248 childId,
249 messageId: started.message_id,
250 get result() {
251 result ??= rpc('subagent/result', {}, call.signal).then((value: any) => {
252 if (value === null || typeof value !== 'object' || typeof value.stop_reason !== 'string' || !Array.isArray(value.output)) {
253 throw new RpcError(ErrorCode.Internal, 'invalid child result receipt')
254 }
255 return Object.freeze({
256 stopReason: value.stop_reason,
257 output: Object.freeze(value.output.map((block: any) => Object.freeze({ type: 'text', text: String(block.text) }))),
258 ...(value.omitted_blocks > 0 ? { diagnostic: `${value.omitted_blocks} non-text output block(s) are not supported` } : {}),
259 })
260 })
261 return result
262 },
263 dispose() {
264 disposed ??= rpc('subagent/dispose', {}, call.signal).then(() => undefined)
265 return disposed
266 },
267 })
268 }
269 }
270 Object.freeze(SubagentsShim.prototype)
271 return SubagentsShim
272 }
273
274 function defineAgents(host: AdapterHost): new (ctx: any) => Service {
275 class AgentsShim extends Service {
276 constructor(ctx: any) { super(ctx, 'agents') }
277 list() {
278 const invocation = host.liveInvocation(this.ctx)
279 return invocation?.agent ? [invocation.agent] : []
280 }
281 get(id: unknown) {
282 const invocation = host.liveInvocation(this.ctx)
283 if (typeof id === 'string' && invocation?.agent && (invocation.agent as any).id === id) {
284 return invocation.agent
285 }
286 return undefined
287 }
288 }
289 Object.freeze(AgentsShim.prototype)
290 return AgentsShim
291 }
292
293 export const DSH_AGENT_ADAPTERS: readonly DshAdapter[] = Object.freeze([
294 { service: 'subagents', define: defineSubagents },
295 { service: 'agents', define: defineAgents },
296 ])
297
297 lines TYPESCRIPT