@starsharryzhu/complete-subagent 0.0.0-stage → 0.1.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.
Files changed (68) hide show
  1. package/AGENTS.md +52 -0
  2. package/LICENSE +21 -0
  3. package/README.md +166 -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 +129 -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 +176 -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 +87 -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 +51 -0
  52. package/src/host/access.ts +82 -0
  53. package/src/host/call-scope.ts +31 -0
  54. package/src/host/delegate.ts +162 -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 +183 -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,44 @@
1
+ /* complete-subagent settings page. Colors come from the host's design tokens. */
2
+ .complete-subagent-settings { display: flex; flex-direction: column; gap: 16px; font-size: 13px; }
3
+ .complete-subagent-section { display: flex; flex-direction: column; gap: 8px; }
4
+ .complete-subagent-section h3 { margin: 0; font-size: 14px; font-weight: 600; }
5
+ .complete-subagent-note { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 12px; font-weight: 400; }
6
+ .complete-subagent-error { color: var(--dsw-alias-state-error-primary); font-size: 12px; }
7
+
8
+ .complete-subagent-models { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 8px; }
9
+ .complete-subagent-model {
10
+ display: flex; flex-direction: column; gap: 8px; padding: 10px 12px;
11
+ border: 1px solid var(--dsw-alias-border-l2); border-radius: 10px; background: var(--dsw-alias-bg-layer-2);
12
+ }
13
+ .complete-subagent-model-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
14
+ .complete-subagent-model-name { font-weight: 500; }
15
+ .complete-subagent-model-head code { color: var(--dsw-alias-label-secondary); font-size: 12px; overflow-wrap: anywhere; }
16
+ .complete-subagent-model-head .complete-subagent-button { margin-left: auto; }
17
+ .complete-subagent-tag {
18
+ padding: 0 6px; border-radius: 6px; font-size: 11px; line-height: 18px;
19
+ color: var(--dsw-alias-state-error-primary); border: 1px solid currentColor;
20
+ }
21
+
22
+ .complete-subagent-efforts { margin: 0; padding: 0; border: 0; display: flex; gap: 6px 14px; flex-wrap: wrap; }
23
+ .complete-subagent-efforts legend { padding: 0; margin-bottom: 4px; font-weight: 500; display: flex; gap: 8px; align-items: baseline; }
24
+ .complete-subagent-check { display: inline-flex; align-items: center; gap: 5px; cursor: pointer; }
25
+
26
+ .complete-subagent-add { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
27
+ .complete-subagent-field { display: flex; flex-direction: column; gap: 4px; max-width: 360px; }
28
+ .complete-subagent-field span { font-weight: 500; }
29
+ .complete-subagent-add select, .complete-subagent-field input {
30
+ padding: 5px 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px;
31
+ background: var(--dsw-alias-bg-layer-2); color: inherit; font: inherit; max-width: 100%;
32
+ }
33
+
34
+ .complete-subagent-button {
35
+ display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border: 0; border-radius: 7px;
36
+ background: transparent; color: inherit; font: inherit; cursor: pointer;
37
+ }
38
+ .complete-subagent-button:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
39
+ .complete-subagent-button[data-primary] { border: 1px solid var(--dsw-alias-border-l4); }
40
+ .complete-subagent-button:disabled { opacity: 0.5; cursor: default; }
41
+ .complete-subagent-button:focus-visible {
42
+ outline: 2px solid var(--dsw-alias-state-business-primary, var(--dsw-alias-label-primary)); outline-offset: -2px;
43
+ }
44
+ .complete-subagent-actions { display: flex; align-items: center; gap: 10px; }
@@ -0,0 +1,51 @@
1
+ # AGENTS.md
2
+
3
+ ## 1. Role
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`.
6
+
7
+ ## 2. Constraints
8
+
9
+ - All stored and compared paths are canonical (`paths.ts`), matching what the host's fs fence and Seatbelt profile compare.
10
+ - Additional writable roots must be existing physical directories, or the host rejects the whole policy; the fence drops anything else.
11
+ - 0.2.1-rc.5 reads only `workspaceRoot`, so the one file-tool call whose target lies in a grant is rooted at that grant; every other call keeps the sub-workspace, which is why shell commands cannot reach grants there.
12
+ - An agent may grant only what its own, possibly narrowed, policy lets it modify.
13
+ - A child's binding is stored before its start call and deleted if the start fails, so the fence applies from its first step and nothing is matched afterwards.
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
+ - The delegation result text is `started subagent <id>`, as the official tools write it.
16
+ - Only a `spawn` start carries the configured `childPreset` as `agentPreset`; a `fork` start never selects a preset.
17
+ - 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
+ - `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
+ - 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.
21
+ - 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.
22
+ - 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
+ - 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
+ - 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.
25
+ - No module imports a host package other than `@deepseek-ai/dsh-tools`; host shapes come from `types.ts`.
26
+
27
+ ## 3. Contents
28
+
29
+ - `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.
31
+ - `legacy.ts` — detecting a host older than 0.2.2-alpha.2, and the per-agent tool filters that replace `when` there.
32
+ - `paths.ts` — resolving, canonicalizing, and comparing paths.
33
+ - `store.ts` — per-child bindings and grants as JSON files under the DSH home.
34
+ - `call-scope.ts` — the running tool call, carried through async work.
35
+ - `policy.ts` — the fence: policy narrowing, the root of a granted file-tool call, inherited access, "may modify" checks, and the prototype patch.
36
+ - `access.ts` — the sub-workspace and `writable_paths` grants of a child about to start.
37
+ - `models.ts` — the parent's route, the child's model and effort choice under the settings and `ownModel`, and its description.
38
+ - `delegate.ts` — the `delegate` and `delegate_fork` tools, the child preset and the `ownModel` rule of a `delegate` start, and when they are offered.
39
+ - `grants.ts` — resolving requested paths and issuing grants within the grantor's reach.
40
+ - `requests.ts` — open write-access requests, answers, timeouts, and cancellation.
41
+ - `tools.ts` — `request_write_access`, `answer_write_request`, `grant_write_access`, and `revoke_write_access`.
42
+ - `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
+
44
+ ## 4. Progress
45
+
46
+ - Done: every module, covered by the specs in the tests folder.
47
+ - 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
+ - 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
+ - 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.
50
+ - Open: `delegate.ts`, `models.ts`, `scope.ts`, `legacy.ts`, and inherited confinement are not yet verified in a real web app.
51
+ - Goal later: nothing planned.
@@ -0,0 +1,82 @@
1
+ /**
2
+ * What a new child may modify, decided from the delegation call's `cwd` and
3
+ * `writable_paths` before the child exists.
4
+ *
5
+ * A `cwd` the parent may modify becomes the child's sub-workspace and is created
6
+ * if missing; no `cwd`, or one outside the parent's writable area, gives the
7
+ * child none. `writable_paths` become grants, checked against the parent's own
8
+ * reach, so nothing outside it can be handed down.
9
+ * @module complete-subagent/host/access
10
+ */
11
+
12
+ import { mkdirSync } from 'node:fs'
13
+ import { issueGrants, requestedPaths } from './grants.ts'
14
+ import { canonical, resolveFrom } from './paths.ts'
15
+ import type { Fence } from './policy.ts'
16
+ import type { BindingStore, Grant } from './store.ts'
17
+ import type { AgentLike, SandboxPolicy, SessionLike, WorkingDirectoryLike } from './types.ts'
18
+
19
+ /** What {@link decideAccess} reads. */
20
+ export interface AccessDeps {
21
+ readonly store: BindingStore
22
+ readonly fence: Fence
23
+ readonly workingDirectory: WorkingDirectoryLike
24
+ /** The session's enforced (already narrowed) sandbox policy. */
25
+ readonly resolvePolicy: (session: SessionLike) => SandboxPolicy
26
+ }
27
+
28
+ /** One delegation call's access arguments, unvalidated. */
29
+ export interface AccessRequest {
30
+ readonly parent: AgentLike
31
+ readonly cwd: unknown
32
+ readonly writablePaths: unknown
33
+ readonly signal?: AbortSignal
34
+ }
35
+
36
+ /** The decided access of a child that is about to start. */
37
+ export interface ChildAccess {
38
+ /** Directory to start the child in; undefined inherits the parent's. */
39
+ readonly cwd?: string
40
+ /** Canonical sub-workspace, or null for none. */
41
+ readonly workspace: string | null
42
+ /** Grants from `writable_paths`. */
43
+ readonly grants: readonly Grant[]
44
+ }
45
+
46
+ /**
47
+ * Decide a new child's sub-workspace and grants, creating the sub-workspace and
48
+ * any granted directory that does not exist yet.
49
+ * @param deps - store, fence, and host services.
50
+ * @param request - the call's parent and arguments.
51
+ * @returns the child's access and start directory.
52
+ * @throws with a model-facing reason when the call must not run.
53
+ */
54
+ export async function decideAccess(deps: AccessDeps, request: AccessRequest): Promise<ChildAccess> {
55
+ const { parent } = request
56
+ const writable = request.writablePaths ?? []
57
+ if (!Array.isArray(writable) || writable.some(path => typeof path !== 'string' || path.trim() === '')) {
58
+ throw new Error('writable_paths must be a list of paths')
59
+ }
60
+ if (request.cwd !== undefined && typeof request.cwd !== 'string') throw new Error('cwd must be a path')
61
+ const base = await deps.workingDirectory.ensure(parent, request.signal)
62
+ const policy = deps.resolvePolicy(parent.session)
63
+ const grants = issueGrants({
64
+ fence: deps.fence,
65
+ store: deps.store,
66
+ grantor: parent,
67
+ policy,
68
+ targets: requestedPaths(base, writable as string[]),
69
+ requestId: 'spawn',
70
+ })
71
+ if (request.cwd === undefined || request.cwd.trim() === '') return { workspace: null, grants }
72
+ const target = canonical(resolveFrom(base, request.cwd))
73
+ if (!deps.fence.canModify(policy, parent.session, target, 'dir')) return { cwd: target, workspace: null, grants }
74
+ try {
75
+ mkdirSync(target, { recursive: true })
76
+ } catch {
77
+ // Not a directory (or not creatable): the host reports it when the child starts.
78
+ return { cwd: target, workspace: null, grants }
79
+ }
80
+ const workspace = canonical(target)
81
+ return { cwd: workspace, workspace, grants }
82
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The tool call whose body is running, for code that the body reaches only
3
+ * indirectly. The sandbox policy is resolved deep inside a tool body with just a
4
+ * session, so a single-file grant can only be honored if the fence can see which
5
+ * call, and which target, asked. A `tools/execute` waterfall listener enters this
6
+ * scope around each body; async work started by the body inherits it.
7
+ * @module complete-subagent/host/call-scope
8
+ */
9
+
10
+ import { AsyncLocalStorage } from 'node:async_hooks'
11
+ import type { ToolCallLike } from './types.ts'
12
+
13
+ const storage = new AsyncLocalStorage<ToolCallLike>()
14
+
15
+ /**
16
+ * The call whose body is running in this async context.
17
+ * @returns the call, or undefined outside a tool body.
18
+ */
19
+ export function currentCall(): ToolCallLike | undefined {
20
+ return storage.getStore()
21
+ }
22
+
23
+ /**
24
+ * Run a tool body inside the scope of its call.
25
+ * @param call - the dispatching call.
26
+ * @param run - the body (the waterfall's `next`).
27
+ * @returns whatever the body returns.
28
+ */
29
+ export function withinCall<T>(call: ToolCallLike, run: () => T): T {
30
+ return storage.run(call, run)
31
+ }
@@ -0,0 +1,162 @@
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
+
14
+ import { randomUUID } from 'node:crypto'
15
+ import { defineTool } from '@deepseek-ai/dsh-tools'
16
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
17
+ import { modelKey } from '../shared/settings.ts'
18
+ import type { ChildModel } from '../shared/settings.ts'
19
+ import { decideAccess } from './access.ts'
20
+ import type { AccessDeps } from './access.ts'
21
+ import { chooseRoute, describeModels } from './models.ts'
22
+ import {
23
+ CWD_DESCRIPTION,
24
+ EFFORT_DESCRIPTION,
25
+ LISTED_MODEL_DESCRIPTION,
26
+ MODEL_DESCRIPTION,
27
+ PROMPT_DESCRIPTION,
28
+ WRITABLE_PATHS_DESCRIPTION,
29
+ delegateDescription,
30
+ } from './prompt.ts'
31
+ import { DELEGATE_TOOLS } from './types.ts'
32
+ import type { AgentLike, DelegateTool, LlmLike, SubagentsLike } from './types.ts'
33
+
34
+ /** What the delegation tools read. */
35
+ export interface DelegateDeps extends AccessDeps {
36
+ readonly subagents: SubagentsLike
37
+ /** The LLM runtime, read at call time because it is optional. */
38
+ readonly llm: () => LlmLike | undefined
39
+ /** Reserves child ids; replaceable in tests. */
40
+ readonly newId?: () => string
41
+ /** Agent preset a `delegate` child runs; undefined keeps the parent's. */
42
+ readonly childPreset?: string
43
+ /** False keeps a `delegate` child off the parent's own model when models are listed. */
44
+ readonly ownModel?: boolean
45
+ }
46
+
47
+ /** The arguments of one delegation call. */
48
+ interface DelegateArgs {
49
+ readonly description: string
50
+ readonly prompt: string
51
+ readonly cwd?: string
52
+ readonly writable_paths?: string[]
53
+ readonly model?: string
54
+ readonly reasoning_effort?: string
55
+ }
56
+
57
+ /**
58
+ * Build one delegation tool for the current settings. The model list is fixed
59
+ * into the schema, so the entry rebuilds the tools when the settings change.
60
+ * @param tool - which tool.
61
+ * @param models - the settings' model list.
62
+ * @param deps - shared state and services.
63
+ * @returns a registry-ready definition.
64
+ */
65
+ export function createDelegateTool(tool: DelegateTool, models: readonly ChildModel[], deps: DelegateDeps): ToolDefinition {
66
+ const provider = DELEGATE_TOOLS[tool]
67
+ // A fork continues the parent's conversation, so its own model stays the default there.
68
+ const ownModel = provider === 'spawn' ? deps.ownModel !== false : true
69
+ return defineTool({
70
+ name: tool,
71
+ description: delegateDescription(tool, describeModels(models, ownModel)),
72
+ parameters: {
73
+ description: {
74
+ type: 'string',
75
+ required: true,
76
+ description: 'A short (3-5 word) description of the delegated task, for display.',
77
+ },
78
+ prompt: { type: 'string', required: true, description: PROMPT_DESCRIPTION[tool] },
79
+ cwd: { type: 'string', description: CWD_DESCRIPTION },
80
+ writable_paths: { type: 'array', items: { type: 'string' }, description: WRITABLE_PATHS_DESCRIPTION },
81
+ ...models.length === 0 ? {} : {
82
+ model: { type: 'string' as const, enum: models.map(modelKey), description: ownModel ? MODEL_DESCRIPTION : LISTED_MODEL_DESCRIPTION },
83
+ },
84
+ reasoning_effort: { type: 'string', description: EFFORT_DESCRIPTION },
85
+ },
86
+ output: {
87
+ schema: {
88
+ type: 'object',
89
+ additionalProperties: false,
90
+ properties: {
91
+ kind: { type: 'string', required: true, const: 'activation' },
92
+ subagentId: { type: 'string', required: true },
93
+ },
94
+ },
95
+ render: (_args, value) => [{ type: 'text', text: `started subagent ${value.subagentId}` }],
96
+ },
97
+ isConcurrencySafe: () => true,
98
+ async execute(raw, exec) {
99
+ const args = raw as DelegateArgs
100
+ const parent = exec.agent as AgentLike | undefined
101
+ if (parent === undefined) throw new Error(`${tool} requires a calling agent`)
102
+ const access = await decideAccess(deps, { parent, cwd: args.cwd, writablePaths: args.writable_paths, signal: exec.signal })
103
+ const route = await chooseRoute({
104
+ parent,
105
+ models,
106
+ request: { model: args.model, reasoning_effort: args.reasoning_effort },
107
+ llm: deps.llm(),
108
+ signal: exec.signal,
109
+ ownModel,
110
+ })
111
+ exec.signal.throwIfAborted()
112
+ const maxDepth = deps.subagents.resolveMaxDepth()
113
+ // The fork backend inherits the parent's context, so only spawn may select a preset.
114
+ const agentPreset = provider === 'spawn' ? deps.childPreset : undefined
115
+ const childId = deps.newId?.() ?? randomUUID()
116
+ deps.store.set({ version: 1, child: childId, parent: parent.session.id, workspace: access.workspace, grants: access.grants })
117
+ try {
118
+ const started = await deps.subagents.startActivation({
119
+ provider,
120
+ label: args.description,
121
+ childId,
122
+ request: {
123
+ ...access.cwd === undefined ? {} : { cwd: access.cwd },
124
+ prompt: [{ type: 'text', text: args.prompt }],
125
+ parent,
126
+ ...agentPreset === undefined ? {} : { agentPreset },
127
+ ...route === undefined ? {} : { agentOptions: route },
128
+ ...maxDepth === undefined ? {} : { maxDepth },
129
+ },
130
+ signal: exec.signal,
131
+ delivery: 'parent',
132
+ })
133
+ return { kind: 'activation' as const, subagentId: started.childId }
134
+ } catch (error) {
135
+ deps.store.delete(childId)
136
+ throw error
137
+ }
138
+ },
139
+ })
140
+ }
141
+
142
+ /**
143
+ * Whether an agent may delegate on a backend now: the backend is registered
144
+ * and the agent is below the user's depth limit. A limit that cannot be read
145
+ * leaves the tool visible; the runtime then rejects the start.
146
+ * @param subagents - the subagent runtime.
147
+ * @param tool - which tool.
148
+ * @param agent - the would-be parent.
149
+ * @returns true when the tool should be offered.
150
+ */
151
+ export function canStart(subagents: SubagentsLike, tool: DelegateTool, agent: AgentLike): boolean {
152
+ if (subagents.getProvider(DELEGATE_TOOLS[tool]) === undefined) return false
153
+ let maxDepth: number | undefined
154
+ try {
155
+ maxDepth = subagents.resolveMaxDepth()
156
+ } catch {
157
+ return true
158
+ }
159
+ if (maxDepth === undefined) return true
160
+ const depth = Math.max(agent.session.header.delegationDepth ?? 0, agent.options?.subagentDepth ?? 0)
161
+ return depth < maxDepth
162
+ }
@@ -0,0 +1,82 @@
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
+
12
+ import { mkdirSync } from 'node:fs'
13
+ import { canonical, namesDirectory, physicalDirectory, resolveFrom } from './paths.ts'
14
+ import type { Fence } from './policy.ts'
15
+ import type { RequestedPath } from './requests.ts'
16
+ import type { BindingStore, Grant } from './store.ts'
17
+ import { REQUEST_TOOL } from './types.ts'
18
+ import type { AgentLike, SandboxPolicy } from './types.ts'
19
+
20
+ /**
21
+ * Resolve model-written paths against an agent's directory. A path names a
22
+ * directory when it ends in "/" or already is one.
23
+ * @param base - the agent's current directory.
24
+ * @param paths - relative or absolute paths as the model wrote them.
25
+ * @returns canonical paths with their kind.
26
+ */
27
+ export function requestedPaths(base: string, paths: readonly string[]): RequestedPath[] {
28
+ return paths.map((raw) => {
29
+ const path = canonical(resolveFrom(base, raw))
30
+ return { path, directory: namesDirectory(raw) || physicalDirectory(path) !== undefined }
31
+ })
32
+ }
33
+
34
+ /** What {@link issueGrants} checks against. */
35
+ export interface IssueOptions {
36
+ readonly fence: Fence
37
+ readonly store: BindingStore
38
+ /** The granting agent. */
39
+ readonly grantor: AgentLike
40
+ /** The grantor's enforced (already narrowed) policy. */
41
+ readonly policy: SandboxPolicy
42
+ readonly targets: readonly RequestedPath[]
43
+ /** Recorded on each grant: a request id, or `spawn` for `writable_paths`. */
44
+ readonly requestId: string
45
+ }
46
+
47
+ /**
48
+ * Check that the grantor may modify every target, create missing directories,
49
+ * and build the grants. Nothing is created unless every target passes.
50
+ * @param options - grantor, policy, and targets.
51
+ * @returns one grant per target.
52
+ * @throws when a target is beyond the grantor's reach, naming where to ask instead.
53
+ */
54
+ export function issueGrants(options: IssueOptions): Grant[] {
55
+ const { fence, store, grantor, policy, targets } = options
56
+ const refused = targets.filter(target => !fence.canModify(policy, grantor.session, target.path, target.directory ? 'dir' : 'file'))
57
+ if (refused.length > 0) {
58
+ const own = store.get(grantor.id)
59
+ const advice = own === undefined
60
+ ? 'They are outside your own sandbox.'
61
+ : own.inherited === true
62
+ ? 'They are outside what the agent above you may modify.'
63
+ : `Request them from your own parent with \`${REQUEST_TOOL}\` first.`
64
+ throw new Error(`You cannot grant paths you cannot modify yourself: ${refused.map(target => target.path).join(', ')}. ${advice}`)
65
+ }
66
+ const at = Date.now()
67
+ return targets.map((target) => {
68
+ if (target.directory && physicalDirectory(target.path) === undefined) mkdirSync(target.path, { recursive: true })
69
+ return { path: canonical(target.path), kind: target.directory ? 'dir' : 'file', requestId: options.requestId, at }
70
+ })
71
+ }
72
+
73
+ /**
74
+ * One granted path as the model reads it.
75
+ * @param grant - the path and its kind.
76
+ * @returns a list line.
77
+ */
78
+ export function grantLine(grant: { path: string; kind: 'dir' | 'file' }): string {
79
+ return grant.kind === 'dir'
80
+ ? `- ${grant.path}/ (directory: any tool, including shell commands)`
81
+ : `- ${grant.path} (file: the write and edit tools only)`
82
+ }
@@ -0,0 +1,86 @@
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
+ import type { AgentLike } from './types.ts'
17
+
18
+ /**
19
+ * Whether this host predates conditional tools. `ToolRuntime.resolve`, which
20
+ * checks each `when`, arrived in the same commit as the option.
21
+ * @param tools - `ctx.tools`.
22
+ * @returns true when `when` would be ignored.
23
+ */
24
+ export function isLegacyHost(tools: { readonly resolve?: unknown }): boolean {
25
+ return typeof tools.resolve !== 'function'
26
+ }
27
+
28
+ /**
29
+ * Keeps each agent's `deny` filter equal to the tools it should not see now.
30
+ * A filter covers the agent it was registered through and not its children,
31
+ * because an agent's scope chain leads to its preset, never to its parent.
32
+ */
33
+ export class ToolRestrictions {
34
+ private readonly applied = new Map<AgentLike, { readonly hidden: string; readonly lift: () => void }>()
35
+
36
+ /**
37
+ * @param tools - the tool names under control, all registered globally.
38
+ * @param visible - whether one agent should see one tool now.
39
+ */
40
+ constructor(
41
+ private readonly tools: readonly string[],
42
+ private readonly visible: (tool: string, agent: AgentLike) => boolean,
43
+ ) {}
44
+
45
+ /**
46
+ * Bring one agent's filter up to date; a filter that still fits stays, so an
47
+ * unchanged agent causes no tool-change notice. A condition may read the
48
+ * agent's own tool view, which the old filter still narrowed (the parent-only
49
+ * tools ask whether `delegate` is visible), so a change is checked once more.
50
+ * @param agent - a live agent.
51
+ * @throws when the agent has no scoped tools service.
52
+ */
53
+ sync(agent: AgentLike): void {
54
+ if (this.apply(agent)) this.apply(agent)
55
+ }
56
+
57
+ /** Apply the current conditions once; returns whether the filter changed. */
58
+ private apply(agent: AgentLike): boolean {
59
+ const hidden = this.tools.filter(tool => !this.visible(tool, agent))
60
+ const key = hidden.join()
61
+ const current = this.applied.get(agent)
62
+ if ((current?.hidden ?? '') === key) return false
63
+ const scoped = agent.ctx?.tools
64
+ if (scoped === undefined) throw new Error(`agent ${agent.id} has no scoped tools service`)
65
+ // The new filter goes in first: if it throws, the old one still holds.
66
+ const lift = hidden.length === 0 ? undefined : scoped.restrict({ deny: hidden })
67
+ current?.lift()
68
+ if (lift === undefined) this.applied.delete(agent)
69
+ else this.applied.set(agent, { hidden: key, lift })
70
+ return true
71
+ }
72
+
73
+ /**
74
+ * Stop tracking a disposed agent; its context already removed the filter.
75
+ * @param agent - the disposed agent.
76
+ */
77
+ forget(agent: AgentLike): void {
78
+ this.applied.delete(agent)
79
+ }
80
+
81
+ /** Lift every filter, for the plugin's dispose: the filters belong to the agents' contexts, not the plugin's. */
82
+ dispose(): void {
83
+ for (const { lift } of this.applied.values()) lift()
84
+ this.applied.clear()
85
+ }
86
+ }