paseo-dsh 0.2.20 → 0.2.22

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
@@ -35,6 +35,8 @@ import {
35
35
  type DshSessionEvent,
36
36
  type DshStatusEvent,
37
37
  type DshUsage,
38
+ type DshApprovalRequest,
39
+ type DshAssistantStream,
38
40
  } from "./dsh-process";
39
41
  import { TimelineBuilder } from "./timeline";
40
42
 
@@ -74,8 +76,8 @@ export interface DshSessionOptions {
74
76
  /** Thinking options the catalog advertises. */
75
77
  thinkingOptions: ProviderThinkingOption[];
76
78
  /**
77
- * Capabilities negotiated for the parent session. Child sessions opened by
78
- * DSH subagents must advertise the same set so Paseo accepts them.
79
+ * Capabilities negotiated for the parent session. Native child sessions may
80
+ * advertise only a subset of these, matching their supported controls.
79
81
  */
80
82
  capabilities: readonly string[];
81
83
  emit(event: ProviderEvent): void;
@@ -129,18 +131,33 @@ export function offersThinking(models: readonly ProviderModel[], route: DshRoute
129
131
  /** One DSH subagent child session observed through the bridge. */
130
132
  interface ChildSessionState {
131
133
  id: string;
134
+ parentSessionId: string;
135
+ mode?: "continuable" | "one-shot";
136
+ toolName?: string;
132
137
  timeline: TimelineBuilder;
133
138
  cwd: string;
134
139
  title?: string;
135
- /** Parent tool call that spawned this child, once its result reveals it. */
140
+ /** Exact native spawning execution, including PTC subcall identity. */
136
141
  toolCallId?: string;
137
142
  opened: boolean;
138
143
  turnId: string | null;
139
144
  /** A terminal turn state was already reported for the current turn. */
140
145
  finished: boolean;
141
146
  /** Events seen before Paseo accepted the child session. */
142
- pending: Array<{ kind: "event"; payload: DshSessionEvent } | { kind: "status"; status: string }>;
147
+ pending: Array<{ kind: "event"; payload: DshSessionEvent } | { kind: "status"; status: string } | { kind: "stream"; frame: DshAssistantFrame }>;
143
148
  openTimer?: ReturnType<typeof setTimeout>;
149
+ live?: LiveAssistantState;
150
+ }
151
+
152
+ interface LiveAssistantState {
153
+ attemptId: string;
154
+ turn: number;
155
+ step: number;
156
+ text: string;
157
+ emitted: string;
158
+ reasoning: string;
159
+ emittedReasoning: string;
160
+ timer: ReturnType<typeof setTimeout> | undefined;
144
161
  }
145
162
 
146
163
  export class DshSession {
@@ -153,6 +170,7 @@ export class DshSession {
153
170
  readonly #timeline = new TimelineBuilder();
154
171
  /** DSH subagent child sessions, keyed by their own DSH session id. */
155
172
  #children = new Map<string, ChildSessionState>();
173
+ #closedChildIds = new Set<string>();
156
174
  /** Parent subagent tool calls waiting for their `started subagent <id>` result. */
157
175
  #pendingSubagentCalls = new Map<string, { description?: string }>();
158
176
  /**
@@ -170,6 +188,9 @@ export class DshSession {
170
188
  #mode: string;
171
189
  #thinkingOption: string | undefined;
172
190
  #turnId: string | null = null;
191
+ #turnSeq = 0;
192
+ /** Suffix for a card id that a sibling session or a retry already took. */
193
+ #cardSeq = 0;
173
194
  #replaySeq = 0;
174
195
  /**
175
196
  * Live text accumulated from DSH's transient assistant-stream frames. The
@@ -220,7 +241,11 @@ export class DshSession {
220
241
  timer: ReturnType<typeof setTimeout> | undefined;
221
242
  }
222
243
  | undefined;
223
- #pendingPermissions = new Map<string, (response: ProviderPermissionResponse) => void>();
244
+ #pendingPermissions = new Map<string, {
245
+ resolve(response: ProviderPermissionResponse): void;
246
+ sessionId: string;
247
+ requestId?: string;
248
+ }>();
224
249
  /** Slash-menu entries by name, tagging why each exists. */
225
250
  #commandKinds = new Map<string, "command" | "skill">();
226
251
  /** Current DSH permission preset name, and the ones it can switch to. */
@@ -271,9 +296,12 @@ export class DshSession {
271
296
  systemPrompt: this.#options.systemPrompt,
272
297
  toolPolicy: this.#options.toolPolicy,
273
298
  onEvent: (payload) => this.#onSessionEvent(payload),
274
- onAssistantStream: (frame) => this.#onAssistantStream(frame),
299
+ onAssistantStream: (frame, payload) => this.#onAssistantStream(frame, payload),
300
+ onChild: (payload) => this.#onChildLink(payload),
275
301
  onStatus: (payload) => this.#onStatus(payload),
276
302
  onQuestion: (request) => this.#onQuestion(request),
303
+ onApproval: (request) => this.#onApproval(request),
304
+ onRequestCancelled: (requestId) => this.#cancelPermissionRequest(requestId),
277
305
  onLog: (line) => this.#options.log(line),
278
306
  onExit: (code, signal) => {
279
307
  if (this.#closed) return;
@@ -282,6 +310,14 @@ export class DshSession {
282
310
  // A dead runtime must not keep writing more of the answer; the failure
283
311
  // below is the last word on this session.
284
312
  this.#clearLive();
313
+ for (const item of this.#timeline.finishPending("failed")) this.#emitItem(item);
314
+ for (const [id] of this.#pendingPermissions) this.resolvePermission(id, { behavior: "deny", message: "Runtime exited" });
315
+ for (const child of this.#children.values()) {
316
+ clearTimeout(child.openTimer);
317
+ this.#finishChildDisplay(child, "failed");
318
+ if (child.opened) this.#options.emit({ type: "session.runtime_failed", sessionId: child.id,
319
+ error: { message: "DeepSeek Harness process ended" } });
320
+ }
285
321
  this.#options.emit({
286
322
  type: "session.runtime_failed",
287
323
  sessionId: this.id,
@@ -403,9 +439,13 @@ export class DshSession {
403
439
  // A preset whose plugins failed to mount can still be listed. Mark it so the
404
440
  // composer does not offer it as a working choice: selecting it would be
405
441
  // rejected and silently snap back to the current preset.
442
+ //
443
+ // The composer draws this label itself and the daemon has no idea which
444
+ // language the app is showing, so the marker is written in both languages
445
+ // instead of picking one.
406
446
  this.#presetOptions = info.presets.map((preset) => ({
407
447
  value: preset.id,
408
- label: `${preset.name ?? preset.id}${preset.broken === undefined ? "" : "(不可用)"}`,
448
+ label: `${preset.name ?? preset.id}${preset.broken === undefined ? "" : " (unavailable / 不可用)"}`,
409
449
  }));
410
450
  }
411
451
 
@@ -517,11 +557,27 @@ export class DshSession {
517
557
  }
518
558
 
519
559
  /** Accept one prompt and start its turn. */
520
- async prompt(prompt: ProviderPrompt): Promise<void> {
521
- // A user turn must not start with the previous answer's live buffer still
522
- // attached; flush it so the two turns cannot interleave.
523
- this.#flushLive();
524
- this.#clearLive();
560
+ async prompt(prompt: ProviderPrompt, sessionId = this.id): Promise<void> {
561
+ if (sessionId !== this.id) return this.#promptChild(sessionId, prompt);
562
+ const isSteer = prompt.delivery === "steer";
563
+ // Paseo's steering admission requires an active turn. Refuse before touching
564
+ // the runtime so the host can fall back to a fresh turn without double-sending.
565
+ if (isSteer && this.#turnId === null) {
566
+ this.#options.emit({
567
+ type: "session.prompt_result",
568
+ sessionId: this.id,
569
+ clientMessageId: prompt.clientMessageId,
570
+ result: { type: "completed" },
571
+ });
572
+ return;
573
+ }
574
+ const steeredTurnId = isSteer ? this.#turnId : null;
575
+ if (!isSteer) {
576
+ // A user turn must not start with the previous answer's live buffer still
577
+ // attached; flush it so the two turns cannot interleave.
578
+ this.#flushLive();
579
+ this.#clearLive();
580
+ }
525
581
  const process = this.#require();
526
582
 
527
583
  // Last chance to land a preset that arrived while the session was opening:
@@ -540,7 +596,9 @@ export class DshSession {
540
596
  type: "notification",
541
597
  id: `preset-error:${Date.now()}`,
542
598
  level: "error",
543
- message: `切换预设失败:${message}`,
599
+ // Rendered by the host as written: both languages, so neither reader
600
+ // gets a message in the other one.
601
+ message: `Preset switch failed / 切换预设失败:${message}`,
544
602
  });
545
603
  }
546
604
  }
@@ -549,6 +607,17 @@ export class DshSession {
549
607
  // skills share the menu but not the execution path, so branch on the kind
550
608
  // the catalog recorded rather than on the name.
551
609
  if (prompt.input.type === "command") {
610
+ if (isSteer && this.#commandKinds.get(prompt.input.name) === "command") {
611
+ // Registered DSH commands answer outside a turn; let Paseo fall back to
612
+ // its normal non-steer command path without mutating the timeline twice.
613
+ this.#options.emit({
614
+ type: "session.prompt_result",
615
+ sessionId: this.id,
616
+ clientMessageId: prompt.clientMessageId,
617
+ result: { type: "completed" },
618
+ });
619
+ return;
620
+ }
552
621
  const args = prompt.input.arguments ?? "";
553
622
  const line = args.trim() === "" ? `/${prompt.input.name}` : `/${prompt.input.name} ${args}`;
554
623
  // A command message has no DSH user event of its own. Anchor it at the
@@ -562,13 +631,13 @@ export class DshSession {
562
631
  } catch (error) {
563
632
  this.#options.log(`command boundary unavailable: ${messageOf(error)}`);
564
633
  }
565
- this.#emitUserMessage(
566
- prompt.clientMessageId,
567
- line,
568
- boundary === undefined ? undefined : { seq: boundary },
569
- );
570
634
 
571
635
  if (this.#commandKinds.get(prompt.input.name) === "command") {
636
+ this.#emitUserMessage(
637
+ prompt.clientMessageId,
638
+ line,
639
+ boundary === undefined ? undefined : { seq: boundary },
640
+ );
572
641
  try {
573
642
  const result = await process.runCommand(prompt.input.name, args);
574
643
  if (result.kind === "error") throw new Error(result.text ?? `/${prompt.input.name} failed`);
@@ -588,11 +657,46 @@ export class DshSession {
588
657
 
589
658
  // A skill (or an unrecognized name): hand DSH the bare `/name` line. Its
590
659
  // skill tool injects a user-invocable skill from exactly that token.
660
+ if (!isSteer) {
661
+ this.#emitUserMessage(
662
+ prompt.clientMessageId,
663
+ line,
664
+ boundary === undefined ? undefined : { seq: boundary },
665
+ );
666
+ }
591
667
  try {
592
668
  const result = await process.prompt(line, [{ type: "text", text: line }], prompt.delivery);
593
- this.#emitPromptAccepted(prompt.clientMessageId);
594
- this.#emitRewindToken(prompt.clientMessageId, line, result.seq);
669
+ if (isSteer && result.disposition === "unavailable") {
670
+ this.#options.emit({
671
+ type: "session.prompt_result",
672
+ sessionId: this.id,
673
+ clientMessageId: prompt.clientMessageId,
674
+ result: { type: "completed" },
675
+ });
676
+ return;
677
+ }
678
+ const seq = result.seq ?? boundary;
679
+ if (isSteer) {
680
+ this.#emitUserMessage(
681
+ prompt.clientMessageId,
682
+ line,
683
+ seq === undefined ? undefined : { seq },
684
+ );
685
+ } else {
686
+ this.#emitRewindToken(prompt.clientMessageId, line, result.seq);
687
+ }
688
+ if (steeredTurnId !== null && prompt.clearPendingPermissions === true) {
689
+ this.#clearPendingPermissionsForSteer(this.#dshSessionId);
690
+ }
691
+ this.#emitPromptAccepted(prompt.clientMessageId, steeredTurnId);
595
692
  } catch (error) {
693
+ if (isSteer) {
694
+ this.#emitUserMessage(
695
+ prompt.clientMessageId,
696
+ line,
697
+ boundary === undefined ? undefined : { seq: boundary },
698
+ );
699
+ }
596
700
  this.#emitPromptFailed(prompt.clientMessageId, error);
597
701
  return;
598
702
  }
@@ -617,10 +721,10 @@ export class DshSession {
617
721
 
618
722
  // An idle auto prompt can wait for DSH to append the durable user event,
619
723
  // so publish the row once with its rewind token instead of publishing it
620
- // twice. Steer and mid-turn prompts must stay optimistic: their user event
621
- // may only arrive in a later turn, so show the row now and attach the token
622
- // when the event (or the bridge response) supplies the seq.
623
- optimistic = prompt.delivery === "steer" || this.#turnId !== null;
724
+ // twice. Mid-turn auto prompts stay optimistic because their user event
725
+ // only arrives in a later turn. Steers wait for bridge admission first so
726
+ // a turn-end race refusal never publishes a duplicate row before fallback.
727
+ optimistic = !isSteer && this.#turnId !== null;
624
728
  if (optimistic) this.#emitUserMessage(prompt.clientMessageId, label);
625
729
 
626
730
  const result = await process.prompt(
@@ -628,6 +732,15 @@ export class DshSession {
628
732
  blocks.length === 0 ? undefined : blocks,
629
733
  prompt.delivery,
630
734
  );
735
+ if (isSteer && result.disposition === "unavailable") {
736
+ this.#options.emit({
737
+ type: "session.prompt_result",
738
+ sessionId: this.id,
739
+ clientMessageId: prompt.clientMessageId,
740
+ result: { type: "completed" },
741
+ });
742
+ return;
743
+ }
631
744
  acceptedSeq = result.seq;
632
745
  if (!optimistic) {
633
746
  this.#emitUserMessage(
@@ -659,8 +772,11 @@ export class DshSession {
659
772
  return;
660
773
  }
661
774
 
662
- this.#emitPromptAccepted(prompt.clientMessageId);
663
- // A steer message was already published optimistically; re-emit the same
775
+ if (steeredTurnId !== null && prompt.clearPendingPermissions === true) {
776
+ this.#clearPendingPermissionsForSteer(this.#dshSessionId);
777
+ }
778
+ this.#emitPromptAccepted(prompt.clientMessageId, steeredTurnId);
779
+ // An optimistic mid-turn message was already published; re-emit the same
664
780
  // id and text so Paseo records the token without adding a second row.
665
781
  if (optimistic && acceptedSeq !== undefined) {
666
782
  this.#emitRewindToken(prompt.clientMessageId, acceptedText, acceptedSeq);
@@ -735,7 +851,16 @@ export class DshSession {
735
851
  });
736
852
  }
737
853
 
738
- #emitPromptAccepted(clientMessageId: string): void {
854
+ #emitPromptAccepted(clientMessageId: string, steeredTurnId: string | null = null): void {
855
+ if (steeredTurnId !== null) {
856
+ this.#options.emit({
857
+ type: "session.prompt_result",
858
+ sessionId: this.id,
859
+ clientMessageId,
860
+ result: { type: "steer", turnId: steeredTurnId },
861
+ });
862
+ return;
863
+ }
739
864
  const turnId = this.#turnId ?? `turn:${clientMessageId}`;
740
865
  this.#options.emit({
741
866
  type: "session.prompt_result",
@@ -820,7 +945,9 @@ export class DshSession {
820
945
  type: "notification",
821
946
  id: `preset-error:${Date.now()}`,
822
947
  level: "error",
823
- message: `切换预设失败:${message}`,
948
+ // Rendered by the host as written: both languages, so neither reader
949
+ // gets a message in the other one.
950
+ message: `Preset switch failed / 切换预设失败:${message}`,
824
951
  });
825
952
  }
826
953
  }
@@ -831,19 +958,34 @@ export class DshSession {
831
958
  }
832
959
 
833
960
  /** Answer a pending question card. */
834
- resolvePermission(permissionId: string, response: ProviderPermissionResponse): void {
835
- const resolve = this.#pendingPermissions.get(permissionId);
836
- if (resolve === undefined) return;
961
+ resolvePermission(permissionId: string, response: ProviderPermissionResponse, sessionId = this.id): void {
962
+ const pending = this.#pendingPermissions.get(permissionId);
963
+ if (pending === undefined) return;
964
+ if (sessionId !== this.id && pending.sessionId !== sessionId) throw new Error('permission belongs to another native session');
837
965
  this.#pendingPermissions.delete(permissionId);
838
966
  this.#options.emit({ type: "session.permission_resolved", sessionId: this.id, permissionId });
839
- resolve(response);
967
+ pending.resolve(response);
968
+ // Deny-and-stop: after the rejection, cancel the turn that asked. A card
969
+ // promoted from a child stops only that child.
970
+ if (response.behavior === "deny" && response.interrupt === true) {
971
+ const owner = pending.sessionId === this.#dshSessionId ? this.id : pending.sessionId;
972
+ this.interrupt(owner).catch((error: unknown) => {
973
+ this.#options.log(`interrupt after denial failed: ${messageOf(error)}`);
974
+ });
975
+ }
840
976
  }
841
977
 
842
978
  /**
843
979
  * Cancel the running turn. The session and its history survive, so the
844
980
  * conversation stays continuable — killing the process stranded it instead.
845
981
  */
846
- async interrupt(): Promise<void> {
982
+ async interrupt(sessionId = this.id): Promise<void> {
983
+ if (sessionId !== this.id) {
984
+ const child = this.#requireChild(sessionId);
985
+ this.#finishChildDisplay(child, "canceled");
986
+ await this.#require().cancel(sessionId);
987
+ return;
988
+ }
847
989
  this.#turnInterrupted = true;
848
990
  this.#flushLive();
849
991
  this.#clearLive();
@@ -855,7 +997,9 @@ export class DshSession {
855
997
  if (this.#closed) return;
856
998
  this.#closed = true;
857
999
  clearTimeout(this.#usageRefreshTimer);
1000
+ for (const [id] of this.#pendingPermissions) this.resolvePermission(id, { behavior: "deny", message: "Session closed" });
858
1001
  for (const child of this.#children.values()) {
1002
+ this.#finishChildDisplay(child, "canceled");
859
1003
  if (child.openTimer !== undefined) clearTimeout(child.openTimer);
860
1004
  if (child.opened) {
861
1005
  this.#options.emit({ type: "session.closed", sessionId: child.id });
@@ -870,6 +1014,75 @@ export class DshSession {
870
1014
  await this.#process?.shutdown();
871
1015
  }
872
1016
 
1017
+ async closeChild(sessionId: string): Promise<void> {
1018
+ this.#requireChild(sessionId);
1019
+ await this.#require().closeChild(sessionId);
1020
+ // The native manager drains descendants with their parent. Close the UI
1021
+ // views child-first too, and never shut down the shared process.
1022
+ const close = (id: string): void => {
1023
+ for (const child of this.#children.values()) if (child.parentSessionId === id) close(child.id);
1024
+ const child = this.#children.get(id);
1025
+ if (child === undefined) return;
1026
+ clearTimeout(child.openTimer);
1027
+ this.#finishChildDisplay(child, "canceled");
1028
+ this.#closedChildIds.add(id);
1029
+ this.#children.delete(id);
1030
+ for (const [permissionId, pending] of this.#pendingPermissions) {
1031
+ if (pending.sessionId === id) this.resolvePermission(permissionId, { behavior: "deny", message: "Subagent closed" });
1032
+ }
1033
+ if (child.opened) this.#options.emit({ type: "session.closed", sessionId: id });
1034
+ };
1035
+ close(sessionId);
1036
+ }
1037
+
1038
+ #requireChild(sessionId: string): ChildSessionState {
1039
+ const child = this.#children.get(sessionId);
1040
+ if (child === undefined) throw new Error(`unknown native child session: ${sessionId}`);
1041
+ return child;
1042
+ }
1043
+
1044
+ async #promptChild(sessionId: string, prompt: ProviderPrompt): Promise<void> {
1045
+ const child = this.#requireChild(sessionId);
1046
+ if (prompt.delivery === "steer" && child.turnId === null) {
1047
+ this.#options.emit({
1048
+ type: "session.prompt_result",
1049
+ sessionId,
1050
+ clientMessageId: prompt.clientMessageId,
1051
+ result: { type: "completed" },
1052
+ });
1053
+ return;
1054
+ }
1055
+ const steeredTurnId = prompt.delivery === "steer" ? child.turnId : null;
1056
+ try {
1057
+ if (prompt.input.type !== "message") throw new Error("native child sessions accept messages, not slash commands");
1058
+ const blocks = prompt.input.content.map(toDshContent);
1059
+ const result = await this.#require().prompt("", blocks, prompt.delivery, sessionId);
1060
+ if (prompt.delivery === "steer" && result.disposition === "unavailable") {
1061
+ this.#options.emit({
1062
+ type: "session.prompt_result",
1063
+ sessionId,
1064
+ clientMessageId: prompt.clientMessageId,
1065
+ result: { type: "completed" },
1066
+ });
1067
+ return;
1068
+ }
1069
+ if (steeredTurnId !== null && prompt.clearPendingPermissions === true) {
1070
+ this.#clearPendingPermissionsForSteer(sessionId);
1071
+ }
1072
+ this.#options.emit({ type: "timeline.item", sessionId, item: {
1073
+ type: "user_message", id: `user:${prompt.clientMessageId}`, clientMessageId: prompt.clientMessageId,
1074
+ text: blocks.filter(block => block.type === "text").map(block => block.text).join("\n"),
1075
+ } });
1076
+ this.#options.emit({ type: "session.prompt_result", sessionId, clientMessageId: prompt.clientMessageId,
1077
+ result: steeredTurnId !== null
1078
+ ? { type: "steer", turnId: steeredTurnId }
1079
+ : { type: "turn", turnId: child.turnId ?? `child:${sessionId}:${prompt.clientMessageId}` } });
1080
+ } catch (error) {
1081
+ this.#options.emit({ type: "session.prompt_result", sessionId, clientMessageId: prompt.clientMessageId,
1082
+ result: { type: "failed", error: { message: messageOf(error) } } });
1083
+ }
1084
+ }
1085
+
873
1086
  #require(): DshProcess {
874
1087
  if (this.#process === undefined || this.#closed) {
875
1088
  throw new Error(`session ${this.id} is not open`);
@@ -890,7 +1103,7 @@ export class DshSession {
890
1103
  // A later usage refresh must not rewrite the previous turn's row.
891
1104
  this.#lastStats = undefined;
892
1105
  }
893
- const turnId = this.#turnId ?? `turn:${Date.now()}`;
1106
+ const turnId = this.#turnId ?? this.#nextTurnId();
894
1107
  this.#turnId = turnId;
895
1108
  this.#options.emit({ type: "session.turn", sessionId: this.id, turnId, state: "started" });
896
1109
  return;
@@ -901,16 +1114,20 @@ export class DshSession {
901
1114
  /**
902
1115
  * Find or create the local view of a child session.
903
1116
  *
904
- * A session is only treated as a child when its header names this session as
905
- * the parent *and* marks it as a subagent. In DSH 0.2.1 `parentSession` also
906
- * records ordinary fork lineage, so the parent link alone is not enough.
1117
+ * Accept direct children and descendants of already observed children, only
1118
+ * when the native header marks delegation. Ordinary conversation forks also
1119
+ * carry parentSession, so lineage alone does not establish a subagent.
907
1120
  */
908
1121
  #ensureChild(meta: {
909
1122
  sessionId: string;
910
1123
  parentSessionId?: string;
911
1124
  origin?: string;
912
1125
  cwd?: string;
1126
+ toolCallId?: string;
1127
+ toolName?: string;
1128
+ toolTitle?: string;
913
1129
  }): ChildSessionState | undefined {
1130
+ if (this.#closedChildIds.has(meta.sessionId)) return undefined;
914
1131
  if (!this.#options.capabilities.includes("session.subsession")) {
915
1132
  if (!this.#warnedNoSubsession) {
916
1133
  this.#warnedNoSubsession = true;
@@ -923,11 +1140,19 @@ export class DshSession {
923
1140
  const existing = this.#children.get(meta.sessionId);
924
1141
  if (existing !== undefined) {
925
1142
  if (meta.cwd !== undefined) existing.cwd = meta.cwd;
1143
+ if (meta.toolCallId !== undefined) existing.toolCallId = meta.toolCallId;
1144
+ if (meta.toolName !== undefined) existing.toolName = meta.toolName;
1145
+ if (meta.toolTitle !== undefined && existing.title === undefined) existing.title = meta.toolTitle;
926
1146
  return existing;
927
1147
  }
928
- if (meta.parentSessionId !== this.#dshSessionId || meta.origin !== "subagent") return undefined;
1148
+ if (meta.origin !== "subagent" || meta.parentSessionId === undefined ||
1149
+ (meta.parentSessionId !== this.#dshSessionId && !this.#children.has(meta.parentSessionId))) return undefined;
929
1150
  const child: ChildSessionState = {
930
1151
  id: meta.sessionId,
1152
+ parentSessionId: meta.parentSessionId,
1153
+ ...(meta.toolCallId === undefined ? {} : { toolCallId: meta.toolCallId }),
1154
+ ...(meta.toolName === undefined ? {} : { toolName: meta.toolName }),
1155
+ ...(meta.toolTitle === undefined ? {} : { title: meta.toolTitle }),
931
1156
  timeline: new TimelineBuilder(),
932
1157
  cwd: meta.cwd ?? this.#options.cwd,
933
1158
  opened: false,
@@ -939,12 +1164,18 @@ export class DshSession {
939
1164
  return child;
940
1165
  }
941
1166
 
1167
+ #onChildLink(meta: Omit<DshStatusEvent, "status">): void {
1168
+ const child = this.#ensureChild(meta);
1169
+ if (child !== undefined) this.#tryOpenChild(child);
1170
+ }
1171
+
942
1172
  #onChildSessionEvent(payload: DshSessionEvent): void {
943
1173
  const child = this.#ensureChild(payload);
944
1174
  if (child === undefined) return;
945
1175
  const event = payload.event;
946
1176
  if (event.type === "subagent/descriptor") {
947
1177
  const data = isRecord(event.data) ? event.data : {};
1178
+ if (data.mode === "continuable" || data.mode === "one-shot") child.mode = data.mode;
948
1179
  const title =
949
1180
  typeof data.label === "string"
950
1181
  ? data.label
@@ -955,6 +1186,10 @@ export class DshSession {
955
1186
  }
956
1187
  if (!child.opened) {
957
1188
  child.pending.push({ kind: "event", payload });
1189
+ if (child.toolCallId !== undefined && child.mode !== undefined) {
1190
+ this.#tryOpenChild(child);
1191
+ return;
1192
+ }
958
1193
  this.#scheduleChildOpen(child);
959
1194
  return;
960
1195
  }
@@ -979,13 +1214,14 @@ export class DshSession {
979
1214
  // toolCallId still beats hiding it from Paseo entirely.
980
1215
  child.openTimer = setTimeout(() => {
981
1216
  child.openTimer = undefined;
982
- this.#tryOpenChild(child);
1217
+ this.#tryOpenChild(child, true);
983
1218
  }, 1500);
984
1219
  child.openTimer.unref?.();
985
1220
  }
986
1221
 
987
- #tryOpenChild(child: ChildSessionState): void {
1222
+ #tryOpenChild(child: ChildSessionState, allowUnknownMode = false): void {
988
1223
  if (child.opened) return;
1224
+ if (child.toolCallId !== undefined && child.mode === undefined && !allowUnknownMode) return;
989
1225
  // A subagent tool is in flight. Wait for its result to learn the call id,
990
1226
  // unless the fallback timer has already fired and cleared that wait.
991
1227
  if (child.toolCallId === undefined && this.#pendingSubagentCalls.size > 0 && child.openTimer !== undefined) {
@@ -996,20 +1232,32 @@ export class DshSession {
996
1232
 
997
1233
  #openChild(child: ChildSessionState): void {
998
1234
  if (child.opened || this.#closed) return;
1235
+ const parent = this.#children.get(child.parentSessionId);
1236
+ if (parent !== undefined && !parent.opened) this.#openChild(parent);
999
1237
  child.opened = true;
1000
1238
  if (child.openTimer !== undefined) {
1001
1239
  clearTimeout(child.openTimer);
1002
1240
  child.openTimer = undefined;
1003
1241
  }
1242
+ // A PTC subcall has its own semantic card; the enclosing run_code remains
1243
+ // the program summary. The host associates children by this exact call id.
1244
+ if (child.toolCallId !== undefined) {
1245
+ const timeline = parent?.timeline ?? this.#timeline;
1246
+ for (const item of timeline.subagent(child.toolCallId, child.toolName ?? "subagent", child.title, child.id)) {
1247
+ this.#options.emit({ type: "timeline.item", sessionId: parent?.id ?? this.id, item });
1248
+ }
1249
+ }
1004
1250
  this.#options.emit({
1005
1251
  type: "session.opened",
1006
1252
  sessionId: child.id,
1007
- parentSessionId: this.id,
1253
+ parentSessionId: parent?.id ?? this.id,
1008
1254
  ...(child.toolCallId === undefined ? {} : { toolCallId: child.toolCallId }),
1009
1255
  // These are the capabilities the host actually negotiated for this
1010
1256
  // connection. Advertising the static CAPABILITIES list here would make
1011
1257
  // Paseo reject the child before it is attached.
1012
- capabilities: [...this.#options.capabilities],
1258
+ capabilities: this.#options.capabilities.filter(capability =>
1259
+ ["permission", "session.subsession"].includes(capability) ||
1260
+ (child.mode === "continuable" && ["prompt.message", "prompt.image", "prompt.steer"].includes(capability))),
1013
1261
  restoration: "parent",
1014
1262
  cwd: child.cwd,
1015
1263
  ...(child.title === undefined ? {} : { title: child.title, description: child.title }),
@@ -1018,7 +1266,8 @@ export class DshSession {
1018
1266
  child.pending = [];
1019
1267
  for (const item of pending) {
1020
1268
  if (item.kind === "event") this.#applyChildEvent(child, item.payload);
1021
- else this.#applyChildStatus(child, item.status);
1269
+ else if (item.kind === "status") this.#applyChildStatus(child, item.status);
1270
+ else this.#applyChildStream(child, item.frame);
1022
1271
  }
1023
1272
  }
1024
1273
 
@@ -1028,6 +1277,7 @@ export class DshSession {
1028
1277
  if (event.type === "turn/start") {
1029
1278
  this.#startChildTurn(child);
1030
1279
  }
1280
+ if (event.type === "assistant/message") this.#finishChildLive(child);
1031
1281
  for (const item of child.timeline.consume(event)) {
1032
1282
  this.#options.emit({ type: "timeline.item", sessionId: child.id, item });
1033
1283
  }
@@ -1052,6 +1302,7 @@ export class DshSession {
1052
1302
  this.#startChildTurn(child);
1053
1303
  return;
1054
1304
  }
1305
+ if (!["idle", "failed", "error", "canceled", "cancelled"].includes(status)) return;
1055
1306
  const state =
1056
1307
  status === "failed" || status === "error"
1057
1308
  ? "failed"
@@ -1079,6 +1330,7 @@ export class DshSession {
1079
1330
  // should produce a terminal turn event.
1080
1331
  if (child.finished) return;
1081
1332
  child.finished = true;
1333
+ this.#finishChildDisplay(child, state);
1082
1334
  // A child can be opened after its turn already ended (late bridge event or
1083
1335
  // replay). Still report the terminal state so Paseo does not leave the
1084
1336
  // subagent stuck on "running".
@@ -1372,8 +1624,17 @@ export class DshSession {
1372
1624
  * Paseo append the delta live; the step's `assistant/message` then arrives as
1373
1625
  * the authoritative final snapshot and replaces the row in place.
1374
1626
  */
1375
- #onAssistantStream(frame: DshAssistantFrame): void {
1627
+ #onAssistantStream(frame: DshAssistantFrame, payload?: DshAssistantStream): void {
1376
1628
  if (this.#closed) return;
1629
+ if (payload !== undefined && payload.sessionId !== this.#dshSessionId) {
1630
+ const child = this.#ensureChild(payload);
1631
+ if (child === undefined) return;
1632
+ if (!child.opened) {
1633
+ child.pending.push({ kind: "stream", frame });
1634
+ this.#scheduleChildOpen(child);
1635
+ } else this.#applyChildStream(child, frame);
1636
+ return;
1637
+ }
1377
1638
  if (frame.type === "start") {
1378
1639
  this.#clearLive();
1379
1640
  this.#streamStats = {
@@ -1424,6 +1685,56 @@ export class DshSession {
1424
1685
  live.timer.unref?.();
1425
1686
  }
1426
1687
 
1688
+ #applyChildStream(child: ChildSessionState, frame: DshAssistantFrame): void {
1689
+ if (frame.type === "start") {
1690
+ this.#finishChildLive(child);
1691
+ child.live = { attemptId: frame.attemptId, turn: frame.turn ?? 0, step: frame.step ?? 0,
1692
+ text: "", emitted: "", reasoning: "", emittedReasoning: "", timer: undefined };
1693
+ return;
1694
+ }
1695
+ const live = child.live;
1696
+ if (live === undefined || live.attemptId !== frame.attemptId) return;
1697
+ if (frame.type === "end") {
1698
+ this.#finishChildLive(child);
1699
+ return;
1700
+ }
1701
+ if (typeof frame.text !== "string") return;
1702
+ if (frame.kind === "reasoning") live.reasoning += frame.text;
1703
+ else live.text += frame.text;
1704
+ if (live.timer !== undefined) return;
1705
+ live.timer = setTimeout(() => this.#flushChildLive(child), 40);
1706
+ live.timer.unref?.();
1707
+ }
1708
+
1709
+ #flushChildLive(child: ChildSessionState): void {
1710
+ const live = child.live;
1711
+ if (live === undefined) return;
1712
+ clearTimeout(live.timer);
1713
+ live.timer = undefined;
1714
+ if (live.reasoning !== live.emittedReasoning) {
1715
+ live.emittedReasoning = live.reasoning;
1716
+ this.#options.emit({ type: "timeline.item", sessionId: child.id, item: {
1717
+ type: "reasoning", id: `reasoning:${live.turn}:${live.step}`, text: live.reasoning,
1718
+ } });
1719
+ }
1720
+ if (live.text !== live.emitted) {
1721
+ live.emitted = live.text;
1722
+ this.#options.emit({ type: "timeline.item", sessionId: child.id, item: {
1723
+ type: "assistant_message", id: `assistant:${live.turn}:${live.step}`, text: live.text,
1724
+ } });
1725
+ }
1726
+ }
1727
+
1728
+ #finishChildLive(child: ChildSessionState): void {
1729
+ this.#flushChildLive(child);
1730
+ child.live = undefined;
1731
+ }
1732
+
1733
+ #finishChildDisplay(child: ChildSessionState, status: "completed" | "failed" | "canceled"): void {
1734
+ this.#finishChildLive(child);
1735
+ for (const item of child.timeline.finishPending(status)) this.#options.emit({ type: "timeline.item", sessionId: child.id, item });
1736
+ }
1737
+
1427
1738
  /** Publish the accumulated live text as the message row's current snapshot. */
1428
1739
  #flushLive(): void {
1429
1740
  const live = this.#live;
@@ -1544,7 +1855,7 @@ export class DshSession {
1544
1855
  } as unknown as Readonly<Record<string, JsonValue>>,
1545
1856
  };
1546
1857
 
1547
- return this.#openCard(permission);
1858
+ return this.#openCard(permission, request.sessionId, request.requestId);
1548
1859
  }
1549
1860
 
1550
1861
  /**
@@ -1578,12 +1889,46 @@ export class DshSession {
1578
1889
  ],
1579
1890
  };
1580
1891
 
1581
- return this.#openCard(permission);
1892
+ return this.#openCard(permission, request.sessionId, request.requestId);
1582
1893
  }
1583
1894
 
1584
- #openCard(permission: ProviderPermissionRequest): Promise<ProviderPermissionResponse> {
1895
+ async #onApproval(request: DshApprovalRequest): Promise<{ behavior: "allow" | "deny" }> {
1896
+ const response = await this.#openCard({
1897
+ id: request.callId ?? request.requestId ?? "approval",
1898
+ name: request.toolName, kind: "tool", title: request.toolName,
1899
+ ...(request.reason === undefined ? {} : { description: request.reason }),
1900
+ actions: [
1901
+ { id: "deny", label: "Deny", behavior: "deny", variant: "danger" },
1902
+ { id: "allow", label: "Allow once", behavior: "allow", variant: "primary" },
1903
+ ],
1904
+ }, request.sessionId, request.requestId);
1905
+ return { behavior: response.behavior };
1906
+ }
1907
+
1908
+ #cancelPermissionRequest(requestId: string): void {
1909
+ for (const [id, pending] of this.#pendingPermissions) {
1910
+ if (pending.requestId === requestId) this.resolvePermission(id, { behavior: "deny", message: "Request cancelled" });
1911
+ }
1912
+ }
1913
+
1914
+ #openCard(permission: ProviderPermissionRequest, nativeSessionId = this.#dshSessionId, requestId?: string): Promise<ProviderPermissionResponse> {
1915
+ if (nativeSessionId !== this.#dshSessionId) {
1916
+ const child = this.#requireChild(nativeSessionId);
1917
+ permission = { ...permission, id: `${child.id}:${permission.id}`,
1918
+ description: [child.title ?? "Subagent", permission.description].filter(Boolean).join(": ") };
1919
+ }
1920
+ // Pending cards are keyed by id, so a duplicate would replace the earlier
1921
+ // promise: that approval would never be answered and DSH would wait for its
1922
+ // own timeout. Sibling sessions can raise the same tool call id, and an
1923
+ // approval without a call id falls back to a shared literal.
1924
+ if (this.#pendingPermissions.has(permission.id)) {
1925
+ permission = { ...permission, id: `${permission.id}:${this.#cardSeq}` };
1926
+ this.#cardSeq += 1;
1927
+ }
1928
+ // Paseo currently ignores child permission events. Promote cards to the
1929
+ // root, retaining their native owner for responses and cancellation.
1585
1930
  return new Promise<ProviderPermissionResponse>((resolve) => {
1586
- this.#pendingPermissions.set(permission.id, resolve);
1931
+ this.#pendingPermissions.set(permission.id, { resolve, sessionId: nativeSessionId, requestId });
1587
1932
  this.#options.emit({ type: "session.permission", sessionId: this.id, request: permission });
1588
1933
  });
1589
1934
  }
@@ -1599,6 +1944,23 @@ export class DshSession {
1599
1944
  };
1600
1945
  this.#thinkingOption = applied.reasoningEffort ?? undefined;
1601
1946
  }
1947
+
1948
+ #clearPendingPermissionsForSteer(nativeSessionId: string): void {
1949
+ for (const [id, pending] of [...this.#pendingPermissions]) {
1950
+ if (pending.sessionId === nativeSessionId) {
1951
+ this.resolvePermission(id, {
1952
+ behavior: "deny",
1953
+ message: "The user answered with a message instead of approving. Their message follows.",
1954
+ });
1955
+ }
1956
+ }
1957
+ }
1958
+
1959
+ #nextTurnId(): string {
1960
+ const now = Date.now();
1961
+ this.#turnSeq = now > this.#turnSeq ? now : this.#turnSeq + 1;
1962
+ return `turn:${this.#turnSeq}`;
1963
+ }
1602
1964
  }
1603
1965
 
1604
1966
  /**