paseo-dsh 0.0.0-stage → 0.2.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.
@@ -0,0 +1,385 @@
1
+ /**
2
+ * One `dsh --profile paseo` child process, speaking the bridge's stdio JSON-RPC.
3
+ *
4
+ * A process owns exactly one agent session. DSH pins the working directory,
5
+ * provider, model and reasoning effort at `initialize`, so a session per
6
+ * process is what lets Paseo run several workspaces against one provider.
7
+ *
8
+ * @module dsh-paseo/server/dsh-process
9
+ */
10
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
11
+ import { existsSync } from "node:fs";
12
+
13
+ /** Provider/model/thinking route pinned for the life of one process. */
14
+ export interface DshRoute {
15
+ provider: string;
16
+ model: string;
17
+ reasoningEffort?: string;
18
+ }
19
+
20
+ /** One question the model asked, mirroring DSH's `AskUserQuestionItem`. */
21
+ export interface DshQuestion {
22
+ id: string;
23
+ question: string;
24
+ detail?: string;
25
+ header?: string;
26
+ options?: Array<{ label: string; description?: string }>;
27
+ multiSelect?: boolean;
28
+ intent?: { kind: string; approve?: string; callId?: string };
29
+ }
30
+
31
+ /** One answer batch returned to DSH. */
32
+ export interface DshAnswer {
33
+ answers: Array<{ id: string; selected: string[]; custom?: string }>;
34
+ }
35
+
36
+ /** A server -> client question request raised by the DSH bridge. */
37
+ export interface DshQuestionRequest {
38
+ callId: string | null;
39
+ timed: boolean;
40
+ questions: DshQuestion[];
41
+ }
42
+
43
+ /** A `session.event` payload's outer envelope. */
44
+ export interface DshSessionEvent {
45
+ sessionId: string;
46
+ event: { type: string; [key: string]: unknown };
47
+ }
48
+
49
+ /** One model the runtime advertises, with its adapter-owned reasoning efforts. */
50
+ export interface DshCatalogModel {
51
+ provider: string;
52
+ id: string;
53
+ name: string;
54
+ description?: string;
55
+ reasoning?: {
56
+ defaultEffort?: string;
57
+ efforts: Array<{ id: string; name: string; description?: string }>;
58
+ };
59
+ }
60
+
61
+ /** The runtime's provider/model catalog. */
62
+ export interface DshCatalog {
63
+ providers: Array<{ id: string; name: string }>;
64
+ models: DshCatalogModel[];
65
+ defaultProvider?: string;
66
+ defaultModel?: string;
67
+ defaultReasoningEffort?: string | null;
68
+ planMode?: boolean;
69
+ }
70
+
71
+ /**
72
+ * One entry of the composer's `/` menu. `kind` decides how running it works:
73
+ * a registered `command` executes in the runtime, a `skill` rides a `/name`
74
+ * user message that DSH's skill tool turns into an injected instruction set.
75
+ */
76
+ export interface DshCommand {
77
+ name: string;
78
+ description: string;
79
+ argumentHint?: string;
80
+ kind: "command" | "skill";
81
+ }
82
+
83
+ export interface DshProcessHandlers {
84
+ onEvent(payload: DshSessionEvent): void;
85
+ onStatus(status: string): void;
86
+ onQuestion(request: DshQuestionRequest): Promise<DshAnswer>;
87
+ onLog(line: string): void;
88
+ onExit(code: number | null, signal: string | null): void;
89
+ onProtocolError(message: string): void;
90
+ }
91
+
92
+ export interface DshProcessOptions extends DshProcessHandlers {
93
+ cwd: string;
94
+ route: DshRoute;
95
+ sessionId: string;
96
+ /** Extra environment for the child; merged over the daemon's environment. */
97
+ env?: Record<string, string>;
98
+ /**
99
+ * Whether `start()` pins a route with `initialize`. Catalog reads skip it,
100
+ * because `paseo/catalog` needs no agent and a bad route must not hide the
101
+ * model list that would let the user pick a good one.
102
+ */
103
+ initializeRoute?: boolean;
104
+ }
105
+
106
+ const BINARY_CANDIDATES = [
107
+ process.env.DSH_BINARY,
108
+ "dsh",
109
+ `${process.env.HOME ?? ""}/.local/bin/dsh`,
110
+ ].filter((value): value is string => typeof value === "string" && value.length > 0);
111
+
112
+ function resolveBinary(): string {
113
+ for (const candidate of BINARY_CANDIDATES) {
114
+ if (candidate.includes("/") && existsSync(candidate)) return candidate;
115
+ if (!candidate.includes("/")) return candidate;
116
+ }
117
+ return "dsh";
118
+ }
119
+
120
+ function toError(value: unknown, fallback: string): Error {
121
+ if (value instanceof Error) return value;
122
+ if (typeof value === "object" && value !== null && "message" in value) {
123
+ return new Error(String((value as { message: unknown }).message));
124
+ }
125
+ return new Error(fallback);
126
+ }
127
+
128
+ interface Pending {
129
+ resolve(value: unknown): void;
130
+ reject(error: Error): void;
131
+ }
132
+
133
+ export class DshProcess {
134
+ readonly #options: DshProcessOptions;
135
+ #child: ChildProcessWithoutNullStreams | undefined;
136
+ #buffer = "";
137
+ #pending = new Map<number, Pending>();
138
+ #nextId = 1;
139
+ #closed = false;
140
+ #initializeTask: Promise<void> | undefined;
141
+
142
+ constructor(options: DshProcessOptions) {
143
+ this.#options = options;
144
+ }
145
+
146
+ /** Spawn the child and complete `initialize`. Idempotent. */
147
+ start(): Promise<void> {
148
+ this.#initializeTask ??= this.#start();
149
+ return this.#initializeTask;
150
+ }
151
+
152
+ async #start(): Promise<void> {
153
+ const child = spawn(resolveBinary(), ["--profile", process.env.DSH_PASEO_PROFILE ?? "paseo"], {
154
+ cwd: this.#options.cwd,
155
+ stdio: ["pipe", "pipe", "pipe"],
156
+ env: { ...process.env, ...this.#options.env },
157
+ });
158
+ this.#child = child;
159
+
160
+ child.stdout.setEncoding("utf8");
161
+ child.stdout.on("data", (chunk: string) => this.#consume(chunk));
162
+ child.stderr.setEncoding("utf8");
163
+ child.stderr.on("data", (chunk: string) => {
164
+ for (const line of chunk.split("\n")) {
165
+ if (line.trim() !== "") this.#options.onLog(line);
166
+ }
167
+ });
168
+ child.on("error", (error) => {
169
+ this.#failAll(error);
170
+ this.#options.onProtocolError(error.message);
171
+ });
172
+ child.on("exit", (code, signal) => {
173
+ this.#closed = true;
174
+ this.#failAll(new Error("DeepSeek Harness process ended"));
175
+ this.#options.onExit(code, signal);
176
+ });
177
+
178
+ if (this.#options.initializeRoute === false) return;
179
+
180
+ await this.#request("initialize", {
181
+ cwd: this.#options.cwd,
182
+ provider: this.#options.route.provider,
183
+ model: this.#options.route.model,
184
+ ...(this.#options.route.reasoningEffort === undefined
185
+ ? {}
186
+ : { reasoningEffort: this.#options.route.reasoningEffort }),
187
+ });
188
+ }
189
+
190
+ /** Read the runtime's provider/model catalog without creating an agent. */
191
+ async catalog(): Promise<DshCatalog> {
192
+ return (await this.#request("paseo/catalog", {}, 60000)) as DshCatalog;
193
+ }
194
+
195
+ /** List the session's registered commands and user-invocable skills. */
196
+ async commands(): Promise<DshCommand[]> {
197
+ const result = (await this.#request(
198
+ "paseo/commands",
199
+ { sessionId: this.#options.sessionId },
200
+ 60000,
201
+ )) as { commands?: DshCommand[] };
202
+ return result.commands ?? [];
203
+ }
204
+
205
+ /** Execute one registered slash command (skills are sent as text instead). */
206
+ async runCommand(name: string, args: string): Promise<{ kind: "success" | "error"; text?: string }> {
207
+ return (await this.#request("paseo/command/run", {
208
+ sessionId: this.#options.sessionId,
209
+ name,
210
+ arguments: args,
211
+ })) as { kind: "success" | "error"; text?: string };
212
+ }
213
+
214
+ /** Send one text prompt. Resolves when the bridge accepts it, not when the turn ends. */
215
+ async prompt(
216
+ text: string,
217
+ contentBlocks?: unknown[],
218
+ delivery?: "auto" | "steer",
219
+ ): Promise<void> {
220
+ await this.#request("session/prompt", {
221
+ sessionId: this.#options.sessionId,
222
+ contentBlocks: contentBlocks ?? [{ type: "text", text }],
223
+ ...(delivery === undefined ? {} : { delivery }),
224
+ });
225
+ }
226
+
227
+ /** Cancel the running turn while keeping the session usable afterwards. */
228
+ async cancel(): Promise<void> {
229
+ await this.#request("session/cancel", { sessionId: this.#options.sessionId });
230
+ }
231
+
232
+ /** Select plan mode and return the committed state. */
233
+ async setPlan(active: boolean): Promise<{ active: boolean; pending: boolean; outcome?: string }> {
234
+ return (await this.#request("paseo/plan/set", {
235
+ sessionId: this.#options.sessionId,
236
+ active,
237
+ })) as { active: boolean; pending: boolean; outcome?: string };
238
+ }
239
+
240
+ /** Read the committed plan state. */
241
+ async getPlan(): Promise<{ active: boolean; pending: boolean; available: boolean }> {
242
+ return (await this.#request("paseo/plan/get", {
243
+ sessionId: this.#options.sessionId,
244
+ })) as { active: boolean; pending: boolean; available: boolean };
245
+ }
246
+
247
+ /** Switch model and/or reasoning effort on the live agent. */
248
+ async setConfig(changes: {
249
+ model?: string;
250
+ provider?: string;
251
+ reasoningEffort?: string | null;
252
+ }): Promise<{ provider: string; model: string; reasoningEffort: string | null }> {
253
+ return (await this.#request("paseo/config/set", {
254
+ sessionId: this.#options.sessionId,
255
+ ...changes,
256
+ })) as { provider: string; model: string; reasoningEffort: string | null };
257
+ }
258
+
259
+ /** Ask the bridge to dispose the agent and exit. */
260
+ async shutdown(): Promise<void> {
261
+ if (this.#closed) return;
262
+ try {
263
+ await this.#request("shutdown", {}, 5000);
264
+ } catch {
265
+ /* the child may exit before answering */
266
+ }
267
+ this.kill();
268
+ }
269
+
270
+ /** Terminate the child without a protocol shutdown. */
271
+ kill(): void {
272
+ this.#closed = true;
273
+ this.#child?.kill("SIGTERM");
274
+ const child = this.#child;
275
+ setTimeout(() => {
276
+ if (child !== undefined && child.exitCode === null && child.signalCode === null) {
277
+ child.kill("SIGKILL");
278
+ }
279
+ }, 4000).unref?.();
280
+ }
281
+
282
+ #request(method: string, params: unknown, timeoutMs = 120000): Promise<unknown> {
283
+ if (this.#closed || this.#child === undefined) {
284
+ return Promise.reject(new Error("DeepSeek Harness process is not running"));
285
+ }
286
+ const id = this.#nextId++;
287
+ return new Promise<unknown>((resolve, reject) => {
288
+ const timer = setTimeout(() => {
289
+ if (this.#pending.delete(id)) reject(new Error(`DeepSeek Harness did not answer ${method}`));
290
+ }, timeoutMs);
291
+ timer.unref?.();
292
+ this.#pending.set(id, {
293
+ resolve: (value) => {
294
+ clearTimeout(timer);
295
+ resolve(value);
296
+ },
297
+ reject: (error) => {
298
+ clearTimeout(timer);
299
+ reject(error);
300
+ },
301
+ });
302
+ this.#send({ jsonrpc: "2.0", id, method, params });
303
+ });
304
+ }
305
+
306
+ #send(frame: unknown): void {
307
+ try {
308
+ this.#child?.stdin.write(`${JSON.stringify(frame)}\n`);
309
+ } catch (error) {
310
+ this.#options.onProtocolError(toError(error, "failed to write to the bridge").message);
311
+ }
312
+ }
313
+
314
+ #consume(chunk: string): void {
315
+ this.#buffer += chunk;
316
+ const lines = this.#buffer.split("\n");
317
+ this.#buffer = lines.pop() ?? "";
318
+ for (const line of lines) {
319
+ if (line.trim() === "") continue;
320
+ let frame: Record<string, unknown>;
321
+ try {
322
+ frame = JSON.parse(line) as Record<string, unknown>;
323
+ } catch {
324
+ this.#options.onLog(line);
325
+ continue;
326
+ }
327
+ void this.#dispatch(frame);
328
+ }
329
+ }
330
+
331
+ async #dispatch(frame: Record<string, unknown>): Promise<void> {
332
+ const method = typeof frame.method === "string" ? frame.method : undefined;
333
+ const id = frame.id;
334
+
335
+ if (method === "paseo/question" && id !== undefined) {
336
+ try {
337
+ const params = (frame.params ?? {}) as DshQuestionRequest;
338
+ const answer = await this.#options.onQuestion({
339
+ callId: params.callId ?? null,
340
+ timed: params.timed === true,
341
+ questions: params.questions ?? [],
342
+ });
343
+ this.#send({ jsonrpc: "2.0", id, result: answer });
344
+ } catch (error) {
345
+ this.#send({
346
+ jsonrpc: "2.0",
347
+ id,
348
+ error: { code: -32000, message: toError(error, "question cancelled").message },
349
+ });
350
+ }
351
+ return;
352
+ }
353
+
354
+ if (method === "session.event") {
355
+ this.#options.onEvent(frame.params as DshSessionEvent);
356
+ return;
357
+ }
358
+ if (method === "session.status") {
359
+ const params = frame.params as { status?: string } | undefined;
360
+ this.#options.onStatus(params?.status ?? "unknown");
361
+ return;
362
+ }
363
+ if (method !== undefined) {
364
+ if (id !== undefined) {
365
+ this.#send({ jsonrpc: "2.0", id, error: { code: -32601, message: `unsupported ${method}` } });
366
+ }
367
+ return;
368
+ }
369
+
370
+ if (id !== undefined && typeof id === "number") {
371
+ const entry = this.#pending.get(id);
372
+ if (entry === undefined) return;
373
+ this.#pending.delete(id);
374
+ const error = frame.error as { message?: string } | undefined;
375
+ if (error !== undefined) entry.reject(new Error(error.message ?? "bridge request failed"));
376
+ else entry.resolve(frame.result);
377
+ }
378
+ }
379
+
380
+ #failAll(error: Error): void {
381
+ const entries = [...this.#pending.values()];
382
+ this.#pending.clear();
383
+ for (const entry of entries) entry.reject(error);
384
+ }
385
+ }
@@ -0,0 +1,326 @@
1
+ /**
2
+ * The Paseo provider that drives DeepSeek Harness through the `paseo` DSH profile.
3
+ *
4
+ * One Paseo session maps onto one `dsh --profile paseo` process, because DSH
5
+ * pins the working directory and initial route at `initialize`. The provider
6
+ * reports DSH's real catalog — providers, models and each model's adapter-owned
7
+ * reasoning efforts — so the composer offers only what the runtime can serve.
8
+ *
9
+ * @module dsh-paseo/server/provider
10
+ */
11
+ import {
12
+ negotiateProviderCapabilities,
13
+ type ProviderCatalog,
14
+ type ProviderConfigState,
15
+ type ProviderConnection,
16
+ type ProviderEvent,
17
+ type ProviderInput,
18
+ type ProviderModel,
19
+ type ProviderRegistration,
20
+ type ProviderThinkingOption,
21
+ } from "@getpaseo/plugin/server/provider";
22
+ import { DshProcess, type DshCatalog } from "./dsh-process";
23
+ import { DshSession, MODES, parseRoute } from "./session";
24
+
25
+ const CAPABILITIES = [
26
+ "prompt.message",
27
+ // Without this Paseo refuses to send any prompt carrying an image, so an
28
+ // attached picture never reaches the bridge (the same class of silent loss as
29
+ // an un-declared `prompt.steer`). The bridge already admits image blocks into
30
+ // DSH's attachment store; declaring the capability is what makes Paseo use it.
31
+ "prompt.image",
32
+ // The `/` menu is capability-gated too: without `prompt.command` Paseo never
33
+ // asks for DSH's commands, so its registered commands and user-invocable
34
+ // skills are invisible.
35
+ "prompt.command",
36
+ "prompt.steer",
37
+ "session.configure",
38
+ "permission",
39
+ ] as const;
40
+
41
+ /** Provider id registered with Paseo; distinct from the ACP `deepseek-harness` entry. */
42
+ export const PROVIDER_ID = "deepseek-harness-native";
43
+
44
+ /**
45
+ * Last-resort route. The DSH profile's `agent-default-model` is the real source
46
+ * of truth and is read from every catalog; this only backs a profile that
47
+ * composes no default at all, so it deliberately names nothing anyone runs.
48
+ */
49
+ const FALLBACK_ROUTE = { provider: "unset", model: "unset" };
50
+ const CATALOG_TTL_MS = 5 * 60 * 1000;
51
+
52
+ function messageOf(error: unknown): string {
53
+ return error instanceof Error ? error.message : String(error);
54
+ }
55
+
56
+ /** The DSH profile that must exist for this provider to work. */
57
+ function profileName(): string {
58
+ return process.env.DSH_PASEO_PROFILE ?? "paseo";
59
+ }
60
+
61
+ let catalogCache: { at: number; cwd: string; value: DisplayCatalog } | undefined;
62
+
63
+ interface DisplayCatalog {
64
+ models: ProviderModel[];
65
+ thinkingOptions: ProviderThinkingOption[];
66
+ /** The profile's configured default route, used when a session names none. */
67
+ fallbackRoute: { provider: string; model: string };
68
+ defaults: ProviderCatalog;
69
+ }
70
+
71
+ /** Read the runtime catalog through a short-lived process and cache it. */
72
+ async function loadCatalog(cwd: string): Promise<DisplayCatalog> {
73
+ if (catalogCache !== undefined && catalogCache.cwd === cwd && Date.now() - catalogCache.at < CATALOG_TTL_MS) {
74
+ return catalogCache.value;
75
+ }
76
+ const probe = new DshProcess({
77
+ cwd,
78
+ sessionId: "catalog-probe",
79
+ route: FALLBACK_ROUTE,
80
+ initializeRoute: false,
81
+ onEvent: () => {},
82
+ onStatus: () => {},
83
+ onQuestion: async () => ({ answers: [] }),
84
+ onLog: () => {},
85
+ onExit: () => {},
86
+ onProtocolError: () => {},
87
+ });
88
+ try {
89
+ await probe.start();
90
+ const raw: DshCatalog = await probe.catalog();
91
+ const value = toDisplayCatalog(raw);
92
+ catalogCache = { at: Date.now(), cwd, value };
93
+ return value;
94
+ } finally {
95
+ probe.kill();
96
+ }
97
+ }
98
+
99
+ function toDisplayCatalog(raw: DshCatalog): DisplayCatalog {
100
+ const providerName = new Map(raw.providers.map((entry) => [entry.id, entry.name]));
101
+ const models: ProviderModel[] = raw.models.map((model) => {
102
+ const thinkingOptions = (model.reasoning?.efforts ?? []).map((effort) => ({
103
+ id: effort.id,
104
+ label: effort.name,
105
+ ...(effort.description === undefined ? {} : { description: effort.description }),
106
+ }));
107
+ return {
108
+ // `provider/model` survives the round trip because DSH model ids carry no slash.
109
+ id: `${model.provider}/${model.id}`,
110
+ label: model.name,
111
+ description: providerName.get(model.provider) ?? model.provider,
112
+ ...(model.description === undefined ? {} : {}),
113
+ ...(model.reasoning?.defaultEffort === undefined || thinkingOptions.length === 0
114
+ ? {}
115
+ : {
116
+ defaultThinkingOptionId: thinkingOptions.some((option) => option.id === model.reasoning?.defaultEffort)
117
+ ? model.reasoning.defaultEffort
118
+ : thinkingOptions[0]?.id,
119
+ }),
120
+ ...(thinkingOptions.length === 0 ? {} : { thinkingOptions }),
121
+ };
122
+ });
123
+
124
+ // Provider-wide options, so they must be ones *every* model declares. A union
125
+ // offered the composer efforts some models cannot serve, and every dropped
126
+ // choice snapped the selector back to off. Models keep their own list, so the
127
+ // ones that do reason still show their real levels.
128
+ const thinkingOptions: ProviderThinkingOption[] = (models[0]?.thinkingOptions ?? []).filter((option) =>
129
+ models.every((model) => (model.thinkingOptions ?? []).some((entry) => entry.id === option.id)),
130
+ );
131
+
132
+ const defaultModel =
133
+ raw.defaultProvider !== undefined && raw.defaultModel !== undefined
134
+ ? `${raw.defaultProvider}/${raw.defaultModel}`
135
+ : models[0]?.id;
136
+
137
+ return {
138
+ models,
139
+ thinkingOptions,
140
+ fallbackRoute:
141
+ raw.defaultProvider !== undefined && raw.defaultModel !== undefined
142
+ ? { provider: raw.defaultProvider, model: raw.defaultModel }
143
+ : FALLBACK_ROUTE,
144
+ defaults: {
145
+ models,
146
+ modes: MODES,
147
+ thinkingOptions,
148
+ ...(defaultModel === undefined ? {} : { defaultModel }),
149
+ defaultMode: "build",
150
+ ...(raw.defaultReasoningEffort === undefined || raw.defaultReasoningEffort === null
151
+ ? {}
152
+ : { defaultThinkingOption: raw.defaultReasoningEffort }),
153
+ },
154
+ };
155
+ }
156
+
157
+ class DshConnection implements ProviderConnection {
158
+ readonly version = 1;
159
+ readonly capabilities: readonly string[];
160
+ readonly #listeners = new Set<(event: ProviderEvent) => void>();
161
+ readonly #sessions = new Map<string, DshSession>();
162
+ #display: DisplayCatalog | undefined;
163
+ #closed = false;
164
+
165
+ constructor(capabilities: readonly string[]) {
166
+ this.capabilities = capabilities;
167
+ }
168
+
169
+ onEvent(listener: (event: ProviderEvent) => void): () => void {
170
+ this.#listeners.add(listener);
171
+ return () => {
172
+ this.#listeners.delete(listener);
173
+ };
174
+ }
175
+
176
+ async send(input: ProviderInput): Promise<void> {
177
+ if (this.#closed) return;
178
+ try {
179
+ await this.#dispatch(input);
180
+ } catch (error) {
181
+ const message = messageOf(error);
182
+ if ("requestId" in input && typeof input.requestId === "string") {
183
+ this.#emit({ type: "request.failed", requestId: input.requestId, error: { message } });
184
+ } else if ("sessionId" in input && typeof input.sessionId === "string") {
185
+ this.#emit({ type: "session.runtime_failed", sessionId: input.sessionId, error: { message } });
186
+ }
187
+ }
188
+ }
189
+
190
+ async close(): Promise<void> {
191
+ this.#closed = true;
192
+ const sessions = [...this.#sessions.values()];
193
+ this.#sessions.clear();
194
+ await Promise.allSettled(sessions.map((session) => session.close()));
195
+ }
196
+
197
+ async #dispatch(input: ProviderInput): Promise<void> {
198
+ switch (input.type) {
199
+ case "catalog":
200
+ return this.#catalog(input.requestId, input.cwd);
201
+ case "session.open":
202
+ return this.#open(input);
203
+ case "session.prompt":
204
+ return this.#require(input.sessionId).prompt(input.prompt);
205
+ case "session.permission":
206
+ this.#require(input.sessionId).resolvePermission(input.permissionId, input.response);
207
+ return;
208
+ case "session.configure": {
209
+ const session = this.#require(input.sessionId);
210
+ await session.configure(input.changes);
211
+ this.#emit({ type: "session.config", sessionId: input.sessionId, config: session.configState() });
212
+ this.#emit({ type: "request.completed", requestId: input.requestId });
213
+ return;
214
+ }
215
+ case "session.interrupt": {
216
+ await this.#require(input.sessionId).interrupt();
217
+ this.#emit({ type: "request.completed", requestId: input.requestId });
218
+ return;
219
+ }
220
+ case "session.close": {
221
+ const session = this.#sessions.get(input.sessionId);
222
+ this.#sessions.delete(input.sessionId);
223
+ await session?.close();
224
+ this.#emit({ type: "session.closed", sessionId: input.sessionId });
225
+ this.#emit({ type: "request.completed", requestId: input.requestId });
226
+ return;
227
+ }
228
+ default:
229
+ // This provider declares no capability for the input, so the caller must
230
+ // not be told it succeeded. Reporting `request.completed` here made an
231
+ // unimplemented request indistinguishable from a finished one.
232
+ this.#emit({
233
+ type: "request.failed",
234
+ requestId: input.requestId,
235
+ error: { message: `unsupported provider input "${input.type}"` },
236
+ });
237
+ }
238
+ }
239
+
240
+ async #catalog(requestId: string, cwd: string | undefined): Promise<void> {
241
+ const display = await loadCatalog(cwd ?? process.cwd());
242
+ this.#display = display;
243
+ this.#emit({ type: "catalog", requestId, catalog: display.defaults });
244
+ }
245
+
246
+ async #open(input: Extract<ProviderInput, { type: "session.open" }>): Promise<void> {
247
+ const { sessionId, config } = input;
248
+ const display = this.#display ?? (await loadCatalog(config.cwd));
249
+ this.#display = display;
250
+
251
+ const route = parseRoute(config.model, display.fallbackRoute);
252
+ const session = new DshSession({
253
+ sessionId,
254
+ cwd: config.cwd,
255
+ env: config.env ?? {},
256
+ route,
257
+ mode: config.mode ?? "build",
258
+ models: display.models,
259
+ thinkingOptions: display.thinkingOptions,
260
+ emit: (event) => this.#emit(event),
261
+ log: (line) => {
262
+ process.stderr.write(`[${PROVIDER_ID}] ${line}\n`);
263
+ },
264
+ });
265
+ this.#sessions.set(sessionId, session);
266
+
267
+ await session.open();
268
+
269
+ if (config.thinkingOption !== undefined) {
270
+ await session.configure({ thinkingOption: config.thinkingOption });
271
+ }
272
+
273
+ // Advertise the `/` menu before `session.ready` so the composer has it the
274
+ // moment the session is usable. A command catalog is an enhancement, never a
275
+ // precondition: a discovery failure logs and leaves the menu empty rather
276
+ // than failing the whole open.
277
+ try {
278
+ await session.loadCommands();
279
+ } catch (error) {
280
+ process.stderr.write(`[${PROVIDER_ID}] command catalog failed: ${messageOf(error)}\n`);
281
+ }
282
+
283
+ this.#emit({
284
+ type: "session.opened",
285
+ requestId: input.requestId,
286
+ sessionId,
287
+ capabilities: [...this.capabilities],
288
+ restoration: "core",
289
+ cwd: config.cwd,
290
+ ...(config.title === undefined ? {} : { title: config.title }),
291
+ });
292
+ this.#emit({ type: "session.config", sessionId, config: session.configState() });
293
+ this.#emit({ type: "session.ready", requestId: input.requestId, sessionId });
294
+ }
295
+
296
+ #require(sessionId: string): DshSession {
297
+ const session = this.#sessions.get(sessionId);
298
+ if (session === undefined) throw new Error(`unknown session: ${sessionId}`);
299
+ return session;
300
+ }
301
+
302
+ #emit(event: ProviderEvent): void {
303
+ for (const listener of [...this.#listeners]) {
304
+ try {
305
+ listener(event);
306
+ } catch (error) {
307
+ process.stderr.write(`[${PROVIDER_ID}] listener failed: ${messageOf(error)}\n`);
308
+ }
309
+ }
310
+ }
311
+ }
312
+
313
+ /** The provider registration Paseo installs for `dsh --profile paseo`. */
314
+ export function createDshProvider(): ProviderRegistration {
315
+ return {
316
+ id: PROVIDER_ID,
317
+ label: "DeepSeek Harness (native)",
318
+ icon: "icon.svg",
319
+ async connect(request) {
320
+ const capabilities = negotiateProviderCapabilities(request.capabilities, CAPABILITIES);
321
+ return new DshConnection(capabilities);
322
+ },
323
+ };
324
+ }
325
+
326
+ export { profileName };