dsh-agent-plugins-market 0.11.0 → 0.11.1
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.
- package/lib/packages/market-bundle/src/index.js +1 -1
- package/lib/packages/market-catalog/src/scanning/validate.js +7 -5
- package/lib/packages/market-runtime/src/runtime/agents/agent-role-router.js +96 -21
- package/lib/packages/market-runtime/src/runtime/agents/role-composition.js +352 -0
- package/lib/packages/market-runtime/src/runtime/agents/subagent-seam.js +107 -10
- package/lib/packages/market-runtime/src/runtime/agents/teammate-role-runtime.js +4 -42
- package/lib/packages/market-runtime/src/runtime/host/extension-session-state.js +67 -1
- package/lib/types/packages/market-runtime/src/runtime/agents/agent-role-router.d.ts +14 -20
- package/lib/types/packages/market-runtime/src/runtime/agents/role-composition.d.ts +163 -0
- package/lib/types/packages/market-runtime/src/runtime/agents/subagent-seam.d.ts +117 -15
- package/lib/types/packages/market-runtime/src/runtime/host/extension-session-state.d.ts +27 -0
- package/package.json +3 -4
- package/packages/market-catalog/README.md +9 -0
- package/packages/market-catalog/schemas/1.0.0/mcp.schema.json +120 -0
- package/packages/market-catalog/schemas/1.0.0/plugin.schema.json +65 -0
- package/packages/market-catalog/schemas/1.1.0/mcp.schema.json +120 -0
- package/packages/market-catalog/schemas/1.1.0/plugin.schema.json +65 -0
- package/packages/market-catalog/schemas/README.md +79 -0
- package/packages/market-catalog/schemas/agent-plugins/spec.md +62 -0
- package/packages/market-catalog/schemas/claude-code/marketplace.schema.json +143 -0
- package/packages/market-catalog/schemas/claude-code/plugin.schema.json +105 -0
- package/packages/market-catalog/schemas/claude-code/spec.md +108 -0
- package/packages/market-catalog/schemas/codex/marketplace.schema.json +78 -0
- package/packages/market-catalog/schemas/codex/plugin.schema.json +77 -0
- package/packages/market-catalog/schemas/codex/spec.md +91 -0
- package/packages/market-catalog/schemas/com.deepseek.harness/namespace.schema.json +42 -0
- package/packages/market-catalog/schemas/com.deepseek.harness/spec.md +52 -0
- package/packages/market-catalog/schemas/cursor/marketplace.schema.json +82 -0
- package/packages/market-catalog/schemas/cursor/plugin.schema.json +58 -0
- package/packages/market-catalog/schemas/cursor/spec.md +92 -0
- package/packages/market-catalog/schemas/github-copilot/marketplace.schema.json +107 -0
- package/packages/market-catalog/schemas/github-copilot/plugin.schema.json +89 -0
- package/packages/market-catalog/schemas/github-copilot/spec.md +105 -0
- package/packages/market-catalog/schemas/kimi/marketplace.schema.json +38 -0
- package/packages/market-catalog/schemas/kimi/plugin.schema.json +84 -0
- package/packages/market-catalog/schemas/kimi/spec.md +94 -0
- package/packages/market-catalog/schemas/qoder/marketplace.schema.json +115 -0
- package/packages/market-catalog/schemas/qoder/plugin.schema.json +127 -0
- package/packages/market-catalog/schemas/qoder/spec.md +111 -0
- package/packages/market-catalog/schemas/skill-collection/spec.md +37 -0
- package/packages/market-catalog/schemas/universal/marketplace.schema.json +98 -0
- package/packages/market-catalog/schemas/universal/plugin.schema.json +49 -0
- package/packages/market-catalog/schemas/universal/spec.md +53 -0
- package/packages/market-catalog/schemas/zcode/marketplace.schema.json +161 -0
- package/packages/market-catalog/schemas/zcode/plugin.schema.json +89 -0
- package/packages/market-catalog/schemas/zcode/spec.md +102 -0
|
@@ -307,7 +307,7 @@ export async function apply(ctx, config = {
|
|
|
307
307
|
// Both entry points read the same live user/project role set. Team owns the
|
|
308
308
|
// enhanced entry's member identities and all subsequent collaboration.
|
|
309
309
|
const listRoles = sessionExtensions.roles;
|
|
310
|
-
ctx.inject(['tools', 'llm', 'subagents', 'agents'], hostCtx => {
|
|
310
|
+
ctx.inject(['tools', 'llm', 'subagents', 'agents', 'systemPrompt'], hostCtx => {
|
|
311
311
|
hostCtx.effect(() => mountUnlessAgentTeams(hostCtx, () => mountAgentRoleTool(hostCtx, listRoles)), 'dsh-agent-plugins-market: agent role routing');
|
|
312
312
|
});
|
|
313
313
|
// Coordination also serves native teammates and does not depend on role discovery.
|
|
@@ -43,15 +43,17 @@ function schemasDirectory() {
|
|
|
43
43
|
const name = JSON.parse(readFileSync(manifest, 'utf8')).name;
|
|
44
44
|
// The workspace package and the packed artifact expose the library at the
|
|
45
45
|
// same two relative spots: beside the catalog package, or under the
|
|
46
|
-
// packages/ path preserved by the npm files entry
|
|
46
|
+
// packages/ path preserved by the npm "files" entry
|
|
47
|
+
// "packages/market-catalog/schemas" in package.json. A tarball without that
|
|
48
|
+
// entry throws ENOENT on the first validation, so
|
|
49
|
+
// packages/market-bundle/test/repo/published-schemas.test.ts guards it.
|
|
47
50
|
if (name === '@dsh-market/catalog')
|
|
48
51
|
return join(directory, 'schemas');
|
|
49
52
|
if (name === 'dsh-agent-plugins-market')
|
|
50
53
|
return join(directory, 'packages/market-catalog/schemas');
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
directory = parentDir;
|
|
54
|
+
// One level per pass: a walk that skips a level could step over the package
|
|
55
|
+
// root the next manifest would have named, which is the only path this
|
|
56
|
+
// resolver can get wrong without also failing loudly.
|
|
55
57
|
const parent = dirname(directory);
|
|
56
58
|
if (parent === directory)
|
|
57
59
|
throw new Error('dsh-agent-plugins-market package root is unavailable');
|
|
@@ -6,7 +6,8 @@ import { isAbsentPath } from '../../application/fs-probe.js';
|
|
|
6
6
|
import { namedAgentRoles } from './agent-role-names.js';
|
|
7
7
|
import { expandPluginPaths } from '../../../../market-catalog/src/index.js';
|
|
8
8
|
import { parseAgentRole } from '../../application/agent-roles.js';
|
|
9
|
-
import { startContinuableChild } from './subagent-seam.js';
|
|
9
|
+
import { roleInstructionChannel, startContinuableChild, startOneShotChild } from './subagent-seam.js';
|
|
10
|
+
import { mintRoleChildId, requireReservedChild, roleInstructionsError, RoleComposition } from './role-composition.js';
|
|
10
11
|
export { parseAgentRole };
|
|
11
12
|
export const AGENT_ROLE_TOOL_NAME = 'subagent_role';
|
|
12
13
|
/**
|
|
@@ -192,6 +193,21 @@ export async function requireCurrentRole(listRoles, resolved, parent) {
|
|
|
192
193
|
if ((current.disabled || policy.disabled) && current.selectionEnabled !== true)
|
|
193
194
|
throw new Error('agent "' + resolved.callName + '" is disabled');
|
|
194
195
|
}
|
|
196
|
+
/**
|
|
197
|
+
* The composition the section channel needs, or a named refusal.
|
|
198
|
+
*
|
|
199
|
+
* The type requires the field, but the mount reaches the host through a cast and
|
|
200
|
+
* this executor is exported, so the runtime keeps its own guard: a missing
|
|
201
|
+
* composition must refuse rather than silently skip the child's instructions.
|
|
202
|
+
* @param host - the exact live seams this call owns.
|
|
203
|
+
* @param role - role name used in the refusal.
|
|
204
|
+
* @returns the composition to install and reserve with.
|
|
205
|
+
*/
|
|
206
|
+
function requireRoleComposition(host, role) {
|
|
207
|
+
if (host.roleComposition === undefined)
|
|
208
|
+
throw roleInstructionsError(role, new Error('the role composition is not mounted'));
|
|
209
|
+
return host.roleComposition;
|
|
210
|
+
}
|
|
195
211
|
/**
|
|
196
212
|
* Run one role child through the requested channel.
|
|
197
213
|
* @param host - the exact live seams this executor owns: tools, llm and subagents.
|
|
@@ -210,30 +226,69 @@ export async function executeAgentRole(host, listRoles, agentName, prompt, paren
|
|
|
210
226
|
// before either channel creates a child.
|
|
211
227
|
await requireCurrentRole(listRoles, entry, parent);
|
|
212
228
|
signal.throwIfAborted();
|
|
229
|
+
// The seam decides the instruction mechanism from the live member spelling, so
|
|
230
|
+
// the request shape and the composition stay one decision.
|
|
231
|
+
const channel = roleInstructionChannel(host.subagents);
|
|
232
|
+
const childId = mintRoleChildId();
|
|
233
|
+
const sectionChannel = channel === 'prompt-section';
|
|
234
|
+
// A section channel composes the child itself. An absent composition refuses
|
|
235
|
+
// here, before the start call, instead of skipping the instructions silently.
|
|
236
|
+
const composition = sectionChannel ? requireRoleComposition(host, agentName) : undefined;
|
|
237
|
+
if (composition !== undefined) {
|
|
238
|
+
composition.requirePersistence(agentName);
|
|
239
|
+
}
|
|
213
240
|
const request = {
|
|
214
241
|
prompt: [{ type: 'text', text: prompt }],
|
|
215
242
|
parent,
|
|
216
243
|
maxDepth: MAX_AGENT_ROLE_DEPTH,
|
|
217
|
-
persona: policy.content,
|
|
244
|
+
...(sectionChannel ? {} : { persona: policy.content }),
|
|
218
245
|
...(agentOptions === undefined ? {} : { agentOptions })
|
|
219
246
|
};
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
const
|
|
247
|
+
composition?.reserve(childId, { roleId: entry.name, role: agentName, persona: policy.content });
|
|
248
|
+
// The composition is keyed by the reserved id, so the host must publish that
|
|
249
|
+
// id. The older line's one-shot start allocates its own identity, which is why
|
|
250
|
+
// the guard is scoped to the channel that composes.
|
|
251
|
+
const requirePublished = (returned) => requireReservedChild(agentName, childId, returned);
|
|
225
252
|
try {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
253
|
+
if (mode === 'continuable') {
|
|
254
|
+
const started = await startContinuableChild(host.subagents, { provider: 'spawn', label: agentName, request, signal, childId });
|
|
255
|
+
if (composition !== undefined) {
|
|
256
|
+
try {
|
|
257
|
+
requirePublished(started.childId);
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
// The child exists, but it is not the one this call reserved, so it
|
|
261
|
+
// carries no role instructions. The foreground channel releases its run
|
|
262
|
+
// in the finally below; this channel has no such handle, so it releases
|
|
263
|
+
// the published child through the seam's drain member instead of
|
|
264
|
+
// leaving an uninstructed child resident.
|
|
265
|
+
await composition.abandon(started.childId);
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return { kind: 'continuable', subagentId: started.childId };
|
|
270
|
+
}
|
|
271
|
+
const run = await startOneShotChild(host.subagents, { provider: 'spawn', label: agentName, request, signal, childId });
|
|
272
|
+
try {
|
|
273
|
+
if (composition !== undefined)
|
|
274
|
+
requirePublished(run.runId);
|
|
275
|
+
const result = await run.result;
|
|
276
|
+
if (result.stopReason !== 'completed') {
|
|
277
|
+
const detail = result.diagnostic === undefined ? '' : `: ${result.diagnostic}`;
|
|
278
|
+
throw new Error(`agent "${agentName}" did not complete (${result.stopReason})${detail}`);
|
|
279
|
+
}
|
|
280
|
+
// The registry performs the authoritative lossless snapshot of the child's
|
|
281
|
+
// output blocks on the way out, exactly as the host's own delegation tool does.
|
|
282
|
+
return { kind: 'foreground', runId: run.runId, output: result.output };
|
|
283
|
+
}
|
|
284
|
+
finally {
|
|
285
|
+
await run.dispose();
|
|
230
286
|
}
|
|
231
|
-
// The registry performs the authoritative lossless snapshot of the child's
|
|
232
|
-
// output blocks on the way out, exactly as the host's own delegation tool does.
|
|
233
|
-
return { kind: 'foreground', runId: run.id, output: result.output };
|
|
234
287
|
}
|
|
235
|
-
|
|
236
|
-
|
|
288
|
+
catch (error) {
|
|
289
|
+
// A call that fails before or after the start leaves no reservation behind.
|
|
290
|
+
composition?.release(childId);
|
|
291
|
+
throw error;
|
|
237
292
|
}
|
|
238
293
|
}
|
|
239
294
|
/** Normalize one observation; a bare list means the read completed. */
|
|
@@ -241,7 +296,23 @@ export function roleSnapshot(observation) {
|
|
|
241
296
|
return Array.isArray(observation) ? { entries: observation, complete: true } : observation;
|
|
242
297
|
}
|
|
243
298
|
export function mountAgentRoleTool(ctx, listRoles) {
|
|
244
|
-
const
|
|
299
|
+
const surface = ctx;
|
|
300
|
+
// The role-instruction composition is this mount's own effect: one reservation
|
|
301
|
+
// map and one `agent/created` subscription per mounted role tool. Reads stay
|
|
302
|
+
// live, because the host services may not exist yet when the tool mounts.
|
|
303
|
+
const composition = new RoleComposition(ctx);
|
|
304
|
+
const host = {
|
|
305
|
+
get tools() {
|
|
306
|
+
return surface.tools;
|
|
307
|
+
},
|
|
308
|
+
get llm() {
|
|
309
|
+
return surface.llm;
|
|
310
|
+
},
|
|
311
|
+
get subagents() {
|
|
312
|
+
return surface.subagents;
|
|
313
|
+
},
|
|
314
|
+
roleComposition: composition
|
|
315
|
+
};
|
|
245
316
|
const entries = async (parent) => roleSnapshot(await listRoles(parent)).entries;
|
|
246
317
|
const tool = defineTool({
|
|
247
318
|
name: AGENT_ROLE_TOOL_NAME,
|
|
@@ -315,9 +386,11 @@ export function mountAgentRoleTool(ctx, listRoles) {
|
|
|
315
386
|
}, mode, exec.signal, message => ctx.logger?.warn(message));
|
|
316
387
|
}
|
|
317
388
|
});
|
|
318
|
-
const
|
|
389
|
+
const disposeComposition = composition.install();
|
|
390
|
+
let disposeTool;
|
|
319
391
|
let disposeCatalog;
|
|
320
392
|
try {
|
|
393
|
+
disposeTool = host.tools.register(tool);
|
|
321
394
|
disposeCatalog = mountSubagentCatalog(ctx, tool, async (agent, signal) => {
|
|
322
395
|
const observation = roleSnapshot(await listRoles(agent));
|
|
323
396
|
return {
|
|
@@ -327,11 +400,13 @@ export function mountAgentRoleTool(ctx, listRoles) {
|
|
|
327
400
|
});
|
|
328
401
|
}
|
|
329
402
|
catch (error) {
|
|
330
|
-
disposeTool();
|
|
403
|
+
disposeTool?.();
|
|
404
|
+
disposeComposition();
|
|
331
405
|
throw error;
|
|
332
406
|
}
|
|
333
407
|
return () => {
|
|
334
|
-
disposeCatalog();
|
|
335
|
-
disposeTool();
|
|
408
|
+
disposeCatalog?.();
|
|
409
|
+
disposeTool?.();
|
|
410
|
+
disposeComposition();
|
|
336
411
|
};
|
|
337
412
|
}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One role child's instructions, composed before its first request.
|
|
3
|
+
*
|
|
4
|
+
* The 0.2.1 host line removed the `persona` field from the subagent start
|
|
5
|
+
* request, so the plugin installs the role card body as the child's own
|
|
6
|
+
* `deployment:persona-prefix` prompt section instead. The composition runs on
|
|
7
|
+
* `agent/created`, before the host delivers the first prompt, and it fails
|
|
8
|
+
* closed: a role child never runs without its instructions.
|
|
9
|
+
*
|
|
10
|
+
* The composed instructions are durable. Creation records one plugin-owned
|
|
11
|
+
* context message carrying the role identity and the card body, and a later
|
|
12
|
+
* resume rebuilds the section from that record instead of from an edited card.
|
|
13
|
+
*
|
|
14
|
+
* @module runtime/agents/role-composition
|
|
15
|
+
*/
|
|
16
|
+
import { randomUUID } from 'node:crypto';
|
|
17
|
+
import { assembleContextFor } from '@deepseek-ai/dsh-agent';
|
|
18
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
19
|
+
import { SessionId } from '@deepseek-ai/dsh-session';
|
|
20
|
+
import { PERSONA_PREFIX_SECTION } from '@deepseek-ai/dsh-system-prompt';
|
|
21
|
+
import { z } from 'zod';
|
|
22
|
+
import { settlesWithin } from '../../../../market-catalog/src/index.js';
|
|
23
|
+
import { optionalService } from '../core/context.js';
|
|
24
|
+
import { drainContinuableChildIds } from './subagent-seam.js';
|
|
25
|
+
/** Plugin-owned message source that makes one role child's instructions replayable. */
|
|
26
|
+
export const ROLE_CHILD_SOURCE = 'agent-role-child-binding';
|
|
27
|
+
/**
|
|
28
|
+
* How long a refusal waits for the child it releases.
|
|
29
|
+
*
|
|
30
|
+
* The release is a courtesy on a path that has already failed, so it must never
|
|
31
|
+
* decide when the caller learns about the failure. A host drain that has not
|
|
32
|
+
* released one child within this bound is treated as the host's own parent
|
|
33
|
+
* teardown problem, and the caller gets its refusal immediately after.
|
|
34
|
+
*/
|
|
35
|
+
export const ROLE_ABANDON_DEADLINE_MS = 5_000;
|
|
36
|
+
const bindingSchema = z.object({ version: z.literal(1), roleId: z.string().min(1), persona: z.string() }).strict();
|
|
37
|
+
const durableBindingSchema = bindingSchema.extend({ childId: z.string().min(1) }).strict();
|
|
38
|
+
/** Add the role card body as the child's own persona section. */
|
|
39
|
+
export function installPersonaSection(prompt, persona) {
|
|
40
|
+
return prompt.section({ name: PERSONA_PREFIX_SECTION, order: prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX'), text: persona, interpolate: false });
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Record the role route on the child's own `AgentOptions`.
|
|
44
|
+
*
|
|
45
|
+
* The host Team creation request carries no per-member route, so the child
|
|
46
|
+
* Agent starts with the Lead's route. Host surfaces read this object rather
|
|
47
|
+
* than the model selection: the Team roster shows it, the image-input gate
|
|
48
|
+
* checks it, and the member's own delegation inherits it. A host that freezes
|
|
49
|
+
* the object is reported and keeps the model selection, which still routes
|
|
50
|
+
* every request.
|
|
51
|
+
* @param agent - the member's live Agent.
|
|
52
|
+
* @param route - the validated route from the creation snapshot.
|
|
53
|
+
* @param diagnose - diagnostic sink for a host that refuses the write.
|
|
54
|
+
* @returns the disposer that restores the inherited values.
|
|
55
|
+
*/
|
|
56
|
+
export function applyRoleRoute(agent, route, diagnose) {
|
|
57
|
+
const options = agent.options;
|
|
58
|
+
const inherited = { provider: options.provider, model: options.model, reasoningEffort: options.reasoningEffort };
|
|
59
|
+
const write = (next) => {
|
|
60
|
+
try {
|
|
61
|
+
options.provider = next.provider;
|
|
62
|
+
options.model = next.model;
|
|
63
|
+
if (next.reasoningEffort === undefined)
|
|
64
|
+
delete options.reasoningEffort;
|
|
65
|
+
else
|
|
66
|
+
options.reasoningEffort = next.reasoningEffort;
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
if (!write(route)) {
|
|
74
|
+
diagnose(`role teammate ${agent.id}: AgentOptions is not writable, so the host reports the inherited route`);
|
|
75
|
+
return () => { };
|
|
76
|
+
}
|
|
77
|
+
return () => {
|
|
78
|
+
write(inherited);
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Mint the durable identity one role child runs under. */
|
|
82
|
+
export function mintRoleChildId() {
|
|
83
|
+
return SessionId(randomUUID());
|
|
84
|
+
}
|
|
85
|
+
/** The model-facing statement that makes the durable binding readable. */
|
|
86
|
+
function roleChildNotice(role) {
|
|
87
|
+
return [`You are the role child "${role}".`, 'The role instructions from the delegation snapshot are applied to your system prompt and restored on resume.'].join('\n');
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* One named refusal for a role child that could not receive its instructions.
|
|
91
|
+
* @param role - role name the refusal names.
|
|
92
|
+
* @param cause - the failure the refusal wraps, when there is one.
|
|
93
|
+
* @returns the error to throw.
|
|
94
|
+
*/
|
|
95
|
+
export function roleInstructionsError(role, cause) {
|
|
96
|
+
const detail = cause === undefined ? '' : `: ${describe(cause)}`;
|
|
97
|
+
return new Error(`agent "${role}" cannot run without its role instructions${detail}`, cause === undefined ? undefined : { cause });
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Prove the host published the child identity this call reserved.
|
|
101
|
+
*
|
|
102
|
+
* The durable binding and the in-flight reservation are both keyed by the
|
|
103
|
+
* reserved id. A host that accepts the spec and publishes another identity would
|
|
104
|
+
* leave the child uncomposed while the call reported success, so a mismatch is
|
|
105
|
+
* a named refusal instead.
|
|
106
|
+
* @param role - role name the refusal names.
|
|
107
|
+
* @param reserved - the identity this call reserved.
|
|
108
|
+
* @param returned - the identity the host published.
|
|
109
|
+
* @throws when the two differ.
|
|
110
|
+
*/
|
|
111
|
+
export function requireReservedChild(role, reserved, returned) {
|
|
112
|
+
if (reserved === returned)
|
|
113
|
+
return;
|
|
114
|
+
throw roleInstructionsError(role, new Error(`the host published child "${returned}" for the reserved child "${reserved}"`));
|
|
115
|
+
}
|
|
116
|
+
/** Render one thrown value without trusting its stringification. */
|
|
117
|
+
function describe(cause) {
|
|
118
|
+
if (cause instanceof Error)
|
|
119
|
+
return cause.message;
|
|
120
|
+
return typeof cause === 'string' ? cause : 'the host rejected the composition';
|
|
121
|
+
}
|
|
122
|
+
/** Read the plugin-owned binding records out of one child session's own events. */
|
|
123
|
+
function bindingRecords(events) {
|
|
124
|
+
const messages = events.flatMap(event => (event.type === 'user/message' ? [event.data] : event.type === 'agent/inbox/spliced' ? event.data.inserted : []));
|
|
125
|
+
// Keyed by message id: one admitted message may be observable twice.
|
|
126
|
+
const sources = new Map(messages.filter(message => message.source.kind === ROLE_CHILD_SOURCE).map(message => [message.id, message.source]));
|
|
127
|
+
return [...sources.values()].flatMap(source => (source.kind === ROLE_CHILD_SOURCE ? [durableBindingSchema.parse(source.binding)] : []));
|
|
128
|
+
}
|
|
129
|
+
/** Compose role children from the durable binding or the in-flight reservation. */
|
|
130
|
+
export class RoleComposition {
|
|
131
|
+
ctx;
|
|
132
|
+
pending = new Map();
|
|
133
|
+
compositions = new Map();
|
|
134
|
+
disposal;
|
|
135
|
+
constructor(ctx) {
|
|
136
|
+
this.ctx = ctx;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Subscribe to child creation; the returned disposer releases every composition.
|
|
140
|
+
* @returns the mount disposer.
|
|
141
|
+
*/
|
|
142
|
+
install() {
|
|
143
|
+
if (this.disposal !== undefined)
|
|
144
|
+
return this.disposal;
|
|
145
|
+
const offCreated = this.ctx.on('agent/created', async ({ agent, signal }) => {
|
|
146
|
+
await this.compose(agent, signal);
|
|
147
|
+
});
|
|
148
|
+
const offDisposed = this.ctx.on('agent/disposed', ({ agent }) => {
|
|
149
|
+
this.compositions.get(agent)?.();
|
|
150
|
+
this.compositions.delete(agent);
|
|
151
|
+
});
|
|
152
|
+
let active = true;
|
|
153
|
+
this.disposal = () => {
|
|
154
|
+
if (!active)
|
|
155
|
+
return;
|
|
156
|
+
active = false;
|
|
157
|
+
offCreated();
|
|
158
|
+
offDisposed();
|
|
159
|
+
for (const off of this.compositions.values())
|
|
160
|
+
off();
|
|
161
|
+
this.compositions.clear();
|
|
162
|
+
this.pending.clear();
|
|
163
|
+
};
|
|
164
|
+
return this.disposal;
|
|
165
|
+
}
|
|
166
|
+
requirePersistence(role) {
|
|
167
|
+
if (optionalService(this.ctx, 'sessionQuery') === undefined)
|
|
168
|
+
throw roleInstructionsError(role, new Error('the session-query service is unavailable'));
|
|
169
|
+
if (optionalService(this.ctx, 'sessions') === undefined)
|
|
170
|
+
throw roleInstructionsError(role, new Error('the session service is unavailable'));
|
|
171
|
+
}
|
|
172
|
+
reserve(childId, input) {
|
|
173
|
+
this.pending.set(childId, input);
|
|
174
|
+
}
|
|
175
|
+
release(childId) {
|
|
176
|
+
this.pending.delete(childId);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Release one child the host published under an identity this plugin could not compose.
|
|
180
|
+
*
|
|
181
|
+
* A host that ignores the reserved id leaves a live child with no role
|
|
182
|
+
* instructions. The caller raises the refusal; this method releases the child
|
|
183
|
+
* through the seam's drain member, using the child's own recorded parent, so an
|
|
184
|
+
* uncomposed child does not stay resident until the parent tears down. A host
|
|
185
|
+
* without a drain member, or a child with no live parent, is reported and then
|
|
186
|
+
* left to the host's own parent teardown, which still owns it.
|
|
187
|
+
* @param childId - the identity the host published.
|
|
188
|
+
*/
|
|
189
|
+
async abandon(childId) {
|
|
190
|
+
try {
|
|
191
|
+
const seam = optionalService(this.ctx, 'subagents');
|
|
192
|
+
const agents = optionalService(this.ctx, 'agents');
|
|
193
|
+
const child = agents?.get(SessionId(childId));
|
|
194
|
+
const parentId = child?.session.header.parentSession;
|
|
195
|
+
const parent = parentId === undefined ? undefined : agents?.get(parentId);
|
|
196
|
+
if (seam === undefined || parent === undefined) {
|
|
197
|
+
this.ctx.logger?.warn(`role child "${childId}" carries no role instructions and has no live parent to release it; the host owns its teardown`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
// Bounded, because this runs while a refusal is on its way out: a host drain
|
|
201
|
+
// that stalls must not hold the error the caller needs. The rejection is captured
|
|
202
|
+
// rather than left to the bounded wait, which counts a rejection as settled: a
|
|
203
|
+
// host that refuses the release, or exposes no drain member, must still be
|
|
204
|
+
// reported instead of passing as a release.
|
|
205
|
+
let rejection;
|
|
206
|
+
const release = drainContinuableChildIds(seam, parent, [SessionId(childId)]).catch((error) => {
|
|
207
|
+
rejection = error;
|
|
208
|
+
});
|
|
209
|
+
if (!(await settlesWithin(release, ROLE_ABANDON_DEADLINE_MS))) {
|
|
210
|
+
this.ctx.logger?.warn(`role child "${childId}" carries no role instructions and the host did not release within ${ROLE_ABANDON_DEADLINE_MS}ms; the host owns its teardown`);
|
|
211
|
+
}
|
|
212
|
+
else if (rejection !== undefined) {
|
|
213
|
+
this.ctx.logger?.warn(`role child "${childId}" carries no role instructions and could not be released: ${describe(rejection)}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
// The refusal is already on its way out. A release failure must not replace
|
|
218
|
+
// it, and the child still belongs to the host parent's teardown.
|
|
219
|
+
this.ctx.logger?.warn(`role child "${childId}" carries no role instructions and could not be released: ${describe(error)}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
async compose(agent, signal) {
|
|
223
|
+
if (this.compositions.has(agent))
|
|
224
|
+
return;
|
|
225
|
+
const pending = this.pending.get(agent.id);
|
|
226
|
+
try {
|
|
227
|
+
const query = optionalService(this.ctx, 'sessionQuery');
|
|
228
|
+
if (query === undefined) {
|
|
229
|
+
if (pending === undefined)
|
|
230
|
+
return;
|
|
231
|
+
throw roleInstructionsError(pending.role, new Error('the session-query service is unavailable'));
|
|
232
|
+
}
|
|
233
|
+
const observation = await query.observeSession(agent.id, { projectionMode: 'none', ...(signal === undefined ? {} : { signal }) });
|
|
234
|
+
let records;
|
|
235
|
+
try {
|
|
236
|
+
records = bindingRecords(observation.events.filter(event => event.seq >= observation.inheritedEventCount));
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
observation[Symbol.dispose]();
|
|
240
|
+
}
|
|
241
|
+
if (records.length > 1)
|
|
242
|
+
throw roleInstructionsError(pending?.role ?? String(agent.id), new Error('the child has multiple role bindings'));
|
|
243
|
+
const durable = records[0];
|
|
244
|
+
if (durable !== undefined) {
|
|
245
|
+
if (durable.childId !== agent.id)
|
|
246
|
+
throw roleInstructionsError(durable.roleId, new Error('the role binding belongs to another child'));
|
|
247
|
+
await this.composeSection(agent, durable.roleId, durable.persona);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
// A plain host child that this plugin never created has no binding and no reservation.
|
|
251
|
+
if (pending === undefined)
|
|
252
|
+
return;
|
|
253
|
+
await this.composeFresh(agent, pending);
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
if (pending !== undefined)
|
|
257
|
+
this.pending.delete(agent.id);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/** Compose one child and persist its binding before the host delivers the first prompt. */
|
|
261
|
+
async composeFresh(agent, pending) {
|
|
262
|
+
const binding = { version: 1, childId: agent.id, roleId: pending.roleId, persona: pending.persona };
|
|
263
|
+
let off;
|
|
264
|
+
try {
|
|
265
|
+
off = await this.composeSection(agent, pending.role, pending.persona);
|
|
266
|
+
agent.inject(createUserMessage({
|
|
267
|
+
source: { kind: ROLE_CHILD_SOURCE, form: 'context', binding },
|
|
268
|
+
content: [{ type: 'text', text: roleChildNotice(pending.role) }]
|
|
269
|
+
}));
|
|
270
|
+
const sessions = optionalService(this.ctx, 'sessions');
|
|
271
|
+
if (sessions === undefined)
|
|
272
|
+
throw roleInstructionsError(pending.role, new Error('the session service is unavailable'));
|
|
273
|
+
// The binding survives a restart only when a durability listener commits it.
|
|
274
|
+
if (!(await sessions.flush(agent.session)))
|
|
275
|
+
throw roleInstructionsError(pending.role, new Error('session persistence did not commit the role binding'));
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (off !== undefined) {
|
|
279
|
+
off();
|
|
280
|
+
this.compositions.delete(agent);
|
|
281
|
+
}
|
|
282
|
+
throw error instanceof Error && error.message.startsWith('agent "') ? error : roleInstructionsError(pending.role, error);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Install the section for one child and keep its disposer on the composition map.
|
|
287
|
+
*
|
|
288
|
+
* A child created on the 0.2.0 line carries a descriptor persona the host
|
|
289
|
+
* re-applies into this same layer when it resumes the child on 0.2.1, so the
|
|
290
|
+
* registration collides. Refusing would break exactly the upgrade path this fix
|
|
291
|
+
* targets, so a colliding slot that holds the same instructions counts as
|
|
292
|
+
* already applied: the plugin owns nothing and the child keeps running. A slot
|
|
293
|
+
* that holds different instructions still refuses, because the child would
|
|
294
|
+
* otherwise run under someone else's persona.
|
|
295
|
+
*/
|
|
296
|
+
async composeSection(agent, role, persona) {
|
|
297
|
+
const prompt = optionalService(agent.ctx, 'systemPrompt');
|
|
298
|
+
if (prompt === undefined)
|
|
299
|
+
throw roleInstructionsError(role, new Error('the system-prompt service is unavailable'));
|
|
300
|
+
try {
|
|
301
|
+
const off = installPersonaSection(prompt, persona);
|
|
302
|
+
this.compositions.set(agent, off);
|
|
303
|
+
return off;
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
const applied = await this.appliedPersona(agent);
|
|
307
|
+
if (applied !== undefined && applied.text === persona) {
|
|
308
|
+
// Equal raw text is not enough. The host re-applies a descriptor persona with
|
|
309
|
+
// no interpolate flag, so a brace-bearing card body would be substituted (or
|
|
310
|
+
// fail to render) under the host's copy while this module's own writer keeps it
|
|
311
|
+
// literal. Accept the host's copy only when it means the same thing.
|
|
312
|
+
if (applied.interpolate === false || !applied.text.includes('{{')) {
|
|
313
|
+
this.ctx.logger?.info?.(`role child "${agent.id}" already carries its role instructions from the host descriptor; the upgrade path installs nothing`);
|
|
314
|
+
// Nothing is owned, so disposal has nothing to release, and the next
|
|
315
|
+
// creation of this same Agent does not attempt the registration again.
|
|
316
|
+
const off = () => { };
|
|
317
|
+
this.compositions.set(agent, off);
|
|
318
|
+
return off;
|
|
319
|
+
}
|
|
320
|
+
throw roleInstructionsError(role, new Error(`the host already applied this text in "${PERSONA_PREFIX_SECTION}" without preserving its template text, so the role instructions would be substituted or fail to render; a child created on an older host line keeps the persona recorded in its descriptor`));
|
|
321
|
+
}
|
|
322
|
+
if (applied !== undefined) {
|
|
323
|
+
throw roleInstructionsError(role, new Error(`the child already carries different instructions in "${PERSONA_PREFIX_SECTION}"; a child created on an older host line keeps the persona recorded in its descriptor, and this role card no longer matches it`));
|
|
324
|
+
}
|
|
325
|
+
throw roleInstructionsError(role, error);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* The section this child's own scope already renders for the persona slot.
|
|
330
|
+
*
|
|
331
|
+
* The interpolate flag travels with the text because the two are one decision: the
|
|
332
|
+
* same raw text means different instructions depending on whether it is rendered
|
|
333
|
+
* literally.
|
|
334
|
+
* @param agent - the live child whose own scope is read.
|
|
335
|
+
* @returns the occupying section, or undefined when the slot is free or unreadable.
|
|
336
|
+
*/
|
|
337
|
+
async appliedPersona(agent) {
|
|
338
|
+
const prompt = optionalService(agent.ctx, 'systemPrompt');
|
|
339
|
+
if (prompt === undefined)
|
|
340
|
+
return undefined;
|
|
341
|
+
try {
|
|
342
|
+
const assembly = await prompt.assemble(assembleContextFor(agent));
|
|
343
|
+
const section = assembly.sections.find(candidate => candidate.name === PERSONA_PREFIX_SECTION);
|
|
344
|
+
return section === undefined ? undefined : { text: section.text, interpolate: section.interpolate };
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
// An unreadable assembly is not evidence that the slot is free; treat it as
|
|
348
|
+
// unknown so the caller reports the original registration failure.
|
|
349
|
+
return undefined;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|