返回 CodeWhale
catalog.ts
根目录 / crates / engine / extension-host / src / dsh / catalog.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 export interface ApprovedRoute {
7 provider: string
8 base_url: string
9 default_model: string | null
10 models: string[]
11 }
12
13 export interface ResolvedRoute extends ApprovedRoute {
14 model: string | null
15 }
16
17 export interface InstallPlan {
18 status: 'review_required' | 'already_present'
19 package: string
20 version: string
21 plugin: string
22 spec?: string
23 command: string
24 message: string
25 }
26
27 export type BalanceAnswer =
28 | { status: 'known', currency: string, total: string, topped_up: string, granted: string }
29 | { status: 'unknown' }
30 | { status: 'absent' }
31
32 interface AccountWallet {
33 currency: string
34 balance: string
35 }
36
37 type AccountBalance = { status: 'ready', value: AccountWallet[], bonusWallets: AccountWallet[] } | { status: 'failed' }
38
39 interface ChangeResult {
40 changed: false
41 application: 'failed'
42 stage: 'install' | 'remove'
43 target: string
44 error: { code: string, diagnostic: string, message: string }
45 }
46
47 const EXACT_VERSION_ONLY = 'Codewhale plans a plugin install only for one exact npm version, written name@1.2.3'
48 const REMOVE_IN_CODEWHALE = 'Codewhale removes a plugin only from its own plugin manager, after you disable it: /plugin uninstall'
49 const WITHHELD_ACCOUNT_METHODS = [
50 'getState', 'getProfile', 'getUnnotifiedBonuses', 'ackBonusNotified', 'startSignIn', 'cancelSignIn', 'signOut', 'watch',
51 'resolveToken', 'rejectToken', 'getPlatformSession', 'getDeviceIdentity',
52 'getNotifications', 'getNotificationContent', 'reportNotificationEvent', 'resolveRequestCredential',
53 'registerRunningTaskReport', 'hasRunningAccountTasks',
54 ] as const
55
56 function invalid(what: string): RpcError {
57 return new RpcError(ErrorCode.Internal, `invalid catalog broker ${what}`)
58 }
59
60 function record(value: unknown, what: string): Record<string, unknown> {
61 if (value === null || typeof value !== 'object' || Array.isArray(value)) throw invalid(what)
62 return value as Record<string, unknown>
63 }
64
65 function text(value: unknown, what: string): string {
66 if (typeof value !== 'string' || value.length === 0) throw invalid(what)
67 return value
68 }
69
70 function named(value: unknown, what: string): string {
71 if (typeof value !== 'string' || value.length === 0) throw new RpcError(ErrorCode.InvalidParams, `${what} is a non-empty string`)
72 return value
73 }
74
75 function approvedRoute(value: unknown): ApprovedRoute {
76 const row = record(value, 'route')
77 const models = row.models
78 const defaultModel = row.default_model
79 if (!Array.isArray(models) || models.some((model) => typeof model !== 'string') || (defaultModel !== null && typeof defaultModel !== 'string')) throw invalid('route')
80 return { provider: text(row.provider, 'route'), base_url: text(row.base_url, 'route'), default_model: defaultModel, models: [...models] }
81 }
82
83 export async function approvedRoutes(host: AdapterHost, ctx: unknown): Promise<ApprovedRoute[]> {
84 const routes = record(await host.broker(ctx, 'catalog', 'routes.list', {}), 'routes').routes
85 if (!Array.isArray(routes)) throw invalid('routes')
86 return routes.map(approvedRoute)
87 }
88
89 export async function resolveRoute(host: AdapterHost, ctx: unknown, provider: unknown, model?: unknown): Promise<ResolvedRoute> {
90 const input = model === undefined || model === null
91 ? { provider: named(provider, 'a provider route') }
92 : { provider: named(provider, 'a provider route'), model: named(model, 'a model') }
93 const answer = record(await host.broker(ctx, 'catalog', 'routes.resolve', input), 'route')
94 const resolved = answer.model
95 if (resolved !== null && typeof resolved !== 'string') throw invalid('route')
96 return { ...approvedRoute(answer.route), model: resolved }
97 }
98
99 export async function accountBalance(host: AdapterHost, ctx: unknown): Promise<BalanceAnswer> {
100 const answer = record(await host.broker(ctx, 'catalog', 'balance', {}), 'balance')
101 const status = answer.status
102 if (status === 'unknown' || status === 'absent') return { status }
103 const toppedUp = answer.topped_up
104 const granted = answer.granted
105 if (status !== 'known' || typeof toppedUp !== 'string' || typeof granted !== 'string') throw invalid('balance')
106 return { status, currency: text(answer.currency, 'balance'), total: text(answer.total, 'balance'), topped_up: toppedUp, granted }
107 }
108
109 export async function planInstall(host: AdapterHost, ctx: unknown, spec: unknown, registry?: unknown): Promise<InstallPlan> {
110 const exact = typeof spec === 'string' ? spec.lastIndexOf('@') : -1
111 if (typeof spec !== 'string' || exact <= 0 || exact === spec.length - 1) throw new RpcError(ErrorCode.InvalidParams, EXACT_VERSION_ONLY)
112 const request = { package: spec.slice(0, exact), version: spec.slice(exact + 1) }
113 const input = registry === undefined || registry === null ? request : { ...request, registry: named(registry, 'a registry URL') }
114 const plan = record(await host.broker(ctx, 'catalog', 'install.plan', input), 'install plan')
115 const status = plan.status
116 const planned = plan.spec
117 if ((status !== 'review_required' && status !== 'already_present') || (planned !== undefined && typeof planned !== 'string')) throw invalid('install plan')
118 return {
119 status,
120 package: text(plan.package, 'install plan'),
121 version: text(plan.version, 'install plan'),
122 plugin: text(plan.plugin, 'install plan'),
123 ...(planned === undefined ? {} : { spec: planned }),
124 command: text(plan.command, 'install plan'),
125 message: text(plan.message, 'install plan'),
126 }
127 }
128
129 function notChanged(stage: ChangeResult['stage'], target: unknown, code: string, diagnostic: string): ChangeResult {
130 return { changed: false, application: 'failed', stage, target: typeof target === 'string' ? target : '', error: { code, diagnostic, message: diagnostic } }
131 }
132
133 function declined(error: unknown): string | undefined {
134 if (!(error instanceof Error)) return undefined
135 if (error instanceof RpcError && error.code === ErrorCode.InvalidParams && error.data === undefined) return error.message
136 const refusal = (error as { data?: { dsh_refusal?: unknown } }).data?.dsh_refusal
137 return refusal === 'refused' || refusal === 'invalid_input' ? error.message : undefined
138 }
139
140 export const pluginManagerAdapter: DshAdapter = {
141 service: 'pluginManager',
142 define(host) {
143 class PluginManagerService extends Service {
144 constructor(ctx: any) { super(ctx, 'pluginManager') }
145
146 async installBundle(spec: unknown, options?: { registry?: unknown } | null): Promise<ChangeResult> {
147 try {
148 const plan = await planInstall(host, this.ctx, spec, options?.registry)
149 return notChanged('install', spec, plan.status === 'already_present' ? 'already-installed' : 'management-required', plan.message)
150 } catch (error) {
151 const diagnostic = declined(error)
152 if (diagnostic === undefined) throw error
153 return notChanged('install', spec, 'invalid-spec', diagnostic)
154 }
155 }
156
157 async removeBundle(target: unknown): Promise<ChangeResult> {
158 return notChanged('remove', target, 'management-required', REMOVE_IN_CODEWHALE)
159 }
160
161 async cancelInstall(): Promise<{ status: 'not-running' }> {
162 return { status: 'not-running' }
163 }
164 }
165 Object.freeze(PluginManagerService.prototype)
166 return PluginManagerService
167 },
168 }
169
170 export const deepseekAccountAdapter: DshAdapter = {
171 service: 'deepseekAccount',
172 define(host) {
173 class DeepSeekAccountService extends Service {
174 constructor(ctx: any) { super(ctx, 'deepseekAccount') }
175
176 async getBalance(): Promise<AccountBalance | null> {
177 const answer = await accountBalance(host, this.ctx)
178 if (answer.status === 'absent') return null
179 if (answer.status === 'unknown') return { status: 'failed' }
180 const { currency, total, topped_up: toppedUp, granted } = answer
181 const wallet = (balance: string): AccountWallet[] => balance.length > 0 ? [{ currency, balance }] : []
182 return { status: 'ready', value: wallet(toppedUp.length > 0 ? toppedUp : total), bonusWallets: wallet(granted) }
183 }
184 }
185 for (const method of WITHHELD_ACCOUNT_METHODS) {
186 Object.defineProperty(DeepSeekAccountService.prototype, method, {
187 value() {
188 throw new RpcError(ErrorCode.NotAvailable, `deepseekAccount.${method} is not provided: Codewhale answers a read-only balance and never gives a plugin an account credential or a sign-in`)
189 },
190 })
191 }
192 Object.freeze(DeepSeekAccountService.prototype)
193 return DeepSeekAccountService
194 },
195 }
196
196 lines TYPESCRIPT