dsh-ccgui 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +327 -2
- package/THIRD_PARTY_NOTICES.md +64 -0
- package/assets/logo.png +0 -0
- package/cordis.patch.yml +32 -0
- package/lib/abortable.d.ts +12 -0
- package/lib/abortable.js +27 -0
- package/lib/adapter.d.ts +39 -0
- package/lib/adapter.js +64 -0
- package/lib/async-queue.d.ts +26 -0
- package/lib/async-queue.js +55 -0
- package/lib/cli-session.d.ts +99 -0
- package/lib/cli-session.js +384 -0
- package/lib/cli-tool.d.ts +18 -0
- package/lib/cli-tool.js +101 -0
- package/lib/client.js +4039 -0
- package/lib/constants.d.ts +22 -0
- package/lib/constants.js +22 -0
- package/lib/git/git-read.d.ts +65 -0
- package/lib/git/git-read.js +139 -0
- package/lib/git/git-requests.d.ts +44 -0
- package/lib/git/git-requests.js +153 -0
- package/lib/git/git-routes.d.ts +38 -0
- package/lib/git/git-routes.js +78 -0
- package/lib/git/git-run.d.ts +58 -0
- package/lib/git/git-run.js +97 -0
- package/lib/git/git-status.d.ts +51 -0
- package/lib/git/git-status.js +122 -0
- package/lib/git/git-write.d.ts +75 -0
- package/lib/git/git-write.js +134 -0
- package/lib/index.d.ts +78 -0
- package/lib/index.js +229 -0
- package/lib/model-cache.d.ts +33 -0
- package/lib/model-cache.js +101 -0
- package/lib/model-catalog.d.ts +63 -0
- package/lib/model-catalog.js +107 -0
- package/lib/model-options.d.ts +26 -0
- package/lib/model-options.js +46 -0
- package/lib/model-probe.d.ts +16 -0
- package/lib/model-probe.js +91 -0
- package/lib/npx-cache.d.ts +39 -0
- package/lib/npx-cache.js +97 -0
- package/lib/permission.d.ts +17 -0
- package/lib/permission.js +34 -0
- package/lib/prompt-images.d.ts +44 -0
- package/lib/prompt-images.js +46 -0
- package/lib/request-input.d.ts +42 -0
- package/lib/request-input.js +113 -0
- package/lib/session/connect.d.ts +41 -0
- package/lib/session/connect.js +68 -0
- package/lib/session/drive-tool.d.ts +39 -0
- package/lib/session/drive-tool.js +37 -0
- package/lib/session/model-state.d.ts +40 -0
- package/lib/session/model-state.js +68 -0
- package/lib/session/outcomes.d.ts +31 -0
- package/lib/session/outcomes.js +67 -0
- package/lib/session/permission-queue.d.ts +24 -0
- package/lib/session/permission-queue.js +33 -0
- package/lib/session/read-step.d.ts +31 -0
- package/lib/session/read-step.js +53 -0
- package/lib/session/tool-mirror.d.ts +65 -0
- package/lib/session/tool-mirror.js +131 -0
- package/lib/session/turn-queue.d.ts +76 -0
- package/lib/session/turn-queue.js +102 -0
- package/lib/session/types.d.ts +58 -0
- package/lib/session/types.js +6 -0
- package/lib/session-registry.d.ts +124 -0
- package/lib/session-registry.js +189 -0
- package/lib/stdio-transport.d.ts +28 -0
- package/lib/stdio-transport.js +164 -0
- package/lib/stream-blocks.d.ts +52 -0
- package/lib/stream-blocks.js +95 -0
- package/lib/tool-record.d.ts +100 -0
- package/lib/tool-record.js +167 -0
- package/lib/transport.d.ts +35 -0
- package/lib/transport.js +5 -0
- package/package.json +136 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host plugin: registers each configured CLI as a model provider and wires the
|
|
3
|
+
* session registry to the harness.
|
|
4
|
+
* @module dsh-ccgui
|
|
5
|
+
*/
|
|
6
|
+
import { mkdir } from 'node:fs/promises';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { Service } from '@deepseek-ai/cordis';
|
|
10
|
+
import z from '@deepseek-ai/schemastery';
|
|
11
|
+
import { CliBridgeAdapter } from "./adapter.js";
|
|
12
|
+
import { CliSession } from "./cli-session.js";
|
|
13
|
+
import { createCliTool } from "./cli-tool.js";
|
|
14
|
+
import { CLI_TOOL_NAME, cliRoute } from "./constants.js";
|
|
15
|
+
import { ModelCacheFile } from "./model-cache.js";
|
|
16
|
+
import { CliModelCatalog } from "./model-catalog.js";
|
|
17
|
+
import { probeModels } from "./model-probe.js";
|
|
18
|
+
import { npxCacheDir, startFromNpxCache } from "./npx-cache.js";
|
|
19
|
+
import { gitHandler, registerGitRoutes } from "./git/git-routes.js";
|
|
20
|
+
import { CliSessionRegistry } from "./session-registry.js";
|
|
21
|
+
import { openStdioTransport } from "./stdio-transport.js";
|
|
22
|
+
/**
|
|
23
|
+
* Shown to turns cut off when this plugin stops. Besides shutdown, the harness restarts a
|
|
24
|
+
* plugin whose files changed, which takes every CLI it started down with it.
|
|
25
|
+
*/
|
|
26
|
+
const PLUGIN_STOPPED_REASON = 'dsh-ccgui 插件已停止或重新加载(例如插件更新后),这条回复没有完成,请重新发送。';
|
|
27
|
+
const PLUGIN_HOME = 'ccgui';
|
|
28
|
+
const MODEL_CACHE_FILE = 'models.json';
|
|
29
|
+
const MODEL_PROBE_DIR = 'model-probe';
|
|
30
|
+
/** Service behind `ctx.cliBridge`. */
|
|
31
|
+
export default class CliBridge extends Service {
|
|
32
|
+
config;
|
|
33
|
+
static inject = ['llm', 'agents', 'subprocess', 'tools'];
|
|
34
|
+
static Config = z.object({
|
|
35
|
+
agents: z
|
|
36
|
+
.array(z.object({
|
|
37
|
+
id: z.string().required(),
|
|
38
|
+
name: z.string().required(),
|
|
39
|
+
command: z.string().required(),
|
|
40
|
+
args: z.array(z.string()).default([]),
|
|
41
|
+
env: z.dict(z.string()).default({}),
|
|
42
|
+
}))
|
|
43
|
+
.default([]),
|
|
44
|
+
disposeGraceMs: z.number().min(1).default(3_000),
|
|
45
|
+
disposeEofGraceMs: z.number().min(1).default(6_000),
|
|
46
|
+
cancelGraceMs: z.number().min(1).default(10_000),
|
|
47
|
+
startTimeoutMs: z.number().min(1).default(120_000),
|
|
48
|
+
});
|
|
49
|
+
registry;
|
|
50
|
+
catalog;
|
|
51
|
+
/** Ends any model probe still running when this plugin goes away. */
|
|
52
|
+
probes = new AbortController();
|
|
53
|
+
constructor(ctx, config) {
|
|
54
|
+
super(ctx, 'cliBridge');
|
|
55
|
+
this.config = config;
|
|
56
|
+
this.registry = new CliSessionRegistry(config.agents, {
|
|
57
|
+
getAgent: (sessionId) => ctx.agents.get(sessionId),
|
|
58
|
+
composedPreset: (agent) => ctx.get('agentPresets')?.composedPreset(agent.ctx),
|
|
59
|
+
ask: (agent, request, signal) => this.ask(agent, request, signal),
|
|
60
|
+
warn: (message) => ctx.logger.warn(message),
|
|
61
|
+
onCliSelected: (provider) => this.catalog.ensureListed(provider),
|
|
62
|
+
createSession: (agent, sessionId, cwd, start) => this.createSession(agent, sessionId, cwd, start),
|
|
63
|
+
});
|
|
64
|
+
const modelCache = new ModelCacheFile(this.homePath(PLUGIN_HOME, MODEL_CACHE_FILE));
|
|
65
|
+
this.catalog = new CliModelCatalog({
|
|
66
|
+
labelFor: (provider) => this.registry.labelFor(provider),
|
|
67
|
+
probe: (provider) => this.probeProvider(provider),
|
|
68
|
+
onUpdated: (provider) => {
|
|
69
|
+
ctx.emit('llm/models-updated', provider);
|
|
70
|
+
},
|
|
71
|
+
warn: (message) => ctx.logger.warn(message),
|
|
72
|
+
save: (lists) => modelCache.save(lists),
|
|
73
|
+
});
|
|
74
|
+
this.restoreModels(modelCache);
|
|
75
|
+
this.registerRoutes();
|
|
76
|
+
this.followSessions();
|
|
77
|
+
this.serveGit();
|
|
78
|
+
}
|
|
79
|
+
/** Read in the background: the menu works without it, and fills in once it arrives. */
|
|
80
|
+
restoreModels(modelCache) {
|
|
81
|
+
const { ctx, catalog, probes } = this;
|
|
82
|
+
modelCache
|
|
83
|
+
.read()
|
|
84
|
+
.then((lists) => {
|
|
85
|
+
if (!probes.signal.aborted)
|
|
86
|
+
catalog.restore(lists);
|
|
87
|
+
})
|
|
88
|
+
.catch((error) => {
|
|
89
|
+
ctx.logger.warn(`ccgui: could not read saved model lists: ${String(error)}`);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/** The harness's home, or `~/.dsh` when it does not say. */
|
|
93
|
+
homePath(...segments) {
|
|
94
|
+
const resolveHome = this.ctx.get('dshHomePath') ?? ((...parts) => join(homedir(), '.dsh', ...parts));
|
|
95
|
+
return resolveHome(...segments);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The 变更 panel's git routes. Taken as optional dependencies: a harness without a web
|
|
99
|
+
* server (a headless run) still gets the CLIs, just not the panel's backend.
|
|
100
|
+
*/
|
|
101
|
+
serveGit() {
|
|
102
|
+
this.ctx.inject(['webServer', 'connection'], (child) => {
|
|
103
|
+
const handler = gitHandler((spec) => child.subprocess.spawn(spec), child.connection, (message) => child.logger.warn(message));
|
|
104
|
+
child.effect(() => registerGitRoutes(child.webServer, handler), 'ccgui: git routes');
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
registerRoutes() {
|
|
108
|
+
const { ctx, registry, catalog } = this;
|
|
109
|
+
if (registry.providers.length > 0) {
|
|
110
|
+
ctx.llm.registerAdapter([...registry.providers], new CliBridgeAdapter({
|
|
111
|
+
labelFor: (provider) => registry.labelFor(provider),
|
|
112
|
+
resolveSession: (provider, sessionId) => registry.resolveSession(provider, sessionId),
|
|
113
|
+
currentTurnMessageIds: (sessionId) => registry.currentTurnMessageIds(sessionId),
|
|
114
|
+
modelsFor: (provider) => catalog.listModels(provider),
|
|
115
|
+
modelName: (provider, model) => catalog.modelName(provider, model),
|
|
116
|
+
}));
|
|
117
|
+
}
|
|
118
|
+
// Admitted only for steps a CLI runs, so no other model ever sees this tool, and a
|
|
119
|
+
// CLI works from any mode without its calls needing a preset of their own.
|
|
120
|
+
ctx.tools.register(createCliTool({ waitForTool: (exec) => registry.waitForTool(exec) }), {
|
|
121
|
+
when: ({ modelSelection }) => registry.isCliRoute(modelSelection.provider),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
followSessions() {
|
|
125
|
+
const { ctx, registry, probes } = this;
|
|
126
|
+
ctx.on('agent/created', ({ agent }) => {
|
|
127
|
+
registry.routeAgent(agent);
|
|
128
|
+
return undefined;
|
|
129
|
+
});
|
|
130
|
+
// The Web client creates a session under the default preset and switches it
|
|
131
|
+
// afterwards, so `agent/created` alone would miss the preset the user chose.
|
|
132
|
+
// This event fires while the session is still publishing the preset change,
|
|
133
|
+
// which rejects a nested append; the microtask runs just after, and still
|
|
134
|
+
// before the first turn because the switch has not returned to its caller.
|
|
135
|
+
ctx.on('agent-preset/selected', (sessionId) => {
|
|
136
|
+
queueMicrotask(() => {
|
|
137
|
+
const agent = ctx.agents.get(sessionId);
|
|
138
|
+
if (agent === undefined)
|
|
139
|
+
return;
|
|
140
|
+
try {
|
|
141
|
+
registry.routeAgent(agent);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
ctx.logger.warn(`ccgui: could not select the CLI for ${sessionId}: ${String(error)}`);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
ctx.on('session/event', (session, event) => registry.observeEvent(session.id, event));
|
|
149
|
+
ctx.on('agent/disposed', ({ agent }) => registry.disposeSession(agent.id));
|
|
150
|
+
ctx.effect(() => () => {
|
|
151
|
+
probes.abort();
|
|
152
|
+
registry.disposeAll(PLUGIN_STOPPED_REASON);
|
|
153
|
+
}, 'cliBridge.sessions()');
|
|
154
|
+
}
|
|
155
|
+
ask(agent, { reason, callId }, signal) {
|
|
156
|
+
const approval = this.ctx.get('approval');
|
|
157
|
+
if (approval === undefined)
|
|
158
|
+
return Promise.resolve('unavailable');
|
|
159
|
+
return approval.request({
|
|
160
|
+
agent,
|
|
161
|
+
toolName: CLI_TOOL_NAME,
|
|
162
|
+
reason,
|
|
163
|
+
signal,
|
|
164
|
+
...(callId === undefined ? {} : { callId: callId }),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
openTransport(agent, cwd, handlers) {
|
|
168
|
+
const { argv, env } = startFromNpxCache({ argv: [agent.command, ...agent.args], env: agent.env }, {
|
|
169
|
+
npxCache: npxCacheDir(process.env, homedir(), process.platform),
|
|
170
|
+
path: process.env.PATH,
|
|
171
|
+
});
|
|
172
|
+
return openStdioTransport({
|
|
173
|
+
argv,
|
|
174
|
+
cwd,
|
|
175
|
+
env,
|
|
176
|
+
graceMs: this.config.disposeGraceMs,
|
|
177
|
+
eofGraceMs: this.config.disposeEofGraceMs,
|
|
178
|
+
spawn: (spec) => this.ctx.subprocess.spawn(spec),
|
|
179
|
+
}, handlers);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The temporary session goes in a directory of its own, away from the user's projects.
|
|
183
|
+
* Some CLIs keep a folder per working directory even for a deleted session, so this one
|
|
184
|
+
* never changes: a new directory on every start would add a folder each time. It is under
|
|
185
|
+
* the harness's home rather than the system temp directory, where on a shared machine
|
|
186
|
+
* another user could plant a project config at a predictable path for a CLI to load.
|
|
187
|
+
*/
|
|
188
|
+
async probeProvider(provider) {
|
|
189
|
+
const agent = this.registry.configFor(provider);
|
|
190
|
+
if (agent === undefined)
|
|
191
|
+
return undefined;
|
|
192
|
+
const { signal } = this.probes;
|
|
193
|
+
const cwd = this.homePath(PLUGIN_HOME, MODEL_PROBE_DIR);
|
|
194
|
+
await mkdir(cwd, { recursive: true });
|
|
195
|
+
try {
|
|
196
|
+
return await probeModels((handlers) => this.openTransport(agent, cwd, handlers), cwd, this.config.startTimeoutMs, signal);
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (signal.aborted)
|
|
200
|
+
return undefined;
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/** Looked up on each read: the attachment service can come and go while the plugin runs. */
|
|
205
|
+
async readImage(ref, signal) {
|
|
206
|
+
const attachments = this.ctx.get('attachments');
|
|
207
|
+
if (attachments === undefined)
|
|
208
|
+
throw new Error('attachment service is not available');
|
|
209
|
+
const { data } = await attachments.readImage(ref, signal);
|
|
210
|
+
return data;
|
|
211
|
+
}
|
|
212
|
+
createSession(agent, sessionId, cwd, start) {
|
|
213
|
+
const provider = cliRoute(agent.id);
|
|
214
|
+
return new CliSession({
|
|
215
|
+
dshSessionId: sessionId,
|
|
216
|
+
provider,
|
|
217
|
+
cwd,
|
|
218
|
+
label: agent.name,
|
|
219
|
+
sentMessageIds: start.sentMessageIds,
|
|
220
|
+
after: start.after,
|
|
221
|
+
cancelGraceMs: this.config.cancelGraceMs,
|
|
222
|
+
startTimeoutMs: this.config.startTimeoutMs,
|
|
223
|
+
knownModels: () => this.catalog.known(provider),
|
|
224
|
+
readImage: (ref, signal) => this.readImage(ref, signal),
|
|
225
|
+
onError: (error) => this.ctx.logger.warn(`ccgui: ${agent.name}: ${String(error)}`),
|
|
226
|
+
openTransport: (handlers) => this.openTransport(agent, cwd, handlers),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps each CLI's model list on disk. The harness restarts this plugin when its files
|
|
3
|
+
* change (an update, or a rebuild under a linked install), and a fresh catalog would show
|
|
4
|
+
* a bare menu until the CLI is probed again; with the saved lists it is filled at once.
|
|
5
|
+
* @module dsh-ccgui/model-cache
|
|
6
|
+
*/
|
|
7
|
+
import type { CliModelList } from './model-options.ts';
|
|
8
|
+
/**
|
|
9
|
+
* Read the saved lists, keeping only well-formed entries.
|
|
10
|
+
* @param text - the file's contents.
|
|
11
|
+
* @returns the lists by provider route; empty for anything unreadable.
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseModelCache(text: string): ReadonlyMap<string, CliModelList>;
|
|
14
|
+
/** One cache file, with writes kept in order. */
|
|
15
|
+
export declare class ModelCacheFile {
|
|
16
|
+
private readonly path;
|
|
17
|
+
private writing;
|
|
18
|
+
constructor(path: string);
|
|
19
|
+
/**
|
|
20
|
+
* Read the saved lists.
|
|
21
|
+
* @returns them by provider route; empty before the first save or for a corrupt file.
|
|
22
|
+
*/
|
|
23
|
+
read(): Promise<ReadonlyMap<string, CliModelList>>;
|
|
24
|
+
/**
|
|
25
|
+
* Replace the saved lists. Writes run one at a time in call order, so a later, fuller
|
|
26
|
+
* snapshot never lands under an earlier one; each goes through a temporary file, so a
|
|
27
|
+
* reader never sees half a file.
|
|
28
|
+
* @param lists - every list to keep, by provider route.
|
|
29
|
+
* @returns settles once this snapshot is on disk; rejects when it could not be written.
|
|
30
|
+
*/
|
|
31
|
+
save(lists: ReadonlyMap<string, CliModelList>): Promise<void>;
|
|
32
|
+
private write;
|
|
33
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps each CLI's model list on disk. The harness restarts this plugin when its files
|
|
3
|
+
* change (an update, or a rebuild under a linked install), and a fresh catalog would show
|
|
4
|
+
* a bare menu until the CLI is probed again; with the saved lists it is filled at once.
|
|
5
|
+
* @module dsh-ccgui/model-cache
|
|
6
|
+
*/
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { dirname } from 'node:path';
|
|
10
|
+
/** Bumped when the layout changes; a file of another version is ignored, not misread. */
|
|
11
|
+
const CACHE_VERSION = 1;
|
|
12
|
+
const isObject = (value) => typeof value === 'object' && value !== null;
|
|
13
|
+
const isText = (value) => typeof value === 'string' && value.length > 0;
|
|
14
|
+
function readOption(value) {
|
|
15
|
+
if (!isObject(value) || !isText(value.value) || !isText(value.name))
|
|
16
|
+
return undefined;
|
|
17
|
+
return { value: value.value, name: value.name };
|
|
18
|
+
}
|
|
19
|
+
/** Checked as strictly as a live answer: one empty id makes the harness drop the whole CLI. */
|
|
20
|
+
function readList(value) {
|
|
21
|
+
if (!isObject(value) || !isText(value.configId) || !isText(value.current) || !Array.isArray(value.options)) {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
const options = value.options.map(readOption);
|
|
25
|
+
if (options.length === 0 || options.some((option) => option === undefined))
|
|
26
|
+
return undefined;
|
|
27
|
+
return { configId: value.configId, current: value.current, options: options.filter((option) => option !== undefined) };
|
|
28
|
+
}
|
|
29
|
+
function parseJson(text) {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(text);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// A torn or hand-edited file is only a lost cache; the next probe writes a good one.
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Read the saved lists, keeping only well-formed entries.
|
|
40
|
+
* @param text - the file's contents.
|
|
41
|
+
* @returns the lists by provider route; empty for anything unreadable.
|
|
42
|
+
*/
|
|
43
|
+
export function parseModelCache(text) {
|
|
44
|
+
const data = parseJson(text);
|
|
45
|
+
if (!isObject(data) || data.version !== CACHE_VERSION || !isObject(data.lists))
|
|
46
|
+
return new Map();
|
|
47
|
+
return new Map(Object.entries(data.lists).flatMap(([provider, value]) => {
|
|
48
|
+
const list = readList(value);
|
|
49
|
+
return list === undefined ? [] : [[provider, list]];
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
const isMissing = (error) => isObject(error) && error.code === 'ENOENT';
|
|
53
|
+
/** One cache file, with writes kept in order. */
|
|
54
|
+
export class ModelCacheFile {
|
|
55
|
+
path;
|
|
56
|
+
writing = Promise.resolve();
|
|
57
|
+
constructor(path) {
|
|
58
|
+
this.path = path;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Read the saved lists.
|
|
62
|
+
* @returns them by provider route; empty before the first save or for a corrupt file.
|
|
63
|
+
*/
|
|
64
|
+
async read() {
|
|
65
|
+
try {
|
|
66
|
+
return parseModelCache(await readFile(this.path, 'utf8'));
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (isMissing(error))
|
|
70
|
+
return new Map();
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Replace the saved lists. Writes run one at a time in call order, so a later, fuller
|
|
76
|
+
* snapshot never lands under an earlier one; each goes through a temporary file, so a
|
|
77
|
+
* reader never sees half a file.
|
|
78
|
+
* @param lists - every list to keep, by provider route.
|
|
79
|
+
* @returns settles once this snapshot is on disk; rejects when it could not be written.
|
|
80
|
+
*/
|
|
81
|
+
save(lists) {
|
|
82
|
+
const text = JSON.stringify({ version: CACHE_VERSION, lists: Object.fromEntries(lists) });
|
|
83
|
+
const written = this.writing.then(() => this.write(text));
|
|
84
|
+
this.writing = written.catch(() => {
|
|
85
|
+
/* the caller of this save is told; the next one still runs */
|
|
86
|
+
});
|
|
87
|
+
return written;
|
|
88
|
+
}
|
|
89
|
+
async write(text) {
|
|
90
|
+
const temporary = `${this.path}.${randomUUID()}.tmp`;
|
|
91
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
92
|
+
try {
|
|
93
|
+
await writeFile(temporary, text, 'utf8');
|
|
94
|
+
await rename(temporary, this.path);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
await rm(temporary, { force: true });
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the model menu shows for each CLI. Asking a CLI means starting it, which can
|
|
3
|
+
* take a while on a cold `npx` and for that command downloads and runs a package. So
|
|
4
|
+
* filling the menu never asks: a CLI is only started once someone has chosen it, and
|
|
5
|
+
* the menu refreshes when the answer arrives. Answers are saved, so a restarted plugin
|
|
6
|
+
* can show the last known lists while it asks again.
|
|
7
|
+
* @module dsh-ccgui/model-catalog
|
|
8
|
+
*/
|
|
9
|
+
import type { LlmModelInfo } from '@deepseek-ai/dsh-llm';
|
|
10
|
+
import type { CliModelList } from './model-options.ts';
|
|
11
|
+
/** What the catalog needs from the bridge. */
|
|
12
|
+
export interface ModelCatalogDeps {
|
|
13
|
+
labelFor(provider: string): string | undefined;
|
|
14
|
+
probe(provider: string): Promise<CliModelList | undefined>;
|
|
15
|
+
/** The list for this route changed; the harness then refreshes its menus. */
|
|
16
|
+
onUpdated(provider: string): void;
|
|
17
|
+
warn(message: string): void;
|
|
18
|
+
/** Keep every known list for the next run. */
|
|
19
|
+
save(lists: ReadonlyMap<string, CliModelList>): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
/** Remembers each CLI's models, seeded from the lists an earlier run saved. */
|
|
22
|
+
export declare class CliModelCatalog {
|
|
23
|
+
private readonly deps;
|
|
24
|
+
private lists;
|
|
25
|
+
private asked;
|
|
26
|
+
/** Routes this run has a CLI's own answer for, as opposed to a restored list. */
|
|
27
|
+
private answered;
|
|
28
|
+
constructor(deps: ModelCatalogDeps);
|
|
29
|
+
/**
|
|
30
|
+
* List a CLI's models. The default entry names the model it stands for, so the menu
|
|
31
|
+
* always shows what is really in use.
|
|
32
|
+
* @param provider - a CLI route.
|
|
33
|
+
* @returns the default entry, followed by the real models once they are known.
|
|
34
|
+
*/
|
|
35
|
+
listModels(provider: string): readonly LlmModelInfo[];
|
|
36
|
+
/**
|
|
37
|
+
* Name one model.
|
|
38
|
+
* @param provider - a CLI route.
|
|
39
|
+
* @param model - a model id.
|
|
40
|
+
* @returns its display name, falling back to the id.
|
|
41
|
+
*/
|
|
42
|
+
modelName(provider: string, model: string): string;
|
|
43
|
+
/**
|
|
44
|
+
* Read what a CLI reported.
|
|
45
|
+
* @param provider - a CLI route.
|
|
46
|
+
* @returns its model list, once known.
|
|
47
|
+
*/
|
|
48
|
+
known(provider: string): CliModelList | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Ask a CLI for its models in the background, unless that is done or under way. A
|
|
51
|
+
* failed attempt can be repeated: the user may have installed it or logged in since.
|
|
52
|
+
* @param provider - a CLI route someone has chosen.
|
|
53
|
+
*/
|
|
54
|
+
ensureListed(provider: string): void;
|
|
55
|
+
/**
|
|
56
|
+
* Show the lists an earlier run saved. They may be out of date, so they never replace
|
|
57
|
+
* an answer from this run and do not stop the CLI from being asked when chosen.
|
|
58
|
+
* @param saved - lists by provider route; routes no longer configured are skipped.
|
|
59
|
+
*/
|
|
60
|
+
restore(saved: ReadonlyMap<string, CliModelList>): void;
|
|
61
|
+
private persist;
|
|
62
|
+
private defaultName;
|
|
63
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the model menu shows for each CLI. Asking a CLI means starting it, which can
|
|
3
|
+
* take a while on a cold `npx` and for that command downloads and runs a package. So
|
|
4
|
+
* filling the menu never asks: a CLI is only started once someone has chosen it, and
|
|
5
|
+
* the menu refreshes when the answer arrives. Answers are saved, so a restarted plugin
|
|
6
|
+
* can show the last known lists while it asks again.
|
|
7
|
+
* @module dsh-ccgui/model-catalog
|
|
8
|
+
*/
|
|
9
|
+
import { DEFAULT_MODEL_ID } from "./constants.js";
|
|
10
|
+
function nameOf(list, value) {
|
|
11
|
+
return list.options.find((option) => option.value === value)?.name ?? value;
|
|
12
|
+
}
|
|
13
|
+
/** The harness rejects a catalog with duplicate ids, which would drop the whole CLI. */
|
|
14
|
+
function selectableOptions(options) {
|
|
15
|
+
return options.filter(({ value }, index) => value !== DEFAULT_MODEL_ID && options.findIndex((option) => option.value === value) === index);
|
|
16
|
+
}
|
|
17
|
+
/** Remembers each CLI's models, seeded from the lists an earlier run saved. */
|
|
18
|
+
export class CliModelCatalog {
|
|
19
|
+
deps;
|
|
20
|
+
lists = new Map();
|
|
21
|
+
asked = new Set();
|
|
22
|
+
/** Routes this run has a CLI's own answer for, as opposed to a restored list. */
|
|
23
|
+
answered = new Set();
|
|
24
|
+
constructor(deps) {
|
|
25
|
+
this.deps = deps;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* List a CLI's models. The default entry names the model it stands for, so the menu
|
|
29
|
+
* always shows what is really in use.
|
|
30
|
+
* @param provider - a CLI route.
|
|
31
|
+
* @returns the default entry, followed by the real models once they are known.
|
|
32
|
+
*/
|
|
33
|
+
listModels(provider) {
|
|
34
|
+
const list = this.lists.get(provider);
|
|
35
|
+
if (list === undefined) {
|
|
36
|
+
return [{ provider, id: DEFAULT_MODEL_ID, name: this.deps.labelFor(provider) ?? provider }];
|
|
37
|
+
}
|
|
38
|
+
return [
|
|
39
|
+
{ provider, id: DEFAULT_MODEL_ID, name: this.defaultName(list) },
|
|
40
|
+
...selectableOptions(list.options).map(({ value, name }) => ({ provider, id: value, name })),
|
|
41
|
+
];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Name one model.
|
|
45
|
+
* @param provider - a CLI route.
|
|
46
|
+
* @param model - a model id.
|
|
47
|
+
* @returns its display name, falling back to the id.
|
|
48
|
+
*/
|
|
49
|
+
modelName(provider, model) {
|
|
50
|
+
const list = this.lists.get(provider);
|
|
51
|
+
if (list === undefined)
|
|
52
|
+
return model;
|
|
53
|
+
return model === DEFAULT_MODEL_ID ? this.defaultName(list) : nameOf(list, model);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Read what a CLI reported.
|
|
57
|
+
* @param provider - a CLI route.
|
|
58
|
+
* @returns its model list, once known.
|
|
59
|
+
*/
|
|
60
|
+
known(provider) {
|
|
61
|
+
return this.lists.get(provider);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Ask a CLI for its models in the background, unless that is done or under way. A
|
|
65
|
+
* failed attempt can be repeated: the user may have installed it or logged in since.
|
|
66
|
+
* @param provider - a CLI route someone has chosen.
|
|
67
|
+
*/
|
|
68
|
+
ensureListed(provider) {
|
|
69
|
+
if (this.asked.has(provider))
|
|
70
|
+
return;
|
|
71
|
+
this.asked = new Set([...this.asked, provider]);
|
|
72
|
+
this.deps
|
|
73
|
+
.probe(provider)
|
|
74
|
+
.then((list) => {
|
|
75
|
+
if (list === undefined)
|
|
76
|
+
return;
|
|
77
|
+
this.lists = new Map([...this.lists, [provider, list]]);
|
|
78
|
+
this.answered = new Set([...this.answered, provider]);
|
|
79
|
+
this.persist();
|
|
80
|
+
this.deps.onUpdated(provider);
|
|
81
|
+
})
|
|
82
|
+
.catch((error) => {
|
|
83
|
+
if (!this.answered.has(provider))
|
|
84
|
+
this.asked = new Set([...this.asked].filter((asked) => asked !== provider));
|
|
85
|
+
this.deps.warn(`ccgui: could not list models for ${provider}: ${String(error)}`);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Show the lists an earlier run saved. They may be out of date, so they never replace
|
|
90
|
+
* an answer from this run and do not stop the CLI from being asked when chosen.
|
|
91
|
+
* @param saved - lists by provider route; routes no longer configured are skipped.
|
|
92
|
+
*/
|
|
93
|
+
restore(saved) {
|
|
94
|
+
const restored = [...saved].filter(([provider]) => !this.answered.has(provider) && this.deps.labelFor(provider) !== undefined);
|
|
95
|
+
this.lists = new Map([...this.lists, ...restored]);
|
|
96
|
+
for (const [provider] of restored)
|
|
97
|
+
this.deps.onUpdated(provider);
|
|
98
|
+
}
|
|
99
|
+
persist() {
|
|
100
|
+
this.deps.save(this.lists).catch((error) => {
|
|
101
|
+
this.deps.warn(`ccgui: could not save model lists: ${String(error)}`);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
defaultName(list) {
|
|
105
|
+
return `${nameOf(list, list.current)}(默认)`;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a CLI's model list out of the configuration options ACP reports.
|
|
3
|
+
* @module dsh-ccgui/model-options
|
|
4
|
+
*/
|
|
5
|
+
import type { SessionConfigOption } from '@agentclientprotocol/sdk';
|
|
6
|
+
/** One model a CLI offers. */
|
|
7
|
+
export interface CliModelOption {
|
|
8
|
+
readonly value: string;
|
|
9
|
+
readonly name: string;
|
|
10
|
+
}
|
|
11
|
+
/** The models a CLI offers and which one is active. */
|
|
12
|
+
export interface CliModelList {
|
|
13
|
+
/** Option id to send when switching; ACP does not fix this name. */
|
|
14
|
+
readonly configId: string;
|
|
15
|
+
readonly current: string;
|
|
16
|
+
readonly options: readonly CliModelOption[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Find the model option. ACP marks it with a category, so that wins; the id is only
|
|
20
|
+
* a convention, for CLIs that report no category. The SDK does not validate responses,
|
|
21
|
+
* so everything here is checked: an empty name or id in the catalog would make the
|
|
22
|
+
* harness drop the whole CLI from its menus.
|
|
23
|
+
* @param configOptions - the options a CLI reported, if any.
|
|
24
|
+
* @returns the model list, or undefined when the CLI offers no selectable models.
|
|
25
|
+
*/
|
|
26
|
+
export declare function readModelList(configOptions: readonly SessionConfigOption[] | null | undefined): CliModelList | undefined;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a CLI's model list out of the configuration options ACP reports.
|
|
3
|
+
* @module dsh-ccgui/model-options
|
|
4
|
+
*/
|
|
5
|
+
import { DEFAULT_MODEL_ID } from "./constants.js";
|
|
6
|
+
const CONVENTIONAL_MODEL_OPTION_ID = 'model';
|
|
7
|
+
const isObject = (value) => typeof value === 'object' && value !== null;
|
|
8
|
+
const isText = (value) => typeof value === 'string' && value.length > 0;
|
|
9
|
+
function flattenEntries(entries) {
|
|
10
|
+
if (!Array.isArray(entries))
|
|
11
|
+
return [];
|
|
12
|
+
return entries.flatMap((entry) => {
|
|
13
|
+
if (!isObject(entry) || !('options' in entry))
|
|
14
|
+
return [entry];
|
|
15
|
+
return Array.isArray(entry.options) ? entry.options : [];
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A CLI's own default entry can be named for its role, "Default (recommended)", with only the
|
|
20
|
+
* description saying which model that is. The menu names the model, as it does for other CLIs.
|
|
21
|
+
*/
|
|
22
|
+
function readEntry(entry) {
|
|
23
|
+
if (!isObject(entry) || !isText(entry.value))
|
|
24
|
+
return [];
|
|
25
|
+
const name = entry.value === DEFAULT_MODEL_ID && isText(entry.description) ? entry.description : entry.name;
|
|
26
|
+
return [{ value: entry.value, name: isText(name) ? name : entry.value }];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Find the model option. ACP marks it with a category, so that wins; the id is only
|
|
30
|
+
* a convention, for CLIs that report no category. The SDK does not validate responses,
|
|
31
|
+
* so everything here is checked: an empty name or id in the catalog would make the
|
|
32
|
+
* harness drop the whole CLI from its menus.
|
|
33
|
+
* @param configOptions - the options a CLI reported, if any.
|
|
34
|
+
* @returns the model list, or undefined when the CLI offers no selectable models.
|
|
35
|
+
*/
|
|
36
|
+
export function readModelList(configOptions) {
|
|
37
|
+
const selects = (Array.isArray(configOptions) ? configOptions : [])
|
|
38
|
+
.filter(isObject)
|
|
39
|
+
.filter((candidate) => candidate.type === 'select');
|
|
40
|
+
const option = selects.find((candidate) => candidate.category === 'model') ??
|
|
41
|
+
selects.find((candidate) => candidate.category == null && candidate.id === CONVENTIONAL_MODEL_OPTION_ID);
|
|
42
|
+
if (option === undefined || !isText(option.id) || !isText(option.currentValue))
|
|
43
|
+
return undefined;
|
|
44
|
+
const options = flattenEntries(option.options).flatMap(readEntry);
|
|
45
|
+
return options.length === 0 ? undefined : { configId: option.id, current: option.currentValue, options };
|
|
46
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Asks a CLI which models it offers. ACP only reports them on a session, so this
|
|
3
|
+
* opens one and removes it again. It sends no prompt, so no model is called.
|
|
4
|
+
* @module dsh-ccgui/model-probe
|
|
5
|
+
*/
|
|
6
|
+
import type { CliModelList } from './model-options.ts';
|
|
7
|
+
import type { AcpTransport, TransportHandlers } from './transport.ts';
|
|
8
|
+
/**
|
|
9
|
+
* Start a CLI just long enough to read its model list.
|
|
10
|
+
* @param open - starts the CLI.
|
|
11
|
+
* @param cwd - working directory for the temporary session.
|
|
12
|
+
* @param timeoutMs - how long to wait, which must allow for a cold `npx` download.
|
|
13
|
+
* @param signal - stops the CLI at once when the bridge is shutting down.
|
|
14
|
+
* @returns the model list, or undefined when the CLI offers none.
|
|
15
|
+
*/
|
|
16
|
+
export declare function probeModels(open: (handlers: TransportHandlers) => AcpTransport, cwd: string, timeoutMs: number, signal?: AbortSignal): Promise<CliModelList | undefined>;
|