@starsharryzhu/complete-subagent 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/AGENTS.md +58 -0
  2. package/LICENSE +21 -0
  3. package/README.md +168 -2
  4. package/cordis.patch.yml +11 -0
  5. package/lib/client.js +439 -0
  6. package/lib/client.modules.txt +8 -0
  7. package/lib/host/access.d.ts +46 -0
  8. package/lib/host/access.js +54 -0
  9. package/lib/host/call-scope.d.ts +21 -0
  10. package/lib/host/call-scope.js +26 -0
  11. package/lib/host/delegate.d.ts +47 -0
  12. package/lib/host/delegate.js +133 -0
  13. package/lib/host/grants.d.ts +51 -0
  14. package/lib/host/grants.js +62 -0
  15. package/lib/host/legacy.d.ts +57 -0
  16. package/lib/host/legacy.js +85 -0
  17. package/lib/host/models.d.ts +59 -0
  18. package/lib/host/models.js +139 -0
  19. package/lib/host/paths.d.ts +51 -0
  20. package/lib/host/paths.js +100 -0
  21. package/lib/host/policy.d.ts +72 -0
  22. package/lib/host/policy.js +169 -0
  23. package/lib/host/prompt.d.ts +41 -0
  24. package/lib/host/prompt.js +100 -0
  25. package/lib/host/requests.d.ts +82 -0
  26. package/lib/host/requests.js +109 -0
  27. package/lib/host/scope.d.ts +33 -0
  28. package/lib/host/scope.js +46 -0
  29. package/lib/host/store.d.ts +89 -0
  30. package/lib/host/store.js +128 -0
  31. package/lib/host/tools.d.ts +58 -0
  32. package/lib/host/tools.js +298 -0
  33. package/lib/host/types.d.ts +184 -0
  34. package/lib/host/types.js +26 -0
  35. package/lib/index.d.ts +55 -0
  36. package/lib/index.js +245 -0
  37. package/lib/shared/settings.d.ts +69 -0
  38. package/lib/shared/settings.js +86 -0
  39. package/locale/AGENTS.md +22 -0
  40. package/locale/en.json +6 -0
  41. package/locale/zh.json +6 -0
  42. package/package.json +95 -4
  43. package/src/AGENTS.md +26 -0
  44. package/src/client/AGENTS.md +28 -0
  45. package/src/client/css.d.ts +5 -0
  46. package/src/client/host.ts +82 -0
  47. package/src/client/index.ts +81 -0
  48. package/src/client/locales.ts +61 -0
  49. package/src/client/settings.tsx +222 -0
  50. package/src/client/styles.css +44 -0
  51. package/src/host/AGENTS.md +53 -0
  52. package/src/host/access.ts +82 -0
  53. package/src/host/call-scope.ts +31 -0
  54. package/src/host/delegate.ts +166 -0
  55. package/src/host/grants.ts +82 -0
  56. package/src/host/legacy.ts +86 -0
  57. package/src/host/models.ts +155 -0
  58. package/src/host/paths.ts +100 -0
  59. package/src/host/policy.ts +169 -0
  60. package/src/host/prompt.ts +113 -0
  61. package/src/host/requests.ts +149 -0
  62. package/src/host/scope.ts +54 -0
  63. package/src/host/store.ts +159 -0
  64. package/src/host/tools.ts +318 -0
  65. package/src/host/types.ts +192 -0
  66. package/src/index.ts +316 -0
  67. package/src/shared/AGENTS.md +20 -0
  68. package/src/shared/settings.ts +104 -0
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Structural mirrors of the host services this plugin reads.
3
+ *
4
+ * The plugin imports only `@deepseek-ai/cordis`, `@deepseek-ai/schemastery`, and
5
+ * `@deepseek-ai/dsh-tools` at runtime, so these types mirror only the fields it
6
+ * uses from `@deepseek-ai/dsh-session` (header), `@deepseek-ai/dsh-agent`,
7
+ * `@deepseek-ai/dsh-agent-preset-registry`, `@deepseek-ai/dsh-session-projection`,
8
+ * `@deepseek-ai/dsh-sandbox-policy`, `@deepseek-ai/dsh-working-directory`,
9
+ * `@deepseek-ai/dsh-subagent`, and `@deepseek-ai/dsh-llm`. Each mirror names its
10
+ * source for the next reader, and says so when a field is missing from the
11
+ * oldest supported host, 0.2.1-rc.5.
12
+ * @module complete-subagent/host/types
13
+ */
14
+ /** `SessionHeader`: the immutable storage metadata of one session. */
15
+ export interface SessionHeaderLike {
16
+ readonly id: string;
17
+ /** Absolute directory the session was created in; the sandbox workspace root. */
18
+ readonly cwd?: string;
19
+ /** Direct creator of a subagent session. */
20
+ readonly parentSession?: string;
21
+ /** `'subagent'` for a delegated child. */
22
+ readonly origin?: 'subagent';
23
+ /** Persisted delegation depth of a child (`delegationDepthOf`). */
24
+ readonly delegationDepth?: number;
25
+ }
26
+ /** The provider, model, and effort of one LLM route (`AgentOptions` / `LlmCallConfig`). */
27
+ export interface RouteLike {
28
+ readonly provider?: string;
29
+ readonly model?: string;
30
+ readonly reasoningEffort?: string;
31
+ }
32
+ /** `Session`: identity, header, and the route of its next request. */
33
+ export interface SessionLike {
34
+ readonly id: string;
35
+ readonly header: SessionHeaderLike;
36
+ /** The latest request header; its `config` is the session's current route. */
37
+ requestHeader?(): {
38
+ readonly config?: RouteLike;
39
+ } | undefined;
40
+ }
41
+ /** `Agent`: a live agent; its id is its session id. */
42
+ export interface AgentLike {
43
+ readonly id: string;
44
+ readonly session: SessionLike;
45
+ /** Creation options: the route before the first request, and a runtime depth. */
46
+ readonly options?: RouteLike & {
47
+ readonly subagentDepth?: number;
48
+ };
49
+ /** The agent's scoped context; a restriction made through it covers this agent only. */
50
+ readonly ctx?: {
51
+ readonly tools?: {
52
+ restrict(filter: {
53
+ readonly deny: readonly string[];
54
+ }): () => void;
55
+ };
56
+ };
57
+ }
58
+ /** `ctx.agents` (`AgentRegistry` of `@deepseek-ai/dsh-agent`): live agents by id. */
59
+ export interface AgentsLike {
60
+ get(id: string): AgentLike | undefined;
61
+ /** All live agents. */
62
+ list?(): readonly AgentLike[];
63
+ }
64
+ /** `ctx.agentPresets` (`AgentPresetRegistry` of `@deepseek-ai/dsh-agent-preset-registry`). */
65
+ export interface AgentPresetsLike {
66
+ /** The preset a session runs: its header's, or a later selection; null when none was recorded. Missing from 0.2.1-rc.5. */
67
+ presetForSession?(session: SessionLike): string | null;
68
+ }
69
+ /** `ctx.sessionProjections` (`SessionProjectionRegistry` of `@deepseek-ai/dsh-session-projection`). */
70
+ export interface SessionProjectionsLike {
71
+ /** One projection's current state, or undefined when its key is not registered. */
72
+ stateOf(session: SessionLike, key: string): unknown;
73
+ }
74
+ /** `SandboxMode` of `@deepseek-ai/dsh-sandbox`. */
75
+ export type SandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access';
76
+ /** `SandboxExecutionPolicy`: what one confined capability call may write. */
77
+ export interface SandboxPolicy {
78
+ readonly mode: SandboxMode;
79
+ readonly workspaceRoot: string;
80
+ readonly additionalWritableRoots?: readonly string[];
81
+ readonly sessionId?: string;
82
+ }
83
+ /** `SandboxPolicyRequest`. */
84
+ export interface SandboxPolicyRequest {
85
+ readonly session?: SessionLike;
86
+ readonly mode?: SandboxMode;
87
+ }
88
+ /** `ctx.sandboxPolicy` (`SandboxPolicyService`). */
89
+ export interface SandboxPolicyServiceLike {
90
+ resolve(request?: SandboxPolicyRequest): SandboxPolicy;
91
+ }
92
+ /** `ctx.workingDirectory` (`WorkingDirectoryService`). */
93
+ export interface WorkingDirectoryLike {
94
+ /** Effective directory of a session, without repairing a vanished one. */
95
+ get(session: SessionLike): string;
96
+ /** Effective directory of an agent, restoring the header cwd when it vanished. */
97
+ ensure(agent: AgentLike, signal?: AbortSignal): Promise<string>;
98
+ }
99
+ /** One text content block, the only kind this plugin authors. */
100
+ export interface TextBlock {
101
+ readonly type: 'text';
102
+ readonly text: string;
103
+ }
104
+ /** `SubagentStartRequest`: the task part of a start, as this plugin fills it. */
105
+ export interface StartRequestLike {
106
+ readonly cwd?: string;
107
+ readonly prompt: TextBlock[];
108
+ readonly parent: AgentLike;
109
+ /** Preset the child runs instead of the parent's; only a backend that does not inherit the parent's context accepts it. */
110
+ readonly agentPreset?: string;
111
+ readonly agentOptions?: RouteLike;
112
+ readonly maxDepth?: number;
113
+ }
114
+ /**
115
+ * `SubagentActivationSpec` with a reserved child id, as this plugin fills it.
116
+ * Hosts from 0.2.2-rc.2 read the task at the top level; older ones read it
117
+ * under `request` and ignore the top-level copy, and newer ones the reverse,
118
+ * so the plugin sends both.
119
+ */
120
+ export interface ActivationSpecLike extends StartRequestLike {
121
+ /** Registered backend: `spawn` (fresh child) or `fork` (inherits the conversation). */
122
+ readonly provider: string;
123
+ /** Short task label shown with the child. */
124
+ readonly label: string;
125
+ /** Reserved child session id, so the child is bound before it exists. */
126
+ readonly childId: string;
127
+ /** The same task, for hosts before 0.2.2-rc.2. */
128
+ readonly request: StartRequestLike;
129
+ readonly signal: AbortSignal;
130
+ /** `parent`: the runtime notifies the parent model when the child finishes. */
131
+ readonly delivery: 'parent';
132
+ }
133
+ /** `ctx.subagents` (`SubagentRuntime`). */
134
+ export interface SubagentsLike {
135
+ /** Adjacent-agent messaging, for write-access requests. */
136
+ sendMessage(sender: AgentLike, targetId: string, content: TextBlock[], options: {
137
+ signal: AbortSignal;
138
+ }): Promise<unknown>;
139
+ /** Start a managed child; resolves once it is published. */
140
+ startActivation(spec: ActivationSpecLike): Promise<{
141
+ readonly childId: string;
142
+ }>;
143
+ /** The user's delegation depth limit, or undefined when there is none. */
144
+ resolveMaxDepth(): number | undefined;
145
+ /** A registered backend, or undefined. */
146
+ getProvider(name: string): unknown;
147
+ }
148
+ /** `LlmResolvedModelInfo`, reduced to its reasoning levels. */
149
+ export interface ModelInfoLike {
150
+ readonly reasoning?: {
151
+ readonly efforts: readonly {
152
+ readonly id: string;
153
+ }[];
154
+ readonly defaultEffort?: string;
155
+ };
156
+ }
157
+ /** `ctx.llm` (`LlmRuntime`). */
158
+ export interface LlmLike {
159
+ resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<ModelInfoLike>;
160
+ resolveCallConfig(config: RouteLike, signal?: AbortSignal): Promise<unknown>;
161
+ }
162
+ /** `ToolExecution`: the fields the pipeline listeners read. */
163
+ export interface ToolCallLike {
164
+ readonly callId: string;
165
+ readonly name: string;
166
+ readonly arguments: unknown;
167
+ readonly agent?: AgentLike;
168
+ readonly signal: AbortSignal;
169
+ }
170
+ /** This plugin's delegation tools and the backend each starts children on. */
171
+ export declare const DELEGATE_TOOLS: {
172
+ readonly delegate: "spawn";
173
+ readonly delegate_fork: "fork";
174
+ };
175
+ /** A delegation tool name. */
176
+ export type DelegateTool = keyof typeof DELEGATE_TOOLS;
177
+ /** The child's tool for asking its parent. */
178
+ export declare const REQUEST_TOOL = "request_write_access";
179
+ /** The parent's tool for answering a request. */
180
+ export declare const ANSWER_TOOL = "answer_write_request";
181
+ /** The parent's tool for granting without a request. */
182
+ export declare const GRANT_TOOL = "grant_write_access";
183
+ /** The parent's tool for taking grants back. */
184
+ export declare const REVOKE_TOOL = "revoke_write_access";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Structural mirrors of the host services this plugin reads.
3
+ *
4
+ * The plugin imports only `@deepseek-ai/cordis`, `@deepseek-ai/schemastery`, and
5
+ * `@deepseek-ai/dsh-tools` at runtime, so these types mirror only the fields it
6
+ * uses from `@deepseek-ai/dsh-session` (header), `@deepseek-ai/dsh-agent`,
7
+ * `@deepseek-ai/dsh-agent-preset-registry`, `@deepseek-ai/dsh-session-projection`,
8
+ * `@deepseek-ai/dsh-sandbox-policy`, `@deepseek-ai/dsh-working-directory`,
9
+ * `@deepseek-ai/dsh-subagent`, and `@deepseek-ai/dsh-llm`. Each mirror names its
10
+ * source for the next reader, and says so when a field is missing from the
11
+ * oldest supported host, 0.2.1-rc.5.
12
+ * @module complete-subagent/host/types
13
+ */
14
+ /** This plugin's delegation tools and the backend each starts children on. */
15
+ export const DELEGATE_TOOLS = {
16
+ delegate: 'spawn',
17
+ delegate_fork: 'fork',
18
+ };
19
+ /** The child's tool for asking its parent. */
20
+ export const REQUEST_TOOL = 'request_write_access';
21
+ /** The parent's tool for answering a request. */
22
+ export const ANSWER_TOOL = 'answer_write_request';
23
+ /** The parent's tool for granting without a request. */
24
+ export const GRANT_TOOL = 'grant_write_access';
25
+ /** The parent's tool for taking grants back. */
26
+ export const REVOKE_TOOL = 'revoke_write_access';
package/lib/index.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * complete-subagent host plugin.
3
+ *
4
+ * Adds its own delegation tools beside the official ones: `delegate` (a fresh
5
+ * child) and `delegate_fork` (a child that inherits the conversation). The
6
+ * `cwd` a parent passes becomes the child's sub-workspace, `writable_paths`
7
+ * grants more up front, and the child may modify nothing else (besides temp
8
+ * directories). For anything else it asks with `request_write_access`; the
9
+ * parent answers with `answer_write_request`, and can grant or revoke at any
10
+ * time with `grant_write_access` / `revoke_write_access`. A parent may also
11
+ * pick the child's model and reasoning effort among those the user lists in
12
+ * the settings. Children run on the host's subagent runtime; the fence narrows
13
+ * the sandbox policy the host already enforces, and anything a confined agent
14
+ * starts by other means is confined the same way. A bundle that mounts the
15
+ * plugin for its own agent preset sets `presets`, and agents of other presets
16
+ * then see none of it; it may also set `childPreset`, the preset `delegate`
17
+ * children run, `ownModel: false`, which keeps those children on the listed
18
+ * models, and the list itself at run time through the `completeSubagent` service.
19
+ * @module complete-subagent
20
+ */
21
+ import type { Context, Volatile } from '@deepseek-ai/cordis';
22
+ import z from '@deepseek-ai/schemastery';
23
+ import type { ChildModel, ChildModelInput } from './shared/settings.ts';
24
+ export declare const name = "complete-subagent";
25
+ export declare const inject: string[];
26
+ export interface Config {
27
+ /** Seconds a parent has to answer a write-access request before it counts as denied. */
28
+ requestTimeoutSeconds: Volatile<number>;
29
+ /** Models a parent may choose for a child, with the efforts each allows. */
30
+ models: Volatile<ChildModel[]>;
31
+ /** Agent presets whose agents the plugin serves; empty serves every agent. */
32
+ presets: string[];
33
+ /** Agent preset `delegate` children run; empty keeps the parent's. */
34
+ childPreset: string;
35
+ /** False keeps `delegate` children off the parent's own model when models are listed. */
36
+ ownModel: boolean;
37
+ }
38
+ /** `ctx.completeSubagent`: what a bundle that mounts this plugin can change at run time. */
39
+ export interface CompleteSubagentService {
40
+ /**
41
+ * Replace the `models` setting until the row reloads, so call it whenever the
42
+ * service appears. Does nothing on a copy without `childPreset`: that is a
43
+ * standalone install, whose list belongs to the user's normal sessions.
44
+ * @param models - the models a parent may choose for a child, in order.
45
+ */
46
+ setChildModels(models: readonly ChildModelInput[]): void;
47
+ }
48
+ export declare const Config: z<Config>;
49
+ /**
50
+ * Install the fence, the delegation tools, the write-access tools, and the
51
+ * guidance.
52
+ * @param ctx - the plugin context; the services in {@link inject} are present.
53
+ * @param config - loaded settings.
54
+ */
55
+ export declare function apply(ctx: Context, config: Config): void;
package/lib/index.js ADDED
@@ -0,0 +1,245 @@
1
+ /**
2
+ * complete-subagent host plugin.
3
+ *
4
+ * Adds its own delegation tools beside the official ones: `delegate` (a fresh
5
+ * child) and `delegate_fork` (a child that inherits the conversation). The
6
+ * `cwd` a parent passes becomes the child's sub-workspace, `writable_paths`
7
+ * grants more up front, and the child may modify nothing else (besides temp
8
+ * directories). For anything else it asks with `request_write_access`; the
9
+ * parent answers with `answer_write_request`, and can grant or revoke at any
10
+ * time with `grant_write_access` / `revoke_write_access`. A parent may also
11
+ * pick the child's model and reasoning effort among those the user lists in
12
+ * the settings. Children run on the host's subagent runtime; the fence narrows
13
+ * the sandbox policy the host already enforces, and anything a confined agent
14
+ * starts by other means is confined the same way. A bundle that mounts the
15
+ * plugin for its own agent preset sets `presets`, and agents of other presets
16
+ * then see none of it; it may also set `childPreset`, the preset `delegate`
17
+ * children run, `ownModel: false`, which keeps those children on the listed
18
+ * models, and the list itself at run time through the `completeSubagent` service.
19
+ * @module complete-subagent
20
+ */
21
+ 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";
23
+ import { withinCall } from "./host/call-scope.js";
24
+ import { canStart, createDelegateTool } from "./host/delegate.js";
25
+ import { isLegacyHost, ToolRestrictions } from "./host/legacy.js";
26
+ import { Fence, patchResolve } from "./host/policy.js";
27
+ import { childContext, pendingContext } from "./host/prompt.js";
28
+ import { RequestBroker } from "./host/requests.js";
29
+ import { presetScope } from "./host/scope.js";
30
+ import { BindingStore, defaultStoreDirectory } from "./host/store.js";
31
+ 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";
33
+ export const name = PLUGIN_ID;
34
+ export const inject = ['tools', 'subagents', 'sandboxPolicy', 'workingDirectory', 'systemPrompt'];
35
+ export const Config = z.object({
36
+ requestTimeoutSeconds: z.natural().min(MIN_TIMEOUT_SECONDS).default(DEFAULT_TIMEOUT_SECONDS)
37
+ .description('Seconds a parent agent has to answer a write-access request before it counts as denied').volatile(),
38
+ models: z.array(z.object({
39
+ provider: z.string().min(1).required(),
40
+ model: z.string().min(1).required(),
41
+ reasoningEfforts: z.array(z.string().min(1)).default([]),
42
+ })).default([])
43
+ .description('Models a parent may choose for a child; an empty effort list allows every effort the model supports').volatile(),
44
+ presets: z.array(z.string().min(1)).default([])
45
+ .description('Agent presets whose agents get the tools and prompt texts; empty means every preset'),
46
+ childPreset: z.string().default('')
47
+ .description('Agent preset that children started with delegate run; empty keeps the parent\'s. delegate_fork children always keep it'),
48
+ ownModel: z.boolean().default(true)
49
+ .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'),
50
+ });
51
+ /** The agent an assembly is for: `agent` when the host sets it, else the agent scope key. */
52
+ function agentOf(context) {
53
+ if (context.agent !== undefined)
54
+ return context.agent;
55
+ const scope = context.scope;
56
+ return typeof scope?.id === 'string' && scope.session !== undefined ? scope : undefined;
57
+ }
58
+ /** A live config value, or undefined when `apply` was called without the loader. */
59
+ function live(value) {
60
+ return value?.get();
61
+ }
62
+ /**
63
+ * Install the fence, the delegation tools, the write-access tools, and the
64
+ * guidance.
65
+ * @param ctx - the plugin context; the services in {@link inject} are present.
66
+ * @param config - loaded settings.
67
+ */
68
+ export function apply(ctx, config) {
69
+ const host = ctx;
70
+ const timeoutMs = () => readTimeout(live(config?.requestTimeoutSeconds)) * 1000;
71
+ const childPreset = readChildPreset(config?.childPreset);
72
+ let bundleModels;
73
+ const models = () => bundleModels ?? readModels(live(config?.models));
74
+ const serves = presetScope(readPresets(config?.presets), {
75
+ agentPresets: () => host.get('agentPresets'),
76
+ sessionProjections: () => host.get('sessionProjections'),
77
+ });
78
+ const legacy = isLegacyHost(host.tools);
79
+ const store = new BindingStore(defaultStoreDirectory());
80
+ const broker = new RequestBroker();
81
+ const resolvePolicy = (session) => host.sandboxPolicy.resolve({ session });
82
+ const warn = (message) => {
83
+ try {
84
+ ctx.logger.warn(message);
85
+ }
86
+ catch {
87
+ // A host call must not fail because its warning could not be logged.
88
+ }
89
+ };
90
+ // The host calls these for every session of every preset, and a throw would
91
+ // fail a step or stop an agent from starting. A plugin failure stays here.
92
+ const guarded = (label, fallback, run) => {
93
+ try {
94
+ return run();
95
+ }
96
+ catch (error) {
97
+ warn(`${PLUGIN_ID}: ${label} failed: ${String(error)}`);
98
+ return fallback;
99
+ }
100
+ };
101
+ const fence = new Fence({ store, workingDirectory: host.workingDirectory, warn });
102
+ let restore;
103
+ try {
104
+ restore = patchResolve(host.sandboxPolicy, (policy, request) => fence.narrow(policy, request));
105
+ }
106
+ catch (error) {
107
+ warn(`${PLUGIN_ID} is disabled: ${String(error)}`);
108
+ return;
109
+ }
110
+ ctx.effect(() => restore);
111
+ // This listener adds no failure of its own; what `next` throws is the host's pipeline and stays its to handle.
112
+ host.on('tools/execute', (call, next) => withinCall(call, next));
113
+ // A child that a confined agent starts by other means (the official tools,
114
+ // a workflow) shares that agent's access instead of the whole project. Only
115
+ // a served parent passes it on; a child judged without its live parent is
116
+ // judged by its own preset, which it took from that parent. When the parent's
117
+ // preset cannot be read, the child is confined rather than freed.
118
+ host.on('agent/created', ({ agent }) => {
119
+ guarded('storing an inherited binding', undefined, () => {
120
+ const { origin, parentSession } = agent.session.header;
121
+ if (origin !== 'subagent' || parentSession === undefined)
122
+ return;
123
+ if (store.get(agent.id) !== undefined || store.get(parentSession) === undefined)
124
+ return;
125
+ if (!guarded('reading the parent preset', true, () => serves((host.get('agents')?.get(parentSession) ?? agent).session)))
126
+ return;
127
+ store.set({ version: 1, child: agent.id, parent: parentSession, workspace: null, grants: [], inherited: true });
128
+ });
129
+ });
130
+ const tools = Object.keys(DELEGATE_TOOLS);
131
+ const canDelegate = (agent) => serves(agent.session)
132
+ && tools.some(tool => host.tools.get(tool, agent) !== undefined && canStart(host.subagents, tool, agent));
133
+ 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),
136
+ [REQUEST_TOOL]: (agent) => {
137
+ const binding = store.get(agent.id);
138
+ return binding !== undefined && binding.inherited !== true && serves(agent.session);
139
+ },
140
+ [ANSWER_TOOL]: (agent) => canDelegate(agent) || (broker.pendingFor(agent.id).length > 0 && serves(agent.session)),
141
+ [GRANT_TOOL]: canDelegate,
142
+ [REVOKE_TOOL]: canDelegate,
143
+ };
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.
146
+ const deps = {
147
+ store,
148
+ fence,
149
+ broker,
150
+ subagents: host.subagents,
151
+ workingDirectory: host.workingDirectory,
152
+ resolvePolicy,
153
+ timeoutMs,
154
+ llm: () => host.get('llm'),
155
+ childPreset,
156
+ ownModel: readOwnModel(config?.ownModel),
157
+ };
158
+ let mounted;
159
+ const mount = () => {
160
+ const list = models();
161
+ const key = JSON.stringify(list);
162
+ if (mounted?.key === key)
163
+ return;
164
+ // 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
+ });
174
+ };
175
+ mount();
176
+ let disposed = false;
177
+ ctx.effect(() => () => {
178
+ disposed = true;
179
+ mounted?.dispose();
180
+ mounted = undefined;
181
+ });
182
+ host.on('loader/volatile-update', () => {
183
+ guarded('rebuilding the delegation tools', undefined, mount);
184
+ });
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
+ // This host drops `when`, so the same conditions become per-agent filters. A
199
+ // step reads its tools before `agent/pre-step`, so a change seen there takes
200
+ // effect on the agent's next step; a new agent is filtered before its first.
201
+ if (legacy) {
202
+ const restrictions = new ToolRestrictions(Object.keys(conditions), (tool, agent) => visible(tool, agent));
203
+ const sync = (agent) => {
204
+ guarded('updating the tool filter', undefined, () => restrictions.sync(agent));
205
+ };
206
+ ctx.effect(() => () => {
207
+ guarded('lifting the tool filters', undefined, () => restrictions.dispose());
208
+ });
209
+ host.on('agent/created', ({ agent }) => sync(agent));
210
+ host.on('agent/pre-step', ({ agent }, next) => {
211
+ sync(agent);
212
+ return next();
213
+ });
214
+ host.on('agent-preset/selected', (sessionId) => {
215
+ const agent = guarded('finding the agent of a preset selection', undefined, () => host.get('agents')?.get(sessionId));
216
+ if (agent !== undefined)
217
+ sync(agent);
218
+ });
219
+ 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
+ }
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
+ }));
245
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The settings both halves read: which models a parent may choose for a child,
3
+ * which reasoning efforts each allows, and how long a parent has to answer.
4
+ * The host half declares them as live config fields; the browser half edits
5
+ * them on the Plugins page. Only the host half reads `presets`, `childPreset`,
6
+ * and `ownModel`, which a bundle that mounts this plugin sets in its patch.
7
+ * @module complete-subagent/shared/settings
8
+ */
9
+ /** The npm package name: the browser bundle's registration id and the Plugins page key. */
10
+ export declare const PACKAGE_NAME = "@starsharryzhu/complete-subagent";
11
+ /** Bundle row id, settings form id, and plugin name; it keeps the original spelling. */
12
+ export declare const PLUGIN_ID = "complete-subagent";
13
+ /** One model a parent may choose for a child. */
14
+ export interface ChildModel {
15
+ /** Registered LLM provider id. */
16
+ readonly provider: string;
17
+ /** Exact model id within that provider. */
18
+ readonly model: string;
19
+ /** Efforts a parent may choose for it; empty allows every effort the model advertises. */
20
+ readonly reasoningEfforts: readonly string[];
21
+ }
22
+ /** A model as a bundle hands it to the plugin at run time: an omitted effort list allows every effort. */
23
+ export type ChildModelInput = Omit<ChildModel, 'reasoningEfforts'> & {
24
+ readonly reasoningEfforts?: readonly string[];
25
+ };
26
+ /** Seconds a parent has to answer a write-access request, unless the settings say otherwise. */
27
+ export declare const DEFAULT_TIMEOUT_SECONDS = 600;
28
+ /** The shortest answer time the settings accept. */
29
+ export declare const MIN_TIMEOUT_SECONDS = 10;
30
+ /**
31
+ * The id a parent passes as `model`.
32
+ * @param route - provider and model.
33
+ * @returns `provider/model`.
34
+ */
35
+ export declare function modelKey(route: {
36
+ readonly provider: string;
37
+ readonly model: string;
38
+ }): string;
39
+ /**
40
+ * Read a stored model list, dropping malformed entries, repeated models, and
41
+ * repeated efforts.
42
+ * @param value - the stored `models` field.
43
+ * @returns the usable entries in their stored order.
44
+ */
45
+ export declare function readModels(value: unknown): ChildModel[];
46
+ /**
47
+ * Read a stored preset list, dropping anything but non-empty strings and repeats.
48
+ * @param value - the stored `presets` field.
49
+ * @returns the preset ids in their stored order; empty means every preset.
50
+ */
51
+ export declare function readPresets(value: unknown): string[];
52
+ /**
53
+ * Read a stored child preset.
54
+ * @param value - the stored `childPreset` field.
55
+ * @returns the preset id, or undefined when none is set.
56
+ */
57
+ export declare function readChildPreset(value: unknown): string | undefined;
58
+ /**
59
+ * Read the stored `ownModel` flag.
60
+ * @param value - the stored field.
61
+ * @returns false only when the field says so.
62
+ */
63
+ export declare function readOwnModel(value: unknown): boolean;
64
+ /**
65
+ * Read a stored answer time.
66
+ * @param value - the stored `requestTimeoutSeconds` field.
67
+ * @returns whole seconds, at least {@link MIN_TIMEOUT_SECONDS}.
68
+ */
69
+ export declare function readTimeout(value: unknown): number;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The settings both halves read: which models a parent may choose for a child,
3
+ * which reasoning efforts each allows, and how long a parent has to answer.
4
+ * The host half declares them as live config fields; the browser half edits
5
+ * them on the Plugins page. Only the host half reads `presets`, `childPreset`,
6
+ * and `ownModel`, which a bundle that mounts this plugin sets in its patch.
7
+ * @module complete-subagent/shared/settings
8
+ */
9
+ /** The npm package name: the browser bundle's registration id and the Plugins page key. */
10
+ export const PACKAGE_NAME = '@starsharryzhu/complete-subagent';
11
+ /** Bundle row id, settings form id, and plugin name; it keeps the original spelling. */
12
+ export const PLUGIN_ID = 'complete-subagent';
13
+ /** Seconds a parent has to answer a write-access request, unless the settings say otherwise. */
14
+ export const DEFAULT_TIMEOUT_SECONDS = 600;
15
+ /** The shortest answer time the settings accept. */
16
+ export const MIN_TIMEOUT_SECONDS = 10;
17
+ /**
18
+ * The id a parent passes as `model`.
19
+ * @param route - provider and model.
20
+ * @returns `provider/model`.
21
+ */
22
+ export function modelKey(route) {
23
+ return `${route.provider}/${route.model}`;
24
+ }
25
+ /**
26
+ * Read a stored model list, dropping malformed entries, repeated models, and
27
+ * repeated efforts.
28
+ * @param value - the stored `models` field.
29
+ * @returns the usable entries in their stored order.
30
+ */
31
+ export function readModels(value) {
32
+ if (!Array.isArray(value))
33
+ return [];
34
+ const seen = new Set();
35
+ const models = [];
36
+ for (const item of value) {
37
+ if (typeof item !== 'object' || item === null)
38
+ continue;
39
+ const { provider, model, reasoningEfforts } = item;
40
+ if (typeof provider !== 'string' || provider === '' || typeof model !== 'string' || model === '')
41
+ continue;
42
+ const key = modelKey({ provider, model });
43
+ if (seen.has(key))
44
+ continue;
45
+ seen.add(key);
46
+ const efforts = Array.isArray(reasoningEfforts)
47
+ ? [...new Set(reasoningEfforts.filter((effort) => typeof effort === 'string' && effort !== ''))]
48
+ : [];
49
+ models.push({ provider, model, reasoningEfforts: efforts });
50
+ }
51
+ return models;
52
+ }
53
+ /**
54
+ * Read a stored preset list, dropping anything but non-empty strings and repeats.
55
+ * @param value - the stored `presets` field.
56
+ * @returns the preset ids in their stored order; empty means every preset.
57
+ */
58
+ export function readPresets(value) {
59
+ if (!Array.isArray(value))
60
+ return [];
61
+ return [...new Set(value.filter((preset) => typeof preset === 'string' && preset !== ''))];
62
+ }
63
+ /**
64
+ * Read a stored child preset.
65
+ * @param value - the stored `childPreset` field.
66
+ * @returns the preset id, or undefined when none is set.
67
+ */
68
+ export function readChildPreset(value) {
69
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
70
+ }
71
+ /**
72
+ * Read the stored `ownModel` flag.
73
+ * @param value - the stored field.
74
+ * @returns false only when the field says so.
75
+ */
76
+ export function readOwnModel(value) {
77
+ return value !== false;
78
+ }
79
+ /**
80
+ * Read a stored answer time.
81
+ * @param value - the stored `requestTimeoutSeconds` field.
82
+ * @returns whole seconds, at least {@link MIN_TIMEOUT_SECONDS}.
83
+ */
84
+ export function readTimeout(value) {
85
+ return typeof value === 'number' && Number.isInteger(value) && value >= MIN_TIMEOUT_SECONDS ? value : DEFAULT_TIMEOUT_SECONDS;
86
+ }