paseo-dsh 0.2.17 → 0.2.18

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/server/session.ts CHANGED
@@ -30,6 +30,8 @@ import {
30
30
  type DshQuestionRequest,
31
31
  type DshAssistantFrame,
32
32
  type DshRoute,
33
+ type DshSessionEvent,
34
+ type DshStatusEvent,
33
35
  type DshUsage,
34
36
  } from "./dsh-process";
35
37
  import { TimelineBuilder } from "./timeline";
@@ -56,10 +58,21 @@ export interface DshSessionOptions {
56
58
  env: Record<string, string>;
57
59
  route: DshRoute;
58
60
  mode: string;
61
+ /**
62
+ * Agent preset this session should be created under. Applied inside `open()`,
63
+ * before `initialize`, so the agent is composed with it — the only moment DSH
64
+ * both accepts the choice and writes it into the session header.
65
+ */
66
+ initialPreset?: string;
59
67
  /** Models Paseo can switch to for this session, from the cached catalog. */
60
68
  models: ProviderModel[];
61
69
  /** Thinking options the catalog advertises. */
62
70
  thinkingOptions: ProviderThinkingOption[];
71
+ /**
72
+ * Capabilities negotiated for the parent session. Child sessions opened by
73
+ * DSH subagents must advertise the same set so Paseo accepts them.
74
+ */
75
+ capabilities: readonly string[];
63
76
  emit(event: ProviderEvent): void;
64
77
  log(line: string): void;
65
78
  }
@@ -72,6 +85,18 @@ function isRecord(value: unknown): value is Record<string, unknown> {
72
85
  return typeof value === "object" && value !== null;
73
86
  }
74
87
 
88
+ /** Tool-call arguments arrive as a JSON string in the durable session log. */
89
+ function parseToolArguments(raw: unknown): Record<string, unknown> {
90
+ if (isRecord(raw)) return raw;
91
+ if (typeof raw !== "string" || raw.trim() === "") return {};
92
+ try {
93
+ const parsed: unknown = JSON.parse(raw);
94
+ return isRecord(parsed) ? parsed : {};
95
+ } catch {
96
+ return {};
97
+ }
98
+ }
99
+
75
100
  /** Concatenate the text blocks of a DSH message's content. */
76
101
  function textBlocks(content: unknown): string {
77
102
  if (!Array.isArray(content)) return "";
@@ -90,12 +115,45 @@ export function parseRoute(model: string | undefined, fallback: DshRoute): DshRo
90
115
  return { provider: model.slice(0, slash), model: model.slice(slash + 1) };
91
116
  }
92
117
 
118
+ /** One DSH subagent child session observed through the bridge. */
119
+ interface ChildSessionState {
120
+ id: string;
121
+ timeline: TimelineBuilder;
122
+ cwd: string;
123
+ title?: string;
124
+ /** Parent tool call that spawned this child, once its result reveals it. */
125
+ toolCallId?: string;
126
+ opened: boolean;
127
+ turnId: string | null;
128
+ /** A terminal turn state was already reported for the current turn. */
129
+ finished: boolean;
130
+ /** Events seen before Paseo accepted the child session. */
131
+ pending: Array<{ kind: "event"; payload: DshSessionEvent } | { kind: "status"; status: string }>;
132
+ openTimer?: ReturnType<typeof setTimeout>;
133
+ }
134
+
93
135
  export class DshSession {
94
136
  readonly id: string;
95
137
  /** DSH's session id (see {@link DshSessionOptions.dshSessionId}). */
96
- readonly #dshSessionId: string;
138
+ #dshSessionId: string;
139
+ /** Previous session ids whose buffered events may still arrive after a rewind. */
140
+ #retiredSessionIds = new Set<string>();
97
141
  readonly #options: DshSessionOptions;
98
142
  readonly #timeline = new TimelineBuilder();
143
+ /** DSH subagent child sessions, keyed by their own DSH session id. */
144
+ #children = new Map<string, ChildSessionState>();
145
+ /** Parent subagent tool calls waiting for their `started subagent <id>` result. */
146
+ #pendingSubagentCalls = new Map<string, { description?: string }>();
147
+ /**
148
+ * Prompts whose user message had no durable seq when the bridge accepted it.
149
+ * The seq arrives later as a session event; the same row is re-emitted then
150
+ * so a message queued behind a long turn still becomes rewindable.
151
+ */
152
+ #pendingUserMessages = new Map<string, { clientMessageId: string; text: string }>();
153
+ /** User events that arrived before their prompt response carried a seq. */
154
+ #recentUserMessageSeqs = new Map<string, number>();
155
+ #childTurnSeq = 0;
156
+ #warnedNoSubsession = false;
99
157
  #process: DshProcess | undefined;
100
158
  #route: DshRoute;
101
159
  #mode: string;
@@ -157,9 +215,19 @@ export class DshSession {
157
215
  /** Current DSH permission preset name, and the ones it can switch to. */
158
216
  #permission: string | null = null;
159
217
  #permissionPresets: string[] = [];
218
+ /** DSH's display name for each preset value, when the bridge reports one. */
219
+ #permissionLabels = new Map<string, string>();
160
220
  /** Current agent preset (persona + capabilities), and the switchable ones. */
161
221
  #preset: string | null = null;
162
222
  #presetOptions: Array<{ label: string; value: string }> = [];
223
+ /**
224
+ * The preset the user picked, kept until DSH confirms it. Paseo can send the
225
+ * pick while the session is still opening, when the agent either does not
226
+ * exist yet or was just created under the profile default; applying it again
227
+ * before the first prompt is the last moment DSH accepts the switch.
228
+ */
229
+ #desiredPreset: string | null = null;
230
+ #presetPending = false;
163
231
  /**
164
232
  * Last usage snapshot published to Paseo. Paseo replaces its whole usage
165
233
  * record on every `session.usage`, so token counts and context occupancy must
@@ -186,10 +254,11 @@ export class DshSession {
186
254
  cwd: this.#options.cwd,
187
255
  route: this.#route,
188
256
  sessionId: this.#dshSessionId,
257
+ ...(this.#options.initialPreset === undefined ? {} : { preset: this.#options.initialPreset }),
189
258
  env: this.#options.env,
190
259
  onEvent: (payload) => this.#onSessionEvent(payload),
191
260
  onAssistantStream: (frame) => this.#onAssistantStream(frame),
192
- onStatus: (status) => this.#onStatus(status),
261
+ onStatus: (payload) => this.#onStatus(payload),
193
262
  onQuestion: (request) => this.#onQuestion(request),
194
263
  onLog: (line) => this.#options.log(line),
195
264
  onExit: (code, signal) => {
@@ -212,9 +281,9 @@ export class DshSession {
212
281
  if (this.#mode === "plan") {
213
282
  await process.setPlan(true);
214
283
  }
215
- // A resumed session already carries DSH's stored context; publish its
216
- // occupancy now so the readout is not blank until the next turn.
217
- void this.refreshUsage();
284
+ // Occupancy is published later, after the agent exists: measuring it here
285
+ // creates the agent, and the preset this session was opened under has not
286
+ // been applied yet, so the session would be composed as the profile default.
218
287
  }
219
288
 
220
289
  /** The committed configuration Paseo renders in the composer. */
@@ -242,7 +311,10 @@ export class DshSession {
242
311
  label: "Permissions",
243
312
  description: "DSH sandbox + approval preset for this session.",
244
313
  value: this.#permission,
245
- options: this.#permissionPresets.map((name) => ({ label: name, value: name })),
314
+ options: this.#permissionPresets.map((name) => ({
315
+ label: permissionPresetLabel(name, this.#permissionLabels.get(name)),
316
+ value: name,
317
+ })),
246
318
  });
247
319
  }
248
320
  const thinkingOptions = this.#thinking();
@@ -305,6 +377,9 @@ export class DshSession {
305
377
  if (!permission.available) return;
306
378
  this.#permission = permission.current;
307
379
  this.#permissionPresets = permission.presets;
380
+ this.#permissionLabels = new Map(
381
+ (permission.presetDetails ?? []).map((preset) => [preset.value, preset.name]),
382
+ );
308
383
  }
309
384
 
310
385
  /**
@@ -315,9 +390,12 @@ export class DshSession {
315
390
  const info = await this.#require().presets();
316
391
  if (!info.available) return;
317
392
  this.#preset = info.current ?? info.default;
393
+ // A preset whose plugins failed to mount can still be listed. Mark it so the
394
+ // composer does not offer it as a working choice: selecting it would be
395
+ // rejected and silently snap back to the current preset.
318
396
  this.#presetOptions = info.presets.map((preset) => ({
319
397
  value: preset.id,
320
- label: preset.name ?? preset.id,
398
+ label: `${preset.name ?? preset.id}${preset.broken === undefined ? "" : "(不可用)"}`,
321
399
  }));
322
400
  }
323
401
 
@@ -409,7 +487,16 @@ export class DshSession {
409
487
  this.#options.emit({
410
488
  type: "timeline.item",
411
489
  sessionId: this.id,
412
- item: { type: "user_message", id: `user:history:${seq}`, text, clientMessageId: `history:${seq}` },
490
+ item: {
491
+ type: "user_message",
492
+ id: `user:history:${seq}`,
493
+ text,
494
+ clientMessageId: `history:${seq}`,
495
+ // Paseo turns this into the provider token it sends back on rewind.
496
+ // The seq is durable: the stored log is replayed with the same
497
+ // numbering after a restart.
498
+ revertToken: { seq },
499
+ },
413
500
  });
414
501
  continue;
415
502
  }
@@ -427,13 +514,49 @@ export class DshSession {
427
514
  this.#clearLive();
428
515
  const process = this.#require();
429
516
 
517
+ // Last chance to land a preset that arrived while the session was opening:
518
+ // DSH locks the choice once this turn starts.
519
+ if (this.#presetPending && this.#desiredPreset !== null) {
520
+ const requested = this.#desiredPreset;
521
+ this.#desiredPreset = null;
522
+ this.#presetPending = false;
523
+ try {
524
+ const applied = await process.setConfig({ preset: requested });
525
+ this.#preset = applied.preset ?? requested;
526
+ } catch (error) {
527
+ const message = messageOf(error);
528
+ this.#options.log(`preset "${requested}" could not be applied: ${message}`);
529
+ this.#emitItem({
530
+ type: "notification",
531
+ id: `preset-error:${Date.now()}`,
532
+ level: "error",
533
+ message: `切换预设失败:${message}`,
534
+ });
535
+ }
536
+ }
537
+
430
538
  // A slash-menu pick arrives as a command, not a message. DSH commands and
431
539
  // skills share the menu but not the execution path, so branch on the kind
432
540
  // the catalog recorded rather than on the name.
433
541
  if (prompt.input.type === "command") {
434
542
  const args = prompt.input.arguments ?? "";
435
543
  const line = args.trim() === "" ? `/${prompt.input.name}` : `/${prompt.input.name} ${args}`;
436
- this.#emitUserMessage(prompt.clientMessageId, line);
544
+ // A command message has no DSH user event of its own. Anchor it at the
545
+ // current end of the log so rewinding it removes everything the command
546
+ // did, just like rewinding a normal message removes its turn. Read the
547
+ // boundary before publishing the row so the message is rewindable from
548
+ // its first appearance.
549
+ let boundary: number | undefined;
550
+ try {
551
+ boundary = await process.currentSeq();
552
+ } catch (error) {
553
+ this.#options.log(`command boundary unavailable: ${messageOf(error)}`);
554
+ }
555
+ this.#emitUserMessage(
556
+ prompt.clientMessageId,
557
+ line,
558
+ boundary === undefined ? undefined : { seq: boundary },
559
+ );
437
560
 
438
561
  if (this.#commandKinds.get(prompt.input.name) === "command") {
439
562
  try {
@@ -456,12 +579,13 @@ export class DshSession {
456
579
  // A skill (or an unrecognized name): hand DSH the bare `/name` line. Its
457
580
  // skill tool injects a user-invocable skill from exactly that token.
458
581
  try {
459
- await process.prompt(line, [{ type: "text", text: line }], prompt.delivery);
582
+ const result = await process.prompt(line, [{ type: "text", text: line }], prompt.delivery);
583
+ this.#emitPromptAccepted(prompt.clientMessageId);
584
+ this.#emitRewindToken(prompt.clientMessageId, line, result.seq);
460
585
  } catch (error) {
461
586
  this.#emitPromptFailed(prompt.clientMessageId, error);
462
587
  return;
463
588
  }
464
- this.#emitPromptAccepted(prompt.clientMessageId);
465
589
  return;
466
590
  }
467
591
 
@@ -470,31 +594,128 @@ export class DshSession {
470
594
  // reference: a block with no DSH counterpart used to throw *outside* this
471
595
  // try, which turned one unsupported file into `session.runtime_failed` and
472
596
  // killed the whole session ("stale after its plugin reloaded" on retry).
597
+ let acceptedSeq: number | undefined;
598
+ let acceptedText = "";
599
+ let optimistic = false;
473
600
  try {
474
601
  const blocks = prompt.input.content.map(toDshContent);
475
602
  const label = blocks
476
603
  .map((block) => (block.type === "text" ? (block.text as string) : ""))
477
604
  .filter((text) => text !== "")
478
605
  .join("\n");
479
-
480
- this.#emitUserMessage(prompt.clientMessageId, label);
481
- await process.prompt(label, blocks.length === 0 ? undefined : blocks, prompt.delivery);
606
+ acceptedText = label;
607
+
608
+ // An idle auto prompt can wait for DSH to append the durable user event,
609
+ // so publish the row once with its rewind token instead of publishing it
610
+ // twice. Steer and mid-turn prompts must stay optimistic: their user event
611
+ // may only arrive in a later turn, so show the row now and attach the token
612
+ // when the event (or the bridge response) supplies the seq.
613
+ optimistic = prompt.delivery === "steer" || this.#turnId !== null;
614
+ if (optimistic) this.#emitUserMessage(prompt.clientMessageId, label);
615
+
616
+ const result = await process.prompt(
617
+ label,
618
+ blocks.length === 0 ? undefined : blocks,
619
+ prompt.delivery,
620
+ );
621
+ acceptedSeq = result.seq;
622
+ if (!optimistic) {
623
+ this.#emitUserMessage(
624
+ prompt.clientMessageId,
625
+ label,
626
+ acceptedSeq === undefined ? undefined : { seq: acceptedSeq },
627
+ );
628
+ }
629
+ if (acceptedSeq === undefined && result.messageId !== undefined) {
630
+ const seenSeq = this.#recentUserMessageSeqs.get(result.messageId);
631
+ if (seenSeq !== undefined) {
632
+ this.#recentUserMessageSeqs.delete(result.messageId);
633
+ this.#emitRewindToken(prompt.clientMessageId, label, seenSeq);
634
+ } else {
635
+ this.#pendingUserMessages.set(result.messageId, {
636
+ clientMessageId: prompt.clientMessageId,
637
+ text: label,
638
+ });
639
+ }
640
+ }
482
641
  } catch (error) {
642
+ // The optimistic paths already published the row. Keep the idle path's
643
+ // previous behaviour too: a rejected prompt still shows the text that
644
+ // failed, next to the failure card.
645
+ if (!optimistic && acceptedText !== "") {
646
+ this.#emitUserMessage(prompt.clientMessageId, acceptedText);
647
+ }
483
648
  this.#emitPromptFailed(prompt.clientMessageId, error);
484
649
  return;
485
650
  }
486
651
 
487
652
  this.#emitPromptAccepted(prompt.clientMessageId);
653
+ // A steer message was already published optimistically; re-emit the same
654
+ // id and text so Paseo records the token without adding a second row.
655
+ if (optimistic && acceptedSeq !== undefined) {
656
+ this.#emitRewindToken(prompt.clientMessageId, acceptedText, acceptedSeq);
657
+ }
488
658
  }
489
659
 
490
- #emitUserMessage(clientMessageId: string, text: string): void {
660
+ /**
661
+ * Rewind the conversation to the boundary carried by a user message's token.
662
+ *
663
+ * DSH cannot delete events from a live log, so the bridge forks a new session
664
+ * that keeps only the events before the chosen message. This object switches
665
+ * its durable id to that fork and tells Paseo the new persistence handle; the
666
+ * host then reopens the session and replays the shorter history.
667
+ */
668
+ async revert(token: unknown, scope: "conversation" | "files" | "both"): Promise<void> {
669
+ if (scope !== "conversation") {
670
+ throw new Error(`rewind scope "${scope}" is not supported; only conversation state can be restored`);
671
+ }
672
+ if (!isRecord(token)) throw new Error("rewind token is not an object");
673
+ const seq = token["seq"];
674
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) {
675
+ throw new Error("rewind token has no valid event seq");
676
+ }
677
+ const result = await this.#require().rewind(seq);
678
+ if (typeof result.sessionId !== "string" || result.sessionId === "") {
679
+ throw new Error("the bridge did not return the forked session id");
680
+ }
681
+ this.#retiredSessionIds.add(this.#dshSessionId);
682
+ this.#dshSessionId = result.sessionId;
683
+ // No event from the discarded branch can belong to the new timeline.
684
+ this.#pendingUserMessages.clear();
685
+ this.#recentUserMessageSeqs.clear();
686
+ // The host reads this from its session state after the request completes,
687
+ // closes the old process, and reopens with the new id.
688
+ this.#options.emit({
689
+ type: "session.persistence",
690
+ sessionId: this.id,
691
+ persistence: { version: 1, data: { sessionId: this.#dshSessionId } },
692
+ });
693
+ }
694
+
695
+ #emitUserMessage(
696
+ clientMessageId: string,
697
+ text: string,
698
+ revertToken?: { seq: number },
699
+ ): void {
491
700
  this.#options.emit({
492
701
  type: "timeline.item",
493
702
  sessionId: this.id,
494
- item: { type: "user_message", id: `user:${clientMessageId}`, text, clientMessageId },
703
+ item: {
704
+ type: "user_message",
705
+ id: `user:${clientMessageId}`,
706
+ text,
707
+ clientMessageId,
708
+ ...(revertToken === undefined ? {} : { revertToken }),
709
+ },
495
710
  });
496
711
  }
497
712
 
713
+ /** Attach a rewind token to an already-published message without a new row. */
714
+ #emitRewindToken(clientMessageId: string, text: string, seq: number | undefined): void {
715
+ if (seq === undefined) return;
716
+ this.#emitUserMessage(clientMessageId, text, { seq });
717
+ }
718
+
498
719
  #emitPromptFailed(clientMessageId: string, error: unknown): void {
499
720
  this.#options.emit({
500
721
  type: "session.prompt_result",
@@ -594,11 +815,24 @@ export class DshSession {
594
815
  // A preset is a creation-time choice; DSH refuses the change once the
595
816
  // session's first turn has started. On refusal keep the real value and log
596
817
  // it — the caller re-emits config, so the composer snaps back.
818
+ this.#desiredPreset = requestedPreset;
819
+ this.#presetPending = true;
820
+ this.#options.log(`preset requested: ${requestedPreset}`);
597
821
  try {
598
822
  const applied = await process.setConfig({ preset: requestedPreset });
599
823
  this.#preset = applied.preset ?? requestedPreset;
824
+ this.#presetPending = false;
600
825
  } catch (error) {
601
- this.#options.log(`preset change rejected: ${messageOf(error)}`);
826
+ const message = messageOf(error);
827
+ this.#options.log(`preset change rejected: ${message}`);
828
+ // Snapping back silently looks like the picker is broken. Say why on the
829
+ // timeline; the caller still re-emits the config with the real value.
830
+ this.#emitItem({
831
+ type: "notification",
832
+ id: `preset-error:${Date.now()}`,
833
+ level: "error",
834
+ message: `切换预设失败:${message}`,
835
+ });
602
836
  }
603
837
  }
604
838
 
@@ -632,6 +866,16 @@ export class DshSession {
632
866
  if (this.#closed) return;
633
867
  this.#closed = true;
634
868
  clearTimeout(this.#usageRefreshTimer);
869
+ for (const child of this.#children.values()) {
870
+ if (child.openTimer !== undefined) clearTimeout(child.openTimer);
871
+ if (child.opened) {
872
+ this.#options.emit({ type: "session.closed", sessionId: child.id });
873
+ }
874
+ }
875
+ this.#children.clear();
876
+ this.#pendingSubagentCalls.clear();
877
+ this.#pendingUserMessages.clear();
878
+ this.#recentUserMessageSeqs.clear();
635
879
  this.#flushLive();
636
880
  this.#clearLive();
637
881
  await this.#process?.shutdown();
@@ -644,8 +888,12 @@ export class DshSession {
644
888
  return this.#process;
645
889
  }
646
890
 
647
- #onStatus(status: string): void {
648
- if (status === "running") {
891
+ #onStatus(payload: DshStatusEvent): void {
892
+ if (payload.sessionId !== this.#dshSessionId) {
893
+ this.#onChildStatus(payload);
894
+ return;
895
+ }
896
+ if (payload.status === "running") {
649
897
  if (this.#turnId === null) {
650
898
  this.#toolStarts.clear();
651
899
  this.#turnTool = { count: 0, ms: 0 };
@@ -661,6 +909,229 @@ export class DshSession {
661
909
  this.#completeTurn();
662
910
  }
663
911
 
912
+ /**
913
+ * Find or create the local view of a child session.
914
+ *
915
+ * A session is only treated as a child when its header names this session as
916
+ * the parent *and* marks it as a subagent. In DSH 0.2.1 `parentSession` also
917
+ * records ordinary fork lineage, so the parent link alone is not enough.
918
+ */
919
+ #ensureChild(meta: {
920
+ sessionId: string;
921
+ parentSessionId?: string;
922
+ origin?: string;
923
+ cwd?: string;
924
+ }): ChildSessionState | undefined {
925
+ if (!this.#options.capabilities.includes("session.subsession")) {
926
+ if (!this.#warnedNoSubsession) {
927
+ this.#warnedNoSubsession = true;
928
+ this.#options.log(
929
+ "Paseo host did not negotiate session.subsession; DSH subagent child sessions stay hidden",
930
+ );
931
+ }
932
+ return undefined;
933
+ }
934
+ const existing = this.#children.get(meta.sessionId);
935
+ if (existing !== undefined) {
936
+ if (meta.cwd !== undefined) existing.cwd = meta.cwd;
937
+ return existing;
938
+ }
939
+ if (meta.parentSessionId !== this.#dshSessionId || meta.origin !== "subagent") return undefined;
940
+ const child: ChildSessionState = {
941
+ id: meta.sessionId,
942
+ timeline: new TimelineBuilder(),
943
+ cwd: meta.cwd ?? this.#options.cwd,
944
+ opened: false,
945
+ turnId: null,
946
+ finished: false,
947
+ pending: [],
948
+ };
949
+ this.#children.set(meta.sessionId, child);
950
+ return child;
951
+ }
952
+
953
+ #onChildSessionEvent(payload: DshSessionEvent): void {
954
+ const child = this.#ensureChild(payload);
955
+ if (child === undefined) return;
956
+ const event = payload.event;
957
+ if (event.type === "subagent/descriptor") {
958
+ const data = isRecord(event.data) ? event.data : {};
959
+ const title =
960
+ typeof data.label === "string"
961
+ ? data.label
962
+ : typeof data.description === "string"
963
+ ? data.description
964
+ : undefined;
965
+ if (title !== undefined && child.title === undefined) child.title = title;
966
+ }
967
+ if (!child.opened) {
968
+ child.pending.push({ kind: "event", payload });
969
+ this.#scheduleChildOpen(child);
970
+ return;
971
+ }
972
+ this.#applyChildEvent(child, payload);
973
+ }
974
+
975
+ #onChildStatus(payload: DshStatusEvent): void {
976
+ const child = this.#ensureChild(payload);
977
+ if (child === undefined) return;
978
+ if (!child.opened) {
979
+ child.pending.push({ kind: "status", status: payload.status });
980
+ this.#scheduleChildOpen(child);
981
+ return;
982
+ }
983
+ this.#applyChildStatus(child, payload.status);
984
+ }
985
+
986
+ #scheduleChildOpen(child: ChildSessionState): void {
987
+ if (child.openTimer !== undefined) return;
988
+ // The parent's tool result normally arrives immediately and tells us which
989
+ // parent tool call to link. If it never does, opening the child without a
990
+ // toolCallId still beats hiding it from Paseo entirely.
991
+ child.openTimer = setTimeout(() => {
992
+ child.openTimer = undefined;
993
+ this.#tryOpenChild(child);
994
+ }, 1500);
995
+ child.openTimer.unref?.();
996
+ }
997
+
998
+ #tryOpenChild(child: ChildSessionState): void {
999
+ if (child.opened) return;
1000
+ // A subagent tool is in flight. Wait for its result to learn the call id,
1001
+ // unless the fallback timer has already fired and cleared that wait.
1002
+ if (child.toolCallId === undefined && this.#pendingSubagentCalls.size > 0 && child.openTimer !== undefined) {
1003
+ return;
1004
+ }
1005
+ this.#openChild(child);
1006
+ }
1007
+
1008
+ #openChild(child: ChildSessionState): void {
1009
+ if (child.opened || this.#closed) return;
1010
+ child.opened = true;
1011
+ if (child.openTimer !== undefined) {
1012
+ clearTimeout(child.openTimer);
1013
+ child.openTimer = undefined;
1014
+ }
1015
+ this.#options.emit({
1016
+ type: "session.opened",
1017
+ sessionId: child.id,
1018
+ parentSessionId: this.id,
1019
+ ...(child.toolCallId === undefined ? {} : { toolCallId: child.toolCallId }),
1020
+ // These are the capabilities the host actually negotiated for this
1021
+ // connection. Advertising the static CAPABILITIES list here would make
1022
+ // Paseo reject the child before it is attached.
1023
+ capabilities: [...this.#options.capabilities],
1024
+ restoration: "parent",
1025
+ cwd: child.cwd,
1026
+ ...(child.title === undefined ? {} : { title: child.title, description: child.title }),
1027
+ });
1028
+ const pending = child.pending;
1029
+ child.pending = [];
1030
+ for (const item of pending) {
1031
+ if (item.kind === "event") this.#applyChildEvent(child, item.payload);
1032
+ else this.#applyChildStatus(child, item.status);
1033
+ }
1034
+ }
1035
+
1036
+ #applyChildEvent(child: ChildSessionState, payload: DshSessionEvent): void {
1037
+ const event = payload.event;
1038
+ const data = isRecord(event.data) ? event.data : {};
1039
+ if (event.type === "turn/start") {
1040
+ this.#startChildTurn(child);
1041
+ }
1042
+ for (const item of child.timeline.consume(event)) {
1043
+ this.#options.emit({ type: "timeline.item", sessionId: child.id, item });
1044
+ }
1045
+ if (event.type === "turn/end") {
1046
+ const reason = isRecord(data.reason) ? data.reason : undefined;
1047
+ const kind = typeof data.reason === "string" ? data.reason : reason?.kind;
1048
+ // DSH names a canceled turn "aborted"; Paseo only knows "canceled".
1049
+ const state =
1050
+ kind === "error" || kind === "failed"
1051
+ ? "failed"
1052
+ : kind === "canceled" || kind === "cancelled" || kind === "aborted"
1053
+ ? "canceled"
1054
+ : "completed";
1055
+ const error = isRecord(reason?.error) ? reason.error : undefined;
1056
+ const message = typeof error?.message === "string" ? error.message : undefined;
1057
+ this.#finishChildTurn(child, state, message);
1058
+ }
1059
+ }
1060
+
1061
+ #applyChildStatus(child: ChildSessionState, status: string): void {
1062
+ if (status === "running") {
1063
+ this.#startChildTurn(child);
1064
+ return;
1065
+ }
1066
+ const state =
1067
+ status === "failed" || status === "error"
1068
+ ? "failed"
1069
+ : status === "canceled" || status === "cancelled"
1070
+ ? "canceled"
1071
+ : "completed";
1072
+ this.#finishChildTurn(child, state);
1073
+ }
1074
+
1075
+ #startChildTurn(child: ChildSessionState): void {
1076
+ if (child.turnId !== null) return;
1077
+ this.#childTurnSeq += 1;
1078
+ const turnId = `child:${child.id}:${this.#childTurnSeq}`;
1079
+ child.turnId = turnId;
1080
+ child.finished = false;
1081
+ this.#options.emit({ type: "session.turn", sessionId: child.id, turnId, state: "started" });
1082
+ }
1083
+
1084
+ #finishChildTurn(
1085
+ child: ChildSessionState,
1086
+ state: "completed" | "failed" | "canceled",
1087
+ message?: string,
1088
+ ): void {
1089
+ // `turn/end` is normally followed by an idle status; only the first one
1090
+ // should produce a terminal turn event.
1091
+ if (child.finished) return;
1092
+ child.finished = true;
1093
+ // A child can be opened after its turn already ended (late bridge event or
1094
+ // replay). Still report the terminal state so Paseo does not leave the
1095
+ // subagent stuck on "running".
1096
+ this.#childTurnSeq += 1;
1097
+ const turnId = child.turnId ?? `child:${child.id}:${this.#childTurnSeq}`;
1098
+ child.turnId = null;
1099
+ this.#options.emit({
1100
+ type: "session.turn",
1101
+ sessionId: child.id,
1102
+ turnId,
1103
+ state,
1104
+ ...(message === undefined ? {} : { error: { message } }),
1105
+ });
1106
+ }
1107
+
1108
+ /** Link a parent subagent tool result (`started subagent <id>`) to its child. */
1109
+ #trackSubagentResult(callId: string, message: unknown): void {
1110
+ const output = isRecord(message) ? textBlocks(message.content) : "";
1111
+ const match = /^\s*started subagent ([A-Za-z0-9][A-Za-z0-9_-]*)\s*$/.exec(output);
1112
+ const pending = this.#pendingSubagentCalls.get(callId);
1113
+ this.#pendingSubagentCalls.delete(callId);
1114
+ if (match === null) {
1115
+ if (this.#pendingSubagentCalls.size === 0) {
1116
+ for (const child of this.#children.values()) {
1117
+ if (!child.opened && child.toolCallId === undefined) this.#tryOpenChild(child);
1118
+ }
1119
+ }
1120
+ return;
1121
+ }
1122
+ const child = this.#ensureChild({
1123
+ sessionId: match[1],
1124
+ parentSessionId: this.#dshSessionId,
1125
+ origin: "subagent",
1126
+ });
1127
+ if (child === undefined) return;
1128
+ child.toolCallId = callId;
1129
+ // The child's own descriptor label is authoritative; fall back to the
1130
+ // parent tool description when it did not publish one.
1131
+ if (child.title === undefined && pending?.description !== undefined) child.title = pending.description;
1132
+ this.#tryOpenChild(child);
1133
+ }
1134
+
664
1135
  /** Mark the current turn completed once its text is fully visible. */
665
1136
  #completeTurn(): void {
666
1137
  if (this.#turnId !== null) {
@@ -681,8 +1152,37 @@ export class DshSession {
681
1152
  }
682
1153
  }
683
1154
 
684
- #onSessionEvent(payload: { event: { type: string; [key: string]: unknown } }): void {
1155
+ #onSessionEvent(payload: DshSessionEvent): void {
1156
+ const sessionId =
1157
+ typeof payload.sessionId === "string" ? payload.sessionId : this.#dshSessionId;
1158
+ if (this.#retiredSessionIds.has(sessionId)) return;
1159
+ if (sessionId !== this.#dshSessionId) {
1160
+ this.#onChildSessionEvent({ ...payload, sessionId });
1161
+ return;
1162
+ }
685
1163
  const event = payload.event;
1164
+ // A prompt accepted while its agent was still starting has no seq yet. The
1165
+ // durable user message arrives later; attach the rewind token then, using
1166
+ // the same id and text so Paseo does not add a duplicate row.
1167
+ if (event.type === "user/message") {
1168
+ const data = isRecord(event.data) ? event.data : {};
1169
+ const messageId = typeof data.id === "string" ? data.id : undefined;
1170
+ if (messageId !== undefined && typeof event.seq === "number") {
1171
+ this.#recentUserMessageSeqs.set(messageId, event.seq);
1172
+ if (this.#recentUserMessageSeqs.size > 100) {
1173
+ const oldest = this.#recentUserMessageSeqs.keys().next().value;
1174
+ if (oldest !== undefined) this.#recentUserMessageSeqs.delete(oldest);
1175
+ }
1176
+ }
1177
+ const pending = messageId === undefined ? undefined : this.#pendingUserMessages.get(messageId);
1178
+ if (pending !== undefined && messageId !== undefined) {
1179
+ this.#pendingUserMessages.delete(messageId);
1180
+ if (typeof event.seq === "number") {
1181
+ this.#emitRewindToken(pending.clientMessageId, pending.text, event.seq);
1182
+ }
1183
+ }
1184
+ return;
1185
+ }
686
1186
  // The model can leave plan mode on its own, for example by submitting a plan
687
1187
  // for approval. Mirror that into the composer's mode selection so the toggle
688
1188
  // never disagrees with the runtime.
@@ -843,7 +1343,15 @@ export class DshSession {
843
1343
  const data = isRecord(event.data) ? event.data : {};
844
1344
  if (event.type === "tool/call") {
845
1345
  const callId = typeof data.callId === "string" ? data.callId : undefined;
846
- if (callId !== undefined) this.#toolStarts.set(callId, Date.now());
1346
+ if (callId !== undefined) {
1347
+ this.#toolStarts.set(callId, Date.now());
1348
+ if (data.name === "subagent") {
1349
+ const input = parseToolArguments(data.arguments);
1350
+ this.#pendingSubagentCalls.set(callId, {
1351
+ ...(typeof input.description === "string" ? { description: input.description } : {}),
1352
+ });
1353
+ }
1354
+ }
847
1355
  return;
848
1356
  }
849
1357
  const message = isRecord(data.message) ? data.message : undefined;
@@ -854,6 +1362,7 @@ export class DshSession {
854
1362
  ? message.toolCallId
855
1363
  : undefined;
856
1364
  if (callId === undefined) return;
1365
+ if (this.#pendingSubagentCalls.has(callId)) this.#trackSubagentResult(callId, message);
857
1366
  const startedAt = this.#toolStarts.get(callId);
858
1367
  if (startedAt === undefined) return;
859
1368
  this.#toolStarts.delete(callId);
@@ -1127,6 +1636,34 @@ function toDshContent(block: ProviderContent): Record<string, unknown> {
1127
1636
  };
1128
1637
  }
1129
1638
 
1639
+ /**
1640
+ * Paseo's select carries a single label per option, so use DSH's product name
1641
+ * instead of the machine value. These three are DSH's built-in labels; custom
1642
+ * profiles keep their own name, and kebab-case names are title-cased the same
1643
+ * way DSH's own client does it.
1644
+ */
1645
+ function permissionPresetLabel(value: string, name?: string): string {
1646
+ const builtIn: Record<string, string> = {
1647
+ "read-only": "Read Only",
1648
+ "workspace-write": "Workspace Write",
1649
+ "danger-full-access": "Full access",
1650
+ "auto": "Auto review",
1651
+ "custom": "Custom",
1652
+ };
1653
+ const product = builtIn[value];
1654
+ if (product !== undefined && (name === undefined || name === value || name === product)) {
1655
+ return product;
1656
+ }
1657
+ const display = name ?? value;
1658
+ if (/^[a-z0-9]+(-[a-z0-9]+)*$/.test(display)) {
1659
+ return display
1660
+ .split("-")
1661
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
1662
+ .join(" ");
1663
+ }
1664
+ return display;
1665
+ }
1666
+
1130
1667
  /**
1131
1668
  * Map DSH's per-step token accounting onto Paseo's usage fields.
1132
1669
  *