@starsharryzhu/complete-subagent 0.1.1 → 0.2.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.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * `switch_child_model`: a parent moves one of its subagents to another listed
3
+ * model, and the subagent continues its own conversation there, the way a user
4
+ * switches models in a chat. Meant first for a child stopped because its model
5
+ * is out of quota (see `outages.ts`), it also serves a child that does poorly.
6
+ *
7
+ * The host fixes a step's model when the step starts, so the choice is recorded
8
+ * for the child's next step: at once for a live child, or as the child comes
9
+ * back to life (`agent/created`) for one the host has put away. A message from
10
+ * the parent then wakes the child, which keeps its session, binding, and grants.
11
+ * @module complete-subagent/host/switch-tool
12
+ */
13
+ import { defineTool } from '@deepseek-ai/dsh-tools';
14
+ import { modelKey } from "../shared/settings.js";
15
+ import { chooseRoute } from "./models.js";
16
+ import { SWITCH_TOOL } from "./types.js";
17
+ /**
18
+ * Record a route for an agent's next step, on any supported host.
19
+ * @param agent - a live agent.
20
+ * @param route - provider, model, and the effort when one is chosen.
21
+ * @param sessionController - the session controller, for 0.2.1-rc.5.
22
+ * @throws when the host offers neither way.
23
+ */
24
+ export function selectRoute(agent, route, sessionController) {
25
+ const selection = { provider: route.provider, model: route.model, ...route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort } };
26
+ if (typeof agent.model?.select === 'function') {
27
+ agent.model.select(selection);
28
+ return;
29
+ }
30
+ const select = sessionController?.agents?.selectForNextRequest;
31
+ if (typeof select !== 'function')
32
+ throw new Error('This host cannot change a subagent\'s model.');
33
+ select.call(sessionController?.agents, agent, selection);
34
+ }
35
+ /**
36
+ * Build the tool for the current model list, which its `model` parameter names.
37
+ * @param models - the settings' model list.
38
+ * @param deps - shared state and services.
39
+ * @returns a registry-ready definition.
40
+ */
41
+ export function createSwitchTool(models, deps) {
42
+ return defineTool({
43
+ name: SWITCH_TOOL,
44
+ description: 'Move one of your subagents to another model it may run, and have it continue its own conversation there, '
45
+ + 'from where it stopped, with everything it did so far. Use it when your context says a subagent stopped because its model '
46
+ + 'cannot serve it now (out of quota or rate-limited), or when the error it failed with lies with its model or that model\'s service, '
47
+ + 'instead of delegating the task again; or when a subagent plainly does poorly on its model. Pick a model whose notes fit the task; when none does, ask your user first and switch only with their permission. '
48
+ + 'Its result reaches you as usual when it finishes.',
49
+ parameters: {
50
+ agent_id: { type: 'string', required: true, description: 'The subagent id returned when you started it.' },
51
+ model: {
52
+ type: 'string',
53
+ required: true,
54
+ ...models.length === 0 ? {} : { enum: models.map(modelKey) },
55
+ description: 'The new model as "provider/model", one of those the delegation tools list.',
56
+ },
57
+ reasoning_effort: { type: 'string', description: 'The reasoning effort id on the new model, among those it allows; omitted, its default.' },
58
+ message: { type: 'string', description: 'Anything the subagent should know as it continues; it is told about the switch either way.' },
59
+ },
60
+ output: {
61
+ schema: {
62
+ type: 'object',
63
+ additionalProperties: false,
64
+ properties: {
65
+ agent_id: { type: 'string', required: true },
66
+ model: { type: 'string', required: true },
67
+ reasoning_effort: { type: 'string' },
68
+ },
69
+ },
70
+ render: (_args, value) => [{
71
+ type: 'text',
72
+ text: `Moved subagent ${value.agent_id} to ${value.model}${value.reasoning_effort === undefined ? '' : ` (effort ${value.reasoning_effort})`}. `
73
+ + 'It continues its own conversation; its result reaches you when it finishes.',
74
+ }],
75
+ },
76
+ isConcurrencySafe: () => true,
77
+ async execute(raw, exec) {
78
+ const args = raw;
79
+ const parent = exec.agent;
80
+ if (parent === undefined)
81
+ throw new Error(`${SWITCH_TOOL} requires a calling agent`);
82
+ const child = typeof args.agent_id === 'string' ? args.agent_id.trim() : '';
83
+ const binding = deps.store.get(child);
84
+ if (binding?.parent !== parent.id || binding.inherited === true) {
85
+ throw new Error(`"${child}" is not a subagent you started with \`delegate\` or \`delegate_fork\`.`);
86
+ }
87
+ if (deps.outages.refused(child).has(args.model)) {
88
+ throw new Error(`${args.model} already refused this subagent; choose another model, or leave it if none is left.`);
89
+ }
90
+ const route = await chooseRoute({
91
+ parent,
92
+ models,
93
+ request: { model: args.model, reasoning_effort: args.reasoning_effort },
94
+ llm: deps.llm(),
95
+ signal: exec.signal,
96
+ ownModel: false,
97
+ });
98
+ if (route === undefined)
99
+ throw new Error('No model is listed for subagents, so there is nothing to switch to.');
100
+ exec.signal.throwIfAborted();
101
+ const before = deps.outages.get(child);
102
+ const live = deps.agents()?.get(child);
103
+ if (live === undefined)
104
+ deps.pendingRoutes.set(child, route);
105
+ else
106
+ selectRoute(live, route, deps.sessionController());
107
+ const effort = route.reasoningEffort === undefined ? '' : ` (effort ${route.reasoningEffort})`;
108
+ const reason = before === undefined ? 'your parent chose it' : `${before.model} could not serve you`;
109
+ const note = args.message?.trim();
110
+ const text = `[model switch] You now run on ${modelKey(route)}${effort}, because ${reason}. Continue your task from where you stopped; `
111
+ + `everything you did so far is above.${note === undefined || note === '' ? '' : ` Your parent adds: ${note}`}`;
112
+ try {
113
+ await deps.subagents.sendMessage(parent, child, [{ type: 'text', text }], { signal: exec.signal });
114
+ }
115
+ catch (error) {
116
+ deps.pendingRoutes.delete(child);
117
+ throw error;
118
+ }
119
+ deps.outages.resolve(child);
120
+ deps.outages.switched(child, modelKey(route));
121
+ return { agent_id: child, model: modelKey(route), ...route.reasoningEffort === undefined ? {} : { reasoning_effort: route.reasoningEffort } };
122
+ },
123
+ });
124
+ }
@@ -54,6 +54,43 @@ export interface AgentLike {
54
54
  }): () => void;
55
55
  };
56
56
  };
57
+ /** Its model for the next step (`AgentModel`); missing before 0.2.2-alpha.2. */
58
+ readonly model?: {
59
+ select(selection: {
60
+ readonly provider: string;
61
+ readonly model: string;
62
+ readonly reasoningEffort?: string;
63
+ }): void;
64
+ };
65
+ }
66
+ /** `LlmFailure`: why a model request failed, as a turn ending records it. */
67
+ export interface LlmFailureLike {
68
+ readonly message: string;
69
+ readonly code: string;
70
+ readonly status?: number;
71
+ }
72
+ /** One session event, as `session/event` delivers it; only the fields read here. */
73
+ export interface SessionEventLike {
74
+ readonly type: string;
75
+ readonly data?: {
76
+ readonly reason?: {
77
+ readonly kind: string;
78
+ readonly error?: LlmFailureLike;
79
+ };
80
+ };
81
+ }
82
+ /**
83
+ * `ctx.sessionController` on 0.2.1-rc.5, which has no `agent.model`: its
84
+ * internal agent controller records a selection for an agent's next request.
85
+ */
86
+ export interface SessionControllerLike {
87
+ readonly agents?: {
88
+ selectForNextRequest?(agent: AgentLike, selection: {
89
+ readonly provider: string;
90
+ readonly model: string;
91
+ readonly reasoningEffort?: string;
92
+ }): void;
93
+ };
57
94
  }
58
95
  /** `ctx.agents` (`AgentRegistry` of `@deepseek-ai/dsh-agent`): live agents by id. */
59
96
  export interface AgentsLike {
@@ -182,3 +219,7 @@ export declare const ANSWER_TOOL = "answer_write_request";
182
219
  export declare const GRANT_TOOL = "grant_write_access";
183
220
  /** The parent's tool for taking grants back. */
184
221
  export declare const REVOKE_TOOL = "revoke_write_access";
222
+ /** The parent's tool for recording what it found out about a model. */
223
+ export declare const NOTES_TOOL = "model_notes_set";
224
+ /** The parent's tool for moving a child to another model. */
225
+ export declare const SWITCH_TOOL = "switch_child_model";
package/lib/host/types.js CHANGED
@@ -24,3 +24,7 @@ export const ANSWER_TOOL = 'answer_write_request';
24
24
  export const GRANT_TOOL = 'grant_write_access';
25
25
  /** The parent's tool for taking grants back. */
26
26
  export const REVOKE_TOOL = 'revoke_write_access';
27
+ /** The parent's tool for recording what it found out about a model. */
28
+ export const NOTES_TOOL = 'model_notes_set';
29
+ /** The parent's tool for moving a child to another model. */
30
+ export const SWITCH_TOOL = 'switch_child_model';
package/lib/index.d.ts CHANGED
@@ -16,6 +16,19 @@
16
16
  * then see none of it; it may also set `childPreset`, the preset `delegate`
17
17
  * children run, `ownModel: false`, which keeps those children on the listed
18
18
  * models, and the list itself at run time through the `completeSubagent` service.
19
+ *
20
+ * A parent that may choose among listed models also gets `model_notes_set`,
21
+ * which fills the model notes table every parent on this machine shares; the
22
+ * delegation tools show each listed model's note and ask for research on the
23
+ * models without one (see `host/notes.ts`). It also gets `switch_child_model`:
24
+ * when a child stops because its model is out of quota, the parent's context
25
+ * says so, and the parent moves the child to another listed model, where it
26
+ * continues its own conversation (see `host/outages.ts`).
27
+ *
28
+ * A package that carries its own copy instead of mounting a row calls
29
+ * {@link embed}: that copy keeps its files in the package's own folder, provides
30
+ * no service, and registers its tools and prompt texts only in the contexts it
31
+ * is given (the package's presets), so it and an installed copy never meet.
19
32
  * @module complete-subagent
20
33
  */
21
34
  import type { Context, Volatile } from '@deepseek-ai/cordis';
@@ -34,6 +47,8 @@ export interface Config {
34
47
  childPreset: string;
35
48
  /** False keeps `delegate` children off the parent's own model when models are listed. */
36
49
  ownModel: boolean;
50
+ /** How deep delegation may go from a top-level session; 0 uses the host's subagent setting. */
51
+ maxDepth: number;
37
52
  }
38
53
  /** `ctx.completeSubagent`: what a bundle that mounts this plugin can change at run time. */
39
54
  export interface CompleteSubagentService {
@@ -45,11 +60,43 @@ export interface CompleteSubagentService {
45
60
  */
46
61
  setChildModels(models: readonly ChildModelInput[]): void;
47
62
  }
63
+ /** What a package that carries its own copy decides. */
64
+ export interface EmbedOptions {
65
+ /** Where the copy keeps its bindings and its model notes. */
66
+ readonly dataDirectory: string;
67
+ /** The agent presets it serves; other copies in this process leave them alone. */
68
+ readonly presets: readonly string[];
69
+ /** The preset `delegate` children run. */
70
+ readonly childPreset: string;
71
+ /** How deep delegation may go from a top-level session; 0 uses the host's subagent setting. */
72
+ readonly maxDepth?: number;
73
+ /** Tools kept from the agents of a preset, by preset id. */
74
+ readonly withhold?: Readonly<Record<string, readonly string[]>>;
75
+ }
76
+ /** An embedded copy; its children run only the models set here. */
77
+ export interface EmbeddedSubagents extends CompleteSubagentService {
78
+ /**
79
+ * Register the tools and prompt texts in one context, for the presets' own
80
+ * scope. They go with that context or with the copy, whichever ends first.
81
+ * @param ctx - a context with the `tools` and `systemPrompt` services.
82
+ * @returns takes them out again.
83
+ */
84
+ mount(ctx: Context): () => void;
85
+ }
48
86
  export declare const Config: z<Config>;
49
87
  /**
50
88
  * Install the fence, the delegation tools, the write-access tools, and the
51
- * guidance.
89
+ * guidance, and provide the `completeSubagent` service.
52
90
  * @param ctx - the plugin context; the services in {@link inject} are present.
53
91
  * @param config - loaded settings.
54
92
  */
55
93
  export declare function apply(ctx: Context, config: Config): void;
94
+ /**
95
+ * Run a copy of the plugin for a package's own presets: the fence, requests, and
96
+ * model switching start at once; the tools and prompt texts appear where
97
+ * {@link EmbeddedSubagents.mount} puts them.
98
+ * @param ctx - a context with the services in {@link inject}; its end stops the copy.
99
+ * @param options - what the package decides.
100
+ * @returns the copy, or undefined when this host cannot carry the fence.
101
+ */
102
+ export declare function embed(ctx: Context, options: EmbedOptions): EmbeddedSubagents | undefined;
package/lib/index.js CHANGED
@@ -16,20 +16,39 @@
16
16
  * then see none of it; it may also set `childPreset`, the preset `delegate`
17
17
  * children run, `ownModel: false`, which keeps those children on the listed
18
18
  * models, and the list itself at run time through the `completeSubagent` service.
19
+ *
20
+ * A parent that may choose among listed models also gets `model_notes_set`,
21
+ * which fills the model notes table every parent on this machine shares; the
22
+ * delegation tools show each listed model's note and ask for research on the
23
+ * models without one (see `host/notes.ts`). It also gets `switch_child_model`:
24
+ * when a child stops because its model is out of quota, the parent's context
25
+ * says so, and the parent moves the child to another listed model, where it
26
+ * continues its own conversation (see `host/outages.ts`).
27
+ *
28
+ * A package that carries its own copy instead of mounting a row calls
29
+ * {@link embed}: that copy keeps its files in the package's own folder, provides
30
+ * no service, and registers its tools and prompt texts only in the contexts it
31
+ * is given (the package's presets), so it and an installed copy never meet.
19
32
  * @module complete-subagent
20
33
  */
34
+ import { join } from 'node:path';
21
35
  import z from '@deepseek-ai/schemastery';
22
- import { DEFAULT_TIMEOUT_SECONDS, MIN_TIMEOUT_SECONDS, PLUGIN_ID, readChildPreset, readModels, readOwnModel, readPresets, readTimeout } from "./shared/settings.js";
36
+ import { DEFAULT_TIMEOUT_SECONDS, MIN_TIMEOUT_SECONDS, PLUGIN_ID, modelKey, readChildPreset, readMaxDepth, readModels, readOwnModel, readPresets, readTimeout } from "./shared/settings.js";
23
37
  import { withinCall } from "./host/call-scope.js";
24
38
  import { canStart, createDelegateTool } from "./host/delegate.js";
39
+ import { routeOf } from "./host/models.js";
40
+ import { createNotesTool } from "./host/notes-tool.js";
41
+ import { ModelNotes, defaultNotesFile } from "./host/notes.js";
42
+ import { ModelOutages, outageContext } from "./host/outages.js";
43
+ import { createSwitchTool, selectRoute } from "./host/switch-tool.js";
25
44
  import { isLegacyHost, ToolRestrictions } from "./host/legacy.js";
26
45
  import { Fence, patchResolve } from "./host/policy.js";
27
46
  import { childContext, pendingContext } from "./host/prompt.js";
28
47
  import { RequestBroker } from "./host/requests.js";
29
- import { presetScope } from "./host/scope.js";
48
+ import { claimPresets, isClaimed, presetScope, sessionPreset } from "./host/scope.js";
30
49
  import { BindingStore, defaultStoreDirectory } from "./host/store.js";
31
50
  import { createAnswerTool, createGrantTool, createRequestTool, createRevokeTool } from "./host/tools.js";
32
- import { ANSWER_TOOL, DELEGATE_TOOLS, GRANT_TOOL, REQUEST_TOOL, REVOKE_TOOL } from "./host/types.js";
51
+ import { ANSWER_TOOL, DELEGATE_TOOLS, GRANT_TOOL, NOTES_TOOL, REQUEST_TOOL, REVOKE_TOOL, SWITCH_TOOL } from "./host/types.js";
33
52
  export const name = PLUGIN_ID;
34
53
  export const inject = ['tools', 'subagents', 'sandboxPolicy', 'workingDirectory', 'systemPrompt'];
35
54
  export const Config = z.object({
@@ -47,6 +66,8 @@ export const Config = z.object({
47
66
  .description('Agent preset that children started with delegate run; empty keeps the parent\'s. delegate_fork children always keep it'),
48
67
  ownModel: z.boolean().default(true)
49
68
  .description('Whether delegate children may run the parent\'s own model. Off, with models listed, they run the first listed model unless the parent names another; delegate_fork children are not affected'),
69
+ maxDepth: z.natural().default(0)
70
+ .description('How deep delegation may go from a top-level session (1: children only, 2: their children too); 0 uses the host\'s subagent setting'),
50
71
  });
51
72
  /** The agent an assembly is for: `agent` when the host sets it, else the agent scope key. */
52
73
  function agentOf(context) {
@@ -61,22 +82,59 @@ function live(value) {
61
82
  }
62
83
  /**
63
84
  * Install the fence, the delegation tools, the write-access tools, and the
64
- * guidance.
85
+ * guidance, and provide the `completeSubagent` service.
65
86
  * @param ctx - the plugin context; the services in {@link inject} are present.
66
87
  * @param config - loaded settings.
67
88
  */
68
89
  export function apply(ctx, config) {
90
+ const copy = start(ctx, config);
91
+ if (copy === undefined)
92
+ return;
93
+ copy.mount(ctx);
94
+ try {
95
+ ctx.provide('completeSubagent', { setChildModels: list => copy.setChildModels(list) });
96
+ }
97
+ catch (error) {
98
+ // Another loaded copy already holds this name; that is a known limit, not a reason to stop.
99
+ ctx.logger.warn(`${PLUGIN_ID}: providing the service failed: ${String(error)}`);
100
+ }
101
+ }
102
+ /**
103
+ * Run a copy of the plugin for a package's own presets: the fence, requests, and
104
+ * model switching start at once; the tools and prompt texts appear where
105
+ * {@link EmbeddedSubagents.mount} puts them.
106
+ * @param ctx - a context with the services in {@link inject}; its end stops the copy.
107
+ * @param options - what the package decides.
108
+ * @returns the copy, or undefined when this host cannot carry the fence.
109
+ */
110
+ export function embed(ctx, options) {
111
+ const { presets, childPreset, maxDepth = 0 } = options;
112
+ return start(ctx, { presets: [...presets], childPreset, maxDepth, ownModel: false }, options);
113
+ }
114
+ /**
115
+ * Start everything but the registrations.
116
+ * @param ctx - the copy's context.
117
+ * @param config - the settings; a missing one has its default.
118
+ * @param own - set for a copy a package carries.
119
+ * @returns the running copy, or undefined when it stays disabled.
120
+ */
121
+ function start(ctx, config, own) {
69
122
  const host = ctx;
70
123
  const timeoutMs = () => readTimeout(live(config?.requestTimeoutSeconds)) * 1000;
71
124
  const childPreset = readChildPreset(config?.childPreset);
125
+ const maxDepth = readMaxDepth(config?.maxDepth);
72
126
  let bundleModels;
73
127
  const models = () => bundleModels ?? readModels(live(config?.models));
74
- const serves = presetScope(readPresets(config?.presets), {
128
+ const presetSources = {
75
129
  agentPresets: () => host.get('agentPresets'),
76
130
  sessionProjections: () => host.get('sessionProjections'),
77
- });
131
+ };
132
+ const serves = presetScope(readPresets(config?.presets), presetSources);
78
133
  const legacy = isLegacyHost(host.tools);
79
- const store = new BindingStore(defaultStoreDirectory());
134
+ const store = new BindingStore(own === undefined ? defaultStoreDirectory() : join(own.dataDirectory, 'children'));
135
+ const notes = new ModelNotes(own === undefined ? defaultNotesFile() : join(own.dataDirectory, 'model-notes.json'));
136
+ const outages = new ModelOutages();
137
+ const pendingRoutes = new Map();
80
138
  const broker = new RequestBroker();
81
139
  const resolvePolicy = (session) => host.sandboxPolicy.resolve({ session });
82
140
  const warn = (message) => {
@@ -105,9 +163,11 @@ export function apply(ctx, config) {
105
163
  }
106
164
  catch (error) {
107
165
  warn(`${PLUGIN_ID} is disabled: ${String(error)}`);
108
- return;
166
+ return undefined;
109
167
  }
110
168
  ctx.effect(() => restore);
169
+ if (own !== undefined)
170
+ ctx.effect(() => claimPresets(own.presets));
111
171
  // This listener adds no failure of its own; what `next` throws is the host's pipeline and stays its to handle.
112
172
  host.on('tools/execute', (call, next) => withinCall(call, next));
113
173
  // A child that a confined agent starts by other means (the official tools,
@@ -126,13 +186,44 @@ export function apply(ctx, config) {
126
186
  return;
127
187
  store.set({ version: 1, child: agent.id, parent: parentSession, workspace: null, grants: [], inherited: true });
128
188
  });
189
+ // A child the host put away comes back for the parent's message: give it the model the parent switched it to before its first step.
190
+ const route = pendingRoutes.get(agent.id);
191
+ if (route !== undefined) {
192
+ pendingRoutes.delete(agent.id);
193
+ guarded('switching a returning subagent\'s model', undefined, () => selectRoute(agent, route, host.get('sessionController')));
194
+ }
195
+ });
196
+ // A child of this plugin whose turn ended in an error waits for its parent, which is told what the error was.
197
+ host.on('session/event', (session, event) => {
198
+ if (event.type !== 'turn/end' && event.type !== 'turn/start')
199
+ return;
200
+ guarded('following a subagent\'s turn', undefined, () => {
201
+ const binding = store.get(session.id);
202
+ if (binding === undefined || binding.inherited === true)
203
+ return;
204
+ if (event.type === 'turn/start') {
205
+ outages.resolve(session.id);
206
+ return;
207
+ }
208
+ const reason = event.data?.reason;
209
+ if (reason?.kind === 'completed')
210
+ outages.finished(session.id);
211
+ if (reason?.kind !== 'error' || reason.error === undefined)
212
+ return;
213
+ const agent = host.get('agents')?.get(session.id);
214
+ const config = session.requestHeader?.()?.config;
215
+ const route = agent === undefined ? undefined : routeOf(agent);
216
+ const model = outages.runsOn(session.id) ?? (route !== undefined ? modelKey(route)
217
+ : config?.provider !== undefined && config.model !== undefined ? modelKey({ provider: config.provider, model: config.model }) : 'its model');
218
+ outages.record({ child: session.id, parent: binding.parent, model, failure: reason.error, at: Date.now() });
219
+ });
129
220
  });
130
221
  const tools = Object.keys(DELEGATE_TOOLS);
131
222
  const canDelegate = (agent) => serves(agent.session)
132
- && tools.some(tool => host.tools.get(tool, agent) !== undefined && canStart(host.subagents, tool, agent));
223
+ && tools.some(tool => host.tools.get(tool, agent) !== undefined && canStart(host.subagents, tool, agent, maxDepth));
133
224
  const conditions = {
134
- delegate: (agent) => serves(agent.session) && canStart(host.subagents, 'delegate', agent),
135
- delegate_fork: (agent) => serves(agent.session) && canStart(host.subagents, 'delegate_fork', agent),
225
+ delegate: (agent) => serves(agent.session) && canStart(host.subagents, 'delegate', agent, maxDepth),
226
+ delegate_fork: (agent) => serves(agent.session) && canStart(host.subagents, 'delegate_fork', agent, maxDepth),
136
227
  [REQUEST_TOOL]: (agent) => {
137
228
  const binding = store.get(agent.id);
138
229
  return binding !== undefined && binding.inherited !== true && serves(agent.session);
@@ -140,9 +231,13 @@ export function apply(ctx, config) {
140
231
  [ANSWER_TOOL]: (agent) => canDelegate(agent) || (broker.pendingFor(agent.id).length > 0 && serves(agent.session)),
141
232
  [GRANT_TOOL]: canDelegate,
142
233
  [REVOKE_TOOL]: canDelegate,
234
+ [NOTES_TOOL]: (agent) => models().length > 0 && canDelegate(agent),
235
+ [SWITCH_TOOL]: (agent) => models().length > 0 && canDelegate(agent),
143
236
  };
144
- const visible = (tool, agent) => guarded(`the visibility check of ${tool}`, false, () => conditions[tool](agent));
145
- // The schema lists the configured models, so settings changes rebuild the tools.
237
+ const withheld = (tool, agent) => own?.withhold !== undefined
238
+ && own.withhold[sessionPreset(agent.session, presetSources) ?? '']?.includes(tool) === true;
239
+ const visible = (tool, agent) => guarded(`the visibility check of ${tool}`, false, () => conditions[tool](agent) && !withheld(tool, agent));
240
+ // The schemas list the configured models, so settings changes rebuild the tools; notes are read live.
146
241
  const deps = {
147
242
  store,
148
243
  fence,
@@ -154,53 +249,80 @@ export function apply(ctx, config) {
154
249
  llm: () => host.get('llm'),
155
250
  childPreset,
156
251
  ownModel: readOwnModel(config?.ownModel),
252
+ notes,
253
+ maxDepth,
157
254
  };
158
- let mounted;
159
- const mount = () => {
255
+ const sites = new Set();
256
+ let disposed = false;
257
+ const buildDelegation = (list) => [
258
+ ...tools.map(tool => [tool, createDelegateTool(tool, list, deps)]),
259
+ [NOTES_TOOL, createNotesTool(list, { notes, llm: deps.llm })],
260
+ [SWITCH_TOOL, createSwitchTool(list, {
261
+ store,
262
+ outages,
263
+ subagents: host.subagents,
264
+ llm: deps.llm,
265
+ agents: () => host.get('agents'),
266
+ sessionController: () => host.get('sessionController'),
267
+ pendingRoutes,
268
+ })],
269
+ ];
270
+ const register = (site, tool, definition) => site.host.tools.register(definition, { when: ({ agent }) => visible(tool, agent) });
271
+ /** Bring the delegation tools of every site up to the current model list. */
272
+ const refresh = () => {
160
273
  const list = models();
161
274
  const key = JSON.stringify(list);
162
- if (mounted?.key === key)
275
+ const stale = [...sites].filter(site => site.key !== key);
276
+ if (stale.length === 0)
163
277
  return;
164
278
  // Build first, so a definition that fails to build leaves the old tools in place.
165
- const definitions = tools.map(tool => createDelegateTool(tool, list, deps));
166
- mounted?.dispose();
167
- const disposers = [];
168
- mounted = { key, dispose: () => { for (const dispose of disposers)
169
- dispose(); } };
170
- definitions.forEach((definition, index) => {
171
- const tool = tools[index];
172
- disposers.push(host.tools.register(definition, { when: ({ agent }) => visible(tool, agent) }));
173
- });
279
+ const definitions = buildDelegation(list);
280
+ for (const site of stale) {
281
+ for (const dispose of site.tools.splice(0))
282
+ dispose();
283
+ site.key = key;
284
+ for (const [tool, definition] of definitions)
285
+ site.tools.push(register(site, tool, definition));
286
+ }
287
+ };
288
+ const remove = (site) => {
289
+ if (!sites.delete(site))
290
+ return;
291
+ for (const dispose of [...site.tools.splice(0), ...site.rest.splice(0)])
292
+ dispose();
293
+ };
294
+ const mount = (target) => {
295
+ if (disposed)
296
+ return () => { };
297
+ const site = { host: target, tools: [], rest: [] };
298
+ sites.add(site);
299
+ target.effect(() => () => remove(site));
300
+ refresh();
301
+ site.rest.push(register(site, REQUEST_TOOL, createRequestTool(deps)), register(site, ANSWER_TOOL, createAnswerTool(deps)), register(site, GRANT_TOOL, createGrantTool(deps)), register(site, REVOKE_TOOL, createRevokeTool(deps)), ...mountContexts(site.host));
302
+ if (legacy)
303
+ for (const agent of guarded('listing the live agents', [], () => host.get('agents')?.list?.() ?? []))
304
+ sync(agent);
305
+ return () => remove(site);
174
306
  };
175
- mount();
176
- let disposed = false;
177
307
  ctx.effect(() => () => {
178
308
  disposed = true;
179
- mounted?.dispose();
180
- mounted = undefined;
309
+ for (const site of sites)
310
+ remove(site);
181
311
  });
182
312
  host.on('loader/volatile-update', () => {
183
- guarded('rebuilding the delegation tools', undefined, mount);
313
+ guarded('rebuilding the delegation tools', undefined, refresh);
184
314
  });
185
- // Another loaded copy already holds this name; that is a known limit, not a reason to stop.
186
- guarded('providing the service', undefined, () => host.provide('completeSubagent', {
187
- setChildModels(list) {
188
- if (childPreset === undefined || disposed)
189
- return;
190
- bundleModels = readModels(list);
191
- guarded('rebuilding the delegation tools', undefined, mount);
192
- },
193
- }));
194
- ctx.effect(() => host.tools.register(createRequestTool(deps), { when: ({ agent }) => visible(REQUEST_TOOL, agent) }));
195
- ctx.effect(() => host.tools.register(createAnswerTool(deps), { when: ({ agent }) => visible(ANSWER_TOOL, agent) }));
196
- ctx.effect(() => host.tools.register(createGrantTool(deps), { when: ({ agent }) => visible(GRANT_TOOL, agent) }));
197
- ctx.effect(() => host.tools.register(createRevokeTool(deps), { when: ({ agent }) => visible(REVOKE_TOOL, agent) }));
198
315
  // This host drops `when`, so the same conditions become per-agent filters. A
199
316
  // step reads its tools before `agent/pre-step`, so a change seen there takes
200
317
  // effect on the agent's next step; a new agent is filtered before its first.
318
+ // An embedded copy's tools exist only for the agents it serves, and those of a
319
+ // preset it claimed are not for any other copy to filter.
320
+ let sync = (_agent) => { };
201
321
  if (legacy) {
202
322
  const restrictions = new ToolRestrictions(Object.keys(conditions), (tool, agent) => visible(tool, agent));
203
- const sync = (agent) => {
323
+ sync = (agent) => {
324
+ if (sites.size === 0 || (own === undefined ? isClaimed(agent.session, presetSources) : !serves(agent.session)))
325
+ return;
204
326
  guarded('updating the tool filter', undefined, () => restrictions.sync(agent));
205
327
  };
206
328
  ctx.effect(() => () => {
@@ -217,29 +339,43 @@ export function apply(ctx, config) {
217
339
  sync(agent);
218
340
  });
219
341
  host.on('agent/disposed', ({ agent }) => restrictions.forget(agent));
220
- // Agents that were already running when the plugin loaded fire no `agent/created`.
221
- for (const agent of guarded('listing the live agents', [], () => host.get('agents')?.list?.() ?? []))
222
- sync(agent);
223
342
  }
224
- ctx.effect(() => host.systemPrompt.context({
225
- name: `${name}:child`,
226
- order: host.systemPrompt.getContextOrder('SUBAGENT_DELEGATION') + 1,
227
- interpolate: false,
228
- required: true,
229
- text: context => guarded('the child context', '', () => {
230
- const agent = agentOf(context);
231
- const binding = agent === undefined || !serves(agent.session) ? undefined : fence.bindingOf(agent.session);
232
- return binding === undefined ? '' : childContext(binding, !legacy);
233
- }),
234
- }));
235
- ctx.effect(() => host.systemPrompt.context({
236
- name: `${name}:requests`,
237
- order: host.systemPrompt.getContextOrder('SUBAGENT_DELEGATION') + 2,
238
- interpolate: false,
239
- required: true,
240
- text: context => guarded('the requests context', '', () => {
241
- const agent = agentOf(context);
242
- return agent === undefined || !serves(agent.session) ? '' : pendingContext(broker.pendingFor(agent.id));
243
- }),
244
- }));
343
+ const mountContexts = (site) => [site.systemPrompt.context({
344
+ name: `${name}:child`,
345
+ order: site.systemPrompt.getContextOrder('SUBAGENT_DELEGATION') + 1,
346
+ interpolate: false,
347
+ required: true,
348
+ text: context => guarded('the child context', '', () => {
349
+ const agent = agentOf(context);
350
+ const binding = agent === undefined || !serves(agent.session) ? undefined : fence.bindingOf(agent.session);
351
+ return binding === undefined ? '' : childContext(binding, !legacy);
352
+ }),
353
+ }), site.systemPrompt.context({
354
+ name: `${name}:requests`,
355
+ order: site.systemPrompt.getContextOrder('SUBAGENT_DELEGATION') + 2,
356
+ interpolate: false,
357
+ required: true,
358
+ text: context => guarded('the requests context', '', () => {
359
+ const agent = agentOf(context);
360
+ return agent === undefined || !serves(agent.session) ? '' : pendingContext(broker.pendingFor(agent.id));
361
+ }),
362
+ }), site.systemPrompt.context({
363
+ name: `${name}:outages`,
364
+ order: site.systemPrompt.getContextOrder('SUBAGENT_DELEGATION') + 3,
365
+ interpolate: false,
366
+ required: true,
367
+ text: context => guarded('the outages context', '', () => {
368
+ const agent = agentOf(context);
369
+ return agent === undefined || !serves(agent.session) ? '' : outageContext(outages.pendingFor(agent.id), models(), child => outages.refused(child));
370
+ }),
371
+ })];
372
+ return {
373
+ mount,
374
+ setChildModels(list) {
375
+ if (childPreset === undefined || disposed)
376
+ return;
377
+ bundleModels = readModels(list);
378
+ guarded('rebuilding the delegation tools', undefined, refresh);
379
+ },
380
+ };
245
381
  }
@@ -55,6 +55,12 @@ export declare function readPresets(value: unknown): string[];
55
55
  * @returns the preset id, or undefined when none is set.
56
56
  */
57
57
  export declare function readChildPreset(value: unknown): string | undefined;
58
+ /**
59
+ * Read a stored depth limit.
60
+ * @param value - the stored `maxDepth` field.
61
+ * @returns a whole number above 0, or undefined when the host's own limit applies.
62
+ */
63
+ export declare function readMaxDepth(value: unknown): number | undefined;
58
64
  /**
59
65
  * Read the stored `ownModel` flag.
60
66
  * @param value - the stored field.
@@ -68,6 +68,14 @@ export function readPresets(value) {
68
68
  export function readChildPreset(value) {
69
69
  return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
70
70
  }
71
+ /**
72
+ * Read a stored depth limit.
73
+ * @param value - the stored `maxDepth` field.
74
+ * @returns a whole number above 0, or undefined when the host's own limit applies.
75
+ */
76
+ export function readMaxDepth(value) {
77
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined;
78
+ }
71
79
  /**
72
80
  * Read the stored `ownModel` flag.
73
81
  * @param value - the stored field.