@fish-under-sea/dsh-agent-teams-fish 1.0.2 → 2.0.0

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 (179) hide show
  1. package/NOTICE.md +13 -7
  2. package/README.en.md +20 -12
  3. package/README.md +20 -12
  4. package/compatibility.json +82 -46
  5. package/icon.png +0 -0
  6. package/lib/artifacts.js +148 -25
  7. package/lib/client/ActivityPanel.js +26 -5
  8. package/lib/client/WorkspaceActivity.js +6 -4
  9. package/lib/client/activity-monitor.js +113 -41
  10. package/lib/client/locales.js +14 -0
  11. package/lib/client.js +433 -199
  12. package/lib/client.js.map +1 -1
  13. package/lib/command.js +7 -4
  14. package/lib/git-artifact-stamp.json +2 -2
  15. package/lib/harness-compat.js +120 -62
  16. package/lib/index.js +7 -10
  17. package/lib/mailbox.js +15 -5
  18. package/lib/members.js +221 -154
  19. package/lib/snapshot.js +15 -10
  20. package/lib/state.js +41 -8
  21. package/lib/tools.js +123 -64
  22. package/lib/types/artifacts.d.ts +6 -3
  23. package/lib/types/client/activity-monitor.d.ts +13 -4
  24. package/lib/types/client/locales.d.ts +14 -0
  25. package/lib/types/harness-compat.d.ts +63 -16
  26. package/lib/types/mailbox.d.ts +2 -0
  27. package/lib/types/members.d.ts +5 -17
  28. package/lib/types/snapshot.d.ts +12 -7
  29. package/lib/types/state.d.ts +10 -3
  30. package/lib/types/types.d.ts +5 -0
  31. package/lib/types/web-routes.d.ts +2 -0
  32. package/lib/types/workspace-audit-service.d.ts +35 -0
  33. package/lib/types/workspace-audit-worker.d.ts +1 -0
  34. package/lib/web-routes.js +31 -0
  35. package/lib/workspace-audit-service.js +165 -0
  36. package/lib/workspace-audit-worker.js +11 -0
  37. package/lib/workspace-audit.js +6 -5
  38. package/locale/en.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +69 -64
  41. package/pnpm-workspace.yaml +306 -273
  42. package/release-notes/v0.1.25.md +16 -0
  43. package/release-notes/v0.1.26.md +19 -0
  44. package/release-notes/v0.1.27.md +42 -0
  45. package/release-notes/v0.1.28.md +45 -0
  46. package/release-notes/v0.1.29.md +23 -0
  47. package/release-notes/v1.1.0.md +42 -0
  48. package/release-notes/v2.0.0.md +17 -0
  49. package/scripts/artwork-role-match.test.mjs +517 -0
  50. package/scripts/capabilities.test.mjs +301 -0
  51. package/scripts/check-install-channel.mjs +55 -0
  52. package/scripts/check-install-channel.test.mjs +39 -0
  53. package/scripts/clean-build.mjs +14 -0
  54. package/scripts/client-harness-migration.test.mjs +46 -0
  55. package/scripts/compatibility.mjs +20 -0
  56. package/scripts/compatibility.test.mjs +187 -0
  57. package/scripts/corrupt-teamjson.test.mjs +180 -0
  58. package/scripts/custom-artwork.test.mjs +273 -0
  59. package/scripts/fallback-tdd.mjs +61 -0
  60. package/scripts/fixtures/harness-benchmark-scope.mjs +16 -0
  61. package/scripts/fixtures/harness-benchmark-scope.test.mjs +18 -0
  62. package/scripts/fixtures/harness-complex-case.mjs +201 -0
  63. package/scripts/fixtures/harness-complex-case.test.mjs +21 -0
  64. package/scripts/fixtures/harness-complex-oracle.mjs +63 -0
  65. package/scripts/fixtures/harness-issue-case.mjs +51 -0
  66. package/scripts/fixtures/harness-issue159-case.mjs +28 -0
  67. package/scripts/fixtures/harness-model-case.mjs +127 -0
  68. package/scripts/fixtures/harness-model-case.test.mjs +37 -0
  69. package/scripts/fixtures/harness-model-driver.mjs +100 -0
  70. package/scripts/fixtures/harness-runtime-credentials.mjs +23 -0
  71. package/scripts/fixtures/harness-runtime-entry.mjs +171 -0
  72. package/scripts/fixtures/harness-runtime-idle.mjs +42 -0
  73. package/scripts/fixtures/harness-runtime-llm.mjs +193 -0
  74. package/scripts/fixtures/harness-runtime-protocol.mjs +187 -0
  75. package/scripts/fixtures/harness-runtime-resume.mjs +24 -0
  76. package/scripts/fixtures/harness-runtime-stability.mjs +282 -0
  77. package/scripts/fixtures/harness-runtime-tools.mjs +13 -0
  78. package/scripts/fixtures/harness-runtime-web-approval.mjs +341 -0
  79. package/scripts/fixtures/issue-336-audit-worker.mjs +18 -0
  80. package/scripts/git-artifacts.mjs +64 -0
  81. package/scripts/git-artifacts.test.mjs +32 -0
  82. package/scripts/harness-compat-tdd.mjs +492 -0
  83. package/scripts/harness-issue-verify.mjs +26 -0
  84. package/scripts/harness-model-benchmark.mjs +163 -0
  85. package/scripts/harness-runtime-platform.test.mjs +31 -0
  86. package/scripts/harness-runtime-scenarios.mjs +297 -0
  87. package/scripts/harness-runtime-verify.mjs +169 -0
  88. package/scripts/harness-source-verify.mjs +211 -0
  89. package/scripts/harness-source-verify.test.mjs +97 -0
  90. package/scripts/harness-validation.mjs +68 -0
  91. package/scripts/harness-validation.test.mjs +95 -0
  92. package/scripts/http-body.test.mjs +72 -0
  93. package/scripts/import-vendor-artwork.mjs +78 -0
  94. package/scripts/inline-plan-blank-optional-tdd.mjs +121 -0
  95. package/scripts/issue-159.test.mjs +78 -0
  96. package/scripts/issue-188.test.mjs +148 -0
  97. package/scripts/issue-189.test.mjs +100 -0
  98. package/scripts/issue-203-card.test.mjs +181 -0
  99. package/scripts/issue-205.test.mjs +163 -0
  100. package/scripts/issue-234.test.mjs +424 -0
  101. package/scripts/issue-236-stale-module.test.mjs +63 -0
  102. package/scripts/issue-236.test.mjs +59 -0
  103. package/scripts/issue-262.test.mjs +98 -0
  104. package/scripts/issue-336.test.mjs +404 -0
  105. package/scripts/legacy-session-source-repair.test.mjs +201 -0
  106. package/scripts/lifecycle-verify.mjs +1573 -0
  107. package/scripts/lineage-identity.test.mjs +77 -0
  108. package/scripts/member-failure-tdd.mjs +451 -0
  109. package/scripts/member-spawn-recovery.test.mjs +92 -0
  110. package/scripts/quality-gates-amend.test.mjs +161 -0
  111. package/scripts/quality-gates-content-bound.test.mjs +572 -0
  112. package/scripts/quality-gates-cross-binding.test.mjs +184 -0
  113. package/scripts/quality-gates-excluded-scope.test.mjs +163 -0
  114. package/scripts/quality-gates-repair-scope.test.mjs +143 -0
  115. package/scripts/quality-gates-repair-wiring.test.mjs +189 -0
  116. package/scripts/quality-gates-tdd.mjs +1238 -0
  117. package/scripts/quality-gates-work-order.test.mjs +494 -0
  118. package/scripts/readme-version.mjs +89 -0
  119. package/scripts/readme-version.test.mjs +77 -0
  120. package/scripts/release-metadata.mjs +45 -0
  121. package/scripts/release-metadata.test.mjs +66 -0
  122. package/scripts/scoped-release.test.mjs +52 -0
  123. package/scripts/stability-tdd.mjs +144 -0
  124. package/scripts/stress-verify.mjs +548 -0
  125. package/scripts/symlink-support.mjs +46 -0
  126. package/scripts/sync-skill.mjs +103 -0
  127. package/scripts/tool-policies.test.mjs +280 -0
  128. package/scripts/update-skills.mjs +105 -0
  129. package/scripts/update-skills.test.mjs +79 -0
  130. package/scripts/upgrade-status.mjs +66 -0
  131. package/scripts/upgrade-status.test.mjs +83 -0
  132. package/scripts/verify-package.mjs +73 -0
  133. package/scripts/verify.mjs +2199 -0
  134. package/scripts/web-routes-verify.mjs +142 -0
  135. package/scripts/workspace-activity.test.mjs +346 -0
  136. package/scripts/workspace-summary.test.mjs +49 -0
  137. package/src/artifacts.ts +487 -0
  138. package/src/artwork-source.ts +262 -0
  139. package/src/capabilities.ts +113 -0
  140. package/src/client/ActivityPanel.module.css +2390 -0
  141. package/src/client/ActivityPanel.tsx +1507 -0
  142. package/src/client/AgentTeamsCard.module.css +148 -0
  143. package/src/client/AgentTeamsCard.tsx +155 -0
  144. package/src/client/StagingPlanEditor.tsx +829 -0
  145. package/src/client/TeamChatEntry.tsx +27 -0
  146. package/src/client/WorkspaceActivity.module.css +41 -0
  147. package/src/client/WorkspaceActivity.tsx +137 -0
  148. package/src/client/activity-model.ts +372 -0
  149. package/src/client/activity-monitor.ts +440 -0
  150. package/src/client/agent-teams-card-definition.ts +250 -0
  151. package/src/client/artwork.ts +374 -0
  152. package/src/client/icons.tsx +17 -0
  153. package/src/client/index.tsx +140 -0
  154. package/src/client/locales.ts +481 -0
  155. package/src/client/panel-geometry.ts +194 -0
  156. package/src/client/session-navigation.ts +73 -0
  157. package/src/client/workspace-state.ts +52 -0
  158. package/src/command.ts +145 -0
  159. package/src/css-modules.d.ts +4 -0
  160. package/src/event-types.ts +177 -0
  161. package/src/events.ts +78 -0
  162. package/src/harness-compat.ts +570 -0
  163. package/src/index.ts +599 -0
  164. package/src/lineage.ts +248 -0
  165. package/src/mailbox.ts +185 -0
  166. package/src/members.ts +1230 -0
  167. package/src/profiles.ts +765 -0
  168. package/src/quality-gates.ts +2124 -0
  169. package/src/scheduler.ts +554 -0
  170. package/src/snapshot.ts +333 -0
  171. package/src/state.ts +1317 -0
  172. package/src/tool-names.ts +14 -0
  173. package/src/tool-policies.ts +219 -0
  174. package/src/tools.ts +2939 -0
  175. package/src/types.ts +414 -0
  176. package/src/web-routes.ts +128 -0
  177. package/src/workspace-audit-service.ts +182 -0
  178. package/src/workspace-audit-worker.ts +12 -0
  179. package/src/workspace-audit.ts +57 -0
package/src/events.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Durable AgentTeams session events and their emitter.
3
+ *
4
+ * Every team-state mutation appends one event to the captain's Session, so
5
+ * the web client's Conversation Node mechanism can fold the tree view from
6
+ * the session log deterministically (same mechanism as `tool-workflow`'s
7
+ * `tool-workflow/*` record events). Events append to the captain's session
8
+ * even when a member agent performed the mutation, so the captain's
9
+ * conversation stream stays the single authoritative monitor surface.
10
+ *
11
+ * Types and the `SessionEventMap` merge live in `event-types.ts` (zero
12
+ * imports) so the browser program can load them without host augmentations.
13
+ * @module dsh-agent-teams/events
14
+ */
15
+
16
+ import type { Context } from '@deepseek-ai/cordis'
17
+ import * as dshSession from '@deepseek-ai/dsh-session'
18
+ import type { Session } from '@deepseek-ai/dsh-session'
19
+ import type { SessionEventMap, SessionId } from '@deepseek-ai/dsh-session/types'
20
+ import type { AgentTeamsEventType } from './event-types.ts'
21
+
22
+ /** Event types already reported as unsupported, to avoid repetitive logs. */
23
+ const skippedEventTypes = new Set<AgentTeamsEventType>()
24
+
25
+ /**
26
+ * Append one AgentTeams event to a Session, containing failures (a broken
27
+ * durable record must never break team tool execution).
28
+ * @param ctx - the plugin context (for logging).
29
+ * @param session - the session to record into (the captain's, normally).
30
+ * @param type - the event type.
31
+ * @param data - the event payload.
32
+ */
33
+ export function appendTeamEvent(
34
+ ctx: Context,
35
+ session: Session,
36
+ type: AgentTeamsEventType,
37
+ data: SessionEventMap[AgentTeamsEventType],
38
+ ): void {
39
+ // Out-of-repo events are not in the harness's generated vocabulary today.
40
+ // Mutating that ReadonlySet would make readability depend on which plugins
41
+ // happen to be loaded. Until Session.append exposes the official
42
+ // `ignorable: true` writer surface, omit these informational records unless
43
+ // the running harness already recognizes them. Disk state remains the
44
+ // authoritative source for the activity panel.
45
+ const known = (dshSession as unknown as {
46
+ KNOWN_SESSION_EVENT_TYPES?: ReadonlySet<string>
47
+ }).KNOWN_SESSION_EVENT_TYPES
48
+ if (known?.has(type) !== true) {
49
+ if (!skippedEventTypes.has(type)) {
50
+ skippedEventTypes.add(type)
51
+ ctx.logger.debug(`agent-teams: session event "${type}" omitted because this harness does not recognize it`)
52
+ }
53
+ return
54
+ }
55
+ try {
56
+ session.append(type, data)
57
+ } catch (error: unknown) {
58
+ ctx.logger.warn(`agent-teams: session record failed after ${type}: ${String(error)}`)
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Resolve the captain's live Session for event recording. The captain agent
64
+ * may be offline (its team outlives the session), in which case the caller's
65
+ * own session is used as the fallback record target.
66
+ * @param ctx - the plugin context (injects `agents`).
67
+ * @param captainSessionId - the captain's durable session id.
68
+ * @param fallback - the calling agent's session, used when the captain is not live.
69
+ * @returns the session to record into.
70
+ */
71
+ export function captainSessionOf(
72
+ ctx: Context,
73
+ captainSessionId: string,
74
+ fallback: Session,
75
+ ): Session {
76
+ const captain = ctx.agents.get(captainSessionId as SessionId)
77
+ return captain?.session ?? fallback
78
+ }
@@ -0,0 +1,570 @@
1
+ /**
2
+ * The audited Harness 0.1.2 / 0.1.5 / 0.1.7 subagent boundary. Keep version-specific shapes
3
+ * here: API presence alone is not a promise of support for future versions.
4
+ *
5
+ * Alpha.2 owns followup/registerContinuableSetup; Alpha.5 and rc.1 own a
6
+ * host-only FIFO queue; 0.1.5 uses a queue/steer deliverer. Both emit
7
+ * synchronous agent/session-start with the explicit Agent. Their public
8
+ * sendMessage instead steers a running Agent and must never carry team jobs.
9
+ */
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import { installModelSelection, type Agent, type AgentOptions, type ModelSelection } from '@deepseek-ai/dsh-agent'
12
+ import type { ContentBlock, MessageId, MessageSource, StreamChunk } from '@deepseek-ai/dsh-llm'
13
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
14
+ import * as dshSession from '@deepseek-ai/dsh-session'
15
+ import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
16
+ import { SubagentError } from '@deepseek-ai/dsh-subagent'
17
+ import { BUILTIN_DENY_TOOLS, resolveMemberToolFilter, type MemberToolFilter } from './tool-policies.ts'
18
+
19
+ /**
20
+ * Exact protocol exported by dsh-subagent/internal in Alpha.5 and rc.1.
21
+ * That subpath does not exist in Alpha.2, so importing it statically prevents
22
+ * the plugin from loading there. This small adapter uses the same process-
23
+ * stable symbol and call signature as upstream queueHostSubagentPrompt.
24
+ * Source: packages/subagent/subagent/src/internal.ts at dsh-v0.1.2-rc.1.
25
+ */
26
+ const hostPromptQueue = Symbol.for('dsh.subagent.queuePrompt')
27
+ // 0.1.5 keeps queueHostSubagentPrompt but replaces its symbol with this
28
+ // delivery-mode-aware implementation (packages/subagent/subagent/src/internal.ts).
29
+ const hostPromptDeliver = Symbol.for('dsh.subagent.deliverPrompt')
30
+ type Setup = (childCtx: Context, child: Agent) => () => void
31
+ type LegacySetup = (childCtx: Context & { agent?: Agent }) => () => void
32
+ type Followup = (parent: Agent, childId: SessionId, content: ContentBlock[], options: {
33
+ source: MessageSource; signal: AbortSignal
34
+ }) => Promise<MessageId>
35
+ type Queue = (parent: Agent, childId: SessionId, content: ContentBlock[], source: MessageSource, signal: AbortSignal) => Promise<MessageId>
36
+ type Deliver = (parent: Agent, childId: SessionId, content: ContentBlock[], source: MessageSource, signal: AbortSignal, delivery: 'queue' | 'steer') => Promise<MessageId>
37
+ type Send = (sender: Agent, targetId: SessionId, content: ContentBlock[], options: { signal: AbortSignal }) => Promise<MessageId>
38
+ interface RuntimeBoundary {
39
+ followup?: Followup
40
+ registerContinuableSetup?: (setup: LegacySetup) => () => void
41
+ sendMessage?: Send
42
+ [hostPromptQueue]?: Queue
43
+ [hostPromptDeliver]?: Deliver
44
+ }
45
+
46
+ /** Version-independent creation contract; legacy-only options stay at this seam. */
47
+ export interface MemberStartSpec {
48
+ provider: string
49
+ label: string
50
+ request: {
51
+ parent: Agent
52
+ prompt: ContentBlock[]
53
+ agentOptions?: AgentOptions
54
+ persona?: string
55
+ toolFilter?: MemberToolFilter
56
+ }
57
+ signal: AbortSignal
58
+ }
59
+ interface CreationBoundary {
60
+ start?: (name: string, request: MemberStartSpec['request']) => Promise<unknown>
61
+ startContinuable?: (spec: MemberStartSpec) => Promise<{ childId: SessionId }>
62
+ startActivation?: (spec: MemberStartSpec & { delivery: 'parent' }) => Promise<{
63
+ childId: SessionId
64
+ result: Promise<unknown>
65
+ }>
66
+ }
67
+ export function usesManagedActivations(runtime: Context['subagents']): boolean {
68
+ return typeof (runtime as unknown as CreationBoundary).startActivation === 'function'
69
+ }
70
+
71
+ export async function startMember(runtime: Context['subagents'], spec: MemberStartSpec): Promise<{ childId: SessionId }> {
72
+ const host = runtime as unknown as CreationBoundary
73
+ if (typeof host.startActivation === 'function') {
74
+ const { persona: _persona, toolFilter: _filter, ...request } = spec.request
75
+ const activation = await host.startActivation.call(runtime, { ...spec, request, delivery: 'parent' })
76
+ // Preserve native settlement as the missing-report/error fallback on both
77
+ // fresh and resumed activations. mailbox.ts deduplicates successful reports.
78
+ void activation.result.catch(() => undefined)
79
+ return activation
80
+ }
81
+ if (typeof host.startContinuable !== 'function') return unsupported('missing member creation API')
82
+ return host.startContinuable.call(runtime, spec)
83
+ }
84
+
85
+ /** Wrap every available creation API, restoring only this plugin's own methods. */
86
+ export function guardSubagentCreation(ctx: Context, check: (parent: Agent) => void): void {
87
+ const runtime = ctx.subagents as unknown as CreationBoundary
88
+ ctx.effect(() => {
89
+ const disposers: (() => void)[] = []
90
+ for (const key of ['start', 'startContinuable', 'startActivation'] as const) {
91
+ const original = runtime[key]
92
+ if (typeof original !== 'function') continue
93
+ const descriptor = Object.getOwnPropertyDescriptor(runtime, key)
94
+ const guarded = async (...args: unknown[]): Promise<unknown> => {
95
+ const request = key === 'start' ? args[1] : (args[0] as MemberStartSpec).request
96
+ check((request as MemberStartSpec['request']).parent)
97
+ return Reflect.apply(original, ctx.subagents, args)
98
+ }
99
+ Object.defineProperty(runtime, key, { value: guarded, writable: true, configurable: true })
100
+ disposers.push(() => {
101
+ if (Object.getOwnPropertyDescriptor(runtime, key)?.value !== guarded) return
102
+ if (descriptor === undefined) Reflect.deleteProperty(runtime, key)
103
+ else Object.defineProperty(runtime, key, descriptor)
104
+ })
105
+ }
106
+ return () => { for (const dispose of disposers) dispose() }
107
+ }, 'agent-teams: member delegation budget')
108
+ }
109
+
110
+ /**
111
+ * Install the member's next-step model selection hook on a child context.
112
+ *
113
+ * 0.2.1 hosts take a caller-owned selection ref here; 0.2.2 moved the selected
114
+ * route into the Agent's own durable model API, so the hook contributes switch
115
+ * notices only and takes the child context alone. Dispatch on the function's
116
+ * own arity so one build serves both declared host lines instead of binding to
117
+ * whichever signature the development host happens to ship.
118
+ * @param childCtx - the member child context the hook belongs to.
119
+ * @param ref - the resolved selection the member is running on.
120
+ * @returns the disposal for the installed hook.
121
+ */
122
+ export function installMemberModelSelection(
123
+ childCtx: Context,
124
+ ref: { current: ModelSelection; assembled?: ModelSelection },
125
+ ): () => void {
126
+ const install = installModelSelection as unknown as (ctx: Context, ref?: unknown) => () => void
127
+ return install.length >= 2 ? install(childCtx, ref) : install(childCtx)
128
+ }
129
+
130
+ function boundary(runtime: Context['subagents']): RuntimeBoundary {
131
+ return runtime as unknown as RuntimeBoundary
132
+ }
133
+
134
+ function unsupported(detail: string): never {
135
+ throw new Error(`agent-teams: unsupported Harness subagent contract (${detail}); use an explicitly tested Harness version and a coherent dependency installation`)
136
+ }
137
+
138
+ declare module '@deepseek-ai/dsh-llm' {
139
+ interface MessageSourceMap {
140
+ 'agent-teams': { readonly kind: 'agent-teams' }
141
+ }
142
+ }
143
+
144
+ /** Package identity a released plugin-wrapper source names on older hosts. */
145
+ export const AGENT_TEAMS_PLUGIN_NAME = '@nanmicoder/dsh-agent-teams'
146
+
147
+ /**
148
+ * First stored format generation whose migration edges admit producer-owned
149
+ * source kinds. The released v2→v3 payload audit validates every message source
150
+ * against a closed list of released kinds, so a stored format older than this
151
+ * must carry a released source or the whole session becomes unreadable once a
152
+ * newer host opens it (#160).
153
+ */
154
+ export const RELEASED_SOURCE_VOCABULARY_VERSION = 3
155
+
156
+ /** Source kinds this plugin mints on a host whose stored format admits them. */
157
+ export type AgentTeamsSource =
158
+ | { readonly kind: 'agent-teams' }
159
+ | { readonly kind: 'agent-teams-command'; readonly goal?: string; readonly profile?: string }
160
+
161
+ /** Anything that exposes the stored format generation on its live session header. */
162
+ export interface SessionFormatBearer {
163
+ readonly session?: { readonly header?: { readonly version?: unknown } } | undefined
164
+ }
165
+
166
+ /**
167
+ * Stored format generation observed on a live session, when the host exposes it.
168
+ *
169
+ * The module constant is only a fallback: a plugin can resolve a *nested*
170
+ * `@deepseek-ai/dsh-session` copy that belongs to a different host generation
171
+ * than the process loading it (a profile whose lockfile pins the DSH package
172
+ * line, a Desktop shell with an embedded core, a duplicated store). That copy
173
+ * then reports the wrong generation — 0 on a v4 host — which selects the
174
+ * retired `plugin` wrapper and makes every durable AgentTeams message fail the
175
+ * host's own admission check (#236). The live session header belongs to the
176
+ * host that persists the message, so it outranks the resolved module.
177
+ */
178
+ export function observedSessionFormatVersion(subject?: SessionFormatBearer): number | undefined {
179
+ const version = subject?.session?.header?.version
180
+ return typeof version === 'number' && Number.isSafeInteger(version) && version >= 0 ? version : undefined
181
+ }
182
+
183
+ /**
184
+ * Stored session format generation of the running host; 0 when neither the live
185
+ * session nor the resolved module exposes one.
186
+ * @param observed - a live session observation; preferred over the module constant.
187
+ */
188
+ export function hostSessionFormatVersion(observed?: number): number {
189
+ if (typeof observed === 'number' && Number.isSafeInteger(observed) && observed >= 0) return observed
190
+ const version = (dshSession as unknown as { SESSION_FORMAT_VERSION?: number }).SESSION_FORMAT_VERSION
191
+ return typeof version === 'number' && Number.isSafeInteger(version) && version >= 0 ? version : 0
192
+ }
193
+
194
+ /**
195
+ * Source for one AgentTeams-authored message on the running host.
196
+ *
197
+ * Current hosts mint producer-owned kinds: the Harness documents message
198
+ * sources as a merge-extensible vocabulary without a catch-all, so this plugin
199
+ * declares its own. Hosts that still store a pre-v3 generation are a different
200
+ * contract — their released v2→v3 migration rejects any source outside the
201
+ * released vocabulary, which is exactly how a plugin kind written on an older
202
+ * supported host poisons its session log for every later host. On those hosts
203
+ * the released plugin wrapper is used instead; the goal and profile already
204
+ * travel in the message text.
205
+ * @param modern - the producer-owned source to use where the host admits it.
206
+ * @param observed - the live session's stored format generation, when callers
207
+ * have the owning agent at hand. Never trust the resolved module alone: on a
208
+ * host whose profile pins another DSH line it reports a retired generation and
209
+ * the v4 writer rejects the wrapper (#236).
210
+ * @returns a source accepted by the running host and by its migration chain.
211
+ */
212
+ export function agentTeamsSource(modern: AgentTeamsSource, observed?: number): MessageSource {
213
+ if (hostSessionFormatVersion(observed) >= RELEASED_SOURCE_VOCABULARY_VERSION) return modern
214
+ // Released-format hosts persist plugin-authored messages as this wrapper; the
215
+ // current vocabulary retired it, so the cast stays confined to this branch
216
+ // and `modern` is the only shape a current host ever sees.
217
+ return { kind: 'plugin', plugin: AGENT_TEAMS_PLUGIN_NAME } as unknown as MessageSource
218
+ }
219
+
220
+ /**
221
+ * 0.1.6 moved startup admission to serial agent/created. Older created events
222
+ * have no source and precede session-start; ignore those until the old hook.
223
+ * Keep the removed event's type confined to this audited compatibility seam.
224
+ */
225
+ export function onAgentReady(ctx: Context, listener: (agent: Agent, vetoable: boolean) => void): () => void {
226
+ const stopCreated = ctx.on('agent/created', payload => {
227
+ if ('source' in payload) listener(payload.agent, true)
228
+ return undefined
229
+ })
230
+ const legacy = ctx as unknown as {
231
+ on(name: 'agent/session-start', listener: (payload: { agent: Agent }) => void): () => void
232
+ }
233
+ const stopLegacy = legacy.on('agent/session-start', ({ agent }) => listener(agent, false))
234
+ return () => { stopCreated(); stopLegacy() }
235
+ }
236
+
237
+ /** Read child-owned history, excluding any descriptor inherited from a parent. */
238
+ export function sessionOwnEvents(session: Session): readonly SessionEvent[] {
239
+ const current = session as unknown as { ownEvents?: () => readonly SessionEvent[] }
240
+ if (typeof current.ownEvents === 'function') return current.ownEvents.call(session)
241
+ const legacy = session as unknown as { events?: readonly SessionEvent[]; header: { seedLength?: number } }
242
+ if (!Array.isArray(legacy.events)) return unsupported('missing ownEvents/legacy session log')
243
+ return legacy.events.slice(legacy.header.seedLength ?? 0)
244
+ }
245
+
246
+ /** Legacy hosts log each chunk separately; current hosts embed the committed stream. */
247
+ export function outputLimitTurn(event: SessionEvent): number | undefined {
248
+ const record = event as SessionEvent | {
249
+ type: 'assistant/chunk'
250
+ data: { turn: number; chunk: StreamChunk }
251
+ }
252
+ if (record.type === 'assistant/chunk') {
253
+ const { chunk, turn } = record.data
254
+ return chunk.type === 'finish' && chunk.reason.kind === 'max-tokens' ? turn : undefined
255
+ }
256
+ if (record.type === 'assistant/message' && record.data.stream?.some(item =>
257
+ item.type === 'chunk' && item.chunk.type === 'finish' && item.chunk.reason.kind === 'max-tokens')) {
258
+ return record.data.turn
259
+ }
260
+ }
261
+
262
+ /** 读取宿主冻结的会话策略,旧版没有投影服务时检查本会话日志。 */
263
+ export function assertMemberModelSelection(ctx: Context, captain: Agent, route: { provider: string; model: string }): void {
264
+ const projections = ctx.get?.('sessionProjections') as {
265
+ stateOf(session: Session, key: string): unknown
266
+ } | undefined
267
+ const session = captain.session as unknown as { ownEvents?: () => readonly SessionEvent[]; events?: readonly SessionEvent[] }
268
+ const projected = projections?.stateOf(captain.session, 'subagentModelSelectionPolicy')
269
+ const policy = projected === undefined
270
+ ? (typeof session.ownEvents === 'function' || Array.isArray(session.events))
271
+ ? (sessionOwnEvents(captain.session) as readonly { type: string; data: unknown }[]).find(event => event.type === 'subagent/model-selection-policy')?.data
272
+ : undefined
273
+ : projected
274
+ if (policy === undefined || policy === null) return
275
+ const routes: unknown = projected === undefined
276
+ ? (policy as { allowedModels?: unknown }).allowedModels
277
+ : policy
278
+ if (!Array.isArray(routes) || routes.length === 0 || routes.some((candidate: unknown) => (
279
+ typeof candidate !== 'object' || candidate === null
280
+ || !('provider' in candidate) || typeof candidate.provider !== 'string' || candidate.provider.length === 0
281
+ || !('model' in candidate) || typeof candidate.model !== 'string' || candidate.model.length === 0
282
+ ))) throw new Error('agent-teams: invalid captured subagent model selection policy')
283
+ if (!routes.some(candidate => candidate.provider === route.provider && candidate.model === route.model)) {
284
+ throw new Error(`agent-teams: child LLM route "${route.provider}/${route.model}" is not allowed for this Session; choose a route from list_subagent_models`)
285
+ }
286
+ }
287
+
288
+ /** Install before the first request, including cold resume, with HMR cleanup. */
289
+ export function installContinuableMemberSetup(ctx: Context, setup: Setup): void {
290
+ const runtime = boundary(ctx.subagents)
291
+ if (typeof runtime.registerContinuableSetup === 'function') {
292
+ // Upstream owns this registration with this.ctx.effect. Cordis resolves
293
+ // that ctx to the accessing plugin, so its disposal revokes installations
294
+ // even while the subagents service and child Agents remain live.
295
+ runtime.registerContinuableSetup.call(ctx.subagents, (childCtx) => {
296
+ if (childCtx.agent === undefined) return unsupported('legacy setup lacks child Agent')
297
+ return setup(childCtx, childCtx.agent)
298
+ })
299
+ return
300
+ }
301
+ if ((typeof runtime[hostPromptQueue] !== 'function' && typeof runtime[hostPromptDeliver] !== 'function') || typeof runtime.sendMessage !== 'function') {
302
+ return unsupported('missing continuable setup and modern host queue')
303
+ }
304
+ const installed = new WeakSet<Agent>()
305
+ const active = new Set<() => void>()
306
+ ctx.effect(() => {
307
+ const attach = (agent: Agent, vetoable: boolean): void => {
308
+ if (installed.has(agent)) return
309
+ // Deliberately synchronous: awaiting here loses the first-request race.
310
+ let teardown: () => void
311
+ try {
312
+ teardown = setup(agent.ctx, agent)
313
+ } catch (error: unknown) {
314
+ if (vetoable) throw error
315
+ // session-start is a notification: Harness logs a thrown listener and
316
+ // still admits the first prompt. Reject request assembly explicitly so
317
+ // a malformed saved route cannot silently execute on a default model.
318
+ const failure = new Error(`agent-teams: member initialization failed: ${String(error)}`, { cause: error })
319
+ ctx.logger.warn(failure.message)
320
+ teardown = agent.ctx.on('agent/request', () => { throw failure })
321
+ }
322
+ installed.add(agent)
323
+ let disposed = false
324
+ const dispose = (): void => {
325
+ if (disposed) return
326
+ disposed = true
327
+ active.delete(dispose)
328
+ installed.delete(agent)
329
+ teardown()
330
+ }
331
+ active.add(dispose)
332
+ // Listeners contributed to agent.ctx already follow its lifetime. Also
333
+ // release our bookkeeping and remove them if this plugin is reloaded.
334
+ try {
335
+ agent.ctx.effect(() => dispose, 'agent-teams: child compatibility setup')
336
+ } catch (error) {
337
+ dispose()
338
+ throw error
339
+ }
340
+ }
341
+ const stop = onAgentReady(ctx, attach)
342
+ const cleanup = (): void => {
343
+ stop()
344
+ for (const dispose of [...active]) dispose()
345
+ }
346
+ try {
347
+ // Reloads keep Agents alive but dispose the previous plugin's setup.
348
+ // Subscribe first, then hydrate the live registry; attach is idempotent.
349
+ for (const agent of ctx.agents.list()) attach(agent, false)
350
+ } catch (error) {
351
+ cleanup()
352
+ throw error
353
+ }
354
+ return cleanup
355
+ }, 'agent-teams: member lifecycle compatibility')
356
+ }
357
+
358
+ /** Queue a distinct host-authored turn; never substitute model-message steer. */
359
+ export async function queueMemberPrompt(
360
+ runtime: Context['subagents'], parent: Agent, childId: SessionId,
361
+ content: ContentBlock[], signal: AbortSignal,
362
+ ): Promise<MessageId> {
363
+ const host = boundary(runtime)
364
+ const source = agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(parent))
365
+ if (typeof host.followup === 'function') {
366
+ return host.followup.call(runtime, parent, childId, content, { source, signal })
367
+ }
368
+ const deliver = host[hostPromptDeliver]
369
+ if (typeof deliver === 'function') return deliver.call(runtime, parent, childId, content, source, signal, 'queue')
370
+ const queue = host[hostPromptQueue]
371
+ if (typeof queue !== 'function') return unsupported('missing host FIFO delivery')
372
+ return queue.call(runtime, parent, childId, content, source, signal)
373
+ }
374
+
375
+ /** Coordination joins the nearest step, including waking an idle/cold child. */
376
+ export async function steerMemberPrompt(
377
+ runtime: Context['subagents'], parent: Agent, childId: SessionId,
378
+ content: ContentBlock[], signal: AbortSignal, live?: Agent,
379
+ ): Promise<MessageId> {
380
+ const host = boundary(runtime)
381
+ const source = agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(live ?? parent))
382
+ const deliver = host[hostPromptDeliver]
383
+ if (typeof deliver === 'function') return deliver.call(runtime, parent, childId, content, source, signal, 'steer')
384
+ if (typeof host.sendMessage === 'function') return host.sendMessage.call(runtime, parent, childId, content, { signal })
385
+ if (typeof host.followup === 'function') {
386
+ if (live === undefined) return queueMemberPrompt(runtime, parent, childId, content, signal)
387
+ if (live.id !== childId || live.session.header.parentSession !== parent.id) throw new Error('invalid member steering authority')
388
+ signal.throwIfAborted()
389
+ const message = createUserMessage({ content, source })
390
+ live.steer(message)
391
+ return message.id
392
+ }
393
+ return unsupported('missing step-boundary message delivery')
394
+ }
395
+
396
+ /** Guard all resumable delivery paths, preserving the native service receiver. */
397
+ export function guardSubagentDelivery(
398
+ ctx: Context, isRetired: (sender: Agent, targetId: SessionId) => Promise<boolean>,
399
+ ): void {
400
+ const runtime = ctx.subagents
401
+ const host = boundary(runtime)
402
+ const legacy = host.followup
403
+ const queue = host[hostPromptQueue]
404
+ const deliver = host[hostPromptDeliver]
405
+ const send = host.sendMessage
406
+ if (typeof legacy !== 'function' && ((typeof queue !== 'function' && typeof deliver !== 'function') || typeof send !== 'function')) {
407
+ return unsupported('cannot install complete retired-member guard')
408
+ }
409
+ ctx.effect(() => {
410
+ const descriptors = new Map<PropertyKey, PropertyDescriptor | undefined>([
411
+ ['followup', Object.getOwnPropertyDescriptor(host, 'followup')],
412
+ [hostPromptQueue, Object.getOwnPropertyDescriptor(host, hostPromptQueue)],
413
+ [hostPromptDeliver, Object.getOwnPropertyDescriptor(host, hostPromptDeliver)],
414
+ ['sendMessage', Object.getOwnPropertyDescriptor(host, 'sendMessage')],
415
+ ])
416
+ let active = true
417
+ const check = async (sender: Agent, targetId: SessionId): Promise<void> => {
418
+ if (active && await isRetired(sender, targetId)) {
419
+ throw new SubagentError(`AgentTeams member "${targetId}" was retired and cannot be resumed`, 'NOT_RESUMABLE')
420
+ }
421
+ }
422
+ const guardedLegacy: Followup = async (parent, childId, content, options) => {
423
+ await check(parent, childId)
424
+ return legacy!.call(runtime, parent, childId, content, options)
425
+ }
426
+ const guardedQueue: Queue = async (parent, childId, content, source, signal) => {
427
+ await check(parent, childId)
428
+ return queue!.call(runtime, parent, childId, content, source, signal)
429
+ }
430
+ const guardedSend: Send = async (sender, targetId, content, options) => {
431
+ await check(sender, targetId)
432
+ return send!.call(runtime, sender, targetId, content, options)
433
+ }
434
+ const guardedDeliver: Deliver = async (parent, childId, content, source, signal, delivery) => {
435
+ await check(parent, childId)
436
+ return deliver!.call(runtime, parent, childId, content, source, signal, delivery)
437
+ }
438
+ if (typeof legacy === 'function') host.followup = guardedLegacy
439
+ if (typeof queue === 'function') host[hostPromptQueue] = guardedQueue
440
+ if (typeof deliver === 'function') host[hostPromptDeliver] = guardedDeliver
441
+ if (typeof send === 'function') host.sendMessage = guardedSend
442
+ // Cordis wraps method reads in fresh Proxies. Compare the actual own
443
+ // descriptor to restore only our contribution, including prototype methods.
444
+ const restore = (key: PropertyKey, installed: unknown): void => {
445
+ if (Object.getOwnPropertyDescriptor(host, key)?.value !== installed) return
446
+ const original = descriptors.get(key)
447
+ if (original === undefined) Reflect.deleteProperty(host, key)
448
+ else Object.defineProperty(host, key, original)
449
+ }
450
+ return () => {
451
+ active = false
452
+ if (typeof legacy === 'function') restore('followup', guardedLegacy)
453
+ if (typeof queue === 'function') restore(hostPromptQueue, guardedQueue)
454
+ if (typeof deliver === 'function') restore(hostPromptDeliver, guardedDeliver)
455
+ if (typeof send === 'function') restore('sendMessage', guardedSend)
456
+ }
457
+ }, 'agent-teams: retired member guard')
458
+ }
459
+
460
+ /** Structural shape of the host tool registry view (dsh-tools `view()`). */
461
+ interface ToolsRegistryView {
462
+ restrictableNames?: ReadonlySet<string>
463
+ }
464
+
465
+ /**
466
+ * Names the host's `tools.restrict()` would admit for this agent's layer
467
+ * chain, or undefined when the host does not expose its registry view.
468
+ * restrict() rejects unknown names with a hard error, so the spawn path must
469
+ * check entries against this view before forwarding them. Source:
470
+ * dsh-tools view()/restrict() in 0.1.5-rc.1; older Harness generations lack
471
+ * the surface and keep the verbatim list.
472
+ */
473
+ export function restrictableToolNames(agent: Agent): ReadonlySet<string> | undefined {
474
+ const tools = (agent?.ctx as unknown as { tools?: { view?: (scope?: unknown) => ToolsRegistryView } })?.tools
475
+ if (typeof tools?.view !== 'function') return undefined
476
+ try {
477
+ const names = tools.view.call(tools, agent.ctx)?.restrictableNames
478
+ return names instanceof Set ? names : undefined
479
+ } catch {
480
+ return undefined
481
+ }
482
+ }
483
+
484
+ /**
485
+ * Member `toolFilter` for one spawn. Captain-only names are registered by
486
+ * this plugin itself and always resolvable; the depth-related entries name
487
+ * HOST tools and are only known under some compositions, so they must be
488
+ * resolved against the running host's registry: the delegation tool name is
489
+ * host configuration (dsh-tool-subagent `toolName`, default `subagent`,
490
+ * renamed per composition, e.g. `subagent_fork` in web-style profiles), and
491
+ * forwarding a name the host dropped aborts every member spawn (#163, #164).
492
+ * Depth enforcement itself does not depend on these names —
493
+ * installMemberDelegationGuard bounds descendant creation by parent chain.
494
+ *
495
+ * This is the legacy filter of a member without a configured tool policy; a
496
+ * selected policy resolves through `resolveMemberToolFilter` instead (#59).
497
+ */
498
+ export function memberToolFilter(maxDepth: number | undefined, knownTools: ReadonlySet<string> | undefined): MemberToolFilter {
499
+ return resolveMemberToolFilter(undefined, { maxDepth, knownTools })
500
+ }
501
+
502
+ /**
503
+ * Names a `tools.restrict()` rejection reported as unknown, or an empty list
504
+ * for every other failure. The host names the offenders verbatim
505
+ * (`tools.restrict() names unknown global tool "x"; known global tools: …`);
506
+ * only that report may relax a filter (#164, #166).
507
+ */
508
+ function unknownToolNames(error: unknown): string[] {
509
+ const message = error instanceof Error ? error.message : String(error)
510
+ if (!message.includes('unknown global tool')) return []
511
+ return [...message.matchAll(/"([^"]+)"/g)].map(match => match[1] as string)
512
+ }
513
+
514
+ /**
515
+ * Start one member, dropping only the built-in filter names the host reports
516
+ * as unknown and retrying.
517
+ *
518
+ * Resolving the filter against the registry view ({@link memberToolFilter})
519
+ * only covers hosts that expose one. A rejected filter still leaves the member
520
+ * without a session for the lifetime of the team, so the start must survive the
521
+ * cases that resolution cannot see — no registry view, a name that is known but
522
+ * not restrictable, a composition that mounted differently than expected. The
523
+ * host names the offenders in its rejection, so the relaxable ones are removed
524
+ * and the start retried.
525
+ *
526
+ * Only `relaxableDeny` names may be dropped, and only from `deny`. The default
527
+ * is exactly the built-in captain-only and depth entries (#163/#164); a name an
528
+ * owner-declared tool policy contributed is never removed, because silently
529
+ * spawning a member with a different filter than the owner declared is contract
530
+ * drift, not recovery. Dropping a denied name the host does not register
531
+ * changes nothing; dropping an allowed name would loosen the policy, so `allow`
532
+ * is never relaxed and the four required coordination tools can never be
533
+ * removed.
534
+ * @param start - performs one start attempt for the given `toolFilter`.
535
+ * @param filter - the filter to attempt first.
536
+ * @param relaxableDeny - built-in deny names the retry may drop.
537
+ * @returns the started member.
538
+ */
539
+ export async function startMemberWithLenientFilter<T>(
540
+ start: (filter: MemberToolFilter) => Promise<T>,
541
+ filter: MemberToolFilter,
542
+ relaxableDeny: readonly string[] = BUILTIN_DENY_TOOLS,
543
+ ): Promise<T> {
544
+ const current: MemberToolFilter = {
545
+ ...filter.allow === undefined ? {} : { allow: [...filter.allow] },
546
+ deny: [...filter.deny],
547
+ }
548
+ for (;;) {
549
+ try {
550
+ return await start(current)
551
+ } catch (error: unknown) {
552
+ const unknown = unknownToolNames(error)
553
+ if (unknown.length === 0) throw error
554
+ const droppable = unknown.filter(name => relaxableDeny.includes(name) && current.deny.includes(name))
555
+ if (droppable.length === 0) throw error
556
+ current.deny = current.deny.filter(name => !droppable.includes(name))
557
+ }
558
+ }
559
+ }
560
+
561
+ /** Targeted recursive cancellation renamed with the unified activation manager. */
562
+ export async function drainMemberChildren(runtime: Context['subagents'], parent: Agent, ids: readonly SessionId[]): Promise<void> {
563
+ const host = runtime as unknown as {
564
+ drainChildren?: (parent: Agent, ids: readonly SessionId[]) => Promise<void>
565
+ drainContinuableChildren?: (parent: Agent, ids: readonly SessionId[]) => Promise<void>
566
+ }
567
+ const drain = host.drainChildren ?? host.drainContinuableChildren
568
+ if (typeof drain !== 'function') return unsupported('missing targeted child drain')
569
+ await drain.call(runtime, parent, ids)
570
+ }