@starsharryzhu/complete-subagent 0.1.0 → 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.
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starsharryzhu/complete-subagent",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Complete subagents for DeepSeek Harness: delegate and delegate_fork tools beside the official ones, where the cwd a parent gives a child is the only place the child may modify, writable_paths grants more up front, anything else needs the parent agent's permission, and the parent can choose the child's model and reasoning effort from the models listed in the settings.",
5
5
  "keywords": [
6
6
  "dsh-plugin",
@@ -85,5 +85,13 @@
85
85
  "access": "public",
86
86
  "tag": "latest"
87
87
  },
88
+ "repository": {
89
+ "type": "git",
90
+ "url": "git+https://github.com/StarsHarryZhu/complete-subagent.git"
91
+ },
92
+ "homepage": "https://github.com/StarsHarryZhu/complete-subagent#readme",
93
+ "bugs": {
94
+ "url": "https://github.com/StarsHarryZhu/complete-subagent/issues"
95
+ },
88
96
  "license": "MIT"
89
97
  }
package/src/AGENTS.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  ## 1. Role
4
4
 
5
- The plugin source. `index.ts` is the host entry the bundle row loads: it declares the injected services and the live settings, wraps the sandbox policy, registers the two delegation tools (rebuilt when the model settings change or a bundle sets the list through the `completeSubagent` service) and the four write-access tools, confines children that confined agents start by other means, and adds the child and open-request contexts to the prompt, all of it only for the agents of the configured `presets` when any are listed. On a host that ignores `when`, it applies the same visibility conditions as per-agent filters. Everything with logic lives in `host/`, so the entry stays a readable wiring diagram. `client/` is the browser half, the settings page, and `shared/` holds the settings shape both halves read.
5
+ The plugin source. `index.ts` is the host entry the bundle row loads: it declares the injected services and the live settings, wraps the sandbox policy, registers the two delegation tools (rebuilt when the model settings change or a bundle sets the list through the `completeSubagent` service) the four write-access tools, `model_notes_set`, and `switch_child_model`, confines children that confined agents start by other means, follows its children's turns for one their model stopped, and adds the child, open-request, and stopped-children contexts to the prompt, all of it only for the agents of the configured `presets` when any are listed. On a host that ignores `when`, it applies the same visibility conditions as per-agent filters. Everything with logic lives in `host/`, so the entry stays a readable wiring diagram. `client/` is the browser half, the settings page, and `shared/` holds the settings shape both halves read.
6
6
 
7
7
  ## 2. Constraints
8
8
 
9
- - The host entry exports only `name`, `inject`, `Config`, and `apply`, plus types: no default export and no top-level `await`, as the host loader requires.
9
+ - The host entry exports only `name`, `inject`, `Config`, `apply`, and `embed` (for a package that carries its own copy), plus types: no default export and no top-level `await`, as the host loader requires.
10
10
  - Every host registration goes through `ctx.effect` or `ctx.on`, or is disposed by an effect, so unloading the plugin removes all of it and restores the sandbox policy.
11
11
  - A callback the host runs for every session (an event listener, a visibility check, a prompt text) logs a warning and falls back rather than throwing, so a plugin failure cannot stop a step or an agent start.
12
12
  - `host/` never imports from `client/`, and `client/` never imports from `host/`; both may import `shared/`.
@@ -14,13 +14,16 @@ The plugin source. `index.ts` is the host entry the bundle row loads: it declare
14
14
 
15
15
  ## 3. Contents
16
16
 
17
- - `index.ts` — the host entry: services, live settings, the `completeSubagent` service, and wiring.
17
+ - `index.ts` — the host entry: services, live settings, the `completeSubagent` service, `embed`, the contexts the tools and texts are registered in, and wiring.
18
18
  - `host` — the fence, delegation, access, model choice, grants, requests, tools, prompts, storage, and path helpers.
19
19
  - `client` — the settings page on the Plugins screen.
20
20
  - `shared` — the settings shape and readers used by both halves.
21
21
 
22
22
  ## 4. Progress
23
23
 
24
+ - Done (2026-11-30, user request): the entry wires the model notes table and the switch of a child stopped by its model.
25
+
24
26
  - Done: entry wiring for every module and both halves, including the `presets` scope on every tool, both contexts, and inherited bindings, one table of visibility conditions for both kinds of host, and failure guards on every host callback; the `completeSubagent` service.
27
+ - Done (2026-12-03): the entry starts a copy first and registers its tools and prompt texts per context after it, so an embedded copy can do so in presets.
25
28
  - Open: nothing.
26
29
  - Goal later: nothing planned.
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## 1. Role
4
4
 
5
- The host modules. A delegation call decides the child's sub-workspace and `writable_paths` grants (`access.ts`) and its model and reasoning effort (`models.ts`), stores the binding under a reserved child id, and only then starts the child on the host's subagent runtime (`delegate.ts`); bindings and grants are stored per child session (`store.ts`); every sandbox policy the host resolves for a bound child, or for a child a confined agent started by other means, is narrowed to its access (`policy.ts`, with `call-scope.ts` for single-file grants); grants are issued under one authority rule (`grants.ts`); the child asks and the parent answers, grants, and revokes through four tools (`tools.ts`, with open requests in `requests.ts`); and the prompt texts explain all of it (`prompt.ts`). When the settings list agent presets, only the agents of those presets are served (`scope.ts`). What differs on a host older than 0.2.2-alpha.2 lives in `legacy.ts`.
5
+ The host modules. A delegation call decides the child's sub-workspace and `writable_paths` grants (`access.ts`) and its model and reasoning effort (`models.ts`), stores the binding under a reserved child id, and only then starts the child on the host's subagent runtime (`delegate.ts`); bindings and grants are stored per child session (`store.ts`); every sandbox policy the host resolves for a bound child, or for a child a confined agent started by other means, is narrowed to its access (`policy.ts`, with `call-scope.ts` for single-file grants); grants are issued under one authority rule (`grants.ts`); the child asks and the parent answers, grants, and revokes through four tools (`tools.ts`, with open requests in `requests.ts`); the prompt texts explain all of it (`prompt.ts`); and a parent records what it found out about each listed model in a table every parent shares (`notes.ts`, through `notes-tool.ts`), which the delegation descriptions show under each model; a child whose model is out of quota or rate-limited is recorded when its turn ends, its parent's context says so (`outages.ts`), and the parent moves it to another listed model, where it continues its own conversation (`switch-tool.ts`); the words of any other error a child's turn ended in reach its parent the same way. When the settings list agent presets, only the agents of those presets are served (`scope.ts`). What differs on a host older than 0.2.2-alpha.2 lives in `legacy.ts`.
6
6
 
7
7
  ## 2. Constraints
8
8
 
@@ -14,11 +14,21 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
14
14
  - An inherited binding holds no access of its own; the fence resolves it to the nearest ancestor's current access, and a broken chain leaves none.
15
15
  - The delegation result text is `started subagent <id>`, as the official tools write it.
16
16
  - Only a `spawn` start carries the configured `childPreset` as `agentPreset`; a `fork` start never selects a preset.
17
+ - A configured `maxDepth` replaces the host's `resolveMaxDepth()` in `canStart` and in the start request; without one both read the host's setting.
18
+ - A start's task (`cwd`, `prompt`, `parent`, `agentPreset`, `agentOptions`, `maxDepth`) goes both at the top level of the spec, for hosts from 0.2.2-rc.2, and under `request`, for older ones; `delegate.ts` builds it once and `types.ts` mirrors both shapes.
17
19
  - A child's route goes only through the start's `agentOptions`, which both 0.2.1-rc.5 and 0.2.2-alpha.2 use for its first request; nothing selects a model afterwards.
18
20
  - `ownModel` off applies to `delegate` only. On the parent's own route the host hands down the parent's effort unless one is named, so `models.ts` names the effort there.
19
21
  - A model outside the list fails first in the tool's own `enum` check, with the host's "must be one of" message; the message in `models.ts` covers a call that gets past it.
20
- - Requests live in memory only; bindings and grants are the only durable state.
22
+ - Requests live in memory only; bindings, grants, and the model notes are the only durable state.
23
+ - The model notes reach the parent only through the delegation descriptions, which change only when a note or the list does: the host re-sends every runtime context in full whenever any of them changes, so a table there would be paid for again and again. A description reads the notes whenever the host projects the schema; a note never rebuilds the tools, because a step admits a tool only while its registered definition is unchanged, and a swapped one would fail a call still running on the old definition (checked in the 0.2.1-rc.5 and 0.2.2-rc.5 sources).
24
+ - A note is for a listed model only, and its efforts must be ones that model allows, checked the same way as a delegation's effort. Its sources are kept in the file but left out of the description.
25
+ - A model is switched for a child's next step, never inside a step: every supported host fixes a step's model before its request (`agent-loop` `prepareRequest`), so a retry from `agent/request-error` would hit the same model. The child's turn ends with the host's own failure notice, and the switch then records the new model (`agent.model.select`, or on 0.2.1-rc.5 the session controller's internal `agents.selectForNextRequest`) and wakes the child with a message from its parent. A child the host has put away gets its new model in `agent/created`, before its first step.
26
+ - A model "cannot serve" a child when its request fails with `QUOTA`, `ACCOUNT_QUOTA`, or `RATE_LIMIT`, or HTTP 402; the same failure codes and turn ending exist from 0.2.1-rc.5 on. A model that refused a child cannot be chosen for it again until the child finishes a turn. Outages are in memory only; after a restart the parent still has the host's notice.
27
+ - Every error a child's turn ends in reaches its parent word for word (at most `MESSAGE_CHARS`), because the host says only that the child failed and a parent left to guess guesses wrong. Only the codes above count as a refusal; what a provider says under a code of its own is the parent's to read, and to have looked up when it does not know it, so no wording rules belong here. Such an error is shown until the child runs again, and for a day at most. A stopped turn is no error.
28
+ - The texts never let a parent force a task onto a model whose notes do not fit it: they say to ask the user first and try one only with their permission (the user's rule, 2026-11-30).
29
+ - The notes file is shared by every host process on this machine: a write rereads it first and replaces it atomically, and a damaged file reads as empty.
21
30
  - With presets listed, an agent whose preset cannot be read (no service, none recorded, a failure) is not served; an empty list serves every agent without reading a preset.
31
+ - A copy that serves every preset leaves the agents of claimed presets alone in both ways: it does not serve them, and on a host without `when` it adds no filter to them, since a filter goes by name and would hide the claiming copy's tools. An embedded copy filters only the agents it serves, because its tools do not exist for others.
22
32
  - A session's preset comes from `agentPresets.presetForSession` when the host has that method, since newer hosts deprecate the alternative, and otherwise from the `agentPreset` session projection.
23
33
  - A `tools.restrict` filter belongs to the agent's own context, not the plugin's, so the plugin lifts it on dispose. It never reaches the agent's children, because an agent's scope chain leads to its preset, not its parent.
24
34
  - A failure in the fence stays in the session it hit: a subagent falls back to read-only, a top-level session keeps the host's policy, and other sessions are not touched.
@@ -27,7 +37,7 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
27
37
  ## 3. Contents
28
38
 
29
39
  - `types.ts` — structural mirrors of the host services, the delegation tools and their backends, and the write-access tool names.
30
- - `scope.ts` — reading a session's preset on any host, and which agents the plugin serves under the `presets` setting.
40
+ - `scope.ts` — reading a session's preset on any host, which agents the plugin serves under the `presets` setting, and the presets embedded copies have claimed.
31
41
  - `legacy.ts` — detecting a host older than 0.2.2-alpha.2, and the per-agent tool filters that replace `when` there.
32
42
  - `paths.ts` — resolving, canonicalizing, and comparing paths.
33
43
  - `store.ts` — per-child bindings and grants as JSON files under the DSH home.
@@ -39,6 +49,10 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
39
49
  - `grants.ts` — resolving requested paths and issuing grants within the grantor's reach.
40
50
  - `requests.ts` — open write-access requests, answers, timeouts, and cancellation.
41
51
  - `tools.ts` — `request_write_access`, `answer_write_request`, `grant_write_access`, and `revoke_write_access`.
52
+ - `notes.ts` — the model notes table: one JSON file under the DSH home, one note per model.
53
+ - `notes-tool.ts` — `model_notes_set`, which checks and stores a note.
54
+ - `outages.ts` — the errors children's turns ended in, which of them mean a model cannot serve the child, the models that refused each child, and the parent's context.
55
+ - `switch-tool.ts` — `switch_child_model`, and recording a model for an agent's next step on every supported host.
42
56
  - `prompt.ts` — the delegation descriptions and parameter texts, the child context, which says what reaches its grants on this host, and the open-requests context.
43
57
 
44
58
  ## 4. Progress
@@ -47,5 +61,9 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
47
61
  - Verified in the real web app, before the move to standalone tools: the fence, grants, requests, and storage with the host's own sandbox enforcing the narrowed policy (2026-10-29 to 2026-11-01).
48
62
  - Checked on the real rc.5 tool, prompt, projection, and sandbox-policy services (2026-11-02): `legacy.ts`, `scope.ts`, and the single-root grant, with stand-ins for agents and the subagent start.
49
63
  - Checked on real 0.2.1-rc.5 and 0.2.2-alpha.2 hosts with a mock model (2026-11-02): `delegate.ts` and `models.ts`, from the tool call to the child's first recorded request.
64
+ - Fixed and checked on real 0.2.1-rc.5, 0.2.2-rc.1, 0.2.2-rc.2, and 0.2.2-rc.3 hosts with a mock model (2026-11-17): `delegate.ts` starts a child on each, where before it failed from 0.2.2-rc.2 on; the fence, a write-access request, its answer, and the grant worked on all four.
65
+ - Done (2026-11-30, user request): the model notes table and `model_notes_set`; the delegation descriptions show each listed model's note and ask for research on the models without one or with an old one.
66
+ - Done (2026-11-30, user request): a child stopped because its model is out of quota is reported to its parent with the reason, and `switch_child_model` moves it to another listed model, where it continues its own conversation; no text lets a parent force a task onto a model that does not fit it without asking the user.
67
+ - Done (2026-12-03): claimed presets, and a wrapper of `sandboxPolicy.resolve` that does nothing after its copy ended.
50
68
  - Open: `delegate.ts`, `models.ts`, `scope.ts`, `legacy.ts`, and inherited confinement are not yet verified in a real web app.
51
69
  - Goal later: nothing planned.