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

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 +59 -59
  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/src/names.ts ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Model-facing agent names. Each child's name is unique among its creator's
3
+ * children and is recorded in the creator's catalog; a member's full name is
4
+ * the slash-separated path of names from the root, whose own name is `lead`.
5
+ *
6
+ * @module @deepseek-ai/dsh-subagent/names
7
+ */
8
+
9
+ import type { Agent } from '@deepseek-ai/dsh-agent'
10
+ import { SubagentError } from './error.ts'
11
+
12
+ /** The root agent's fixed name; no child may take it. */
13
+ export const ROOT_AGENT_NAME = 'lead'
14
+
15
+ /** One lower-case segment of at most 32 characters, so a 36-character UUID never matches. */
16
+ const NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/u
17
+
18
+ /**
19
+ * Whether a string is a valid child name.
20
+ * @param value - candidate name segment.
21
+ * @returns true for 1–32 lower-case letters, digits, or hyphens starting with a letter, other than `lead`.
22
+ */
23
+ export function isAgentName(value: string): boolean {
24
+ return NAME_PATTERN.test(value) && value !== ROOT_AGENT_NAME
25
+ }
26
+
27
+ /**
28
+ * Append a child's name to its creator's path. The root's path is the empty string.
29
+ * @param parentPath - the creator's path, or undefined when an ancestor below the root has no name.
30
+ * @param name - the child's catalog name, absent on historical entries.
31
+ * @returns the child's path, or undefined when any link is unnamed.
32
+ */
33
+ export function joinAgentPath(parentPath: string | undefined, name: string | undefined): string | undefined {
34
+ if (parentPath === undefined || name === undefined) return undefined
35
+ return parentPath === '' ? name : `${parentPath}/${name}`
36
+ }
37
+
38
+ /**
39
+ * Select the model-facing name of one tree member.
40
+ * @param path - the member's path; `''` for the root and undefined for unnamed history.
41
+ * @param id - the member's Session id, used when no complete path exists.
42
+ * @returns `lead`, the full path, or the Session id.
43
+ */
44
+ export function agentAddress(path: string | undefined, id: string): string {
45
+ if (path === '') return ROOT_AGENT_NAME
46
+ return path ?? id
47
+ }
48
+
49
+ /**
50
+ * Remove the last name from a descendant path.
51
+ * @param path - a non-empty descendant path.
52
+ * @returns the creator's path; `''` when the creator is the root.
53
+ */
54
+ export function parentAgentPath(path: string): string {
55
+ const separator = path.lastIndexOf('/')
56
+ return separator < 0 ? '' : path.slice(0, separator)
57
+ }
58
+
59
+ /** A sibling name held from admission until the creator's catalog commits or startup fails. */
60
+ export interface SiblingNameReservation {
61
+ readonly name: string
62
+ /** Return the name to the pool; repeated calls are harmless. */
63
+ release(): void
64
+ }
65
+
66
+ /** Names claimed by in-flight creations, keyed by the exact live creator. */
67
+ export class SiblingNameReservations {
68
+ private readonly pending = new Map<Agent, Set<string>>()
69
+
70
+ /**
71
+ * Claim a name synchronously before startup awaits, so concurrent siblings cannot share it.
72
+ * @param parent - exact live creator whose catalog receives the name.
73
+ * @param committed - names already recorded in the creator's catalog.
74
+ * @param requested - requested name; omission selects the first free `agent-N`.
75
+ * @returns the claimed name and its release.
76
+ * @throws {@link SubagentError} `INVALID_AGENT_NAME` or `DUPLICATE_AGENT_NAME`.
77
+ */
78
+ reserve(parent: Agent, committed: ReadonlySet<string>, requested?: string): SiblingNameReservation {
79
+ const pending = this.pending.get(parent) ?? new Set<string>()
80
+ const taken = (name: string): boolean => committed.has(name) || pending.has(name)
81
+ let name: string
82
+ if (requested === undefined) {
83
+ let ordinal = 1
84
+ while (taken(`agent-${ordinal}`)) ordinal++
85
+ name = `agent-${ordinal}`
86
+ } else {
87
+ if (!isAgentName(requested)) {
88
+ throw new SubagentError(
89
+ `agent name ${JSON.stringify(requested)} is invalid; use 1-32 lower-case letters, digits, or hyphens `
90
+ + `starting with a letter, other than "${ROOT_AGENT_NAME}"`,
91
+ 'INVALID_AGENT_NAME',
92
+ )
93
+ }
94
+ if (taken(requested)) {
95
+ throw new SubagentError(
96
+ `agent name ${JSON.stringify(requested)} is already used by another subagent you created; choose another name`,
97
+ 'DUPLICATE_AGENT_NAME',
98
+ )
99
+ }
100
+ name = requested
101
+ }
102
+ pending.add(name)
103
+ this.pending.set(parent, pending)
104
+ return {
105
+ name,
106
+ release: () => {
107
+ pending.delete(name)
108
+ // A later reservation for the same creator replaces the set; a stale release must not drop it.
109
+ if (pending.size === 0 && this.pending.get(parent) === pending) this.pending.delete(parent)
110
+ },
111
+ }
112
+ }
113
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Provider-side vocabulary for OUT-OF-PROCESS subagent backends — the pieces
3
+ * that enforce this seam's own contracts around a child in another process:
4
+ * the no-capabilities advertisement, timing-bound validation, child
5
+ * working-directory validation, the never-reject result settlement, and the standard
6
+ * run-handle publication. Backends compose these with their own wire drivers;
7
+ * the process machinery itself (spawn, env scrub, managed-range teardown)
8
+ * belongs to the `dsh-subprocess` seam.
9
+ *
10
+ * @module @deepseek-ai/dsh-subagent/out-of-process
11
+ */
12
+
13
+ import { accessSync, constants, statSync } from 'node:fs'
14
+ import { isAbsolute } from 'node:path'
15
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
16
+ import type { SubagentCapabilities, SubagentResult, SubagentRun, SubagentStopReason } from './types.ts'
17
+
18
+ /** Maximum UTF-8 size of {@link SubagentResult.diagnostic}. */
19
+ const MAX_SUBAGENT_DIAGNOSTIC_BYTES = 4_096
20
+
21
+ const DIAGNOSTIC_TRUNCATION_SUFFIX = '\n[diagnostic truncated]'
22
+ const utf8Encoder = new TextEncoder()
23
+ const utf8Decoder = new TextDecoder()
24
+
25
+ /**
26
+ * Limit provider-authored failure detail without splitting a UTF-8 sequence.
27
+ * @param diagnostic - safe diagnostic text produced by the provider.
28
+ * @returns the original text, or a visibly truncated value within the limit.
29
+ */
30
+ function limitSubagentDiagnostic(diagnostic: string): string {
31
+ const bytes = utf8Encoder.encode(diagnostic)
32
+ if (bytes.byteLength <= MAX_SUBAGENT_DIAGNOSTIC_BYTES) return diagnostic
33
+
34
+ const suffixBytes = utf8Encoder.encode(DIAGNOSTIC_TRUNCATION_SUFFIX).byteLength
35
+ let prefixBytes = MAX_SUBAGENT_DIAGNOSTIC_BYTES - suffixBytes
36
+ while (((bytes[prefixBytes] as number) & 0b1100_0000) === 0b1000_0000) {
37
+ prefixBytes -= 1
38
+ }
39
+ return utf8Decoder.decode(bytes.subarray(0, prefixBytes))
40
+ + DIAGNOSTIC_TRUNCATION_SUFFIX
41
+ }
42
+
43
+ /** Enforce the byte limit on a provider-returned diagnostic. */
44
+ function normalizeSubagentDiagnostic(result: SubagentResult): SubagentResult {
45
+ return result.diagnostic === undefined
46
+ ? result
47
+ : { ...result, diagnostic: limitSubagentDiagnostic(result.diagnostic) }
48
+ }
49
+
50
+ /**
51
+ * The capability advertisement of an out-of-process backend: NONE. A child in
52
+ * another process cannot honor parent-enforced start features
53
+ * (`agentOptions`/`agentPreset`/`outputSchema`/`maxDepth`), so the service rejects a
54
+ * request needing any of them before `start` runs — never accepted-then-ignored.
55
+ */
56
+ export const NO_START_CAPABILITIES: SubagentCapabilities = Object.freeze({
57
+ agentOptions: false,
58
+ agentPreset: false,
59
+ outputSchema: false,
60
+ depthLimit: false,
61
+ })
62
+
63
+ /**
64
+ * Assert a configured timing bound is a positive finite number (it bounds a
65
+ * teardown or shutdown wait; zero, negative, or NaN would skip or wedge it).
66
+ * @param prefix - the consuming plugin's diagnostic prefix (e.g. `subagent-acp`).
67
+ * @param name - the config field name, for the diagnostic.
68
+ * @param value - the configured value.
69
+ */
70
+ export function assertPositiveFinite(prefix: string, name: string, value: number): void {
71
+ if (!Number.isFinite(value) || value <= 0) {
72
+ throw new Error(`${prefix}: ${name} must be a positive finite number`)
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Whether `path` names an existing directory the harness can ENTER. The
78
+ * search-permission probe matters: `statSync().isDirectory()` is true for a
79
+ * mode-600 directory, but a subprocess cwd needs `X_OK` or spawn fails EACCES.
80
+ */
81
+ function isEnterableDirectory(path: string): boolean {
82
+ try {
83
+ if (!statSync(path).isDirectory()) return false
84
+ accessSync(path, constants.X_OK)
85
+ return true
86
+ } catch {
87
+ // statSync/accessSync throw only filesystem access errors here
88
+ // (ENOENT/EACCES/ENOTDIR/…), and every one of them means the path cannot
89
+ // serve as the child's cwd.
90
+ return false
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Assert `cwd` can actually host the child: absolute (it doubles as the
96
+ * child's workspace identity, and a relative path would be re-anchored to the
97
+ * server process's launch directory) and an existing directory (fail here,
98
+ * before the process boundary, instead of as an ambiguous spawn ENOENT).
99
+ * @param prefix - the consuming plugin's diagnostic prefix.
100
+ * @param label - which source supplied the value, for the diagnostic.
101
+ * @param cwd - the candidate working directory.
102
+ * @returns `cwd`, validated.
103
+ */
104
+ export function assertUsableCwd(prefix: string, label: string, cwd: string): string {
105
+ if (!isAbsolute(cwd)) {
106
+ throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`)
107
+ }
108
+ if (!isEnterableDirectory(cwd)) {
109
+ throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`)
110
+ }
111
+ return cwd
112
+ }
113
+
114
+ /** Normalize an unknown thrown value to an Error (the catch binding is `unknown`). */
115
+ function toError(value: unknown): Error {
116
+ // The rejecting surfaces (wire clients, spawn failures) only throw
117
+ // `Error`s; the `String(value)` arm is a defensive fallback for a non-Error
118
+ // throw the typed surfaces cannot produce.
119
+ /* v8 ignore next */
120
+ return value instanceof Error ? value : new Error(String(value))
121
+ }
122
+
123
+ /** Inputs to {@link settleRunResult}. */
124
+ export interface RunResultSettlement {
125
+ /** The turn attempt (typically racing local cancellation); returns the terminal result. */
126
+ attempt: () => Promise<SubagentResult>
127
+ /** Snapshot the provider exposes when cancellation or failure wins settlement. */
128
+ collectOutput: () => readonly ContentBlock[]
129
+ /** Snapshot safe provider-authored detail when a failure wins settlement. */
130
+ collectDiagnostic?: (() => string | undefined) | undefined
131
+ /** Whether local cancellation settled before the attempt's outcome is observed. */
132
+ cancelled: () => boolean
133
+ /** Diagnostic sink for a failure flattened to a stop reason; a throw from it is contained. */
134
+ onError?: ((error: Error, stopReason: SubagentStopReason) => void) | undefined
135
+ /** The request's cancellation signal (the listener is removed at settlement). */
136
+ signal: AbortSignal
137
+ /** The abort listener registered on {@link signal} at start. */
138
+ onAbort: () => void
139
+ }
140
+
141
+ /**
142
+ * Settle an out-of-process run result under the seam contract: `result` never
143
+ * rejects after publication. A normally completed or rejected attempt resolves
144
+ * as `aborted` when cancellation already settled locally; another rejection is
145
+ * flattened to `stopReason: 'error'` through the contained diagnostic sink.
146
+ * Provider-returned diagnostics use the same byte limit. The abort listener is
147
+ * removed on every path.
148
+ * @param parts - the attempt, output snapshot, cancellation state, sink, and signal wiring.
149
+ * @returns the terminal result (never a rejection).
150
+ */
151
+ export async function settleRunResult(parts: RunResultSettlement): Promise<SubagentResult> {
152
+ try {
153
+ const result = await parts.attempt()
154
+ return parts.cancelled()
155
+ ? { output: parts.collectOutput(), stopReason: 'aborted' }
156
+ : normalizeSubagentDiagnostic(result)
157
+ } catch (error: unknown) {
158
+ // Cover a rejection already queued when cancellation arrives.
159
+ if (parts.cancelled()) return { output: parts.collectOutput(), stopReason: 'aborted' }
160
+ // Flatten post-publication transport failures while preserving diagnostics.
161
+ try {
162
+ parts.onError?.(toError(error), 'error')
163
+ } catch {
164
+ // The diagnostic sink cannot reject the run result.
165
+ }
166
+ const collected = parts.collectDiagnostic?.()
167
+ const diagnostic = collected === undefined
168
+ ? undefined
169
+ : limitSubagentDiagnostic(collected)
170
+ return {
171
+ output: parts.collectOutput(),
172
+ ...diagnostic === undefined ? {} : { diagnostic },
173
+ stopReason: 'error',
174
+ }
175
+ } finally {
176
+ parts.signal.removeEventListener('abort', parts.onAbort)
177
+ }
178
+ }
179
+
180
+ /** Inputs to {@link subprocessRunHandle}. */
181
+ export interface SubprocessRunHandleParts {
182
+ /** The parent-scoped run id. */
183
+ id: SubagentRun['id']
184
+ /** The flattened, never-rejecting result (the seam contract). */
185
+ result: Promise<SubagentResult>
186
+ /** The request's cancellation signal (the listener is removed on dispose). */
187
+ signal: AbortSignal
188
+ /** The abort listener registered on {@link signal} at start. */
189
+ onAbort: () => void
190
+ /** Settle local cancellation so {@link result} resolves without the child. */
191
+ requestCancel: () => void
192
+ /** Tear the child process down to quiescence (backend-owned ladder). */
193
+ teardown: () => Promise<void>
194
+ }
195
+
196
+ /**
197
+ * Publish the seam run handle for an out-of-process child. `dispose()` is
198
+ * idempotent (one memoized teardown): it removes the abort listener, settles
199
+ * local cancellation — there is no assumption the child cooperates — and then
200
+ * awaits the backend's teardown to actual exit.
201
+ * @param parts - the run identity, result, cancellation wiring, and teardown.
202
+ * @returns the external run handle.
203
+ */
204
+ export function subprocessRunHandle(parts: SubprocessRunHandleParts): SubagentRun {
205
+ let disposal: Promise<void> | undefined
206
+ return {
207
+ id: parts.id,
208
+ result: parts.result,
209
+ dispose(): Promise<void> {
210
+ if (disposal !== undefined) return disposal
211
+ parts.signal.removeEventListener('abort', parts.onAbort)
212
+ parts.requestCancel()
213
+ disposal = parts.teardown()
214
+ return disposal
215
+ },
216
+ }
217
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Pure client-safe subagent projection vocabulary.
3
+ *
4
+ * @module @deepseek-ai/dsh-subagent/projection-types
5
+ */
6
+
7
+ import type { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types'
8
+
9
+ /** Known child modes with their creation labels and names, shared by catalog views. */
10
+ export type KnownSubagentCatalogFields =
11
+ | {
12
+ /** A terminal one-shot child. */
13
+ readonly mode: 'one-shot'
14
+ /** Optional durable creation label from the parent catalog. */
15
+ readonly label?: string
16
+ }
17
+ | {
18
+ /** An external execution without a local child Session. */
19
+ readonly mode: 'external'
20
+ /** Optional durable creation label from the parent catalog. */
21
+ readonly label?: string
22
+ /** Name unique among the parent's children; absent on historical entries. */
23
+ readonly name?: string
24
+ }
25
+ | {
26
+ /** A resumable conversation. */
27
+ readonly mode: 'continuable'
28
+ /** Durable creation label from the parent catalog. */
29
+ readonly label: string
30
+ /** Name unique among the parent's children; absent on historical entries. */
31
+ readonly name?: string
32
+ }
33
+
34
+ /** One current direct-child discovery row materialized from parent facts. */
35
+ export type SubagentCatalogEntry =
36
+ & {
37
+ readonly id: SessionId
38
+ readonly createdAt: number
39
+ }
40
+ & (
41
+ | KnownSubagentCatalogFields
42
+ | { readonly mode: 'unknown'; readonly label?: string }
43
+ )
44
+
45
+ /** Durable active-turn timing for one descriptor-backed child session. */
46
+ export interface SubagentTimingProjection {
47
+ /** Milliseconds accumulated across completed turns after the child's own descriptor. */
48
+ settledMs: number
49
+ /** Same-cut bounds of the currently open turn, when one has not reached `turn/end`. */
50
+ active?: {
51
+ /** Start of the open turn. */
52
+ since: number
53
+ /** Latest event time folded into this projection cut. */
54
+ through: number
55
+ }
56
+ /**
57
+ * Whether the latest closed turn after the child's own descriptor completed
58
+ * normally; absent while a turn is open or before one closes.
59
+ */
60
+ lastTurnCompleted?: boolean
61
+ }
62
+
63
+ /**
64
+ * Durable identity of one descriptor-backed subagent session: lifecycle mode
65
+ * plus creation label, folded last-wins from `subagent/descriptor` events.
66
+ * Label strength follows the descriptor schema: a continuable child always
67
+ * carries one, a one-shot child may omit it.
68
+ */
69
+ export type SubagentIdentityProjection =
70
+ | {
71
+ /** A terminal one-shot child. */
72
+ mode: 'one-shot'
73
+ /** Optional durable creation label from the child's descriptor. */
74
+ label?: string
75
+ /**
76
+ * Seq of the `subagent/descriptor` event this identity was folded from.
77
+ * `session.isOwnSeq(seq)` proves the identity comes from the child's
78
+ * OWN log suffix — where a descriptor is immutable once appended — and
79
+ * not from a fork seed's replayed ancestor descriptor.
80
+ */
81
+ seq: SessionSeq
82
+ }
83
+ | {
84
+ /** A resumable conversation. */
85
+ mode: 'continuable'
86
+ /** Durable creation label from the child's descriptor. */
87
+ label: string
88
+ /** Seq of the folded descriptor event; see the one-shot arm for the own-suffix proof. */
89
+ seq: SessionSeq
90
+ }
91
+
92
+ declare module '@deepseek-ai/dsh-session-projection/types' {
93
+ interface SessionProjectionMap {
94
+ /** Direct children in parent catalog event order, excluding fork-inherited facts. */
95
+ subagentCatalog: SubagentCatalogEntry[]
96
+ /** Active-turn duration and latest closed-turn completion for a descriptor-backed subagent session. */
97
+ subagentTiming: SubagentTimingProjection
98
+ /**
99
+ * Identity of a descriptor-backed subagent session. `null` ⟺ no valid
100
+ * descriptor (missing, malformed, or unrecognized-version — deliberately
101
+ * undistinguished). The sentinel is deliberately serializable: a
102
+ * value pushed over JSON transports must survive `JSON.stringify`
103
+ * losslessly, where an `undefined` field would be dropped and a stale
104
+ * identity would survive on the receiving side. The entry itself stays
105
+ * non-optional.
106
+ */
107
+ subagent: SubagentIdentityProjection | null
108
+ }
109
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Pure session projections for subagent identity (mode/label) and active-turn
3
+ * duration.
4
+ *
5
+ * @module @deepseek-ai/dsh-subagent/projection
6
+ */
7
+
8
+ import { z } from 'zod'
9
+ import { SessionSeq } from '@deepseek-ai/dsh-session'
10
+ import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
11
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
12
+ import { foldSubagentDescriptor } from './descriptor.ts'
13
+ import type { SubagentDescriptorData } from './descriptor.ts'
14
+ import type { SubagentIdentityProjection, SubagentTimingProjection } from './projection-types.ts'
15
+
16
+ /** Fold state for a subagent's latest timing snapshot. */
17
+ export interface TimingState {
18
+ /** Milliseconds accumulated across completed post-descriptor turns. */
19
+ settledMs: number
20
+ /** Current open interval kept paired inside the fold. */
21
+ active?: { since: number; through: number } | undefined
22
+ /** Latest pre-descriptor turn start, promoted when the child's own descriptor arrives. */
23
+ pendingTurnStart?: number | undefined
24
+ /** Whether the fold has crossed a descriptor in this logical log. */
25
+ descriptorSeen: boolean
26
+ /** Whether the latest closed post-descriptor turn completed normally; absent while a turn is open or before one closes. */
27
+ lastTurnCompleted?: boolean | undefined
28
+ }
29
+
30
+ const activeIntervalSchema = z.object({
31
+ since: z.number().int().nonnegative(),
32
+ through: z.number().int().nonnegative(),
33
+ }).strict()
34
+
35
+ const projectionSchema: z.ZodType<SubagentTimingProjection> = z.object({
36
+ settledMs: z.number().int().nonnegative(),
37
+ active: activeIntervalSchema.optional(),
38
+ lastTurnCompleted: z.boolean().optional(),
39
+ }).strict().transform(({ settledMs, active, lastTurnCompleted }) => ({
40
+ settledMs,
41
+ ...active === undefined ? {} : { active },
42
+ ...lastTurnCompleted === undefined ? {} : { lastTurnCompleted },
43
+ }))
44
+
45
+ const timingStateSchema: z.ZodType<TimingState> = z.object({
46
+ settledMs: z.number().int().nonnegative(),
47
+ active: activeIntervalSchema.optional(),
48
+ pendingTurnStart: z.number().int().nonnegative().optional(),
49
+ descriptorSeen: z.boolean(),
50
+ lastTurnCompleted: z.boolean().optional(),
51
+ }).strict()
52
+
53
+ /**
54
+ * Fold turn boundaries around the child's own durable descriptor.
55
+ *
56
+ * A fork seed may contain an ancestor descriptor and completed turns. Every
57
+ * descriptor therefore resets the accumulated state; the healthy catalog
58
+ * admits only a child with exactly one descriptor in its own suffix, making
59
+ * the final reset the child's authoritative timing origin.
60
+ */
61
+ export const subagentTimingProjectionDefinition = {
62
+ key: 'subagentTiming',
63
+ stateSchema: timingStateSchema,
64
+ init: () => ({ descriptorSeen: false, settledMs: 0 }),
65
+ apply: (state, event) => {
66
+ if (event.type === 'turn/start') {
67
+ const { lastTurnCompleted: _closed, ...openState } = state
68
+ return state.descriptorSeen
69
+ ? { ...openState, active: { since: event.time, through: event.time } }
70
+ : { ...openState, pendingTurnStart: event.time }
71
+ }
72
+ if (event.type === 'subagent/descriptor') {
73
+ const activeSince = state.active?.since ?? state.pendingTurnStart
74
+ return {
75
+ descriptorSeen: true,
76
+ settledMs: 0,
77
+ ...(activeSince === undefined
78
+ ? {}
79
+ : { active: { since: activeSince, through: event.time } }),
80
+ }
81
+ }
82
+ if (event.type === 'turn/end') {
83
+ if (!state.descriptorSeen) {
84
+ if (state.pendingTurnStart === undefined) return state
85
+ const { pendingTurnStart: _closed, ...next } = state
86
+ return next
87
+ }
88
+ if (state.active === undefined) return state
89
+ const { active, ...rest } = state
90
+ return {
91
+ ...rest,
92
+ settledMs: state.settledMs + Math.max(0, event.time - active.since),
93
+ lastTurnCompleted: event.data.reason.kind === 'completed',
94
+ }
95
+ }
96
+ if (state.active === undefined) return state
97
+ return { ...state, active: { ...state.active, through: event.time } }
98
+ },
99
+ wire: {
100
+ viewSchema: projectionSchema,
101
+ view: state => ({
102
+ settledMs: state.settledMs,
103
+ ...(state.active === undefined ? {} : { active: state.active }),
104
+ ...(state.lastTurnCompleted === undefined ? {} : { lastTurnCompleted: state.lastTurnCompleted }),
105
+ }),
106
+ },
107
+ stateVersion: 3,
108
+ } satisfies ProjectionDefinition<'subagentTiming', TimingState>
109
+
110
+ /** Descriptor identity retained by the subagent projection. */
111
+ export interface IdentityState {
112
+ /** Identity from the last valid descriptor; absent before one, and after an invalid one. */
113
+ identity?: SubagentIdentityProjection | undefined
114
+ }
115
+
116
+ // The cast bridges only the optional-label arm: Zod's optional output
117
+ // includes explicit `undefined`, which exactOptionalPropertyTypes excludes
118
+ // from the public interface. The no-value state itself is the serializable
119
+ // `null` arm — never `undefined` — so every registry read and push frame
120
+ // survives JSON.stringify losslessly.
121
+ const identityValueSchema = z.discriminatedUnion('mode', [
122
+ z.object({
123
+ mode: z.literal('one-shot'),
124
+ label: z.string().optional(),
125
+ seq: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq),
126
+ }).strict(),
127
+ z.object({
128
+ mode: z.literal('continuable'),
129
+ label: z.string(),
130
+ seq: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq),
131
+ }).strict(),
132
+ ]) as unknown as z.ZodType<SubagentIdentityProjection>
133
+
134
+ const identitySchema = identityValueSchema.nullable()
135
+
136
+ const identityStateSchema: z.ZodType<IdentityState> = z.object({
137
+ identity: identityValueSchema.optional(),
138
+ }).strict()
139
+
140
+ /** Interpret one `subagent/descriptor` event's identity; no value when the payload cannot be trusted. */
141
+ function descriptorIdentity(event: SessionEvent): SubagentIdentityProjection | undefined {
142
+ let descriptor: SubagentDescriptorData | undefined
143
+ try {
144
+ descriptor = foldSubagentDescriptor([event])
145
+ } catch {
146
+ // Only a malformed current-version payload throws in descriptor parsing;
147
+ // a projection fold must never throw, so damage folds to no value.
148
+ descriptor = undefined
149
+ }
150
+ if (descriptor === undefined) return undefined
151
+ return descriptor.mode === 'one-shot'
152
+ ? {
153
+ mode: 'one-shot',
154
+ ...descriptor.label !== undefined ? { label: descriptor.label } : {},
155
+ seq: event.seq,
156
+ }
157
+ : { mode: 'continuable', label: descriptor.label, seq: event.seq }
158
+ }
159
+
160
+ /**
161
+ * Fold the durable mode/label identity from `subagent/descriptor` events,
162
+ * last-wins: a fork seed may replay an ancestor's descriptor, and the child's
163
+ * own descriptor must override it — the same reset discipline as
164
+ * {@link subagentTimingProjectionDefinition}. A malformed or unknown-version
165
+ * payload resets to the `null` sentinel instead of throwing, so a fork of a
166
+ * healthy ancestor never inherits an identity its own descriptor failed to
167
+ * establish — and the reset survives every JSON push frame, so a consumer
168
+ * holding the earlier identity replaces it instead of keeping it stale;
169
+ * `null` ⟺ no valid descriptor, with the causes deliberately undistinguished.
170
+ */
171
+ export const subagentIdentityProjectionDefinition = {
172
+ key: 'subagent',
173
+ stateSchema: identityStateSchema,
174
+ init: () => ({}),
175
+ apply: (state, event) => {
176
+ if (event.type !== 'subagent/descriptor') return state
177
+ const identity = descriptorIdentity(event)
178
+ return identity === undefined ? {} : { identity }
179
+ },
180
+ wire: { viewSchema: identitySchema, view: state => state.identity ?? null },
181
+ // Bumped when the identity gained its `seq` field: an older checkpoint row
182
+ // would replay into a value the schema rejects, so it must refold instead.
183
+ stateVersion: 2,
184
+ } satisfies ProjectionDefinition<'subagent', IdentityState>