paseo-dsh 0.2.21 → 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,
@@ -521,11 +557,27 @@ export class DshSession {
521
557
  }
522
558
 
523
559
  /** Accept one prompt and start its turn. */
524
- async prompt(prompt: ProviderPrompt): Promise<void> {
525
- // A user turn must not start with the previous answer's live buffer still
526
- // attached; flush it so the two turns cannot interleave.
527
- this.#flushLive();
528
- 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
+ }
529
581
  const process = this.#require();
530
582
 
531
583
  // Last chance to land a preset that arrived while the session was opening:
@@ -555,6 +607,17 @@ export class DshSession {
555
607
  // skills share the menu but not the execution path, so branch on the kind
556
608
  // the catalog recorded rather than on the name.
557
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
+ }
558
621
  const args = prompt.input.arguments ?? "";
559
622
  const line = args.trim() === "" ? `/${prompt.input.name}` : `/${prompt.input.name} ${args}`;
560
623
  // A command message has no DSH user event of its own. Anchor it at the
@@ -568,13 +631,13 @@ export class DshSession {
568
631
  } catch (error) {
569
632
  this.#options.log(`command boundary unavailable: ${messageOf(error)}`);
570
633
  }
571
- this.#emitUserMessage(
572
- prompt.clientMessageId,
573
- line,
574
- boundary === undefined ? undefined : { seq: boundary },
575
- );
576
634
 
577
635
  if (this.#commandKinds.get(prompt.input.name) === "command") {
636
+ this.#emitUserMessage(
637
+ prompt.clientMessageId,
638
+ line,
639
+ boundary === undefined ? undefined : { seq: boundary },
640
+ );
578
641
  try {
579
642
  const result = await process.runCommand(prompt.input.name, args);
580
643
  if (result.kind === "error") throw new Error(result.text ?? `/${prompt.input.name} failed`);
@@ -594,11 +657,46 @@ export class DshSession {
594
657
 
595
658
  // A skill (or an unrecognized name): hand DSH the bare `/name` line. Its
596
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
+ }
597
667
  try {
598
668
  const result = await process.prompt(line, [{ type: "text", text: line }], prompt.delivery);
599
- this.#emitPromptAccepted(prompt.clientMessageId);
600
- 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);
601
692
  } catch (error) {
693
+ if (isSteer) {
694
+ this.#emitUserMessage(
695
+ prompt.clientMessageId,
696
+ line,
697
+ boundary === undefined ? undefined : { seq: boundary },
698
+ );
699
+ }
602
700
  this.#emitPromptFailed(prompt.clientMessageId, error);
603
701
  return;
604
702
  }
@@ -623,10 +721,10 @@ export class DshSession {
623
721
 
624
722
  // An idle auto prompt can wait for DSH to append the durable user event,
625
723
  // so publish the row once with its rewind token instead of publishing it
626
- // twice. Steer and mid-turn prompts must stay optimistic: their user event
627
- // may only arrive in a later turn, so show the row now and attach the token
628
- // when the event (or the bridge response) supplies the seq.
629
- 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;
630
728
  if (optimistic) this.#emitUserMessage(prompt.clientMessageId, label);
631
729
 
632
730
  const result = await process.prompt(
@@ -634,6 +732,15 @@ export class DshSession {
634
732
  blocks.length === 0 ? undefined : blocks,
635
733
  prompt.delivery,
636
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
+ }
637
744
  acceptedSeq = result.seq;
638
745
  if (!optimistic) {
639
746
  this.#emitUserMessage(
@@ -665,8 +772,11 @@ export class DshSession {
665
772
  return;
666
773
  }
667
774
 
668
- this.#emitPromptAccepted(prompt.clientMessageId);
669
- // 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
670
780
  // id and text so Paseo records the token without adding a second row.
671
781
  if (optimistic && acceptedSeq !== undefined) {
672
782
  this.#emitRewindToken(prompt.clientMessageId, acceptedText, acceptedSeq);
@@ -741,7 +851,16 @@ export class DshSession {
741
851
  });
742
852
  }
743
853
 
744
- #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
+ }
745
864
  const turnId = this.#turnId ?? `turn:${clientMessageId}`;
746
865
  this.#options.emit({
747
866
  type: "session.prompt_result",
@@ -839,19 +958,34 @@ export class DshSession {
839
958
  }
840
959
 
841
960
  /** Answer a pending question card. */
842
- resolvePermission(permissionId: string, response: ProviderPermissionResponse): void {
843
- const resolve = this.#pendingPermissions.get(permissionId);
844
- 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');
845
965
  this.#pendingPermissions.delete(permissionId);
846
966
  this.#options.emit({ type: "session.permission_resolved", sessionId: this.id, permissionId });
847
- 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
+ }
848
976
  }
849
977
 
850
978
  /**
851
979
  * Cancel the running turn. The session and its history survive, so the
852
980
  * conversation stays continuable — killing the process stranded it instead.
853
981
  */
854
- 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
+ }
855
989
  this.#turnInterrupted = true;
856
990
  this.#flushLive();
857
991
  this.#clearLive();
@@ -863,7 +997,9 @@ export class DshSession {
863
997
  if (this.#closed) return;
864
998
  this.#closed = true;
865
999
  clearTimeout(this.#usageRefreshTimer);
1000
+ for (const [id] of this.#pendingPermissions) this.resolvePermission(id, { behavior: "deny", message: "Session closed" });
866
1001
  for (const child of this.#children.values()) {
1002
+ this.#finishChildDisplay(child, "canceled");
867
1003
  if (child.openTimer !== undefined) clearTimeout(child.openTimer);
868
1004
  if (child.opened) {
869
1005
  this.#options.emit({ type: "session.closed", sessionId: child.id });
@@ -878,6 +1014,75 @@ export class DshSession {
878
1014
  await this.#process?.shutdown();
879
1015
  }
880
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
+
881
1086
  #require(): DshProcess {
882
1087
  if (this.#process === undefined || this.#closed) {
883
1088
  throw new Error(`session ${this.id} is not open`);
@@ -898,7 +1103,7 @@ export class DshSession {
898
1103
  // A later usage refresh must not rewrite the previous turn's row.
899
1104
  this.#lastStats = undefined;
900
1105
  }
901
- const turnId = this.#turnId ?? `turn:${Date.now()}`;
1106
+ const turnId = this.#turnId ?? this.#nextTurnId();
902
1107
  this.#turnId = turnId;
903
1108
  this.#options.emit({ type: "session.turn", sessionId: this.id, turnId, state: "started" });
904
1109
  return;
@@ -909,16 +1114,20 @@ export class DshSession {
909
1114
  /**
910
1115
  * Find or create the local view of a child session.
911
1116
  *
912
- * A session is only treated as a child when its header names this session as
913
- * the parent *and* marks it as a subagent. In DSH 0.2.1 `parentSession` also
914
- * 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.
915
1120
  */
916
1121
  #ensureChild(meta: {
917
1122
  sessionId: string;
918
1123
  parentSessionId?: string;
919
1124
  origin?: string;
920
1125
  cwd?: string;
1126
+ toolCallId?: string;
1127
+ toolName?: string;
1128
+ toolTitle?: string;
921
1129
  }): ChildSessionState | undefined {
1130
+ if (this.#closedChildIds.has(meta.sessionId)) return undefined;
922
1131
  if (!this.#options.capabilities.includes("session.subsession")) {
923
1132
  if (!this.#warnedNoSubsession) {
924
1133
  this.#warnedNoSubsession = true;
@@ -931,11 +1140,19 @@ export class DshSession {
931
1140
  const existing = this.#children.get(meta.sessionId);
932
1141
  if (existing !== undefined) {
933
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;
934
1146
  return existing;
935
1147
  }
936
- 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;
937
1150
  const child: ChildSessionState = {
938
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 }),
939
1156
  timeline: new TimelineBuilder(),
940
1157
  cwd: meta.cwd ?? this.#options.cwd,
941
1158
  opened: false,
@@ -947,12 +1164,18 @@ export class DshSession {
947
1164
  return child;
948
1165
  }
949
1166
 
1167
+ #onChildLink(meta: Omit<DshStatusEvent, "status">): void {
1168
+ const child = this.#ensureChild(meta);
1169
+ if (child !== undefined) this.#tryOpenChild(child);
1170
+ }
1171
+
950
1172
  #onChildSessionEvent(payload: DshSessionEvent): void {
951
1173
  const child = this.#ensureChild(payload);
952
1174
  if (child === undefined) return;
953
1175
  const event = payload.event;
954
1176
  if (event.type === "subagent/descriptor") {
955
1177
  const data = isRecord(event.data) ? event.data : {};
1178
+ if (data.mode === "continuable" || data.mode === "one-shot") child.mode = data.mode;
956
1179
  const title =
957
1180
  typeof data.label === "string"
958
1181
  ? data.label
@@ -963,6 +1186,10 @@ export class DshSession {
963
1186
  }
964
1187
  if (!child.opened) {
965
1188
  child.pending.push({ kind: "event", payload });
1189
+ if (child.toolCallId !== undefined && child.mode !== undefined) {
1190
+ this.#tryOpenChild(child);
1191
+ return;
1192
+ }
966
1193
  this.#scheduleChildOpen(child);
967
1194
  return;
968
1195
  }
@@ -987,13 +1214,14 @@ export class DshSession {
987
1214
  // toolCallId still beats hiding it from Paseo entirely.
988
1215
  child.openTimer = setTimeout(() => {
989
1216
  child.openTimer = undefined;
990
- this.#tryOpenChild(child);
1217
+ this.#tryOpenChild(child, true);
991
1218
  }, 1500);
992
1219
  child.openTimer.unref?.();
993
1220
  }
994
1221
 
995
- #tryOpenChild(child: ChildSessionState): void {
1222
+ #tryOpenChild(child: ChildSessionState, allowUnknownMode = false): void {
996
1223
  if (child.opened) return;
1224
+ if (child.toolCallId !== undefined && child.mode === undefined && !allowUnknownMode) return;
997
1225
  // A subagent tool is in flight. Wait for its result to learn the call id,
998
1226
  // unless the fallback timer has already fired and cleared that wait.
999
1227
  if (child.toolCallId === undefined && this.#pendingSubagentCalls.size > 0 && child.openTimer !== undefined) {
@@ -1004,20 +1232,32 @@ export class DshSession {
1004
1232
 
1005
1233
  #openChild(child: ChildSessionState): void {
1006
1234
  if (child.opened || this.#closed) return;
1235
+ const parent = this.#children.get(child.parentSessionId);
1236
+ if (parent !== undefined && !parent.opened) this.#openChild(parent);
1007
1237
  child.opened = true;
1008
1238
  if (child.openTimer !== undefined) {
1009
1239
  clearTimeout(child.openTimer);
1010
1240
  child.openTimer = undefined;
1011
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
+ }
1012
1250
  this.#options.emit({
1013
1251
  type: "session.opened",
1014
1252
  sessionId: child.id,
1015
- parentSessionId: this.id,
1253
+ parentSessionId: parent?.id ?? this.id,
1016
1254
  ...(child.toolCallId === undefined ? {} : { toolCallId: child.toolCallId }),
1017
1255
  // These are the capabilities the host actually negotiated for this
1018
1256
  // connection. Advertising the static CAPABILITIES list here would make
1019
1257
  // Paseo reject the child before it is attached.
1020
- 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))),
1021
1261
  restoration: "parent",
1022
1262
  cwd: child.cwd,
1023
1263
  ...(child.title === undefined ? {} : { title: child.title, description: child.title }),
@@ -1026,7 +1266,8 @@ export class DshSession {
1026
1266
  child.pending = [];
1027
1267
  for (const item of pending) {
1028
1268
  if (item.kind === "event") this.#applyChildEvent(child, item.payload);
1029
- else this.#applyChildStatus(child, item.status);
1269
+ else if (item.kind === "status") this.#applyChildStatus(child, item.status);
1270
+ else this.#applyChildStream(child, item.frame);
1030
1271
  }
1031
1272
  }
1032
1273
 
@@ -1036,6 +1277,7 @@ export class DshSession {
1036
1277
  if (event.type === "turn/start") {
1037
1278
  this.#startChildTurn(child);
1038
1279
  }
1280
+ if (event.type === "assistant/message") this.#finishChildLive(child);
1039
1281
  for (const item of child.timeline.consume(event)) {
1040
1282
  this.#options.emit({ type: "timeline.item", sessionId: child.id, item });
1041
1283
  }
@@ -1060,6 +1302,7 @@ export class DshSession {
1060
1302
  this.#startChildTurn(child);
1061
1303
  return;
1062
1304
  }
1305
+ if (!["idle", "failed", "error", "canceled", "cancelled"].includes(status)) return;
1063
1306
  const state =
1064
1307
  status === "failed" || status === "error"
1065
1308
  ? "failed"
@@ -1087,6 +1330,7 @@ export class DshSession {
1087
1330
  // should produce a terminal turn event.
1088
1331
  if (child.finished) return;
1089
1332
  child.finished = true;
1333
+ this.#finishChildDisplay(child, state);
1090
1334
  // A child can be opened after its turn already ended (late bridge event or
1091
1335
  // replay). Still report the terminal state so Paseo does not leave the
1092
1336
  // subagent stuck on "running".
@@ -1380,8 +1624,17 @@ export class DshSession {
1380
1624
  * Paseo append the delta live; the step's `assistant/message` then arrives as
1381
1625
  * the authoritative final snapshot and replaces the row in place.
1382
1626
  */
1383
- #onAssistantStream(frame: DshAssistantFrame): void {
1627
+ #onAssistantStream(frame: DshAssistantFrame, payload?: DshAssistantStream): void {
1384
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
+ }
1385
1638
  if (frame.type === "start") {
1386
1639
  this.#clearLive();
1387
1640
  this.#streamStats = {
@@ -1432,6 +1685,56 @@ export class DshSession {
1432
1685
  live.timer.unref?.();
1433
1686
  }
1434
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
+
1435
1738
  /** Publish the accumulated live text as the message row's current snapshot. */
1436
1739
  #flushLive(): void {
1437
1740
  const live = this.#live;
@@ -1552,7 +1855,7 @@ export class DshSession {
1552
1855
  } as unknown as Readonly<Record<string, JsonValue>>,
1553
1856
  };
1554
1857
 
1555
- return this.#openCard(permission);
1858
+ return this.#openCard(permission, request.sessionId, request.requestId);
1556
1859
  }
1557
1860
 
1558
1861
  /**
@@ -1586,12 +1889,46 @@ export class DshSession {
1586
1889
  ],
1587
1890
  };
1588
1891
 
1589
- return this.#openCard(permission);
1892
+ return this.#openCard(permission, request.sessionId, request.requestId);
1590
1893
  }
1591
1894
 
1592
- #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.
1593
1930
  return new Promise<ProviderPermissionResponse>((resolve) => {
1594
- this.#pendingPermissions.set(permission.id, resolve);
1931
+ this.#pendingPermissions.set(permission.id, { resolve, sessionId: nativeSessionId, requestId });
1595
1932
  this.#options.emit({ type: "session.permission", sessionId: this.id, request: permission });
1596
1933
  });
1597
1934
  }
@@ -1607,6 +1944,23 @@ export class DshSession {
1607
1944
  };
1608
1945
  this.#thinkingOption = applied.reasoningEffort ?? undefined;
1609
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
+ }
1610
1964
  }
1611
1965
 
1612
1966
  /**