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,566 @@
1
+ /**
2
+ * One Paseo agent session backed by one `dsh --profile paseo` process.
3
+ *
4
+ * The session translates between Paseo's provider vocabulary (models, modes,
5
+ * thinking options, permission cards) and the bridge's JSON-RPC surface.
6
+ *
7
+ * @module dsh-paseo/server/session
8
+ */
9
+ import type {
10
+ ProviderConfigChanges,
11
+ ProviderConfigState,
12
+ ProviderContent,
13
+ ProviderEvent,
14
+ ProviderMode,
15
+ ProviderModel,
16
+ ProviderPermissionRequest,
17
+ ProviderPermissionResponse,
18
+ ProviderPrompt,
19
+ ProviderSetting,
20
+ ProviderThinkingOption,
21
+ ProviderToolCallDetail,
22
+ ProviderUsage,
23
+ } from "@getpaseo/plugin/server/provider";
24
+ import type { JsonValue } from "@getpaseo/protocol/agent-types";
25
+ import { DshProcess, type DshAnswer, type DshQuestion, type DshQuestionRequest, type DshRoute } from "./dsh-process";
26
+ import { TimelineBuilder } from "./timeline";
27
+
28
+ /** Modes Paseo offers in the composer. `plan` drives DSH's plan-mode service. */
29
+ export const MODES: ProviderMode[] = [
30
+ { id: "build", label: "Build", description: "Investigate and implement changes directly." },
31
+ {
32
+ id: "plan",
33
+ label: "Plan",
34
+ description: "Investigate, then submit a plan for approval before implementing.",
35
+ },
36
+ ];
37
+
38
+ export interface DshSessionOptions {
39
+ sessionId: string;
40
+ cwd: string;
41
+ env: Record<string, string>;
42
+ route: DshRoute;
43
+ mode: string;
44
+ /** Models Paseo can switch to for this session, from the cached catalog. */
45
+ models: ProviderModel[];
46
+ /** Thinking options the catalog advertises. */
47
+ thinkingOptions: ProviderThinkingOption[];
48
+ emit(event: ProviderEvent): void;
49
+ log(line: string): void;
50
+ }
51
+
52
+ function messageOf(error: unknown): string {
53
+ return error instanceof Error ? error.message : String(error);
54
+ }
55
+
56
+ function isRecord(value: unknown): value is Record<string, unknown> {
57
+ return typeof value === "object" && value !== null;
58
+ }
59
+
60
+ /** Resolve Paseo's catalog id (`provider/model`) back into a DSH route. */
61
+ export function parseRoute(model: string | undefined, fallback: DshRoute): DshRoute {
62
+ if (model === undefined || model === "") return fallback;
63
+ const slash = model.indexOf("/");
64
+ if (slash <= 0) return { ...fallback, model };
65
+ return { provider: model.slice(0, slash), model: model.slice(slash + 1) };
66
+ }
67
+
68
+ export class DshSession {
69
+ readonly id: string;
70
+ readonly #options: DshSessionOptions;
71
+ readonly #timeline = new TimelineBuilder();
72
+ #process: DshProcess | undefined;
73
+ #route: DshRoute;
74
+ #mode: string;
75
+ #thinkingOption: string | undefined;
76
+ #turnId: string | null = null;
77
+ #pendingPermissions = new Map<string, (response: ProviderPermissionResponse) => void>();
78
+ /** Slash-menu entries by name, tagging why each exists. */
79
+ #commandKinds = new Map<string, "command" | "skill">();
80
+ #closed = false;
81
+
82
+ constructor(options: DshSessionOptions) {
83
+ this.id = options.sessionId;
84
+ this.#options = options;
85
+ this.#route = options.route;
86
+ this.#mode = options.mode === "plan" ? "plan" : "build";
87
+ this.#thinkingOption = options.route.reasoningEffort;
88
+ }
89
+
90
+ /** Spawn the process, pin the route, and reconcile the requested mode. */
91
+ async open(): Promise<void> {
92
+ const process = new DshProcess({
93
+ cwd: this.#options.cwd,
94
+ route: this.#route,
95
+ sessionId: this.id,
96
+ env: this.#options.env,
97
+ onEvent: (payload) => this.#onSessionEvent(payload),
98
+ onStatus: (status) => this.#onStatus(status),
99
+ onQuestion: (request) => this.#onQuestion(request),
100
+ onLog: (line) => this.#options.log(line),
101
+ onExit: (code, signal) => {
102
+ if (this.#closed) return;
103
+ this.#closed = true;
104
+ this.#options.emit({
105
+ type: "session.runtime_failed",
106
+ sessionId: this.id,
107
+ error: { message: `DeepSeek Harness exited (code ${code ?? "null"}, signal ${signal ?? "none"})` },
108
+ });
109
+ },
110
+ onProtocolError: (message) => this.#options.log(`protocol: ${message}`),
111
+ });
112
+ this.#process = process;
113
+ await process.start();
114
+ if (this.#mode === "plan") {
115
+ await process.setPlan(true);
116
+ }
117
+ }
118
+
119
+ /** The committed configuration Paseo renders in the composer. */
120
+ configState(): ProviderConfigState {
121
+ const settings: ProviderSetting[] = [];
122
+ const thinkingOptions = this.#thinking();
123
+ return {
124
+ model: `${this.#route.provider}/${this.#route.model}`,
125
+ mode: this.#mode,
126
+ ...(this.#thinkingOption === undefined ? {} : { thinkingOption: this.#thinkingOption }),
127
+ models: this.#models(),
128
+ modes: MODES,
129
+ thinkingOptions,
130
+ settings,
131
+ };
132
+ }
133
+
134
+ #models(): ProviderModel[] {
135
+ return this.#options.models;
136
+ }
137
+
138
+ /**
139
+ * The current model's own thinking options. Reporting a global fallback made
140
+ * the composer offer efforts the model cannot serve, and every dropped choice
141
+ * snapped the selector back to off.
142
+ */
143
+ #thinking(): ProviderThinkingOption[] {
144
+ const id = `${this.#route.provider}/${this.#route.model}`;
145
+ return this.#options.models.find((entry) => entry.id === id)?.thinkingOptions ?? [];
146
+ }
147
+
148
+ /** Thinking-effort ids the current model actually declares; empty means none. */
149
+ #supportedEfforts(): string[] {
150
+ return this.#thinking().map((option) => option.id);
151
+ }
152
+
153
+ /**
154
+ * Publish the session's `/` menu: DSH's registered human commands plus every
155
+ * user-invocable skill.
156
+ *
157
+ * Both appear in the composer's slash menu, but they run differently, so the
158
+ * kind is remembered for {@link prompt}: a command executes in the runtime, a
159
+ * skill rides a `/name` user message.
160
+ */
161
+ async loadCommands(): Promise<void> {
162
+ const commands = await this.#require().commands();
163
+ this.#commandKinds.clear();
164
+ for (const command of commands) this.#commandKinds.set(command.name, command.kind);
165
+ this.#options.emit({
166
+ type: "session.commands",
167
+ sessionId: this.id,
168
+ commands: commands.map((command) => ({
169
+ name: command.name,
170
+ description: command.description,
171
+ ...(command.argumentHint === undefined ? {} : { argumentHint: command.argumentHint }),
172
+ })),
173
+ });
174
+ }
175
+
176
+ /** Accept one prompt and start its turn. */
177
+ async prompt(prompt: ProviderPrompt): Promise<void> {
178
+ const process = this.#require();
179
+
180
+ // A slash-menu pick arrives as a command, not a message. DSH commands and
181
+ // skills share the menu but not the execution path, so branch on the kind
182
+ // the catalog recorded rather than on the name.
183
+ if (prompt.input.type === "command") {
184
+ const args = prompt.input.arguments ?? "";
185
+ const line = args.trim() === "" ? `/${prompt.input.name}` : `/${prompt.input.name} ${args}`;
186
+ this.#emitUserMessage(prompt.clientMessageId, line);
187
+
188
+ if (this.#commandKinds.get(prompt.input.name) === "command") {
189
+ try {
190
+ const result = await process.runCommand(prompt.input.name, args);
191
+ if (result.kind === "error") throw new Error(result.text ?? `/${prompt.input.name} failed`);
192
+ } catch (error) {
193
+ this.#emitPromptFailed(prompt.clientMessageId, error);
194
+ return;
195
+ }
196
+ // A command answers with its own timeline items rather than a turn.
197
+ this.#options.emit({
198
+ type: "session.prompt_result",
199
+ sessionId: this.id,
200
+ clientMessageId: prompt.clientMessageId,
201
+ result: { type: "completed" },
202
+ });
203
+ return;
204
+ }
205
+
206
+ // A skill (or an unrecognized name): hand DSH the bare `/name` line. Its
207
+ // skill tool injects a user-invocable skill from exactly that token.
208
+ try {
209
+ await process.prompt(line, [{ type: "text", text: line }], prompt.delivery);
210
+ } catch (error) {
211
+ this.#emitPromptFailed(prompt.clientMessageId, error);
212
+ return;
213
+ }
214
+ this.#emitPromptAccepted(prompt.clientMessageId);
215
+ return;
216
+ }
217
+
218
+ // Paseo and the bridge already agree on the text/image block shape, so the
219
+ // blocks ride through untouched. They used to be collapsed to a text label,
220
+ // which silently discarded every non-text attachment.
221
+ const blocks = prompt.input.content.map(toDshContent);
222
+ const label = blocks
223
+ .map((block) => (block.type === "text" ? (block.text as string) : ""))
224
+ .filter((text) => text !== "")
225
+ .join("\n");
226
+
227
+ this.#emitUserMessage(prompt.clientMessageId, label);
228
+
229
+ try {
230
+ await process.prompt(label, blocks.length === 0 ? undefined : blocks, prompt.delivery);
231
+ } catch (error) {
232
+ this.#emitPromptFailed(prompt.clientMessageId, error);
233
+ return;
234
+ }
235
+
236
+ this.#emitPromptAccepted(prompt.clientMessageId);
237
+ }
238
+
239
+ #emitUserMessage(clientMessageId: string, text: string): void {
240
+ this.#options.emit({
241
+ type: "timeline.item",
242
+ sessionId: this.id,
243
+ item: { type: "user_message", id: `user:${clientMessageId}`, text, clientMessageId },
244
+ });
245
+ }
246
+
247
+ #emitPromptFailed(clientMessageId: string, error: unknown): void {
248
+ this.#options.emit({
249
+ type: "session.prompt_result",
250
+ sessionId: this.id,
251
+ clientMessageId,
252
+ result: { type: "failed", error: { message: messageOf(error) } },
253
+ });
254
+ }
255
+
256
+ #emitPromptAccepted(clientMessageId: string): void {
257
+ const turnId = this.#turnId ?? `turn:${clientMessageId}`;
258
+ this.#options.emit({
259
+ type: "session.prompt_result",
260
+ sessionId: this.id,
261
+ clientMessageId,
262
+ result: { type: "turn", turnId },
263
+ });
264
+ }
265
+
266
+ /** Apply a composer change: model, mode, thinking option or settings. */
267
+ async configure(changes: ProviderConfigChanges): Promise<void> {
268
+ const process = this.#require();
269
+
270
+ if (changes.model !== undefined && changes.model !== null) {
271
+ const next = parseRoute(changes.model, this.#route);
272
+ this.#route = next;
273
+ await process.setConfig({
274
+ provider: next.provider,
275
+ model: next.model,
276
+ reasoningEffort: next.reasoningEffort ?? null,
277
+ });
278
+ }
279
+
280
+ if (changes.thinkingOption !== undefined) {
281
+ const requested =
282
+ changes.thinkingOption === null || changes.thinkingOption === "" ? undefined : changes.thinkingOption;
283
+ // The runtime rejects a whole turn when handed an effort the model does not
284
+ // declare, and Paseo can carry a stale selection across a model switch.
285
+ // Serve only what this model advertises and drop anything else.
286
+ const supported = this.#supportedEfforts();
287
+ const effort = requested !== undefined && supported.includes(requested) ? requested : undefined;
288
+ if (requested !== undefined && effort === undefined) {
289
+ this.#options.log(
290
+ `ignoring unsupported thinking option "${requested}" for ${this.#route.provider}/${this.#route.model}`,
291
+ );
292
+ }
293
+ this.#thinkingOption = effort;
294
+ const applied = await process.setConfig({
295
+ provider: this.#route.provider,
296
+ model: this.#route.model,
297
+ reasoningEffort: effort ?? null,
298
+ });
299
+ this.#route = {
300
+ provider: applied.provider,
301
+ model: applied.model,
302
+ ...(applied.reasoningEffort === null ? {} : { reasoningEffort: applied.reasoningEffort }),
303
+ };
304
+ }
305
+
306
+ if (changes.mode !== undefined && changes.mode !== null) {
307
+ this.#mode = changes.mode === "plan" ? "plan" : "build";
308
+ await process.setPlan(this.#mode === "plan");
309
+ }
310
+ }
311
+
312
+ /** Answer a pending question card. */
313
+ resolvePermission(permissionId: string, response: ProviderPermissionResponse): void {
314
+ const resolve = this.#pendingPermissions.get(permissionId);
315
+ if (resolve === undefined) return;
316
+ this.#pendingPermissions.delete(permissionId);
317
+ this.#options.emit({ type: "session.permission_resolved", sessionId: this.id, permissionId });
318
+ resolve(response);
319
+ }
320
+
321
+ /**
322
+ * Cancel the running turn. The session and its history survive, so the
323
+ * conversation stays continuable — killing the process stranded it instead.
324
+ */
325
+ async interrupt(): Promise<void> {
326
+ await this.#require().cancel();
327
+ }
328
+
329
+ /** Release the process. */
330
+ async close(): Promise<void> {
331
+ if (this.#closed) return;
332
+ this.#closed = true;
333
+ await this.#process?.shutdown();
334
+ }
335
+
336
+ #require(): DshProcess {
337
+ if (this.#process === undefined || this.#closed) {
338
+ throw new Error(`session ${this.id} is not open`);
339
+ }
340
+ return this.#process;
341
+ }
342
+
343
+ #onStatus(status: string): void {
344
+ if (status === "running") {
345
+ const turnId = this.#turnId ?? `turn:${Date.now()}`;
346
+ this.#turnId = turnId;
347
+ this.#options.emit({ type: "session.turn", sessionId: this.id, turnId, state: "started" });
348
+ return;
349
+ }
350
+ if (this.#turnId !== null) {
351
+ const turnId = this.#turnId;
352
+ this.#turnId = null;
353
+ this.#options.emit({ type: "session.turn", sessionId: this.id, turnId, state: "completed" });
354
+ }
355
+ }
356
+
357
+ #onSessionEvent(payload: { event: { type: string; [key: string]: unknown } }): void {
358
+ const event = payload.event;
359
+ // The model can leave plan mode on its own, for example by submitting a plan
360
+ // for approval. Mirror that into the composer's mode selection so the toggle
361
+ // never disagrees with the runtime.
362
+ if (event.type === "plan/mode") {
363
+ const data = isRecord(event.data) ? event.data : {};
364
+ const next = data.active === true ? "plan" : "build";
365
+ if (next !== this.#mode) {
366
+ this.#mode = next;
367
+ this.#options.emit({ type: "session.config", sessionId: this.id, config: this.configState() });
368
+ }
369
+ return;
370
+ }
371
+ // DSH reports token accounting on the assistant message and nowhere else, so
372
+ // without this the composer's usage readout never had anything to show.
373
+ if (event.type === "assistant/message") {
374
+ const data = isRecord(event.data) ? event.data : {};
375
+ if (isRecord(data.usage)) {
376
+ this.#options.emit({
377
+ type: "session.usage",
378
+ sessionId: this.id,
379
+ ...(this.#turnId === null ? {} : { turnId: this.#turnId }),
380
+ usage: providerUsage(data.usage),
381
+ });
382
+ }
383
+ }
384
+ for (const item of this.#timeline.consume(event)) {
385
+ this.#options.emit({ type: "timeline.item", sessionId: this.id, item });
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Turn one DSH question request into a single Paseo permission card. Paseo's
391
+ * shared picker steps through every entry of `input.questions` and submits all
392
+ * answers together, so splitting questions across cards forced one submission
393
+ * each. Its own providers bundle them the same way.
394
+ */
395
+ async #onQuestion(request: DshQuestionRequest): Promise<DshAnswer> {
396
+ const headers = request.questions.map((question, index) => headerOf(question, index));
397
+ const planIndex = request.questions.findIndex((question) => question.intent?.kind === "plan-review");
398
+ const response =
399
+ planIndex < 0
400
+ ? await this.#askQuestions(request, headers)
401
+ : await this.#reviewPlan(request, request.questions[planIndex] as DshQuestion);
402
+
403
+ const answers = request.questions.map((question, index) => ({
404
+ id: question.id,
405
+ selected:
406
+ index === planIndex
407
+ ? planAnswer(question, response)
408
+ : selectAnswer(question, headers[index] as string, response),
409
+ ...(response.behavior === "deny" && response.message !== undefined
410
+ ? { custom: response.message }
411
+ : {}),
412
+ }));
413
+
414
+ return { answers };
415
+ }
416
+
417
+ /** One card carrying every question, answered in a single submission. */
418
+ #askQuestions(
419
+ request: DshQuestionRequest,
420
+ headers: string[],
421
+ ): Promise<ProviderPermissionResponse> {
422
+ const permission: ProviderPermissionRequest = {
423
+ id: request.callId ?? "question",
424
+ name: "ask_user_question",
425
+ kind: "question",
426
+ title: request.questions.length === 1 ? (headers[0] as string) : "Questions",
427
+ input: {
428
+ questions: request.questions.map((question, index) => ({
429
+ question: question.question,
430
+ header: headers[index] as string,
431
+ options: (question.options ?? []).map((option) => ({
432
+ label: option.label,
433
+ ...(typeof option.description === "string" && option.description.length > 0
434
+ ? { description: option.description }
435
+ : {}),
436
+ })),
437
+ ...(question.multiSelect === true ? { multiSelect: true } : {}),
438
+ allowOther: true,
439
+ })),
440
+ } as unknown as Readonly<Record<string, JsonValue>>,
441
+ };
442
+
443
+ return this.#openCard(permission);
444
+ }
445
+
446
+ /**
447
+ * Plan review, shaped exactly like Paseo's own Codex plan approval: the plan
448
+ * rides in `input.plan` and two buttons decide it. The plan itself is also
449
+ * emitted as a timeline `plan` item so it stays readable before the choice.
450
+ */
451
+ #reviewPlan(
452
+ request: DshQuestionRequest,
453
+ question: DshQuestion,
454
+ ): Promise<ProviderPermissionResponse> {
455
+ const permission: ProviderPermissionRequest = {
456
+ id: `${request.callId ?? "question"}:${question.id}`,
457
+ name: "exit_plan_mode",
458
+ kind: "plan",
459
+ title: "Plan",
460
+ description: "Review the proposed plan before implementation starts.",
461
+ input: {
462
+ plan: typeof question.detail === "string" ? question.detail : "",
463
+ ...(question.intent === undefined ? {} : { intent: question.intent }),
464
+ } as unknown as Readonly<Record<string, JsonValue>>,
465
+ actions: [
466
+ { id: "dismiss", label: "Dismiss", behavior: "deny", variant: "danger", intent: "dismiss" },
467
+ {
468
+ id: "implement",
469
+ label: "Implement",
470
+ behavior: "allow",
471
+ variant: "primary",
472
+ intent: "implement",
473
+ },
474
+ ],
475
+ };
476
+
477
+ return this.#openCard(permission);
478
+ }
479
+
480
+ #openCard(permission: ProviderPermissionRequest): Promise<ProviderPermissionResponse> {
481
+ return new Promise<ProviderPermissionResponse>((resolve) => {
482
+ this.#pendingPermissions.set(permission.id, resolve);
483
+ this.#options.emit({ type: "session.permission", sessionId: this.id, request: permission });
484
+ });
485
+ }
486
+ }
487
+
488
+ /**
489
+ * Translate one Paseo content block into the shape the bridge hands DSH.
490
+ *
491
+ * A block with no DSH counterpart fails loudly rather than being dropped: the
492
+ * model would otherwise receive a prompt silently missing its evidence.
493
+ */
494
+ function toDshContent(block: ProviderContent): Record<string, unknown> {
495
+ if (block.type === "text") return { type: "text", text: block.text };
496
+ if (block.type === "image") return { type: "image", data: block.data, mimeType: block.mimeType };
497
+ throw new Error(`unsupported prompt content type "${block.type}"`);
498
+ }
499
+
500
+ /**
501
+ * Map DSH's per-step token accounting onto Paseo's usage fields.
502
+ *
503
+ * DSH attaches usage to the assistant message because it keeps no separate usage
504
+ * record, so this is the only place the numbers exist to forward.
505
+ */
506
+ function providerUsage(raw: Record<string, unknown>): ProviderUsage {
507
+ return {
508
+ ...(typeof raw.inputTokens === "number" ? { inputTokens: raw.inputTokens } : {}),
509
+ ...(typeof raw.cacheReadTokens === "number" ? { cachedInputTokens: raw.cacheReadTokens } : {}),
510
+ ...(typeof raw.outputTokens === "number" ? { outputTokens: raw.outputTokens } : {}),
511
+ };
512
+ }
513
+
514
+ /**
515
+ * Answer key Paseo's shared question UI returns under `updatedInput.answers`.
516
+ * Questions without a header still need a distinct key, so the position is used.
517
+ */
518
+ function headerOf(question: DshQuestion, index: number): string {
519
+ if (typeof question.header === "string" && question.header.trim().length > 0) return question.header;
520
+ if (typeof question.id === "string" && question.id.trim().length > 0) return question.id;
521
+ return `Question ${index + 1}`;
522
+ }
523
+
524
+ /**
525
+ * Recover the chosen labels from a permission response. Paseo answers through
526
+ * `updatedInput.answers[<header>]` — a string, comma-joined when multi-select —
527
+ * so `selectedActionId` is only a fallback for button-style resolutions.
528
+ */
529
+ function selectAnswer(
530
+ question: DshQuestion,
531
+ header: string,
532
+ response: ProviderPermissionResponse,
533
+ ): string[] {
534
+ if (response.behavior === "deny") return [];
535
+ const answers = isRecord(response.updatedInput) ? response.updatedInput["answers"] : undefined;
536
+ const raw = isRecord(answers) ? answers[header] : undefined;
537
+ if (typeof raw === "string" && raw.trim().length > 0) {
538
+ if (question.multiSelect === true) {
539
+ return raw
540
+ .split(",")
541
+ .map((entry) => entry.trim())
542
+ .filter((entry) => entry.length > 0);
543
+ }
544
+ return [raw.trim()];
545
+ }
546
+ const options = question.options ?? [];
547
+ const index = Number(response.selectedActionId);
548
+ const label = Number.isInteger(index) ? options[index]?.label : undefined;
549
+ return label === undefined ? [] : [label];
550
+ }
551
+
552
+ /**
553
+ * Decide a plan review. Only the `implement` button approves; anything else —
554
+ * including a dismissal — names the non-approval option so the model is told to
555
+ * revise the plan rather than to start implementing it.
556
+ */
557
+ function planAnswer(question: DshQuestion, response: ProviderPermissionResponse): string[] {
558
+ const picked = selectAnswer(question, headerOf(question, 0), response);
559
+ if (picked.length > 0) return picked;
560
+ const approve = question.intent?.approve;
561
+ if (response.behavior === "allow" && response.selectedActionId === "implement") {
562
+ return approve === undefined ? [] : [approve];
563
+ }
564
+ const keep = (question.options ?? []).find((option) => option.label !== approve)?.label;
565
+ return keep === undefined ? [] : [keep];
566
+ }