返回 CodeWhale
plugin-manager.ts
根目录 / crates / engine / extension-host / src / dsh / plugin-manager.ts
1 import { Service } from '@deepseek-ai/cordis'
2 import { ErrorCode } from '../protocol.ts'
3 import { RpcError } from '../rpc.ts'
4 import type { AdapterHost, DshAdapter } from './adapters.ts'
5
6 interface ChangeResult {
7 changed: boolean
8 application: 'applied' | 'cancelled' | 'overridden' | 'restart-required' | 'failed'
9 stage?: string
10 target?: string
11 error?: { code: string, diagnostic: string, message: string }
12 [key: string]: unknown
13 }
14
15 const EXEMPTIONS_DISABLED = 'Codewhale does not exempt plugins from the host compatibility contract.'
16 const APPLICATIONS = new Set(['applied', 'cancelled', 'overridden', 'restart-required', 'failed'])
17
18 function invalid(what: string): RpcError {
19 return new RpcError(ErrorCode.Internal, `invalid plugins broker ${what}`)
20 }
21
22 function record(value: unknown, what: string): Record<string, unknown> {
23 if (value === null || typeof value !== 'object' || Array.isArray(value)) throw invalid(what)
24 return value as Record<string, unknown>
25 }
26
27 function named(value: unknown, what: string): string {
28 if (typeof value !== 'string' || value.length === 0) {
29 throw new RpcError(ErrorCode.InvalidParams, `${what} must be a non-empty string`)
30 }
31 return value
32 }
33
34 function booleanFlag(value: unknown, what: string): boolean {
35 if (typeof value !== 'boolean') {
36 throw new RpcError(ErrorCode.InvalidParams, `${what} must be a boolean`)
37 }
38 return value
39 }
40
41 function changeResult(value: unknown, what: string): ChangeResult {
42 const row = record(value, what)
43 if (typeof row.changed !== 'boolean' || typeof row.application !== 'string' || !APPLICATIONS.has(row.application)) {
44 throw invalid(what)
45 }
46 return row as ChangeResult
47 }
48
49 function requireCreator(host: AdapterHost, ctx: unknown, service: string): void {
50 if (host.tier !== 'builtin' || host.ownerOf(ctx)?.ref.plugin_id !== 'host:creator') {
51 throw new RpcError(ErrorCode.Refused, `${service} is only available to the built-in creator module`)
52 }
53 if (host.liveInvocation(ctx) === undefined) {
54 throw new RpcError(ErrorCode.Refused, `${service} requires a live tool invocation`)
55 }
56 }
57
58 export const builtinPluginManagerAdapter: DshAdapter = {
59 service: 'pluginManager',
60 define(host) {
61 class BuiltinPluginManagerService extends Service {
62 constructor(ctx: any) {
63 super(ctx, 'pluginManager')
64 }
65
66 async listBundles(): Promise<unknown[]> {
67 requireCreator(host, this.ctx, 'pluginManager')
68 const answer = record(await host.broker(this.ctx, 'plugins', 'list', {}), 'list')
69 if (!Array.isArray(answer.entries)) throw invalid('list')
70 return answer.entries
71 }
72
73 async listPlugins(signal?: AbortSignal): Promise<unknown[]> {
74 requireCreator(host, this.ctx, 'pluginManager')
75 const answer = record(await host.broker(this.ctx, 'plugins', 'status', {}, signal), 'status')
76 if (!Array.isArray(answer.entries)) throw invalid('status')
77 return answer.entries
78 }
79
80 async listTools(signal?: AbortSignal): Promise<string[]> {
81 requireCreator(host, this.ctx, 'pluginManager')
82 const answer = record(await host.broker(this.ctx, 'plugins', 'tools', {}, signal), 'tools')
83 const list = answer.names ?? answer.tools
84 if (!Array.isArray(list)) throw invalid('tools')
85 return list.map((item) => String(item))
86 }
87
88 async setPluginEnabled(target: unknown, enabled: unknown): Promise<ChangeResult> {
89 requireCreator(host, this.ctx, 'pluginManager')
90 const entry = named(target, 'target')
91 const method = booleanFlag(enabled, 'enabled') ? 'enable' : 'disable'
92 return changeResult(await host.broker(this.ctx, 'plugins', method, { target: entry, row: entry }), method)
93 }
94
95 async setBundleEnabled(target: unknown, enabled: unknown): Promise<ChangeResult> {
96 requireCreator(host, this.ctx, 'pluginManager')
97 const bundle = named(target, 'target')
98 const method = booleanFlag(enabled, 'enabled') ? 'enable' : 'disable'
99 return changeResult(await host.broker(this.ctx, 'plugins', method, { target: bundle }), method)
100 }
101
102 async installBundle(
103 target: unknown,
104 options?: { enabled?: unknown, approvedBuilds?: unknown, registry?: unknown } | null,
105 ): Promise<ChangeResult> {
106 requireCreator(host, this.ctx, 'pluginManager')
107 const spec = named(target, 'target')
108 if (options !== undefined && options !== null && (typeof options !== 'object' || Array.isArray(options))) {
109 throw new RpcError(ErrorCode.InvalidParams, 'options must be an object')
110 }
111 const payload: Record<string, unknown> = { target: spec }
112 if (options?.enabled !== undefined) payload.enabled = booleanFlag(options.enabled, 'enabled')
113 if (options?.approvedBuilds !== undefined) {
114 if (!Array.isArray(options.approvedBuilds) || options.approvedBuilds.some((name) => typeof name !== 'string' || name.length === 0)) {
115 throw new RpcError(ErrorCode.InvalidParams, 'approvedBuilds must be an array of non-empty strings')
116 }
117 payload.approved_builds = [...options.approvedBuilds]
118 }
119 if (options?.registry !== undefined && options.registry !== null) {
120 payload.registry = named(options.registry, 'registry')
121 }
122 return changeResult(await host.broker(this.ctx, 'plugins', 'install', payload), 'install')
123 }
124
125 async removeBundle(target: unknown): Promise<ChangeResult> {
126 requireCreator(host, this.ctx, 'pluginManager')
127 const bundle = named(target, 'target')
128 return changeResult(await host.broker(this.ctx, 'plugins', 'remove', { target: bundle }), 'remove')
129 }
130
131 listVersionExemptions(): { exemptions: [], warnings: string[] } {
132 requireCreator(host, this.ctx, 'pluginManager')
133 return { exemptions: [], warnings: [EXEMPTIONS_DISABLED] }
134 }
135
136 async setVersionExemption(
137 target: unknown,
138 runtimeVersion: unknown,
139 enabled: unknown,
140 _acceptRisk?: unknown,
141 ): Promise<ChangeResult> {
142 requireCreator(host, this.ctx, 'pluginManager')
143 named(target, 'target')
144 named(runtimeVersion, 'runtimeVersion')
145 booleanFlag(enabled, 'enabled')
146 return {
147 changed: false,
148 application: 'failed',
149 stage: 'install',
150 target: String(target),
151 error: {
152 code: 'incompatible-version',
153 diagnostic: EXEMPTIONS_DISABLED,
154 message: EXEMPTIONS_DISABLED,
155 },
156 }
157 }
158
159 async cancelInstall(): Promise<{ status: 'not-running' }> {
160 requireCreator(host, this.ctx, 'pluginManager')
161 return { status: 'not-running' }
162 }
163 }
164 Object.freeze(BuiltinPluginManagerService.prototype)
165 return BuiltinPluginManagerService
166 },
167 }
168
169 export const builtinSandboxPolicyAdapter: DshAdapter = {
170 service: 'sandboxPolicy',
171 define(host) {
172 class BuiltinSandboxPolicyService extends Service {
173 constructor(ctx: any) {
174 super(ctx, 'sandboxPolicy')
175 }
176
177 resolve(_query?: unknown): { mode: 'read-only' } {
178 requireCreator(host, this.ctx, 'sandboxPolicy')
179 return { mode: 'read-only' }
180 }
181 }
182 Object.freeze(BuiltinSandboxPolicyService.prototype)
183 return BuiltinSandboxPolicyService
184 },
185 }
186
187 export const builtinApprovalAdapter: DshAdapter = {
188 service: 'approval',
189 define(host) {
190 class BuiltinApprovalService extends Service {
191 constructor(ctx: any) {
192 super(ctx, 'approval')
193 }
194
195 async request(req: unknown): Promise<'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'> {
196 if (host.tier !== 'builtin') return 'unavailable'
197 if (host.ownerOf(this.ctx)?.ref.plugin_id !== 'host:creator') return 'unavailable'
198 const invocation = host.liveInvocation(this.ctx)
199 if (invocation === undefined) return 'unavailable'
200 if (req === null || typeof req !== 'object' || Array.isArray(req)) return 'unavailable'
201 const candidate = req as { agent?: unknown, callId?: unknown, signal?: unknown }
202 const signal = candidate.signal
203 if (signal !== undefined && !(signal instanceof AbortSignal)) return 'unavailable'
204 if (signal?.aborted || invocation.signal.aborted) return 'cancelled'
205 if (invocation.agent === undefined || candidate.agent !== invocation.agent || candidate.callId !== invocation.callId) {
206 return 'unavailable'
207 }
208 try {
209 const answer = record(await host.broker(this.ctx, 'plugins', 'posture', {}, signal), 'posture')
210 const mode = answer.mode
211 if (mode === 'read-only') return 'rejected'
212 if (mode === 'workspace-write' || mode === 'danger-full-access') return 'allowed-once'
213 return 'unavailable'
214 } catch (error) {
215 if (signal?.aborted || invocation.signal.aborted) return 'cancelled'
216 if (error instanceof RpcError && error.code === ErrorCode.Cancelled) return 'cancelled'
217 return 'unavailable'
218 }
219 }
220 }
221 Object.freeze(BuiltinApprovalService.prototype)
222 return BuiltinApprovalService
223 },
224 }
225
226 export const BUILTIN_DSH_ADAPTERS: readonly DshAdapter[] = [
227 builtinPluginManagerAdapter,
228 builtinSandboxPolicyAdapter,
229 builtinApprovalAdapter,
230 ]
231
231 lines TYPESCRIPT