返回 CodeWhale
harness-compat.js
根目录 / crates / plugins / assets / agent-teams / lib / harness-compat.js
1 import { createUserMessage } from '@deepseek-ai/dsh-llm';
2 import * as dshSession from '@deepseek-ai/dsh-session';
3 import { SubagentError } from '@deepseek-ai/dsh-subagent';
4 import { BUILTIN_DENY_TOOLS, resolveMemberToolFilter } from "./tool-policies.js";
5 /**
6 * Exact protocol exported by dsh-subagent/internal in Alpha.5 and rc.1.
7 * That subpath does not exist in Alpha.2, so importing it statically prevents
8 * the plugin from loading there. This small adapter uses the same process-
9 * stable symbol and call signature as upstream queueHostSubagentPrompt.
10 * Source: packages/subagent/subagent/src/internal.ts at dsh-v0.1.2-rc.1.
11 */
12 const hostPromptQueue = Symbol.for('dsh.subagent.queuePrompt');
13 // 0.1.5 keeps queueHostSubagentPrompt but replaces its symbol with this
14 // delivery-mode-aware implementation (packages/subagent/subagent/src/internal.ts).
15 const hostPromptDeliver = Symbol.for('dsh.subagent.deliverPrompt');
16 export function usesManagedActivations(runtime) {
17 return typeof runtime.startActivation === 'function';
18 }
19 export async function startMember(runtime, spec) {
20 const host = runtime;
21 if (typeof host.startActivation === 'function') {
22 const { persona: _persona, toolFilter: _filter, ...request } = spec.request;
23 const activation = await host.startActivation.call(runtime, { ...spec, request, delivery: 'parent' });
24 // Preserve native settlement as the missing-report/error fallback on both
25 // fresh and resumed activations. mailbox.ts deduplicates successful reports.
26 void activation.result.catch(() => undefined);
27 return activation;
28 }
29 if (typeof host.startContinuable !== 'function')
30 return unsupported('missing member creation API');
31 return host.startContinuable.call(runtime, spec);
32 }
33 /** Wrap every available creation API, restoring only this plugin's own methods. */
34 export function guardSubagentCreation(ctx, check) {
35 const runtime = ctx.subagents;
36 ctx.effect(() => {
37 const disposers = [];
38 for (const key of ['start', 'startContinuable', 'startActivation']) {
39 const original = runtime[key];
40 if (typeof original !== 'function')
41 continue;
42 const descriptor = Object.getOwnPropertyDescriptor(runtime, key);
43 const guarded = async (...args) => {
44 const request = key === 'start' ? args[1] : args[0].request;
45 check(request.parent);
46 return Reflect.apply(original, ctx.subagents, args);
47 };
48 Object.defineProperty(runtime, key, { value: guarded, writable: true, configurable: true });
49 disposers.push(() => {
50 if (Object.getOwnPropertyDescriptor(runtime, key)?.value !== guarded)
51 return;
52 if (descriptor === undefined)
53 Reflect.deleteProperty(runtime, key);
54 else
55 Object.defineProperty(runtime, key, descriptor);
56 });
57 }
58 return () => { for (const dispose of disposers)
59 dispose(); };
60 }, 'agent-teams: member delegation budget');
61 }
62 function boundary(runtime) {
63 return runtime;
64 }
65 function unsupported(detail) {
66 throw new Error(`agent-teams: unsupported Harness subagent contract (${detail}); use an explicitly tested Harness version and a coherent dependency installation`);
67 }
68 /** Package identity a released plugin-wrapper source names on older hosts. */
69 export const AGENT_TEAMS_PLUGIN_NAME = '@nanmicoder/dsh-agent-teams';
70 /**
71 * First stored format generation whose migration edges admit producer-owned
72 * source kinds. The released v2→v3 payload audit validates every message source
73 * against a closed list of released kinds, so a stored format older than this
74 * must carry a released source or the whole session becomes unreadable once a
75 * newer host opens it (#160).
76 */
77 export const RELEASED_SOURCE_VOCABULARY_VERSION = 3;
78 /**
79 * Stored format generation observed on a live session, when the host exposes it.
80 *
81 * The module constant is only a fallback: a plugin can resolve a *nested*
82 * `@deepseek-ai/dsh-session` copy that belongs to a different host generation
83 * than the process loading it (a profile whose lockfile pins the DSH package
84 * line, a Desktop shell with an embedded core, a duplicated store). That copy
85 * then reports the wrong generation — 0 on a v4 host — which selects the
86 * retired `plugin` wrapper and makes every durable AgentTeams message fail the
87 * host's own admission check (#236). The live session header belongs to the
88 * host that persists the message, so it outranks the resolved module.
89 */
90 export function observedSessionFormatVersion(subject) {
91 const version = subject?.session?.header?.version;
92 return typeof version === 'number' && Number.isSafeInteger(version) && version >= 0 ? version : undefined;
93 }
94 /**
95 * Stored session format generation of the running host; 0 when neither the live
96 * session nor the resolved module exposes one.
97 * @param observed - a live session observation; preferred over the module constant.
98 */
99 export function hostSessionFormatVersion(observed) {
100 if (typeof observed === 'number' && Number.isSafeInteger(observed) && observed >= 0)
101 return observed;
102 const version = dshSession.SESSION_FORMAT_VERSION;
103 return typeof version === 'number' && Number.isSafeInteger(version) && version >= 0 ? version : 0;
104 }
105 /**
106 * Source for one AgentTeams-authored message on the running host.
107 *
108 * Current hosts mint producer-owned kinds: the Harness documents message
109 * sources as a merge-extensible vocabulary without a catch-all, so this plugin
110 * declares its own. Hosts that still store a pre-v3 generation are a different
111 * contract — their released v2→v3 migration rejects any source outside the
112 * released vocabulary, which is exactly how a plugin kind written on an older
113 * supported host poisons its session log for every later host. On those hosts
114 * the released plugin wrapper is used instead; the goal and profile already
115 * travel in the message text.
116 * @param modern - the producer-owned source to use where the host admits it.
117 * @param observed - the live session's stored format generation, when callers
118 * have the owning agent at hand. Never trust the resolved module alone: on a
119 * host whose profile pins another DSH line it reports a retired generation and
120 * the v4 writer rejects the wrapper (#236).
121 * @returns a source accepted by the running host and by its migration chain.
122 */
123 export function agentTeamsSource(modern, observed) {
124 if (hostSessionFormatVersion(observed) >= RELEASED_SOURCE_VOCABULARY_VERSION)
125 return modern;
126 // Released-format hosts persist plugin-authored messages as this wrapper; the
127 // current vocabulary retired it, so the cast stays confined to this branch
128 // and `modern` is the only shape a current host ever sees.
129 return { kind: 'plugin', plugin: AGENT_TEAMS_PLUGIN_NAME };
130 }
131 /**
132 * 0.1.6 moved startup admission to serial agent/created. Older created events
133 * have no source and precede session-start; ignore those until the old hook.
134 * Keep the removed event's type confined to this audited compatibility seam.
135 */
136 export function onAgentReady(ctx, listener) {
137 const stopCreated = ctx.on('agent/created', payload => {
138 if ('source' in payload)
139 listener(payload.agent, true);
140 return undefined;
141 });
142 const legacy = ctx;
143 const stopLegacy = legacy.on('agent/session-start', ({ agent }) => listener(agent, false));
144 return () => { stopCreated(); stopLegacy(); };
145 }
146 /** Read child-owned history, excluding any descriptor inherited from a parent. */
147 export function sessionOwnEvents(session) {
148 const current = session;
149 if (typeof current.ownEvents === 'function')
150 return current.ownEvents.call(session);
151 const legacy = session;
152 if (!Array.isArray(legacy.events))
153 return unsupported('missing ownEvents/legacy session log');
154 return legacy.events.slice(legacy.header.seedLength ?? 0);
155 }
156 /** Legacy hosts log each chunk separately; current hosts embed the committed stream. */
157 export function outputLimitTurn(event) {
158 const record = event;
159 if (record.type === 'assistant/chunk') {
160 const { chunk, turn } = record.data;
161 return chunk.type === 'finish' && chunk.reason.kind === 'max-tokens' ? turn : undefined;
162 }
163 if (record.type === 'assistant/message' && record.data.stream?.some(item => item.type === 'chunk' && item.chunk.type === 'finish' && item.chunk.reason.kind === 'max-tokens')) {
164 return record.data.turn;
165 }
166 }
167 /** Install before the first request, including cold resume, with HMR cleanup. */
168 export function installContinuableMemberSetup(ctx, setup) {
169 const runtime = boundary(ctx.subagents);
170 if (typeof runtime.registerContinuableSetup === 'function') {
171 // Upstream owns this registration with this.ctx.effect. Cordis resolves
172 // that ctx to the accessing plugin, so its disposal revokes installations
173 // even while the subagents service and child Agents remain live.
174 runtime.registerContinuableSetup.call(ctx.subagents, (childCtx) => {
175 if (childCtx.agent === undefined)
176 return unsupported('legacy setup lacks child Agent');
177 return setup(childCtx, childCtx.agent);
178 });
179 return;
180 }
181 if ((typeof runtime[hostPromptQueue] !== 'function' && typeof runtime[hostPromptDeliver] !== 'function') || typeof runtime.sendMessage !== 'function') {
182 return unsupported('missing continuable setup and modern host queue');
183 }
184 const installed = new WeakSet();
185 const active = new Set();
186 ctx.effect(() => {
187 const attach = (agent, vetoable) => {
188 if (installed.has(agent))
189 return;
190 // Deliberately synchronous: awaiting here loses the first-request race.
191 let teardown;
192 try {
193 teardown = setup(agent.ctx, agent);
194 }
195 catch (error) {
196 if (vetoable)
197 throw error;
198 // session-start is a notification: Harness logs a thrown listener and
199 // still admits the first prompt. Reject request assembly explicitly so
200 // a malformed saved route cannot silently execute on a default model.
201 const failure = new Error(`agent-teams: member initialization failed: ${String(error)}`, { cause: error });
202 ctx.logger.warn(failure.message);
203 teardown = agent.ctx.on('agent/request', () => { throw failure; });
204 }
205 installed.add(agent);
206 let disposed = false;
207 const dispose = () => {
208 if (disposed)
209 return;
210 disposed = true;
211 active.delete(dispose);
212 installed.delete(agent);
213 teardown();
214 };
215 active.add(dispose);
216 // Listeners contributed to agent.ctx already follow its lifetime. Also
217 // release our bookkeeping and remove them if this plugin is reloaded.
218 try {
219 agent.ctx.effect(() => dispose, 'agent-teams: child compatibility setup');
220 }
221 catch (error) {
222 dispose();
223 throw error;
224 }
225 };
226 const stop = onAgentReady(ctx, attach);
227 const cleanup = () => {
228 stop();
229 for (const dispose of [...active])
230 dispose();
231 };
232 try {
233 // Reloads keep Agents alive but dispose the previous plugin's setup.
234 // Subscribe first, then hydrate the live registry; attach is idempotent.
235 for (const agent of ctx.agents.list())
236 attach(agent, false);
237 }
238 catch (error) {
239 cleanup();
240 throw error;
241 }
242 return cleanup;
243 }, 'agent-teams: member lifecycle compatibility');
244 }
245 /** Queue a distinct host-authored turn; never substitute model-message steer. */
246 export async function queueMemberPrompt(runtime, parent, childId, content, signal) {
247 const host = boundary(runtime);
248 const source = agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(parent));
249 if (typeof host.followup === 'function') {
250 return host.followup.call(runtime, parent, childId, content, { source, signal });
251 }
252 const deliver = host[hostPromptDeliver];
253 if (typeof deliver === 'function')
254 return deliver.call(runtime, parent, childId, content, source, signal, 'queue');
255 const queue = host[hostPromptQueue];
256 if (typeof queue !== 'function')
257 return unsupported('missing host FIFO delivery');
258 return queue.call(runtime, parent, childId, content, source, signal);
259 }
260 /** Coordination joins the nearest step, including waking an idle/cold child. */
261 export async function steerMemberPrompt(runtime, parent, childId, content, signal, live) {
262 const host = boundary(runtime);
263 const source = agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(live ?? parent));
264 const deliver = host[hostPromptDeliver];
265 if (typeof deliver === 'function')
266 return deliver.call(runtime, parent, childId, content, source, signal, 'steer');
267 if (typeof host.sendMessage === 'function')
268 return host.sendMessage.call(runtime, parent, childId, content, { signal });
269 if (typeof host.followup === 'function') {
270 if (live === undefined)
271 return queueMemberPrompt(runtime, parent, childId, content, signal);
272 if (live.id !== childId || live.session.header.parentSession !== parent.id)
273 throw new Error('invalid member steering authority');
274 signal.throwIfAborted();
275 const message = createUserMessage({ content, source });
276 live.steer(message);
277 return message.id;
278 }
279 return unsupported('missing step-boundary message delivery');
280 }
281 /** Guard all resumable delivery paths, preserving the native service receiver. */
282 export function guardSubagentDelivery(ctx, isRetired) {
283 const runtime = ctx.subagents;
284 const host = boundary(runtime);
285 const legacy = host.followup;
286 const queue = host[hostPromptQueue];
287 const deliver = host[hostPromptDeliver];
288 const send = host.sendMessage;
289 if (typeof legacy !== 'function' && ((typeof queue !== 'function' && typeof deliver !== 'function') || typeof send !== 'function')) {
290 return unsupported('cannot install complete retired-member guard');
291 }
292 ctx.effect(() => {
293 const descriptors = new Map([
294 ['followup', Object.getOwnPropertyDescriptor(host, 'followup')],
295 [hostPromptQueue, Object.getOwnPropertyDescriptor(host, hostPromptQueue)],
296 [hostPromptDeliver, Object.getOwnPropertyDescriptor(host, hostPromptDeliver)],
297 ['sendMessage', Object.getOwnPropertyDescriptor(host, 'sendMessage')],
298 ]);
299 let active = true;
300 const check = async (sender, targetId) => {
301 if (active && await isRetired(sender, targetId)) {
302 throw new SubagentError(`AgentTeams member "${targetId}" was retired and cannot be resumed`, 'NOT_RESUMABLE');
303 }
304 };
305 const guardedLegacy = async (parent, childId, content, options) => {
306 await check(parent, childId);
307 return legacy.call(runtime, parent, childId, content, options);
308 };
309 const guardedQueue = async (parent, childId, content, source, signal) => {
310 await check(parent, childId);
311 return queue.call(runtime, parent, childId, content, source, signal);
312 };
313 const guardedSend = async (sender, targetId, content, options) => {
314 await check(sender, targetId);
315 return send.call(runtime, sender, targetId, content, options);
316 };
317 const guardedDeliver = async (parent, childId, content, source, signal, delivery) => {
318 await check(parent, childId);
319 return deliver.call(runtime, parent, childId, content, source, signal, delivery);
320 };
321 if (typeof legacy === 'function')
322 host.followup = guardedLegacy;
323 if (typeof queue === 'function')
324 host[hostPromptQueue] = guardedQueue;
325 if (typeof deliver === 'function')
326 host[hostPromptDeliver] = guardedDeliver;
327 if (typeof send === 'function')
328 host.sendMessage = guardedSend;
329 // Cordis wraps method reads in fresh Proxies. Compare the actual own
330 // descriptor to restore only our contribution, including prototype methods.
331 const restore = (key, installed) => {
332 if (Object.getOwnPropertyDescriptor(host, key)?.value !== installed)
333 return;
334 const original = descriptors.get(key);
335 if (original === undefined)
336 Reflect.deleteProperty(host, key);
337 else
338 Object.defineProperty(host, key, original);
339 };
340 return () => {
341 active = false;
342 if (typeof legacy === 'function')
343 restore('followup', guardedLegacy);
344 if (typeof queue === 'function')
345 restore(hostPromptQueue, guardedQueue);
346 if (typeof deliver === 'function')
347 restore(hostPromptDeliver, guardedDeliver);
348 if (typeof send === 'function')
349 restore('sendMessage', guardedSend);
350 };
351 }, 'agent-teams: retired member guard');
352 }
353 /**
354 * Names the host's `tools.restrict()` would admit for this agent's layer
355 * chain, or undefined when the host does not expose its registry view.
356 * restrict() rejects unknown names with a hard error, so the spawn path must
357 * check entries against this view before forwarding them. Source:
358 * dsh-tools view()/restrict() in 0.1.5-rc.1; older Harness generations lack
359 * the surface and keep the verbatim list.
360 */
361 export function restrictableToolNames(agent) {
362 const tools = agent?.ctx?.tools;
363 if (typeof tools?.view !== 'function')
364 return undefined;
365 try {
366 const names = tools.view.call(tools, agent.ctx)?.restrictableNames;
367 return names instanceof Set ? names : undefined;
368 }
369 catch {
370 return undefined;
371 }
372 }
373 /**
374 * Member `toolFilter` for one spawn. Captain-only names are registered by
375 * this plugin itself and always resolvable; the depth-related entries name
376 * HOST tools and are only known under some compositions, so they must be
377 * resolved against the running host's registry: the delegation tool name is
378 * host configuration (dsh-tool-subagent `toolName`, default `subagent`,
379 * renamed per composition, e.g. `subagent_fork` in web-style profiles), and
380 * forwarding a name the host dropped aborts every member spawn (#163, #164).
381 * Depth enforcement itself does not depend on these names —
382 * installMemberDelegationGuard bounds descendant creation by parent chain.
383 *
384 * This is the legacy filter of a member without a configured tool policy; a
385 * selected policy resolves through `resolveMemberToolFilter` instead (#59).
386 */
387 export function memberToolFilter(maxDepth, knownTools) {
388 return resolveMemberToolFilter(undefined, { maxDepth, knownTools });
389 }
390 /**
391 * Names a `tools.restrict()` rejection reported as unknown, or an empty list
392 * for every other failure. The host names the offenders verbatim
393 * (`tools.restrict() names unknown global tool "x"; known global tools: …`);
394 * only that report may relax a filter (#164, #166).
395 */
396 function unknownToolNames(error) {
397 const message = error instanceof Error ? error.message : String(error);
398 if (!message.includes('unknown global tool'))
399 return [];
400 return [...message.matchAll(/"([^"]+)"/g)].map(match => match[1]);
401 }
402 /**
403 * Start one member, dropping only the built-in filter names the host reports
404 * as unknown and retrying.
405 *
406 * Resolving the filter against the registry view ({@link memberToolFilter})
407 * only covers hosts that expose one. A rejected filter still leaves the member
408 * without a session for the lifetime of the team, so the start must survive the
409 * cases that resolution cannot see — no registry view, a name that is known but
410 * not restrictable, a composition that mounted differently than expected. The
411 * host names the offenders in its rejection, so the relaxable ones are removed
412 * and the start retried.
413 *
414 * Only `relaxableDeny` names may be dropped, and only from `deny`. The default
415 * is exactly the built-in captain-only and depth entries (#163/#164); a name an
416 * owner-declared tool policy contributed is never removed, because silently
417 * spawning a member with a different filter than the owner declared is contract
418 * drift, not recovery. Dropping a denied name the host does not register
419 * changes nothing; dropping an allowed name would loosen the policy, so `allow`
420 * is never relaxed and the four required coordination tools can never be
421 * removed.
422 * @param start - performs one start attempt for the given `toolFilter`.
423 * @param filter - the filter to attempt first.
424 * @param relaxableDeny - built-in deny names the retry may drop.
425 * @returns the started member.
426 */
427 export async function startMemberWithLenientFilter(start, filter, relaxableDeny = BUILTIN_DENY_TOOLS) {
428 const current = {
429 ...filter.allow === undefined ? {} : { allow: [...filter.allow] },
430 deny: [...filter.deny],
431 };
432 for (;;) {
433 try {
434 return await start(current);
435 }
436 catch (error) {
437 const unknown = unknownToolNames(error);
438 if (unknown.length === 0)
439 throw error;
440 const droppable = unknown.filter(name => relaxableDeny.includes(name) && current.deny.includes(name));
441 if (droppable.length === 0)
442 throw error;
443 current.deny = current.deny.filter(name => !droppable.includes(name));
444 }
445 }
446 }
447 /** Targeted recursive cancellation renamed with the unified activation manager. */
448 export async function drainMemberChildren(runtime, parent, ids) {
449 const host = runtime;
450 const drain = host.drainChildren ?? host.drainContinuableChildren;
451 if (typeof drain !== 'function')
452 return unsupported('missing targeted child drain');
453 await drain.call(runtime, parent, ids);
454 }
455
455 lines JAVASCRIPT