@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
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Contained lifecycle notifications for subagents.
3
+ *
4
+ * The service owns scoped dispatch and listener containment; the manager
5
+ * supplies event payloads from each activation.
6
+ *
7
+ * @module @deepseek-ai/dsh-subagent/lifecycle
8
+ */
9
+
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import type { Agent } from '@deepseek-ai/dsh-agent'
12
+ import { foldConsumedWork } from '@deepseek-ai/dsh-agent'
13
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
14
+ import type { SubagentResult, SubagentRunEndInfo, SubagentRunInfo } from './types.ts'
15
+
16
+ /**
17
+ * Publish one notification with per-listener exception containment. Run edges
18
+ * carry the subagent tree root that keys scoped dispatch. Provider removal
19
+ * reaches all scopes.
20
+ *
21
+ * The service owns this closure because scoped dispatch keys its carrier by the
22
+ * exact service instance, whose own context filter composes into the carrier;
23
+ * a narrowed stand-in would silently change scope filtering.
24
+ */
25
+ export type LifecycleEmitter = {
26
+ (name: 'subagent/start', info: SubagentRunInfo, parent: Agent): void
27
+ (name: 'subagent/end', info: SubagentRunEndInfo, parent: Agent): void
28
+ (name: 'subagent/provider-removed', info: string): void
29
+ }
30
+
31
+ /**
32
+ * Build the contained lifecycle emitter this seam publishes every edge through.
33
+ * Every listener is independently contained: a synchronous throw or a rejected
34
+ * returned promise is logged without starving peer listeners, changing the run,
35
+ * or — for provider removal, which fires from a disposer — breaking teardown.
36
+ * @param ctx - the service's own context, owning dispatch and the logger.
37
+ * @param carrier - resolve the scoped dispatch carrier for one subagent tree root.
38
+ * @returns the emitter the manager and provider registry publish through.
39
+ */
40
+ export function createLifecycleEmitter(
41
+ ctx: Context,
42
+ carrier: (parent: Agent) => object,
43
+ ): LifecycleEmitter {
44
+ return (
45
+ name: 'subagent/start' | 'subagent/end' | 'subagent/provider-removed',
46
+ info: SubagentRunInfo | SubagentRunEndInfo | string,
47
+ parent?: Agent,
48
+ ): void => {
49
+ const dispatchArgs: unknown[] = parent === undefined
50
+ ? [name, info]
51
+ : [carrier(parent), name, info]
52
+ for (const callback of ctx.events.dispatch('emit', dispatchArgs)) {
53
+ try {
54
+ const returned: unknown = callback(info)
55
+ void Promise.resolve(returned).catch((error: unknown) => {
56
+ ctx.logger.warn(`subagent: ${name} listener rejected: ${renderThrown(error)}`)
57
+ })
58
+ } catch (error: unknown) {
59
+ ctx.logger.warn(`subagent: ${name} listener threw: ${renderThrown(error)}`)
60
+ }
61
+ }
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Why this child's epoch ended, for the terminal lifecycle edge and the
67
+ * manager's own parent delivery. The child's own log is authoritative:
68
+ * teardown succeeding says nothing about whether the model errored, hit its
69
+ * token ceiling, or was cancelled, so deriving the reason from disposal would
70
+ * report failed work as completed.
71
+ *
72
+ * {@link foldConsumedWork} supplies both halves the raw turn sequence cannot:
73
+ * which turn accounts for the work this epoch consumed, and whether accepted
74
+ * work was cancelled after it without any turn opening over it. A recorded
75
+ * failure still wins over a cancellation — stopping a child that had already
76
+ * failed does not turn its failure into a cancellation.
77
+ * @param events - this epoch's own event suffix.
78
+ * @returns its terminal stop reason; `completed` only for an epoch that both
79
+ * closed cleanly and had nothing left to run.
80
+ */
81
+ export function epochStopReason(events: readonly SessionEvent[]): SubagentResult['stopReason'] {
82
+ const { end, droppedUnrun } = foldConsumedWork(events)
83
+ switch (end?.data.reason.kind) {
84
+ case 'max-tokens':
85
+ return 'max-tokens'
86
+ case 'aborted':
87
+ case 'interrupted':
88
+ return 'aborted'
89
+ case 'error':
90
+ return 'error'
91
+ // A pre-step rejection — a hook deny, a policy plugin — discarded input
92
+ // this epoch had claimed: the work was declined, not done.
93
+ case 'blocked':
94
+ return 'refusal'
95
+ // A clean ending and no accounting turn at all share one rule: the epoch
96
+ // finished what it was given unless a cancelled queue says otherwise.
97
+ case undefined:
98
+ case 'completed':
99
+ return droppedUnrun ? 'aborted' : 'completed'
100
+ /* v8 ignore next 4 -- `forked` appears only in constructor seed history, while
101
+ * this function reads an epoch-owned suffix. `TurnEndReason` is merge-extensible,
102
+ * so a backend-added variant cannot be listed; treating an unnameable reason as
103
+ * success would report failed work as completed. */
104
+ default:
105
+ return 'error'
106
+ }
107
+ }
108
+
109
+ /** Render any listener-thrown value without letting coercion escape containment. */
110
+ function renderThrown(value: unknown): string {
111
+ try {
112
+ return value instanceof Error ? `${value.name}: ${value.message}` : String(value)
113
+ } catch {
114
+ return '<unrenderable thrown value>'
115
+ }
116
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Direct-child and recursive descendant discovery from parent-owned catalogs.
3
+ * Each catalog read releases its Session observation before the next branch.
4
+ * @module @deepseek-ai/dsh-subagent
5
+ */
6
+
7
+ import type { Context } from '@deepseek-ai/cordis'
8
+ import type { SessionId } from '@deepseek-ai/dsh-session'
9
+ import type { SubagentListEntry } from './control-types.ts'
10
+ import { SubagentError } from './error.ts'
11
+ import { isAgentName, joinAgentPath } from './names.ts'
12
+ import type { SubagentCatalogEntry } from './projection-types.ts'
13
+
14
+ export type { SubagentListEntry } from './control-types.ts'
15
+
16
+ /** One catalog descendant with its direct parent and edge distance from the requested root. */
17
+ export type SubagentDescendantListEntry = SubagentListEntry & {
18
+ /** Parent whose catalog contains this child. */
19
+ readonly parentId: SessionId
20
+ /** Edge distance from the requested root; direct children are `1`. */
21
+ readonly depth: number
22
+ /** Slash-separated names from the requested root; absent when this child or an ancestor below the root has no name. */
23
+ readonly path?: string
24
+ }
25
+
26
+ /**
27
+ * Read one parent's durable catalog through a live-preferred Session observation.
28
+ * @param ctx - context carrying the Session query service.
29
+ * @param parentSessionId - parent whose direct children are requested.
30
+ * @param signal - cancellation forwarded to the Session observation.
31
+ * @returns direct-child rows in parent catalog event order.
32
+ * @throws {@link SubagentError} when query or catalog projection is unavailable.
33
+ */
34
+ export async function listChildren(
35
+ ctx: Context,
36
+ parentSessionId: SessionId,
37
+ signal?: AbortSignal,
38
+ ): Promise<SubagentCatalogEntry[]> {
39
+ const query = ctx.get('sessionQuery')
40
+ if (query === undefined) {
41
+ throw new SubagentError(
42
+ 'listing subagents requires the sessionQuery service (load @deepseek-ai/dsh-session-query)',
43
+ 'SUBAGENT_CONTROL_QUERY_UNAVAILABLE',
44
+ )
45
+ }
46
+ using parent = await query.observeSession(parentSessionId, {
47
+ ...signal === undefined ? {} : { signal },
48
+ })
49
+ const entries = parent.projections?.values.subagentCatalog
50
+ if (entries === undefined) {
51
+ throw new SubagentError(
52
+ 'listing subagents requires the registered subagentCatalog projection',
53
+ 'SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE',
54
+ )
55
+ }
56
+ return entries
57
+ }
58
+
59
+ /**
60
+ * Walk reachable parent catalogs in stable pre-order without loading Agents.
61
+ * @see SubagentRuntime.listDescendants for failure and cancellation semantics.
62
+ * @param ctx - context carrying the Session store and query service.
63
+ * @param rootSessionId - parent whose catalog starts the traversal.
64
+ * @param signal - cancellation checked around each catalog read.
65
+ * @returns children and branch diagnostics with catalog parent and depth.
66
+ */
67
+ export async function listDescendants(
68
+ ctx: Context,
69
+ rootSessionId: SessionId,
70
+ signal?: AbortSignal,
71
+ ): Promise<SubagentDescendantListEntry[]> {
72
+ const sessions = ctx.get('sessions')
73
+ if (sessions === undefined) {
74
+ throw new SubagentError(
75
+ 'listing subagents requires the session store (load @deepseek-ai/dsh-session)',
76
+ 'SUBAGENT_CONTROL_SESSION_STORE_UNAVAILABLE',
77
+ )
78
+ }
79
+ const readChildren = async (id: SessionId): Promise<SubagentCatalogEntry[]> => {
80
+ assertListingNotCancelled(signal)
81
+ let children: SubagentCatalogEntry[]
82
+ try {
83
+ children = await listChildren(ctx, id, signal)
84
+ } catch (error) {
85
+ assertListingNotCancelled(signal)
86
+ throw error
87
+ }
88
+ assertListingNotCancelled(signal)
89
+ return children
90
+ }
91
+ type Position = { entry: SubagentCatalogEntry; parentId: SessionId; depth: number; parentPath: string | undefined }
92
+ const stack: Position[] = (await readChildren(rootSessionId))
93
+ .map(entry => ({ entry, parentId: rootSessionId, depth: 1, parentPath: '' }))
94
+ .reverse()
95
+ const visited = new Set<SessionId>([rootSessionId])
96
+ const result: SubagentDescendantListEntry[] = []
97
+ for (let position = stack.pop(); position !== undefined; position = stack.pop()) {
98
+ const { entry, parentId, depth, parentPath } = position
99
+ if (visited.has(entry.id)) continue
100
+ visited.add(entry.id)
101
+ const path = joinAgentPath(parentPath, 'name' in entry ? entry.name : undefined)
102
+ const at = { parentId, depth, ...path === undefined ? {} : { path } }
103
+ let children: SubagentCatalogEntry[]
104
+ try {
105
+ children = entry.mode === 'external' ? [] : await readChildren(entry.id)
106
+ } catch (error) {
107
+ if (error instanceof SubagentError) throw error
108
+ const code = error instanceof Error && 'code' in error ? error.code : undefined
109
+ result.push({
110
+ kind: 'diagnostic', id: entry.id, ...at,
111
+ reason: code === 'SESSION_QUERY_CORRUPT_SESSION' || code === 'SESSION_QUERY_SOURCE_CONFLICT'
112
+ ? 'corrupt' : 'unavailable',
113
+ })
114
+ continue
115
+ }
116
+ if (entry.mode === 'unknown') {
117
+ result.push({ kind: 'diagnostic', id: entry.id, ...at, reason: 'unsupported' })
118
+ } else {
119
+ const { createdAt: _createdAt, ...identity } = entry
120
+ result.push({
121
+ ...identity, kind: 'child', ...at,
122
+ activity: sessions.get(entry.id) === undefined ? 'inactive' : 'running',
123
+ hasChildren: children.length > 0,
124
+ })
125
+ }
126
+ // Catalog event order defines siblings; the stack visits the first one next.
127
+ for (const child of [...children].reverse()) {
128
+ stack.push({ entry: child, parentId: entry.id, depth: depth + 1, parentPath: path })
129
+ }
130
+ }
131
+ return result
132
+ }
133
+
134
+ /**
135
+ * Resolve a slash-separated name by reading only the catalogs along its path.
136
+ * @param ctx - context carrying the Session query service.
137
+ * @param rootSessionId - tree root whose catalog holds the first name.
138
+ * @param name - candidate full name relative to the root.
139
+ * @param signal - cancellation forwarded to each catalog read.
140
+ * @returns the named member's Session id, or undefined when the text is not a name in this tree.
141
+ * @throws {@link SubagentError} when a catalog dependency is unavailable; Session read failures propagate.
142
+ */
143
+ export async function resolveAgentPath(
144
+ ctx: Context,
145
+ rootSessionId: SessionId,
146
+ name: string,
147
+ signal: AbortSignal,
148
+ ): Promise<SessionId | undefined> {
149
+ const segments = name.split('/')
150
+ if (!segments.every(isAgentName)) return undefined
151
+ let current = rootSessionId
152
+ for (const [index, segment] of segments.entries()) {
153
+ const children = await listChildren(ctx, current, signal)
154
+ const child = children.find(entry => 'name' in entry && entry.name === segment)
155
+ if (child === undefined) return undefined
156
+ // External and unknown children own no local Session, so they are the last segment too.
157
+ if (index < segments.length - 1 && child.mode !== 'continuable' && child.mode !== 'one-shot') return undefined
158
+ current = child.id
159
+ }
160
+ return current
161
+ }
162
+
163
+ /** Stop the complete traversal when its caller cancels. */
164
+ function assertListingNotCancelled(signal: AbortSignal | undefined): void {
165
+ if (signal?.aborted) {
166
+ throw new SubagentError('subagent listing was cancelled', 'CANCELLED')
167
+ }
168
+ }