@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/host/scope.js CHANGED
@@ -6,6 +6,11 @@
6
6
  * tools and prompt texts stay out of every other preset's sessions. A child
7
7
  * records its parent's preset unless it was started with one of its own, so a
8
8
  * served agent's children are served too.
9
+ *
10
+ * A package that carries its own copy (`embed`) claims its presets: a copy
11
+ * without `presets` in the same process then leaves the agents of those presets
12
+ * alone, whichever copy loaded first. The claims live on `globalThis`, because
13
+ * two copies are two modules.
9
14
  * @module complete-subagent/host/scope
10
15
  */
11
16
  /**
@@ -23,16 +28,50 @@ export function sessionPreset(session, sources) {
23
28
  : sources.sessionProjections()?.stateOf(session, 'agentPreset');
24
29
  return typeof preset === 'string' ? preset : undefined;
25
30
  }
31
+ const CLAIMS = Symbol.for('complete-subagent.claimedPresets');
32
+ /** @returns every live claim in this process; each holds the presets one embedded copy serves. */
33
+ function claims() {
34
+ const shared = globalThis;
35
+ return shared[CLAIMS] ??= new Set();
36
+ }
37
+ /**
38
+ * Keep copies that serve every preset away from these presets' agents.
39
+ * @param presets - the presets an embedded copy serves.
40
+ * @returns ends the claim.
41
+ */
42
+ export function claimPresets(presets) {
43
+ const claim = [...presets];
44
+ claims().add(claim);
45
+ return () => { claims().delete(claim); };
46
+ }
47
+ /**
48
+ * Whether another copy in this process has claimed the preset a session runs.
49
+ * @param session - any session.
50
+ * @param sources - the host services a session's preset is read from.
51
+ * @returns false also when nothing is claimed or the preset cannot be read.
52
+ */
53
+ export function isClaimed(session, sources) {
54
+ const live = claims();
55
+ if (live.size === 0)
56
+ return false;
57
+ try {
58
+ const preset = sessionPreset(session, sources);
59
+ return preset !== undefined && [...live].some(claim => claim.includes(preset));
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
26
65
  /**
27
66
  * Build the "does the plugin serve this session" check.
28
- * @param presets - the configured preset ids; empty serves every session.
67
+ * @param presets - the configured preset ids; empty serves every session but those of presets an embedded copy claimed.
29
68
  * @param sources - the host services a session's preset is read from.
30
69
  * @returns the check. With presets configured, a session whose preset cannot be
31
70
  * read (no service, none recorded, a failure) is not served.
32
71
  */
33
72
  export function presetScope(presets, sources) {
34
73
  if (presets.length === 0)
35
- return () => true;
74
+ return session => !isClaimed(session, sources);
36
75
  const allowed = new Set(presets);
37
76
  return (session) => {
38
77
  try {
@@ -0,0 +1,47 @@
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 type { ToolDefinition } from '@deepseek-ai/dsh-tools';
14
+ import type { ChildModel } from '../shared/settings.ts';
15
+ import type { Route } from './models.ts';
16
+ import type { ModelOutages } from './outages.ts';
17
+ import type { BindingStore } from './store.ts';
18
+ import type { AgentLike, AgentsLike, LlmLike, SessionControllerLike, SubagentsLike } from './types.ts';
19
+ /** What the tool reads. */
20
+ export interface SwitchToolDeps {
21
+ readonly store: BindingStore;
22
+ readonly outages: ModelOutages;
23
+ readonly subagents: SubagentsLike;
24
+ /** The LLM runtime, read at call time because it is optional. */
25
+ readonly llm: () => LlmLike | undefined;
26
+ /** Live agents, to switch a child at once. */
27
+ readonly agents: () => AgentsLike | undefined;
28
+ /** 0.2.1-rc.5's session controller, which records a selection where `agent.model` is missing. */
29
+ readonly sessionController: () => SessionControllerLike | undefined;
30
+ /** Routes waiting for children the host has put away, applied when each comes back. */
31
+ readonly pendingRoutes: Map<string, Route>;
32
+ }
33
+ /**
34
+ * Record a route for an agent's next step, on any supported host.
35
+ * @param agent - a live agent.
36
+ * @param route - provider, model, and the effort when one is chosen.
37
+ * @param sessionController - the session controller, for 0.2.1-rc.5.
38
+ * @throws when the host offers neither way.
39
+ */
40
+ export declare function selectRoute(agent: AgentLike, route: Route, sessionController: SessionControllerLike | undefined): void;
41
+ /**
42
+ * Build the tool for the current model list, which its `model` parameter names.
43
+ * @param models - the settings' model list.
44
+ * @param deps - shared state and services.
45
+ * @returns a registry-ready definition.
46
+ */
47
+ export declare function createSwitchTool(models: readonly ChildModel[], deps: SwitchToolDeps): ToolDefinition;
@@ -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 {
@@ -101,23 +138,31 @@ export interface TextBlock {
101
138
  readonly type: 'text';
102
139
  readonly text: string;
103
140
  }
104
- /** `SubagentActivationSpec` with a reserved child id, as this plugin fills it. */
105
- export interface ActivationSpecLike {
141
+ /** `SubagentStartRequest`: the task part of a start, as this plugin fills it. */
142
+ export interface StartRequestLike {
143
+ readonly cwd?: string;
144
+ readonly prompt: TextBlock[];
145
+ readonly parent: AgentLike;
146
+ /** Preset the child runs instead of the parent's; only a backend that does not inherit the parent's context accepts it. */
147
+ readonly agentPreset?: string;
148
+ readonly agentOptions?: RouteLike;
149
+ readonly maxDepth?: number;
150
+ }
151
+ /**
152
+ * `SubagentActivationSpec` with a reserved child id, as this plugin fills it.
153
+ * Hosts from 0.2.2-rc.2 read the task at the top level; older ones read it
154
+ * under `request` and ignore the top-level copy, and newer ones the reverse,
155
+ * so the plugin sends both.
156
+ */
157
+ export interface ActivationSpecLike extends StartRequestLike {
106
158
  /** Registered backend: `spawn` (fresh child) or `fork` (inherits the conversation). */
107
159
  readonly provider: string;
108
160
  /** Short task label shown with the child. */
109
161
  readonly label: string;
110
162
  /** Reserved child session id, so the child is bound before it exists. */
111
163
  readonly childId: string;
112
- readonly request: {
113
- readonly cwd?: string;
114
- readonly prompt: TextBlock[];
115
- readonly parent: AgentLike;
116
- /** Preset the child runs instead of the parent's; only a backend that does not inherit the parent's context accepts it. */
117
- readonly agentPreset?: string;
118
- readonly agentOptions?: RouteLike;
119
- readonly maxDepth?: number;
120
- };
164
+ /** The same task, for hosts before 0.2.2-rc.2. */
165
+ readonly request: StartRequestLike;
121
166
  readonly signal: AbortSignal;
122
167
  /** `parent`: the runtime notifies the parent model when the child finishes. */
123
168
  readonly delivery: 'parent';
@@ -174,3 +219,7 @@ export declare const ANSWER_TOOL = "answer_write_request";
174
219
  export declare const GRANT_TOOL = "grant_write_access";
175
220
  /** The parent's tool for taking grants back. */
176
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;