File size: 7,586 Bytes
68d7816 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | import { homedir } from 'node:os';
import { KIMI_CODE_PROVIDER_NAME, resolveKimiRegion } from '@moonshot-ai/kimi-code-oauth';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { Disposable } from '#/_base/di/lifecycle';
import { Emitter, type Event } from '#/_base/event';
import { ILogService } from '#/_base/log/log';
import { Error2 } from '#/errors';
import { IBootstrapService } from '#/app/bootstrap/bootstrap';
import { IPluginService } from '#/app/plugin/plugin';
import { IProviderService } from '#/llm-adapter/provider/provider';
import { IHostProcessService } from '#/os/interface/hostProcess';
import { ICapabilityService } from './capability';
import { CapabilityErrors } from './errors';
import { createKimiCuEntry } from './entries/kimiCu';
import { createKimiWebbridgeEntry } from './entries/kimiWebbridge';
import type {
CapabilityEntry,
CapabilityId,
CapabilityDescriptor,
CapabilityInstallChange,
CapabilityInstallProgress,
CapabilityReadiness,
CapabilityStatus,
} from './types';
const IDLE_PROGRESS: CapabilityInstallProgress = { running: false };
export class CapabilityService extends Disposable implements ICapabilityService {
declare readonly _serviceBrand: undefined;
private readonly onDidChangeInstallEmitter = this._register(
new Emitter<CapabilityInstallChange>(),
);
readonly onDidChangeInstall: Event<CapabilityInstallChange> =
this.onDidChangeInstallEmitter.event;
private readonly entries: ReadonlyMap<CapabilityId, CapabilityEntry>;
private readonly installProgress = new Map<CapabilityId, CapabilityInstallProgress>();
private readonly runningInstalls = new Set<CapabilityId>();
private setInstallProgress(id: CapabilityId, progress: CapabilityInstallProgress): void {
this.installProgress.set(id, progress);
this.onDidChangeInstallEmitter.fire({ id, install: progress });
}
constructor(
@IBootstrapService bootstrap: IBootstrapService,
@IPluginService plugins: IPluginService,
@IHostProcessService hostProcess: IHostProcessService,
@ILogService private readonly log: ILogService,
@IProviderService providers: IProviderService,
entriesOverride?: readonly CapabilityEntry[],
) {
super();
if (entriesOverride !== undefined) {
this.entries = new Map(entriesOverride.map((entry) => [entry.id, entry]));
} else {
const ctx = {
platform: process.platform,
arch: process.arch,
kimiHomeDir: bootstrap.homeDir,
userHomeDir: homedir(),
plugins,
hostProcess,
resolveRegion: () => {
const oauth = providers.get(KIMI_CODE_PROVIDER_NAME)?.oauth;
return resolveKimiRegion({
configuredOAuthHost: oauth?.oauthHost,
configuredOAuthKey: oauth?.key,
readMarker:
(bootstrap.getEnv('KIMI_CODE_REGION_MARKER') ??
process.env['KIMI_CODE_REGION_MARKER']) !== 'off',
homeDir: bootstrap.homeDir,
});
},
};
this.entries = new Map<CapabilityId, CapabilityEntry>([
['kimi-cu', createKimiCuEntry(ctx)],
['kimi-webbridge', createKimiWebbridgeEntry(ctx)],
]);
}
}
describeCapabilities(): readonly CapabilityDescriptor[] {
return [...this.entries.values()].map((entry) => ({
id: entry.id,
pluginId: entry.pluginId,
displayName: entry.displayName,
description: entry.description,
supported: entry.supported,
}));
}
listCapabilities(): Promise<readonly CapabilityStatus[]> {
return Promise.all([...this.entries.values()].map((entry) => this.statusOfSafe(entry)));
}
async getCapability(id: string): Promise<CapabilityStatus> {
return this.statusOf(this.requireEntry(id));
}
async installCapability(id: string): Promise<CapabilityStatus> {
const entry = this.requireEntry(id);
if (!entry.supported) {
throw new Error2(
CapabilityErrors.codes.CAPABILITY_UNSUPPORTED,
`Capability "${entry.id}" is not supported on ${process.platform}/${process.arch}`,
{ details: { id: entry.id } },
);
}
if (this.runningInstalls.has(entry.id)) {
throw new Error2(
CapabilityErrors.codes.CAPABILITY_INSTALL_IN_PROGRESS,
`Capability "${entry.id}" is already being installed`,
{ details: { id: entry.id } });
}
this.runningInstalls.add(entry.id);
this.setInstallProgress(entry.id, { running: true });
void (async () => {
try {
const note = await entry.install((step, percent) => {
this.setInstallProgress(
entry.id,
percent === undefined ? { running: true, step } : { running: true, step, percent },
);
});
this.setInstallProgress(entry.id, { running: false, note });
} catch (error) {
const step = this.installProgress.get(entry.id)?.step;
this.log.warn('capability install failed', {
capabilityId: entry.id,
step,
error,
});
this.setInstallProgress(entry.id, {
running: false,
error: error instanceof Error ? error.message : String(error),
});
} finally {
this.runningInstalls.delete(entry.id);
}
})();
return this.statusOf(entry);
}
private requireEntry(id: string): CapabilityEntry {
const entry = this.entries.get(id as CapabilityId);
if (entry === undefined) {
throw new Error2(
CapabilityErrors.codes.CAPABILITY_NOT_FOUND,
`Capability "${id}" is not registered`,
{ details: { id } },
);
}
return entry;
}
private async statusOf(entry: CapabilityEntry): Promise<CapabilityStatus> {
const install = this.installProgress.get(entry.id) ?? IDLE_PROGRESS;
const base = {
id: entry.id,
pluginId: entry.pluginId,
displayName: entry.displayName,
description: entry.description,
install,
};
if (!entry.supported) {
return { ...base, supported: false, state: 'unsupported', steps: [] };
}
const detected = await entry.detect();
const required = detected.steps.filter((step) => step.optional !== true);
const requiredOk = required.length > 0 && required.every((step) => step.state === 'ok');
const anyOk = detected.steps.some((step) => step.state === 'ok');
const state: CapabilityReadiness = requiredOk ? 'ready' : anyOk ? 'partial' : 'not_installed';
return {
...base,
supported: true,
state,
steps: detected.steps,
version: detected.version,
};
}
private async statusOfSafe(entry: CapabilityEntry): Promise<CapabilityStatus> {
try {
return await this.statusOf(entry);
} catch (error) {
const install = this.installProgress.get(entry.id) ?? IDLE_PROGRESS;
const detail = error instanceof Error ? error.message : String(error);
const base = {
id: entry.id,
pluginId: entry.pluginId,
displayName: entry.displayName,
description: entry.description,
install,
};
if (!entry.supported) {
return { ...base, supported: false, state: 'unsupported', steps: [] };
}
return {
...base,
supported: true,
state: 'partial',
steps: [{ id: 'detect', state: 'failed' as const, detail }],
};
}
}
}
registerScopedService(
LifecycleScope.App,
ICapabilityService,
CapabilityService,
ScopeActivation.OnScopeCreated,
'capability',
);
|