@deepseek-ai/dsh-subagent 0.2.2-rc.1 → 0.2.2-rc.3

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.
Files changed (108) hide show
  1. package/README.i18n.yaml +46 -28
  2. package/README.md +52 -23
  3. package/README.zh.md +52 -23
  4. package/lib/index.js +845 -902
  5. package/lib/typert.host.js +91 -125
  6. package/lib/typert.remote-client.d.ts +3 -3
  7. package/lib/typert.remote-client.d.ts.map +1 -0
  8. package/lib/typert.remote-client.js +17 -63
  9. package/lib/types/activation.d.ts +17 -25
  10. package/lib/types/activation.d.ts.map +1 -0
  11. package/lib/types/activation.js +1 -1
  12. package/lib/types/activation.js.map +1 -0
  13. package/lib/types/archive-admission.d.ts +11 -4
  14. package/lib/types/archive-admission.d.ts.map +1 -0
  15. package/lib/types/archive-admission.js +39 -115
  16. package/lib/types/archive-admission.js.map +1 -0
  17. package/lib/types/assistant-output.d.ts.map +1 -0
  18. package/lib/types/assistant-output.js.map +1 -0
  19. package/lib/types/catalog.d.ts +27 -7
  20. package/lib/types/catalog.d.ts.map +1 -0
  21. package/lib/types/catalog.js +31 -8
  22. package/lib/types/catalog.js.map +1 -0
  23. package/lib/types/child-agent.d.ts +7 -17
  24. package/lib/types/child-agent.d.ts.map +1 -0
  25. package/lib/types/child-agent.js +6 -4
  26. package/lib/types/child-agent.js.map +1 -0
  27. package/lib/types/client.d.ts.map +1 -0
  28. package/lib/types/client.js.map +1 -0
  29. package/lib/types/continuation-messages.d.ts +13 -10
  30. package/lib/types/continuation-messages.d.ts.map +1 -0
  31. package/lib/types/continuation-messages.js +22 -22
  32. package/lib/types/continuation-messages.js.map +1 -0
  33. package/lib/types/control-types.d.ts +7 -28
  34. package/lib/types/control-types.d.ts.map +1 -0
  35. package/lib/types/control-types.js.map +1 -0
  36. package/lib/types/control.d.ts +0 -4
  37. package/lib/types/control.d.ts.map +1 -0
  38. package/lib/types/control.js +1 -5
  39. package/lib/types/control.js.map +1 -0
  40. package/lib/types/depth.d.ts.map +1 -0
  41. package/lib/types/depth.js.map +1 -0
  42. package/lib/types/descriptor.d.ts +1 -1
  43. package/lib/types/descriptor.d.ts.map +1 -0
  44. package/lib/types/descriptor.js +1 -1
  45. package/lib/types/descriptor.js.map +1 -0
  46. package/lib/types/error.d.ts.map +1 -0
  47. package/lib/types/error.js.map +1 -0
  48. package/lib/types/index.d.ts +74 -97
  49. package/lib/types/index.d.ts.map +1 -0
  50. package/lib/types/index.js +125 -146
  51. package/lib/types/index.js.map +1 -0
  52. package/lib/types/lifecycle.d.ts +9 -38
  53. package/lib/types/lifecycle.d.ts.map +1 -0
  54. package/lib/types/lifecycle.js +5 -31
  55. package/lib/types/lifecycle.js.map +1 -0
  56. package/lib/types/list-children.d.ts +12 -0
  57. package/lib/types/list-children.d.ts.map +1 -0
  58. package/lib/types/list-children.js +35 -6
  59. package/lib/types/list-children.js.map +1 -0
  60. package/lib/types/manager.d.ts +96 -112
  61. package/lib/types/manager.d.ts.map +1 -0
  62. package/lib/types/manager.js +471 -568
  63. package/lib/types/manager.js.map +1 -0
  64. package/lib/types/names.d.ts +56 -0
  65. package/lib/types/names.d.ts.map +1 -0
  66. package/lib/types/names.js +96 -0
  67. package/lib/types/names.js.map +1 -0
  68. package/lib/types/out-of-process.d.ts.map +1 -0
  69. package/lib/types/out-of-process.js.map +1 -0
  70. package/lib/types/projection-types.d.ts +18 -6
  71. package/lib/types/projection-types.d.ts.map +1 -0
  72. package/lib/types/projection-types.js.map +1 -0
  73. package/lib/types/projection.d.ts +2 -2
  74. package/lib/types/projection.d.ts.map +1 -0
  75. package/lib/types/projection.js.map +1 -0
  76. package/lib/types/structured.d.ts +1 -1
  77. package/lib/types/structured.d.ts.map +1 -0
  78. package/lib/types/structured.js +2 -2
  79. package/lib/types/structured.js.map +1 -0
  80. package/lib/types/types.d.ts +34 -28
  81. package/lib/types/types.d.ts.map +1 -0
  82. package/lib/types/types.js +2 -4
  83. package/lib/types/types.js.map +1 -0
  84. package/package.json +54 -54
  85. package/src/activation.ts +184 -0
  86. package/src/archive-admission.ts +84 -0
  87. package/src/assistant-output.ts +75 -0
  88. package/src/catalog.ts +194 -0
  89. package/src/child-agent.ts +280 -0
  90. package/src/client.ts +8 -0
  91. package/src/continuation-messages.ts +176 -0
  92. package/src/control-types.ts +127 -0
  93. package/src/control.ts +103 -0
  94. package/src/depth.ts +51 -0
  95. package/src/descriptor.ts +269 -0
  96. package/src/error.ts +15 -0
  97. package/src/index.ts +604 -0
  98. package/src/lifecycle.ts +116 -0
  99. package/src/list-children.ts +168 -0
  100. package/src/manager.ts +1359 -0
  101. package/src/names.ts +113 -0
  102. package/src/out-of-process.ts +217 -0
  103. package/src/projection-types.ts +109 -0
  104. package/src/projection.ts +184 -0
  105. package/src/structured.ts +155 -0
  106. package/src/types.ts +364 -0
  107. package/lib/types/internal.d.ts +0 -58
  108. package/lib/types/internal.js +0 -58
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-subagent",
3
3
  "description": "Abstract subagent seam (ctx.subagents): named-provider registry for delegating to child agents",
4
- "version": "0.2.2-rc.1",
4
+ "version": "0.2.2-rc.3",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -18,10 +18,6 @@
18
18
  "types": "./lib/types/index.d.ts",
19
19
  "default": "./lib/index.js"
20
20
  },
21
- "./internal": {
22
- "types": "./lib/types/internal.d.ts",
23
- "default": "./lib/types/internal.js"
24
- },
25
21
  "./client": {
26
22
  "types": "./lib/types/client.d.ts",
27
23
  "default": "./lib/types/client.js"
@@ -43,40 +39,44 @@
43
39
  "lib/index.js",
44
40
  "lib/types/**/*.js",
45
41
  "lib/types/**/*.d.ts",
42
+ "lib/types/**/*.d.ts.map",
43
+ "lib/**/*.js.map",
46
44
  "lib/typert.host.js",
47
45
  "lib/typert.host.d.ts",
48
46
  "lib/typert.remote-client.js",
49
- "lib/typert.remote-client.d.ts"
47
+ "lib/typert.remote-client.d.ts",
48
+ "lib/typert.remote-client.d.ts.map",
49
+ "src"
50
50
  ],
51
51
  "license": "MIT",
52
52
  "dependencies": {
53
- "@deepseek-ai/dsh-brand": "0.2.2-rc.1",
54
- "@deepseek-ai/dsh-chunked-list": "0.2.2-rc.1",
55
- "@deepseek-ai/dsh-util-values": "0.2.2-rc.1",
53
+ "@deepseek-ai/dsh-brand": "0.2.2-rc.3",
54
+ "@deepseek-ai/dsh-chunked-list": "0.2.2-rc.3",
55
+ "@deepseek-ai/dsh-util-values": "0.2.2-rc.3",
56
56
  "@deepseek-ai/schemastery": "~3.19.0",
57
- "zod": "4.4.3"
57
+ "zod": "4.6.6"
58
58
  },
59
59
  "peerDependencies": {
60
60
  "@deepseek-ai/cordis": "~4.1.0",
61
- "@deepseek-ai/dsh-agent": "0.2.2-rc.1",
62
- "@deepseek-ai/dsh-agent-preset-registry": "0.2.2-rc.1",
63
- "@deepseek-ai/dsh-attachment": "0.2.2-rc.1",
64
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
65
- "@deepseek-ai/dsh-sandbox": "0.2.2-rc.1",
66
- "@deepseek-ai/dsh-sandbox-policy": "0.2.2-rc.1",
67
- "@deepseek-ai/dsh-scope": "0.2.2-rc.1",
68
- "@deepseek-ai/dsh-session": "0.2.2-rc.1",
69
- "@deepseek-ai/dsh-session-persistence": "0.2.2-rc.1",
70
- "@deepseek-ai/dsh-session-projection": "0.2.2-rc.1",
71
- "@deepseek-ai/dsh-session-query": "0.2.2-rc.1",
72
- "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.1",
73
- "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
74
- "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.1",
75
- "@deepseek-ai/dsh-user-approval": "0.2.2-rc.1",
76
- "@deepseek-ai/dsh-util-time": "0.2.2-rc.1",
77
- "@deepseek-ai/dsh-permission-presets": "0.2.2-rc.1",
78
- "@deepseek-ai/dsh-workspace": "0.2.2-rc.1",
79
- "@deepseek-ai/dsh-working-directory": "0.2.2-rc.1"
61
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.3",
62
+ "@deepseek-ai/dsh-agent-preset-registry": "0.2.2-rc.3",
63
+ "@deepseek-ai/dsh-attachment": "0.2.2-rc.3",
64
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
65
+ "@deepseek-ai/dsh-sandbox": "0.2.2-rc.3",
66
+ "@deepseek-ai/dsh-sandbox-policy": "0.2.2-rc.3",
67
+ "@deepseek-ai/dsh-scope": "0.2.2-rc.3",
68
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3",
69
+ "@deepseek-ai/dsh-session-persistence": "0.2.2-rc.3",
70
+ "@deepseek-ai/dsh-session-projection": "0.2.2-rc.3",
71
+ "@deepseek-ai/dsh-session-query": "0.2.2-rc.3",
72
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.3",
73
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.3",
74
+ "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.3",
75
+ "@deepseek-ai/dsh-user-approval": "0.2.2-rc.3",
76
+ "@deepseek-ai/dsh-util-time": "0.2.2-rc.3",
77
+ "@deepseek-ai/dsh-permission-presets": "0.2.2-rc.3",
78
+ "@deepseek-ai/dsh-workspace": "0.2.2-rc.3",
79
+ "@deepseek-ai/dsh-working-directory": "0.2.2-rc.3"
80
80
  },
81
81
  "peerDependenciesMeta": {
82
82
  "@deepseek-ai/dsh-agent-preset-registry": {
@@ -106,32 +106,32 @@
106
106
  },
107
107
  "devDependencies": {
108
108
  "@deepseek-ai/cordis": "~4.1.0",
109
- "@deepseek-ai/dsh-agent": "0.2.2-rc.1",
110
- "@deepseek-ai/dsh-agent-preset-registry": "0.2.2-rc.1",
111
- "@deepseek-ai/dsh-attachment": "0.2.2-rc.1",
112
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
113
- "@deepseek-ai/dsh-sandbox": "0.2.2-rc.1",
114
- "@deepseek-ai/dsh-sandbox-policy": "0.2.2-rc.1",
115
- "@deepseek-ai/dsh-scope": "0.2.2-rc.1",
116
- "@deepseek-ai/dsh-session": "0.2.2-rc.1",
117
- "@deepseek-ai/dsh-session-persistence": "0.2.2-rc.1",
118
- "@deepseek-ai/dsh-session-projection": "0.2.2-rc.1",
119
- "@deepseek-ai/dsh-session-query": "0.2.2-rc.1",
120
- "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.1",
121
- "@deepseek-ai/dsh-tool-testkit": "0.2.2-rc.1",
122
- "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
123
- "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.1",
124
- "@deepseek-ai/dsh-user-approval": "0.2.2-rc.1",
125
- "@deepseek-ai/dsh-util-time": "0.2.2-rc.1",
126
- "@deepseek-ai/dsh-permission-presets": "0.2.2-rc.1",
127
- "@deepseek-ai/dsh-workspace": "0.2.2-rc.1",
109
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.3",
110
+ "@deepseek-ai/dsh-agent-preset-registry": "0.2.2-rc.3",
111
+ "@deepseek-ai/dsh-attachment": "0.2.2-rc.3",
112
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
113
+ "@deepseek-ai/dsh-sandbox": "0.2.2-rc.3",
114
+ "@deepseek-ai/dsh-sandbox-policy": "0.2.2-rc.3",
115
+ "@deepseek-ai/dsh-scope": "0.2.2-rc.3",
116
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3",
117
+ "@deepseek-ai/dsh-session-persistence": "0.2.2-rc.3",
118
+ "@deepseek-ai/dsh-session-projection": "0.2.2-rc.3",
119
+ "@deepseek-ai/dsh-session-query": "0.2.2-rc.3",
120
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.3",
121
+ "@deepseek-ai/dsh-tool-testkit": "0.2.2-rc.3",
122
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.3",
123
+ "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.3",
124
+ "@deepseek-ai/dsh-user-approval": "0.2.2-rc.3",
125
+ "@deepseek-ai/dsh-util-time": "0.2.2-rc.3",
126
+ "@deepseek-ai/dsh-permission-presets": "0.2.2-rc.3",
127
+ "@deepseek-ai/dsh-workspace": "0.2.2-rc.3",
128
128
  "@deepseek-ai/cordis-plugin-include": "~1.1.0",
129
129
  "@deepseek-ai/cordis-plugin-loader": "~1.1.0",
130
- "@deepseek-ai/dsh-agent-loop": "0.2.2-rc.1",
131
- "@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.1",
132
- "@deepseek-ai/dsh-fs-sandbox": "0.2.2-rc.1",
133
- "@deepseek-ai/dsh-tool-fs": "0.2.2-rc.1",
134
- "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.2-rc.1",
135
- "@deepseek-ai/dsh-working-directory": "0.2.2-rc.1"
130
+ "@deepseek-ai/dsh-agent-loop": "0.2.2-rc.3",
131
+ "@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.3",
132
+ "@deepseek-ai/dsh-fs-sandbox": "0.2.2-rc.3",
133
+ "@deepseek-ai/dsh-tool-fs": "0.2.2-rc.3",
134
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.2-rc.3",
135
+ "@deepseek-ai/dsh-working-directory": "0.2.2-rc.3"
136
136
  }
137
137
  }
@@ -0,0 +1,184 @@
1
+ /** Execution-period records, capacity slots, child serialization, and local output capture.
2
+ * @module @deepseek-ai/dsh-subagent/activation
3
+ */
4
+
5
+ import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'
6
+ import type { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
7
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
8
+ import { finalAssistantOutput } from './assistant-output.ts'
9
+ import { epochStopReason } from './lifecycle.ts'
10
+ import { SubagentError } from './error.ts'
11
+ import type { StructuredAttachment } from './structured.ts'
12
+ import type { SubagentResult, SubagentRun, SubagentRunId } from './types.ts'
13
+
14
+ /** Process-local capacity shared by every member of a subagent tree. */
15
+ export class ActivationPool {
16
+ private readonly slots = new Set<symbol>()
17
+
18
+ /**
19
+ * Reserve before reconstruction; release also tolerates unpublished rollback.
20
+ * @param capacity - the maximum simultaneous activations in this pool.
21
+ * @returns an idempotent slot release.
22
+ */
23
+ reserve(capacity: number): () => void {
24
+ if (this.slots.size >= capacity) {
25
+ throw new SubagentError(
26
+ `subagent limit reached (active child limit: ${capacity}); wait for an existing child to finish `
27
+ + 'or complete this work with the current agents',
28
+ 'ACTIVATION_LIMIT_REACHED',
29
+ )
30
+ }
31
+ const slot = Symbol()
32
+ this.slots.add(slot)
33
+ return () => { this.slots.delete(slot) }
34
+ }
35
+ }
36
+
37
+ /**
38
+ * One residency epoch for a local child or an external execution.
39
+ * The manager owns admission, execution handles, and resource release.
40
+ */
41
+ interface ActivationBase {
42
+ /** Return this epoch's slot after its handle has finished disposal. */
43
+ readonly releaseSlot: () => void
44
+ /** The durable child this Activation is an epoch of. */
45
+ readonly childId: SessionId
46
+ /** Unique identity shared by this residency epoch's start/end event pair. */
47
+ readonly runId: SubagentRunId
48
+ /** Provider recorded at creation, retained across cold resumes. */
49
+ readonly provider: string
50
+ /** Exact live subagent tree root owning this instance and its shared capacity. */
51
+ readonly root: Agent
52
+ /** Verified creation ancestors, from subagent tree root to direct creator. */
53
+ readonly ancestors: readonly SessionId[]
54
+ /** Slash-separated names from the root; undefined when this child or a creator below the root has no name. */
55
+ readonly path: string | undefined
56
+ readonly delivery: 'parent' | 'caller'
57
+ readonly result: PromiseWithResolvers<SubagentResult>
58
+ /** Published synchronously before teardown; subsequent callers share this transaction. */
59
+ closing: Promise<void> | undefined
60
+ /**
61
+ * Whether local input was accepted or external startup completed, including
62
+ * any required catalog publication. Until then, teardown owes the parent no
63
+ * settlement notice, even if this epoch's start event was already published.
64
+ */
65
+ accepted: boolean
66
+ }
67
+
68
+ /** Resources retained only for the selected execution kind. */
69
+ export type ActivationResource =
70
+ | {
71
+ readonly kind: 'local'
72
+ readonly handle: AgentHandle
73
+ readonly outputStart: SessionLogOffset
74
+ readonly structured: StructuredAttachment | undefined
75
+ /** Latest live failure not superseded by a later committed turn ending. */
76
+ failureAt: SessionLogOffset | undefined
77
+ /** Renewed when local settlement must recheck input. */
78
+ poke: PromiseWithResolvers<void>
79
+ /**
80
+ * Whether this child's settlement notice omits its closing text: true while
81
+ * the child's last logged tool call was a message to its direct parent and
82
+ * no input was claimed since.
83
+ */
84
+ omitClosingText: boolean
85
+ }
86
+ | {
87
+ readonly kind: 'external'
88
+ readonly run: SubagentRun
89
+ readonly controller: AbortController
90
+ }
91
+
92
+ /** One managed execution period with its provider-specific resources. */
93
+ export type Activation = ActivationBase & ActivationResource
94
+
95
+ /** Local residency with input admission and Session-backed result capture. */
96
+ export type LocalActivation = Extract<Activation, { kind: 'local' }>
97
+
98
+ /**
99
+ * Read the live Agent retained by local execution.
100
+ * @param activation - the managed local or external execution.
101
+ * @returns the local Agent, absent for an external run.
102
+ */
103
+ export function activationAgent(activation: Activation): Agent | undefined {
104
+ return activation.kind === 'local' ? activation.handle.agent : undefined
105
+ }
106
+
107
+ /**
108
+ * Require local residency before accepting further input.
109
+ * @param activation - execution targeted by message delivery.
110
+ * @returns the local activation.
111
+ * @throws when the external backend cannot accept another message.
112
+ */
113
+ export function requireLocalActivation(activation: Activation): LocalActivation {
114
+ switch (activation.kind) {
115
+ case 'local': return activation
116
+ case 'external':
117
+ throw new SubagentError(`subagent "${activation.childId}" does not accept follow-up input`, 'NOT_CONTINUABLE')
118
+ /* v8 ignore next 2 -- Both execution kinds are handled above. */
119
+ default: return assertNever(activation)
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Retain local failures whose turn ending could not be committed.
125
+ * @param activation - exact local Agent and epoch receiving the scoped observers.
126
+ * @param wake - notify its settlement watcher when failure changes readiness.
127
+ */
128
+ export function observeLocalFailure(activation: LocalActivation, wake: () => void): void {
129
+ const child = activation.handle.agent
130
+ child.ctx.on('agent/error', ({ agent }) => {
131
+ if (agent !== child) return
132
+ activation.failureAt = child.session.seq
133
+ wake()
134
+ })
135
+ child.ctx.on('session/event', (session, event) => {
136
+ if (session === child.session && event.type === 'turn/end'
137
+ && activation.failureAt !== undefined && event.seq >= activation.failureAt) {
138
+ activation.failureAt = undefined
139
+ }
140
+ })
141
+ }
142
+
143
+ /**
144
+ * Capture local output and retain failures without a later committed turn ending.
145
+ * @param activation - the settled local execution and any structured result.
146
+ * @returns final output, stop reason, and committed structured value.
147
+ */
148
+ export function captureLocalResult(activation: LocalActivation): SubagentResult {
149
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
150
+ const events = activation.handle.agent.session.snapshotEvents(activation.outputStart)
151
+ const output = finalAssistantOutput(events) ?? []
152
+ const stopReason = activation.failureAt === undefined ? epochStopReason(events) : 'error'
153
+ const structured = activation.structured
154
+ if (structured !== undefined) {
155
+ const captured = structured.captured()
156
+ if (captured !== undefined) return { output, stopReason, structured: captured.value }
157
+ if (stopReason === 'completed') return { output, stopReason: 'error' }
158
+ }
159
+ return { output, stopReason }
160
+ }
161
+
162
+ /** Serialize each durable child's delivery, release, and disposal. */
163
+ export class ChildLock {
164
+ private tails = new Map<SessionId, Promise<unknown>>()
165
+
166
+ /**
167
+ * Run `operation` after every previously queued operation for `childId`.
168
+ * @param childId - the durable child whose operations are linearized.
169
+ * @param operation - the critical section to run in order.
170
+ * @returns the operation's own settlement.
171
+ */
172
+ run<T>(childId: SessionId, operation: () => Promise<T>): Promise<T> {
173
+ const previous = this.tails.get(childId) ?? Promise.resolve()
174
+ const result = previous.then(operation, operation)
175
+ // Absorb rejections in the chaining tail so one failed critical section
176
+ // cannot reject an unrelated later caller.
177
+ const tail = result.then(() => undefined, () => undefined)
178
+ this.tails.set(childId, tail)
179
+ void tail.then(() => {
180
+ if (this.tails.get(childId) === tail) this.tails.delete(childId)
181
+ })
182
+ return result
183
+ }
184
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The `subagent` family of the Workspace registry's archive admission: which
3
+ * subagent descendants of a Session are still inside a turn, and how they
4
+ * stop when the Session is archived with its work. Archived ancestors also
5
+ * block later model steps, including when their Sessions have been released.
6
+ *
7
+ * @module @deepseek-ai/dsh-subagent
8
+ */
9
+
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import type { Agent } from '@deepseek-ai/dsh-agent'
12
+ import type { Session, SessionId } from '@deepseek-ai/dsh-session'
13
+ import type { SessionActivity, SessionActivityItem } from '@deepseek-ai/dsh-workspace'
14
+ import type { SubagentIdentityProjection } from './projection-types.ts'
15
+
16
+ /**
17
+ * Answer `workspace/session-activity` with the running subagent descendants of
18
+ * the asked Session, and `workspace/session-stop` by cancelling each of them
19
+ * as their parent would. Reject subsequent steps beneath archived ancestors.
20
+ * All listeners live as long as `ctx`'s fiber.
21
+ * @param ctx - context carrying the Agent registry.
22
+ * @param residentAncestors - verified creation ancestors for an exact managed Agent, absent before publication or for unmanaged Agents.
23
+ * @param identityOf - ready service-owned descriptor identity reader; absent or invalid descriptors yield no identity.
24
+ */
25
+ export function installSubagentArchiveAdmission(
26
+ ctx: Context,
27
+ residentAncestors: (agent: Agent) => readonly SessionId[] | undefined,
28
+ identityOf: (session: Session) => SubagentIdentityProjection | undefined,
29
+ ): void {
30
+ const ancestorsOf = (agent: Agent): readonly SessionId[] => residentAncestors(agent) ?? headerAncestors(ctx, agent)
31
+ const runningDescendants = (sessionId: SessionId): Agent[] => ctx.agents.list()
32
+ .filter(agent => agent.status === 'running' && ancestorsOf(agent).includes(sessionId))
33
+ ctx.on('workspace/session-activity', async ({ sessionId }, next) => {
34
+ const running = runningDescendants(sessionId)
35
+ const rest = await next()
36
+ if (running.length === 0) return rest
37
+ const own: SessionActivity = { kind: 'subagent', items: running.map(child => describe(child, identityOf(child.session))) }
38
+ return [own, ...rest]
39
+ })
40
+ ctx.on('workspace/session-stop', ({ sessionId }) => {
41
+ for (const child of runningDescendants(sessionId)) {
42
+ try {
43
+ child.cancel({ kind: 'parent' })
44
+ } catch (error: unknown) {
45
+ // One child refusing its cancel must not keep its siblings running for an archived parent.
46
+ ctx.logger.warn(`subagent: cancelling "${child.id}" for an archived Session failed: ${String(error)}`)
47
+ }
48
+ }
49
+ })
50
+ ctx.on('agent/pre-step', ({ agent }, next) => {
51
+ const archived = ctx.get('workspaceRegistry')?.archivedSessionIds
52
+ return archived !== undefined && ancestorsOf(agent).some(id => archived.includes(id))
53
+ ? Promise.resolve({ kind: 'reject' as const })
54
+ : next()
55
+ })
56
+ }
57
+
58
+ /**
59
+ * Header-only ancestry for Agents without a published Activation. Include an
60
+ * offline direct creator; ordinary forks stop the chain and cycles terminate.
61
+ */
62
+ function headerAncestors(ctx: Context, agent: Agent): readonly SessionId[] {
63
+ const ancestors: SessionId[] = []
64
+ const visited = new Set<SessionId>([agent.id])
65
+ let header = agent.session.header
66
+ while (header.origin === 'subagent' && header.parentSession !== undefined && !visited.has(header.parentSession)) {
67
+ const parentId = header.parentSession
68
+ ancestors.push(parentId)
69
+ visited.add(parentId)
70
+ const parent = ctx.agents.get(parentId)?.session
71
+ if (parent === undefined) break
72
+ header = parent.header
73
+ }
74
+ return ancestors
75
+ }
76
+
77
+ /**
78
+ * Report the child's current projected label only when its descriptor belongs
79
+ * to the child's own log; inherited, absent, or invalid identities yield the id alone.
80
+ */
81
+ function describe(child: Agent, identity: SubagentIdentityProjection | undefined): SessionActivityItem {
82
+ const label = identity !== undefined && child.session.isOwnSeq(identity.seq) ? identity.label : undefined
83
+ return label === undefined ? { id: child.id } : { id: child.id, label }
84
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Canonical selection of a child's final assistant output. Backend run results
3
+ * and `subagent/end.lastAssistantMessage` apply the same rule: select the last
4
+ * non-empty assistant message. An empty-content message records usage only
5
+ * when the loop appends it after a max-tokens step with no executable blocks,
6
+ * so it does not replace earlier output. If no non-empty message exists,
7
+ * select the accumulated assistant text. Selection is independent of the
8
+ * run's stop reason.
9
+ *
10
+ * @module @deepseek-ai/dsh-subagent/assistant-output
11
+ */
12
+
13
+ import { joinAssistantStreamText, type ContentBlock } from '@deepseek-ai/dsh-llm'
14
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
15
+
16
+ /**
17
+ * Incremental fold of the selection rule, for backends that observe a child's
18
+ * output as it streams: session-event backends {@link push} each event, and
19
+ * transports without session events (ACP content chunks) {@link pushText} raw
20
+ * text into the same streamed fallback.
21
+ */
22
+ export class AssistantOutputFold {
23
+ private message: readonly ContentBlock[] | undefined
24
+ private partial: string[] = []
25
+
26
+ /**
27
+ * Fold one session event: a non-empty assistant message becomes the
28
+ * candidate final answer, while its embedded stream and any log-only attempt
29
+ * extend the streamed fallback; every other event contributes nothing.
30
+ * @param event - the next observed session event.
31
+ */
32
+ push(event: SessionEvent): void {
33
+ if (event.type === 'assistant/message') {
34
+ const content = event.data.message.content
35
+ if (content.length > 0) this.message = content
36
+ }
37
+ if (event.type === 'assistant/message' || event.type === 'assistant/attempt') {
38
+ this.pushText(joinAssistantStreamText(event.data.stream))
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Extend the streamed fallback with text observed outside session events.
44
+ * @param text - the next streamed text piece (an empty piece is a no-op).
45
+ */
46
+ pushText(text: string): void {
47
+ if (text.length > 0) this.partial.push(text)
48
+ }
49
+
50
+ /**
51
+ * Select the final output folded so far.
52
+ * @returns the last non-empty assistant message, else the accumulated
53
+ * streamed text, or `undefined` when the child produced neither.
54
+ */
55
+ collect(): readonly ContentBlock[] | undefined {
56
+ if (this.message !== undefined) return this.message
57
+ const text = this.partial.join('')
58
+ return text.length > 0 ? [{ type: 'text', text }] : undefined
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Apply the selection rule to one complete child-owned event suffix.
64
+ * @param events - the child-owned events (after any seed or epoch boundary).
65
+ * @returns the selected output, or `undefined` when the child produced none.
66
+ */
67
+ export function finalAssistantOutput(events: readonly SessionEvent[]): readonly ContentBlock[] | undefined {
68
+ // TODO: this folds the complete suffix once per run/epoch settlement. If a
69
+ // long continuable epoch ever profiles hot here, scan backward with early
70
+ // exit for the last non-empty message and fold text deltas only on the
71
+ // no-message fallback.
72
+ const fold = new AssistantOutputFold()
73
+ for (const event of events) fold.push(event)
74
+ return fold.collect()
75
+ }