@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,133 @@
1
+ /**
2
+ * The delegation tools: `delegate` starts a fresh child on the host's `spawn`
3
+ * backend, `delegate_fork` one that inherits this conversation on `fork`.
4
+ *
5
+ * Children run on the host's own subagent runtime, so `send_message`,
6
+ * `list_agents`, `interrupt_agent`, the child conversations in the UI, result
7
+ * notices, and cold resume all work as they do for the official tools. The
8
+ * call decides the child's access and route first, stores the binding under a
9
+ * reserved child id, and only then starts the child, so the fence applies from
10
+ * the child's first step and no binding has to be matched afterwards.
11
+ * @module complete-subagent/host/delegate
12
+ */
13
+ import { randomUUID } from 'node:crypto';
14
+ import { defineTool } from '@deepseek-ai/dsh-tools';
15
+ import { modelKey } from "../shared/settings.js";
16
+ import { decideAccess } from "./access.js";
17
+ import { chooseRoute, describeModels } from "./models.js";
18
+ import { CWD_DESCRIPTION, EFFORT_DESCRIPTION, LISTED_MODEL_DESCRIPTION, MODEL_DESCRIPTION, PROMPT_DESCRIPTION, WRITABLE_PATHS_DESCRIPTION, delegateDescription, } from "./prompt.js";
19
+ import { DELEGATE_TOOLS } from "./types.js";
20
+ /**
21
+ * Build one delegation tool for the current settings. The model list is fixed
22
+ * into the schema, so the entry rebuilds the tools when the settings change.
23
+ * @param tool - which tool.
24
+ * @param models - the settings' model list.
25
+ * @param deps - shared state and services.
26
+ * @returns a registry-ready definition.
27
+ */
28
+ export function createDelegateTool(tool, models, deps) {
29
+ const provider = DELEGATE_TOOLS[tool];
30
+ // A fork continues the parent's conversation, so its own model stays the default there.
31
+ const ownModel = provider === 'spawn' ? deps.ownModel !== false : true;
32
+ return defineTool({
33
+ name: tool,
34
+ description: delegateDescription(tool, describeModels(models, ownModel)),
35
+ parameters: {
36
+ description: {
37
+ type: 'string',
38
+ required: true,
39
+ description: 'A short (3-5 word) description of the delegated task, for display.',
40
+ },
41
+ prompt: { type: 'string', required: true, description: PROMPT_DESCRIPTION[tool] },
42
+ cwd: { type: 'string', description: CWD_DESCRIPTION },
43
+ writable_paths: { type: 'array', items: { type: 'string' }, description: WRITABLE_PATHS_DESCRIPTION },
44
+ ...models.length === 0 ? {} : {
45
+ model: { type: 'string', enum: models.map(modelKey), description: ownModel ? MODEL_DESCRIPTION : LISTED_MODEL_DESCRIPTION },
46
+ },
47
+ reasoning_effort: { type: 'string', description: EFFORT_DESCRIPTION },
48
+ },
49
+ output: {
50
+ schema: {
51
+ type: 'object',
52
+ additionalProperties: false,
53
+ properties: {
54
+ kind: { type: 'string', required: true, const: 'activation' },
55
+ subagentId: { type: 'string', required: true },
56
+ },
57
+ },
58
+ render: (_args, value) => [{ type: 'text', text: `started subagent ${value.subagentId}` }],
59
+ },
60
+ isConcurrencySafe: () => true,
61
+ async execute(raw, exec) {
62
+ const args = raw;
63
+ const parent = exec.agent;
64
+ if (parent === undefined)
65
+ throw new Error(`${tool} requires a calling agent`);
66
+ const access = await decideAccess(deps, { parent, cwd: args.cwd, writablePaths: args.writable_paths, signal: exec.signal });
67
+ const route = await chooseRoute({
68
+ parent,
69
+ models,
70
+ request: { model: args.model, reasoning_effort: args.reasoning_effort },
71
+ llm: deps.llm(),
72
+ signal: exec.signal,
73
+ ownModel,
74
+ });
75
+ exec.signal.throwIfAborted();
76
+ const maxDepth = deps.subagents.resolveMaxDepth();
77
+ // The fork backend inherits the parent's context, so only spawn may select a preset.
78
+ const agentPreset = provider === 'spawn' ? deps.childPreset : undefined;
79
+ const childId = deps.newId?.() ?? randomUUID();
80
+ deps.store.set({ version: 1, child: childId, parent: parent.session.id, workspace: access.workspace, grants: access.grants });
81
+ const task = {
82
+ ...access.cwd === undefined ? {} : { cwd: access.cwd },
83
+ prompt: [{ type: 'text', text: args.prompt }],
84
+ parent,
85
+ ...agentPreset === undefined ? {} : { agentPreset },
86
+ ...route === undefined ? {} : { agentOptions: route },
87
+ ...maxDepth === undefined ? {} : { maxDepth },
88
+ };
89
+ try {
90
+ // The task goes both ways: hosts from 0.2.2-rc.2 read it at the top level and those before under
91
+ // `request`, and neither reads the other's fields, so one call starts the child on every host.
92
+ const started = await deps.subagents.startActivation({
93
+ provider,
94
+ label: args.description,
95
+ childId,
96
+ ...task,
97
+ request: task,
98
+ signal: exec.signal,
99
+ delivery: 'parent',
100
+ });
101
+ return { kind: 'activation', subagentId: started.childId };
102
+ }
103
+ catch (error) {
104
+ deps.store.delete(childId);
105
+ throw error;
106
+ }
107
+ },
108
+ });
109
+ }
110
+ /**
111
+ * Whether an agent may delegate on a backend now: the backend is registered
112
+ * and the agent is below the user's depth limit. A limit that cannot be read
113
+ * leaves the tool visible; the runtime then rejects the start.
114
+ * @param subagents - the subagent runtime.
115
+ * @param tool - which tool.
116
+ * @param agent - the would-be parent.
117
+ * @returns true when the tool should be offered.
118
+ */
119
+ export function canStart(subagents, tool, agent) {
120
+ if (subagents.getProvider(DELEGATE_TOOLS[tool]) === undefined)
121
+ return false;
122
+ let maxDepth;
123
+ try {
124
+ maxDepth = subagents.resolveMaxDepth();
125
+ }
126
+ catch {
127
+ return true;
128
+ }
129
+ if (maxDepth === undefined)
130
+ return true;
131
+ const depth = Math.max(agent.session.header.delegationDepth ?? 0, agent.options?.subagentDepth ?? 0);
132
+ return depth < maxDepth;
133
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Turning model-written paths into grants.
3
+ *
4
+ * Grants come from three places: `writable_paths` on a delegation call, an
5
+ * `answer_write_request` that allows, and `grant_write_access`. All three follow
6
+ * one rule: an agent may grant only what its own, possibly narrowed, policy lets
7
+ * it modify, which makes grants nest — a grandchild's need beyond its parent's
8
+ * reach must first be requested one level up.
9
+ * @module complete-subagent/host/grants
10
+ */
11
+ import type { Fence } from './policy.ts';
12
+ import type { RequestedPath } from './requests.ts';
13
+ import type { BindingStore, Grant } from './store.ts';
14
+ import type { AgentLike, SandboxPolicy } from './types.ts';
15
+ /**
16
+ * Resolve model-written paths against an agent's directory. A path names a
17
+ * directory when it ends in "/" or already is one.
18
+ * @param base - the agent's current directory.
19
+ * @param paths - relative or absolute paths as the model wrote them.
20
+ * @returns canonical paths with their kind.
21
+ */
22
+ export declare function requestedPaths(base: string, paths: readonly string[]): RequestedPath[];
23
+ /** What {@link issueGrants} checks against. */
24
+ export interface IssueOptions {
25
+ readonly fence: Fence;
26
+ readonly store: BindingStore;
27
+ /** The granting agent. */
28
+ readonly grantor: AgentLike;
29
+ /** The grantor's enforced (already narrowed) policy. */
30
+ readonly policy: SandboxPolicy;
31
+ readonly targets: readonly RequestedPath[];
32
+ /** Recorded on each grant: a request id, or `spawn` for `writable_paths`. */
33
+ readonly requestId: string;
34
+ }
35
+ /**
36
+ * Check that the grantor may modify every target, create missing directories,
37
+ * and build the grants. Nothing is created unless every target passes.
38
+ * @param options - grantor, policy, and targets.
39
+ * @returns one grant per target.
40
+ * @throws when a target is beyond the grantor's reach, naming where to ask instead.
41
+ */
42
+ export declare function issueGrants(options: IssueOptions): Grant[];
43
+ /**
44
+ * One granted path as the model reads it.
45
+ * @param grant - the path and its kind.
46
+ * @returns a list line.
47
+ */
48
+ export declare function grantLine(grant: {
49
+ path: string;
50
+ kind: 'dir' | 'file';
51
+ }): string;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Turning model-written paths into grants.
3
+ *
4
+ * Grants come from three places: `writable_paths` on a delegation call, an
5
+ * `answer_write_request` that allows, and `grant_write_access`. All three follow
6
+ * one rule: an agent may grant only what its own, possibly narrowed, policy lets
7
+ * it modify, which makes grants nest — a grandchild's need beyond its parent's
8
+ * reach must first be requested one level up.
9
+ * @module complete-subagent/host/grants
10
+ */
11
+ import { mkdirSync } from 'node:fs';
12
+ import { canonical, namesDirectory, physicalDirectory, resolveFrom } from "./paths.js";
13
+ import { REQUEST_TOOL } from "./types.js";
14
+ /**
15
+ * Resolve model-written paths against an agent's directory. A path names a
16
+ * directory when it ends in "/" or already is one.
17
+ * @param base - the agent's current directory.
18
+ * @param paths - relative or absolute paths as the model wrote them.
19
+ * @returns canonical paths with their kind.
20
+ */
21
+ export function requestedPaths(base, paths) {
22
+ return paths.map((raw) => {
23
+ const path = canonical(resolveFrom(base, raw));
24
+ return { path, directory: namesDirectory(raw) || physicalDirectory(path) !== undefined };
25
+ });
26
+ }
27
+ /**
28
+ * Check that the grantor may modify every target, create missing directories,
29
+ * and build the grants. Nothing is created unless every target passes.
30
+ * @param options - grantor, policy, and targets.
31
+ * @returns one grant per target.
32
+ * @throws when a target is beyond the grantor's reach, naming where to ask instead.
33
+ */
34
+ export function issueGrants(options) {
35
+ const { fence, store, grantor, policy, targets } = options;
36
+ const refused = targets.filter(target => !fence.canModify(policy, grantor.session, target.path, target.directory ? 'dir' : 'file'));
37
+ if (refused.length > 0) {
38
+ const own = store.get(grantor.id);
39
+ const advice = own === undefined
40
+ ? 'They are outside your own sandbox.'
41
+ : own.inherited === true
42
+ ? 'They are outside what the agent above you may modify.'
43
+ : `Request them from your own parent with \`${REQUEST_TOOL}\` first.`;
44
+ throw new Error(`You cannot grant paths you cannot modify yourself: ${refused.map(target => target.path).join(', ')}. ${advice}`);
45
+ }
46
+ const at = Date.now();
47
+ return targets.map((target) => {
48
+ if (target.directory && physicalDirectory(target.path) === undefined)
49
+ mkdirSync(target.path, { recursive: true });
50
+ return { path: canonical(target.path), kind: target.directory ? 'dir' : 'file', requestId: options.requestId, at };
51
+ });
52
+ }
53
+ /**
54
+ * One granted path as the model reads it.
55
+ * @param grant - the path and its kind.
56
+ * @returns a list line.
57
+ */
58
+ export function grantLine(grant) {
59
+ return grant.kind === 'dir'
60
+ ? `- ${grant.path}/ (directory: any tool, including shell commands)`
61
+ : `- ${grant.path} (file: the write and edit tools only)`;
62
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * What the plugin does differently on a host older than 0.2.2-alpha.2, which
3
+ * includes 0.2.1-rc.5, the oldest it supports.
4
+ *
5
+ * Two host features arrived in that release: conditional tools, where
6
+ * `tools.register` takes a `when` the host checks before every step, and
7
+ * `additionalWritableRoots` on the sandbox policy. An older `tools.register`
8
+ * silently drops `when`, so every agent would see all of this plugin's tools;
9
+ * {@link ToolRestrictions} applies the same conditions as per-agent `deny`
10
+ * filters instead. An older sandbox ignores the extra roots, so the fence also
11
+ * moves the root of a granted file-tool call, and shell commands cannot reach
12
+ * grants at all there (see `policy.ts` and `childContext`).
13
+ * @module complete-subagent/host/legacy
14
+ */
15
+ import type { AgentLike } from './types.ts';
16
+ /**
17
+ * Whether this host predates conditional tools. `ToolRuntime.resolve`, which
18
+ * checks each `when`, arrived in the same commit as the option.
19
+ * @param tools - `ctx.tools`.
20
+ * @returns true when `when` would be ignored.
21
+ */
22
+ export declare function isLegacyHost(tools: {
23
+ readonly resolve?: unknown;
24
+ }): boolean;
25
+ /**
26
+ * Keeps each agent's `deny` filter equal to the tools it should not see now.
27
+ * A filter covers the agent it was registered through and not its children,
28
+ * because an agent's scope chain leads to its preset, never to its parent.
29
+ */
30
+ export declare class ToolRestrictions {
31
+ private readonly tools;
32
+ private readonly visible;
33
+ private readonly applied;
34
+ /**
35
+ * @param tools - the tool names under control, all registered globally.
36
+ * @param visible - whether one agent should see one tool now.
37
+ */
38
+ constructor(tools: readonly string[], visible: (tool: string, agent: AgentLike) => boolean);
39
+ /**
40
+ * Bring one agent's filter up to date; a filter that still fits stays, so an
41
+ * unchanged agent causes no tool-change notice. A condition may read the
42
+ * agent's own tool view, which the old filter still narrowed (the parent-only
43
+ * tools ask whether `delegate` is visible), so a change is checked once more.
44
+ * @param agent - a live agent.
45
+ * @throws when the agent has no scoped tools service.
46
+ */
47
+ sync(agent: AgentLike): void;
48
+ /** Apply the current conditions once; returns whether the filter changed. */
49
+ private apply;
50
+ /**
51
+ * Stop tracking a disposed agent; its context already removed the filter.
52
+ * @param agent - the disposed agent.
53
+ */
54
+ forget(agent: AgentLike): void;
55
+ /** Lift every filter, for the plugin's dispose: the filters belong to the agents' contexts, not the plugin's. */
56
+ dispose(): void;
57
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * What the plugin does differently on a host older than 0.2.2-alpha.2, which
3
+ * includes 0.2.1-rc.5, the oldest it supports.
4
+ *
5
+ * Two host features arrived in that release: conditional tools, where
6
+ * `tools.register` takes a `when` the host checks before every step, and
7
+ * `additionalWritableRoots` on the sandbox policy. An older `tools.register`
8
+ * silently drops `when`, so every agent would see all of this plugin's tools;
9
+ * {@link ToolRestrictions} applies the same conditions as per-agent `deny`
10
+ * filters instead. An older sandbox ignores the extra roots, so the fence also
11
+ * moves the root of a granted file-tool call, and shell commands cannot reach
12
+ * grants at all there (see `policy.ts` and `childContext`).
13
+ * @module complete-subagent/host/legacy
14
+ */
15
+ /**
16
+ * Whether this host predates conditional tools. `ToolRuntime.resolve`, which
17
+ * checks each `when`, arrived in the same commit as the option.
18
+ * @param tools - `ctx.tools`.
19
+ * @returns true when `when` would be ignored.
20
+ */
21
+ export function isLegacyHost(tools) {
22
+ return typeof tools.resolve !== 'function';
23
+ }
24
+ /**
25
+ * Keeps each agent's `deny` filter equal to the tools it should not see now.
26
+ * A filter covers the agent it was registered through and not its children,
27
+ * because an agent's scope chain leads to its preset, never to its parent.
28
+ */
29
+ export class ToolRestrictions {
30
+ tools;
31
+ visible;
32
+ applied = new Map();
33
+ /**
34
+ * @param tools - the tool names under control, all registered globally.
35
+ * @param visible - whether one agent should see one tool now.
36
+ */
37
+ constructor(tools, visible) {
38
+ this.tools = tools;
39
+ this.visible = visible;
40
+ }
41
+ /**
42
+ * Bring one agent's filter up to date; a filter that still fits stays, so an
43
+ * unchanged agent causes no tool-change notice. A condition may read the
44
+ * agent's own tool view, which the old filter still narrowed (the parent-only
45
+ * tools ask whether `delegate` is visible), so a change is checked once more.
46
+ * @param agent - a live agent.
47
+ * @throws when the agent has no scoped tools service.
48
+ */
49
+ sync(agent) {
50
+ if (this.apply(agent))
51
+ this.apply(agent);
52
+ }
53
+ /** Apply the current conditions once; returns whether the filter changed. */
54
+ apply(agent) {
55
+ const hidden = this.tools.filter(tool => !this.visible(tool, agent));
56
+ const key = hidden.join();
57
+ const current = this.applied.get(agent);
58
+ if ((current?.hidden ?? '') === key)
59
+ return false;
60
+ const scoped = agent.ctx?.tools;
61
+ if (scoped === undefined)
62
+ throw new Error(`agent ${agent.id} has no scoped tools service`);
63
+ // The new filter goes in first: if it throws, the old one still holds.
64
+ const lift = hidden.length === 0 ? undefined : scoped.restrict({ deny: hidden });
65
+ current?.lift();
66
+ if (lift === undefined)
67
+ this.applied.delete(agent);
68
+ else
69
+ this.applied.set(agent, { hidden: key, lift });
70
+ return true;
71
+ }
72
+ /**
73
+ * Stop tracking a disposed agent; its context already removed the filter.
74
+ * @param agent - the disposed agent.
75
+ */
76
+ forget(agent) {
77
+ this.applied.delete(agent);
78
+ }
79
+ /** Lift every filter, for the plugin's dispose: the filters belong to the agents' contexts, not the plugin's. */
80
+ dispose() {
81
+ for (const { lift } of this.applied.values())
82
+ lift();
83
+ this.applied.clear();
84
+ }
85
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Choosing a child's model and reasoning effort.
3
+ *
4
+ * A parent keeps its own model unless it names one the user listed in the
5
+ * settings. A listed model allows the efforts listed with it, or every effort
6
+ * it advertises when none are listed; the parent's own model, when it is not
7
+ * listed, allows every effort it advertises. An omitted effort keeps the
8
+ * parent's effort on the parent's model; on another model it is that model's
9
+ * default, or the first listed effort when the default is not among them.
10
+ *
11
+ * With `ownModel` off and models listed, only the listed models run: an omitted
12
+ * model is the first one, an effort-only call sets that model's effort, and an
13
+ * omitted effort never comes from the parent, even when the parent runs the
14
+ * same model. An empty list leaves the rules above.
15
+ * @module complete-subagent/host/models
16
+ */
17
+ import type { ChildModel } from '../shared/settings.ts';
18
+ import type { AgentLike, LlmLike } from './types.ts';
19
+ /** A route with its provider and model known. */
20
+ export interface Route {
21
+ readonly provider: string;
22
+ readonly model: string;
23
+ readonly reasoningEffort?: string;
24
+ }
25
+ /** The model-facing selection fields of one delegation call, unvalidated. */
26
+ export interface ModelRequest {
27
+ readonly model?: unknown;
28
+ readonly reasoning_effort?: unknown;
29
+ }
30
+ /**
31
+ * The route an agent's next request uses, as the host hands it to a child
32
+ * (`parentAgentOptionsForDelegation`): the session's request header once it
33
+ * has one, the agent's creation options before.
34
+ * @param agent - the parent.
35
+ * @returns its route, or undefined when the provider or model is unknown.
36
+ */
37
+ export declare function routeOf(agent: AgentLike): Route | undefined;
38
+ /**
39
+ * Validate one call's model and effort and turn them into child options.
40
+ * @param options - the parent, the settings list, the call's fields, the LLM runtime, and the `ownModel` rule.
41
+ * @returns the child's route, or undefined when the call selects nothing and the child inherits the parent's route.
42
+ * @throws with a model-facing reason naming the allowed choices.
43
+ */
44
+ export declare function chooseRoute(options: {
45
+ readonly parent: AgentLike;
46
+ readonly models: readonly ChildModel[];
47
+ readonly request: ModelRequest;
48
+ readonly llm: LlmLike | undefined;
49
+ readonly signal?: AbortSignal;
50
+ /** False keeps the child off the parent's own model when models are listed. */
51
+ readonly ownModel?: boolean;
52
+ }): Promise<Route | undefined>;
53
+ /**
54
+ * The model-selection paragraph of a delegation tool's description.
55
+ * @param models - the settings list.
56
+ * @param ownModel - false keeps the child off the parent's own model when models are listed.
57
+ * @returns the text the parent reads.
58
+ */
59
+ export declare function describeModels(models: readonly ChildModel[], ownModel?: boolean): string;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Choosing a child's model and reasoning effort.
3
+ *
4
+ * A parent keeps its own model unless it names one the user listed in the
5
+ * settings. A listed model allows the efforts listed with it, or every effort
6
+ * it advertises when none are listed; the parent's own model, when it is not
7
+ * listed, allows every effort it advertises. An omitted effort keeps the
8
+ * parent's effort on the parent's model; on another model it is that model's
9
+ * default, or the first listed effort when the default is not among them.
10
+ *
11
+ * With `ownModel` off and models listed, only the listed models run: an omitted
12
+ * model is the first one, an effort-only call sets that model's effort, and an
13
+ * omitted effort never comes from the parent, even when the parent runs the
14
+ * same model. An empty list leaves the rules above.
15
+ * @module complete-subagent/host/models
16
+ */
17
+ import { modelKey } from "../shared/settings.js";
18
+ /**
19
+ * The route an agent's next request uses, as the host hands it to a child
20
+ * (`parentAgentOptionsForDelegation`): the session's request header once it
21
+ * has one, the agent's creation options before.
22
+ * @param agent - the parent.
23
+ * @returns its route, or undefined when the provider or model is unknown.
24
+ */
25
+ export function routeOf(agent) {
26
+ const source = agent.session.requestHeader?.()?.config ?? agent.options ?? {};
27
+ if (source.provider === undefined || source.model === undefined)
28
+ return undefined;
29
+ return {
30
+ provider: source.provider,
31
+ model: source.model,
32
+ ...source.reasoningEffort === undefined ? {} : { reasoningEffort: source.reasoningEffort },
33
+ };
34
+ }
35
+ /** The choices as one line for an error message. */
36
+ function choicesLine(models) {
37
+ return models.length === 0 ? 'none are listed in the settings' : models.map(modelKey).join(', ');
38
+ }
39
+ /** Read one optional non-empty string field. */
40
+ function optionalId(value, field) {
41
+ if (value === undefined)
42
+ return undefined;
43
+ if (typeof value !== 'string' || value.trim() === '')
44
+ throw new Error(`\`${field}\` must be a non-empty id`);
45
+ return value.trim();
46
+ }
47
+ /**
48
+ * Validate one call's model and effort and turn them into child options.
49
+ * @param options - the parent, the settings list, the call's fields, the LLM runtime, and the `ownModel` rule.
50
+ * @returns the child's route, or undefined when the call selects nothing and the child inherits the parent's route.
51
+ * @throws with a model-facing reason naming the allowed choices.
52
+ */
53
+ export async function chooseRoute(options) {
54
+ const named = optionalId(options.request.model, 'model');
55
+ const effort = optionalId(options.request.reasoning_effort, 'reasoning_effort');
56
+ const onlyListed = options.ownModel === false && options.models.length > 0;
57
+ if (named === undefined && effort === undefined && !onlyListed)
58
+ return undefined;
59
+ const own = routeOf(options.parent);
60
+ const listed = (key) => options.models.find(entry => modelKey(entry) === key);
61
+ let route;
62
+ if (onlyListed) {
63
+ const entry = named === undefined ? options.models[0] : listed(named);
64
+ if (entry === undefined)
65
+ throw new Error(`Model "${named}" is not offered for subagents. Choose one of: ${choicesLine(options.models)}; or omit \`model\` to use the first.`);
66
+ route = entry;
67
+ }
68
+ else if (named === undefined || (own !== undefined && named === modelKey(own))) {
69
+ if (own === undefined)
70
+ throw new Error('Your own model is not known yet, so the child\'s reasoning effort cannot be set; omit `reasoning_effort`.');
71
+ route = own;
72
+ }
73
+ else {
74
+ const entry = listed(named);
75
+ if (entry === undefined)
76
+ throw new Error(`Model "${named}" is not offered for subagents. Choose one of: ${choicesLine(options.models)}; or omit \`model\` to use your own.`);
77
+ route = entry;
78
+ }
79
+ const key = modelKey(route);
80
+ const sameRoute = own !== undefined && modelKey(own) === key;
81
+ const allowed = listed(key)?.reasoningEfforts ?? [];
82
+ const llm = options.llm;
83
+ if (llm === undefined)
84
+ throw new Error('The child model cannot be checked because the `llm` service is unavailable.');
85
+ let chosen = effort;
86
+ if (effort !== undefined) {
87
+ const offered = allowed.length > 0
88
+ ? allowed
89
+ : (await llm.resolveModelInfo(route.provider, route.model, options.signal)).reasoning?.efforts.map(item => item.id) ?? [];
90
+ if (!offered.includes(effort)) {
91
+ throw new Error(offered.length === 0
92
+ ? `${key} has no selectable reasoning effort; omit \`reasoning_effort\`.`
93
+ : `Reasoning effort "${effort}" is not offered for ${key}. Choose one of: ${offered.join(', ')}.`);
94
+ }
95
+ }
96
+ else if (sameRoute ? onlyListed : allowed.length > 0) {
97
+ const fallback = (await llm.resolveModelInfo(route.provider, route.model, options.signal)).reasoning?.defaultEffort;
98
+ if (allowed.length > 0 && (fallback === undefined || !allowed.includes(fallback)))
99
+ chosen = allowed[0];
100
+ // On the parent's own route the host keeps the parent's effort unless one is named.
101
+ else if (sameRoute)
102
+ chosen = fallback;
103
+ }
104
+ const reasoningEffort = chosen ?? (sameRoute ? own?.reasoningEffort : undefined);
105
+ await llm.resolveCallConfig({
106
+ provider: route.provider,
107
+ model: route.model,
108
+ ...reasoningEffort === undefined ? {} : { reasoningEffort },
109
+ }, options.signal);
110
+ return { provider: route.provider, model: route.model, ...chosen === undefined ? {} : { reasoningEffort: chosen } };
111
+ }
112
+ /**
113
+ * The model-selection paragraph of a delegation tool's description.
114
+ * @param models - the settings list.
115
+ * @param ownModel - false keeps the child off the parent's own model when models are listed.
116
+ * @returns the text the parent reads.
117
+ */
118
+ export function describeModels(models, ownModel = true) {
119
+ const efforts = (entry) => entry.reasoningEfforts.length === 0
120
+ ? 'any effort it supports'
121
+ : `efforts ${entry.reasoningEfforts.join(', ')}`;
122
+ if (models.length === 0) {
123
+ return 'Model: the child uses your own model. `reasoning_effort` may be any effort your model supports; omitted, the child keeps your current effort.';
124
+ }
125
+ if (!ownModel) {
126
+ return [
127
+ 'Model: the child runs one of these models, never your own. Omit `model` to use the first; `reasoning_effort` applies to the model the child runs.',
128
+ ...models.map(entry => `- ${modelKey(entry)}: ${efforts(entry)}`),
129
+ 'An omitted effort uses the model\'s default, or its first listed effort when the default is not listed.',
130
+ ].join('\n');
131
+ }
132
+ return [
133
+ 'Model: omit `model` to give the child your own model; `reasoning_effort` may then be any effort your model supports '
134
+ + '(only the listed ones if your model is listed below), and an omitted effort keeps your current one.',
135
+ 'Other models you may choose with `model`:',
136
+ ...models.map(entry => `- ${modelKey(entry)}: ${efforts(entry)}`),
137
+ 'On another model, an omitted effort uses that model\'s default, or its first listed effort when the default is not listed.',
138
+ ].join('\n');
139
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Path helpers shared by the fence, the spawn binder, and the request tools.
3
+ *
4
+ * Every path the plugin stores or compares is canonical: absolute, with the
5
+ * longest existing prefix resolved through `realpath` (so `/tmp` is
6
+ * `/private/tmp` on darwin, as in the host's own sandbox roots) and any missing
7
+ * suffix appended as spelled. Comparing canonical paths is what the host's fs
8
+ * fence and Seatbelt profile do, so a decision made here matches the one they
9
+ * enforce.
10
+ * @module complete-subagent/host/paths
11
+ */
12
+ /**
13
+ * Resolve a model-supplied path against a base directory. `~` and `~/…` name the
14
+ * user's home, as the host's file tools accept.
15
+ * @param base - absolute directory relative paths start from.
16
+ * @param path - the path as the model wrote it.
17
+ * @returns an absolute, lexically normalized path.
18
+ */
19
+ export declare function resolveFrom(base: string, path: string): string;
20
+ /**
21
+ * The canonical spelling of a path that may not exist yet.
22
+ * @param path - an absolute path.
23
+ * @returns the realpath of its longest existing prefix plus the missing rest.
24
+ */
25
+ export declare function canonical(path: string): string;
26
+ /**
27
+ * Whether `path` is `root` or lies below it. Both must be canonical.
28
+ * @param path - candidate path.
29
+ * @param root - containing directory.
30
+ * @returns true when contained.
31
+ */
32
+ export declare function isUnder(path: string, root: string): boolean;
33
+ /**
34
+ * The physical directory a path names right now, as the host accepts it for an
35
+ * additional writable root: existing, a directory, and spelled without symlinks.
36
+ * @param path - a canonical path.
37
+ * @returns the path when it qualifies, otherwise undefined.
38
+ */
39
+ export declare function physicalDirectory(path: string): string | undefined;
40
+ /**
41
+ * The deepest existing directory at or above a path.
42
+ * @param path - an absolute path.
43
+ * @returns a physical directory that exists.
44
+ */
45
+ export declare function nearestDirectory(path: string): string;
46
+ /**
47
+ * Whether a model-written path asks for a whole directory: it ends in a separator.
48
+ * @param path - the path as written.
49
+ * @returns true for `dir/` spellings.
50
+ */
51
+ export declare function namesDirectory(path: string): boolean;