@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,155 @@
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
+
18
+ import { modelKey } from '../shared/settings.ts'
19
+ import type { ChildModel } from '../shared/settings.ts'
20
+ import type { AgentLike, LlmLike, RouteLike } from './types.ts'
21
+
22
+ /** A route with its provider and model known. */
23
+ export interface Route {
24
+ readonly provider: string
25
+ readonly model: string
26
+ readonly reasoningEffort?: string
27
+ }
28
+
29
+ /** The model-facing selection fields of one delegation call, unvalidated. */
30
+ export interface ModelRequest {
31
+ readonly model?: unknown
32
+ readonly reasoning_effort?: unknown
33
+ }
34
+
35
+ /**
36
+ * The route an agent's next request uses, as the host hands it to a child
37
+ * (`parentAgentOptionsForDelegation`): the session's request header once it
38
+ * has one, the agent's creation options before.
39
+ * @param agent - the parent.
40
+ * @returns its route, or undefined when the provider or model is unknown.
41
+ */
42
+ export function routeOf(agent: AgentLike): Route | undefined {
43
+ const source: RouteLike = agent.session.requestHeader?.()?.config ?? agent.options ?? {}
44
+ if (source.provider === undefined || source.model === undefined) return undefined
45
+ return {
46
+ provider: source.provider,
47
+ model: source.model,
48
+ ...source.reasoningEffort === undefined ? {} : { reasoningEffort: source.reasoningEffort },
49
+ }
50
+ }
51
+
52
+ /** The choices as one line for an error message. */
53
+ function choicesLine(models: readonly ChildModel[]): string {
54
+ return models.length === 0 ? 'none are listed in the settings' : models.map(modelKey).join(', ')
55
+ }
56
+
57
+ /** Read one optional non-empty string field. */
58
+ function optionalId(value: unknown, field: string): string | undefined {
59
+ if (value === undefined) return undefined
60
+ if (typeof value !== 'string' || value.trim() === '') throw new Error(`\`${field}\` must be a non-empty id`)
61
+ return value.trim()
62
+ }
63
+
64
+ /**
65
+ * Validate one call's model and effort and turn them into child options.
66
+ * @param options - the parent, the settings list, the call's fields, the LLM runtime, and the `ownModel` rule.
67
+ * @returns the child's route, or undefined when the call selects nothing and the child inherits the parent's route.
68
+ * @throws with a model-facing reason naming the allowed choices.
69
+ */
70
+ export async function chooseRoute(options: {
71
+ readonly parent: AgentLike
72
+ readonly models: readonly ChildModel[]
73
+ readonly request: ModelRequest
74
+ readonly llm: LlmLike | undefined
75
+ readonly signal?: AbortSignal
76
+ /** False keeps the child off the parent's own model when models are listed. */
77
+ readonly ownModel?: boolean
78
+ }): Promise<Route | undefined> {
79
+ const named = optionalId(options.request.model, 'model')
80
+ const effort = optionalId(options.request.reasoning_effort, 'reasoning_effort')
81
+ const onlyListed = options.ownModel === false && options.models.length > 0
82
+ if (named === undefined && effort === undefined && !onlyListed) return undefined
83
+ const own = routeOf(options.parent)
84
+ const listed = (key: string) => options.models.find(entry => modelKey(entry) === key)
85
+ let route: Route
86
+ if (onlyListed) {
87
+ const entry = named === undefined ? options.models[0] : listed(named)
88
+ if (entry === undefined) throw new Error(`Model "${named}" is not offered for subagents. Choose one of: ${choicesLine(options.models)}; or omit \`model\` to use the first.`)
89
+ route = entry
90
+ } else if (named === undefined || (own !== undefined && named === modelKey(own))) {
91
+ if (own === undefined) throw new Error('Your own model is not known yet, so the child\'s reasoning effort cannot be set; omit `reasoning_effort`.')
92
+ route = own
93
+ } else {
94
+ const entry = listed(named)
95
+ if (entry === undefined) throw new Error(`Model "${named}" is not offered for subagents. Choose one of: ${choicesLine(options.models)}; or omit \`model\` to use your own.`)
96
+ route = entry
97
+ }
98
+ const key = modelKey(route)
99
+ const sameRoute = own !== undefined && modelKey(own) === key
100
+ const allowed = listed(key)?.reasoningEfforts ?? []
101
+ const llm = options.llm
102
+ if (llm === undefined) throw new Error('The child model cannot be checked because the `llm` service is unavailable.')
103
+ let chosen = effort
104
+ if (effort !== undefined) {
105
+ const offered = allowed.length > 0
106
+ ? allowed
107
+ : (await llm.resolveModelInfo(route.provider, route.model, options.signal)).reasoning?.efforts.map(item => item.id) ?? []
108
+ if (!offered.includes(effort)) {
109
+ throw new Error(offered.length === 0
110
+ ? `${key} has no selectable reasoning effort; omit \`reasoning_effort\`.`
111
+ : `Reasoning effort "${effort}" is not offered for ${key}. Choose one of: ${offered.join(', ')}.`)
112
+ }
113
+ } else if (sameRoute ? onlyListed : allowed.length > 0) {
114
+ const fallback = (await llm.resolveModelInfo(route.provider, route.model, options.signal)).reasoning?.defaultEffort
115
+ if (allowed.length > 0 && (fallback === undefined || !allowed.includes(fallback))) chosen = allowed[0]
116
+ // On the parent's own route the host keeps the parent's effort unless one is named.
117
+ else if (sameRoute) chosen = fallback
118
+ }
119
+ const reasoningEffort = chosen ?? (sameRoute ? own?.reasoningEffort : undefined)
120
+ await llm.resolveCallConfig({
121
+ provider: route.provider,
122
+ model: route.model,
123
+ ...reasoningEffort === undefined ? {} : { reasoningEffort },
124
+ }, options.signal)
125
+ return { provider: route.provider, model: route.model, ...chosen === undefined ? {} : { reasoningEffort: chosen } }
126
+ }
127
+
128
+ /**
129
+ * The model-selection paragraph of a delegation tool's description.
130
+ * @param models - the settings list.
131
+ * @param ownModel - false keeps the child off the parent's own model when models are listed.
132
+ * @returns the text the parent reads.
133
+ */
134
+ export function describeModels(models: readonly ChildModel[], ownModel = true): string {
135
+ const efforts = (entry: ChildModel): string => entry.reasoningEfforts.length === 0
136
+ ? 'any effort it supports'
137
+ : `efforts ${entry.reasoningEfforts.join(', ')}`
138
+ if (models.length === 0) {
139
+ return 'Model: the child uses your own model. `reasoning_effort` may be any effort your model supports; omitted, the child keeps your current effort.'
140
+ }
141
+ if (!ownModel) {
142
+ return [
143
+ '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.',
144
+ ...models.map(entry => `- ${modelKey(entry)}: ${efforts(entry)}`),
145
+ 'An omitted effort uses the model\'s default, or its first listed effort when the default is not listed.',
146
+ ].join('\n')
147
+ }
148
+ return [
149
+ 'Model: omit `model` to give the child your own model; `reasoning_effort` may then be any effort your model supports '
150
+ + '(only the listed ones if your model is listed below), and an omitted effort keeps your current one.',
151
+ 'Other models you may choose with `model`:',
152
+ ...models.map(entry => `- ${modelKey(entry)}: ${efforts(entry)}`),
153
+ 'On another model, an omitted effort uses that model\'s default, or its first listed effort when the default is not listed.',
154
+ ].join('\n')
155
+ }
@@ -0,0 +1,100 @@
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
+ import { realpathSync, statSync } from 'node:fs'
14
+ import { homedir } from 'node:os'
15
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'
16
+
17
+ /**
18
+ * Resolve a model-supplied path against a base directory. `~` and `~/…` name the
19
+ * user's home, as the host's file tools accept.
20
+ * @param base - absolute directory relative paths start from.
21
+ * @param path - the path as the model wrote it.
22
+ * @returns an absolute, lexically normalized path.
23
+ */
24
+ export function resolveFrom(base: string, path: string): string {
25
+ if (path === '~') return homedir()
26
+ if (path.startsWith('~/')) return join(homedir(), path.slice(2))
27
+ return isAbsolute(path) ? resolve(path) : resolve(base, path)
28
+ }
29
+
30
+ /**
31
+ * The canonical spelling of a path that may not exist yet.
32
+ * @param path - an absolute path.
33
+ * @returns the realpath of its longest existing prefix plus the missing rest.
34
+ */
35
+ export function canonical(path: string): string {
36
+ const missing: string[] = []
37
+ let current = resolve(path)
38
+ while (true) {
39
+ try {
40
+ const real = realpathSync.native(current)
41
+ return missing.length === 0 ? real : join(real, ...missing.reverse())
42
+ } catch {
43
+ const parent = dirname(current)
44
+ if (parent === current) return resolve(path)
45
+ missing.push(basename(current))
46
+ current = parent
47
+ }
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Whether `path` is `root` or lies below it. Both must be canonical.
53
+ * @param path - candidate path.
54
+ * @param root - containing directory.
55
+ * @returns true when contained.
56
+ */
57
+ export function isUnder(path: string, root: string): boolean {
58
+ if (path === root) return true
59
+ const prefix = root.endsWith(sep) ? root : root + sep
60
+ return path.startsWith(prefix)
61
+ }
62
+
63
+ /**
64
+ * The physical directory a path names right now, as the host accepts it for an
65
+ * additional writable root: existing, a directory, and spelled without symlinks.
66
+ * @param path - a canonical path.
67
+ * @returns the path when it qualifies, otherwise undefined.
68
+ */
69
+ export function physicalDirectory(path: string): string | undefined {
70
+ try {
71
+ const real = realpathSync.native(path)
72
+ return real === resolve(path) && statSync(real).isDirectory() ? real : undefined
73
+ } catch {
74
+ return undefined
75
+ }
76
+ }
77
+
78
+ /**
79
+ * The deepest existing directory at or above a path.
80
+ * @param path - an absolute path.
81
+ * @returns a physical directory that exists.
82
+ */
83
+ export function nearestDirectory(path: string): string {
84
+ let current = canonical(path)
85
+ while (physicalDirectory(current) === undefined) {
86
+ const parent = dirname(current)
87
+ if (parent === current) return current
88
+ current = parent
89
+ }
90
+ return current
91
+ }
92
+
93
+ /**
94
+ * Whether a model-written path asks for a whole directory: it ends in a separator.
95
+ * @param path - the path as written.
96
+ * @returns true for `dir/` spellings.
97
+ */
98
+ export function namesDirectory(path: string): boolean {
99
+ return path.endsWith('/') || path.endsWith(sep)
100
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The write fence: narrows a bound child's sandbox policy to its sub-workspace
3
+ * plus what its parent granted.
4
+ *
5
+ * Every enforcing capability (bash's OS sandbox, the fs write fence, terminals,
6
+ * PTC) asks `ctx.sandboxPolicy.resolve({ session })` for each call, and the
7
+ * host's child agents copy the parent's header cwd, so by default a child may
8
+ * write anywhere in the parent's project. {@link patchResolve} wraps the
9
+ * service's prototype method, so every holder of the service, including ones
10
+ * that captured it at load, sees the narrowed policy; disposing restores it.
11
+ * @module complete-subagent/host/policy
12
+ */
13
+
14
+ import { tmpdir } from 'node:os'
15
+ import { dirname } from 'node:path'
16
+ import { currentCall } from './call-scope.ts'
17
+ import { canonical, isUnder, nearestDirectory, physicalDirectory, resolveFrom } from './paths.ts'
18
+ import type { Binding, BindingStore } from './store.ts'
19
+ import type { SandboxPolicy, SandboxPolicyRequest, SessionLike, WorkingDirectoryLike } from './types.ts'
20
+
21
+ /** File tools whose single target a grant may admit by moving the call's root, and the argument naming it. */
22
+ const FILE_TOOLS: Readonly<Record<string, string>> = {
23
+ write: 'file_path',
24
+ edit: 'file_path',
25
+ str_replace_editor: 'path',
26
+ }
27
+
28
+ /** What the fence reads besides the store. */
29
+ export interface FenceOptions {
30
+ readonly store: BindingStore
31
+ /** Effective directories, for relative file-tool targets. */
32
+ readonly workingDirectory?: WorkingDirectoryLike
33
+ /** Reports a failure that made the fence fall back to read-only. */
34
+ readonly warn?: (message: string) => void
35
+ }
36
+
37
+ /** How many inherited bindings the fence follows before it gives up and closes. */
38
+ const MAX_INHERITANCE = 32
39
+
40
+ /** Narrows policies for bound children and answers "may this agent modify that path". */
41
+ export class Fence {
42
+ private readonly temp = canonical(tmpdir())
43
+
44
+ constructor(private readonly options: FenceOptions) {}
45
+
46
+ /**
47
+ * The binding in force for a session. An inherited binding takes the access
48
+ * of the nearest ancestor with a binding of its own, as that ancestor holds it
49
+ * now; a broken chain leaves no access (fail closed).
50
+ * @param session - any session.
51
+ * @returns the binding, or undefined for sessions the fence leaves alone.
52
+ */
53
+ bindingOf(session: SessionLike): Binding | undefined {
54
+ const own = this.options.store.get(session.id)
55
+ if (own?.inherited !== true) return own
56
+ let source: Binding | undefined = own
57
+ for (let hops = 0; source?.inherited === true && hops < MAX_INHERITANCE; hops++) source = this.options.store.get(source.parent)
58
+ const access = source === undefined || source.inherited === true ? { workspace: null, grants: [] } : source
59
+ return { ...own, workspace: access.workspace, grants: access.grants }
60
+ }
61
+
62
+ /**
63
+ * Narrow one resolved policy. Unbound sessions pass through untouched; a
64
+ * bound child gets `workspace-write` rooted at its sub-workspace (or the temp
65
+ * directory when it has none) and its directory grants as extra roots. The
66
+ * one `write`/`edit` call whose target was granted is rooted at that grant
67
+ * instead, because a host older than 0.2.2-alpha.2 reads only `workspaceRoot`.
68
+ * `read-only` stays read-only. A failure falls back to read-only for subagent
69
+ * sessions rather than widening anything, and stays within that one session.
70
+ * @param policy - the host's resolved policy.
71
+ * @param request - the resolve request (its session decides).
72
+ * @returns the policy to enforce.
73
+ */
74
+ narrow(policy: SandboxPolicy, request: SandboxPolicyRequest): SandboxPolicy {
75
+ const session = request.session
76
+ if (session === undefined) return policy
77
+ try {
78
+ const binding = this.bindingOf(session)
79
+ if (binding === undefined || policy.mode === 'read-only') return policy
80
+ const roots = new Set<string>(policy.additionalWritableRoots ?? [])
81
+ for (const grant of binding.grants) {
82
+ if (grant.kind !== 'dir') continue
83
+ const directory = physicalDirectory(grant.path)
84
+ if (directory !== undefined) roots.add(directory)
85
+ }
86
+ const callRoot = this.grantedCallRoot(session, binding)
87
+ if (callRoot !== undefined) roots.add(callRoot)
88
+ return {
89
+ ...policy,
90
+ mode: 'workspace-write',
91
+ workspaceRoot: callRoot ?? binding.workspace ?? this.temp,
92
+ additionalWritableRoots: [...roots],
93
+ }
94
+ } catch (error) {
95
+ if (session.header.origin !== 'subagent') return policy
96
+ this.options.warn?.(`complete-subagent: fence failed for ${session.id}, using read-only: ${String(error)}`)
97
+ return { ...policy, mode: 'read-only' }
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Whether a session may itself modify a path, judged by its own (possibly
103
+ * narrowed) policy and, for a file, its own file grants. Temp directories
104
+ * count, as they do for the host's `workspace-write`.
105
+ * @param policy - the session's resolved policy.
106
+ * @param session - the session asking.
107
+ * @param path - canonical target.
108
+ * @param kind - whether the target is a directory subtree or one file.
109
+ * @returns true when the session could write there.
110
+ */
111
+ canModify(policy: SandboxPolicy, session: SessionLike, path: string, kind: 'dir' | 'file'): boolean {
112
+ if (policy.mode === 'danger-full-access') return true
113
+ if (policy.mode === 'read-only') return false
114
+ const roots = [policy.workspaceRoot, ...policy.additionalWritableRoots ?? [], '/tmp', this.temp].map(canonical)
115
+ if (roots.some(root => isUnder(path, root))) return true
116
+ if (kind !== 'file') return false
117
+ return this.bindingOf(session)?.grants.some(grant => grant.kind === 'file' && grant.path === path) === true
118
+ }
119
+
120
+ /** The root that admits the running file-tool call's target when it lies in a grant: a granted directory, or a granted file's folder. */
121
+ private grantedCallRoot(session: SessionLike, binding: Binding): string | undefined {
122
+ if (binding.grants.length === 0) return undefined
123
+ const call = currentCall()
124
+ if (call?.agent?.session.id !== session.id) return undefined
125
+ const key = FILE_TOOLS[call.name]
126
+ if (key === undefined) return undefined
127
+ const raw = (call.arguments as Record<string, unknown> | null | undefined)?.[key]
128
+ if (typeof raw !== 'string' || raw === '') return undefined
129
+ const base = this.options.workingDirectory?.get(session) ?? session.header.cwd ?? process.cwd()
130
+ const target = canonical(resolveFrom(base, raw))
131
+ if (binding.workspace !== null && isUnder(target, binding.workspace)) return undefined
132
+ for (const grant of binding.grants) {
133
+ if (grant.kind === 'file' && grant.path === target) return nearestDirectory(dirname(target))
134
+ if (grant.kind === 'dir' && isUnder(target, grant.path)) {
135
+ const directory = physicalDirectory(grant.path)
136
+ if (directory !== undefined) return directory
137
+ }
138
+ }
139
+ return undefined
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Wrap `resolve` on the sandbox-policy service's prototype. Cordis hands
145
+ * consumers a tracing proxy whose property reads fall through to the
146
+ * prototype, so patching the prototype reaches every consumer at once.
147
+ * @param service - `ctx.sandboxPolicy` (the proxy or the instance).
148
+ * @param narrow - turns the host's policy into the enforced one.
149
+ * @returns a disposer that restores the original method if it is still ours.
150
+ * @throws when the service has no prototype `resolve` method (a host change).
151
+ */
152
+ export function patchResolve(
153
+ service: object,
154
+ narrow: (policy: SandboxPolicy, request: SandboxPolicyRequest) => SandboxPolicy,
155
+ ): () => void {
156
+ const prototype = Object.getPrototypeOf(service) as { resolve?: unknown } | null
157
+ const original = prototype?.resolve
158
+ if (prototype === null || typeof original !== 'function') {
159
+ throw new Error('sandboxPolicy.resolve is not a prototype method; this host version is not supported')
160
+ }
161
+ const patched = function resolve(this: unknown, request?: SandboxPolicyRequest): SandboxPolicy {
162
+ const policy = (original as (request?: SandboxPolicyRequest) => SandboxPolicy).call(this, request)
163
+ return narrow(policy, request ?? {})
164
+ }
165
+ prototype.resolve = patched
166
+ return () => {
167
+ if (prototype.resolve === patched) prototype.resolve = original
168
+ }
169
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Model-facing guidance. A parent reads the delegation and sub-workspace rules
3
+ * in the `delegate` / `delegate_fork` descriptions and parameters; a bound
4
+ * child reads its sub-workspace and grants in a runtime context; a parent with
5
+ * open requests reads them in another.
6
+ * @module complete-subagent/host/prompt
7
+ */
8
+
9
+ import type { WriteRequest } from './requests.ts'
10
+ import type { Binding } from './store.ts'
11
+ import { ANSWER_TOOL, GRANT_TOOL, REQUEST_TOOL, REVOKE_TOOL } from './types.ts'
12
+ import type { DelegateTool } from './types.ts'
13
+
14
+ /** What a delegation tool is for, by whether the child inherits this conversation. */
15
+ const PURPOSE: Readonly<Record<DelegateTool, string>> = {
16
+ delegate: 'Delegate a self-contained task to a subagent: a separate agent that works in its own context, so the work '
17
+ + '(research, a scoped implementation, an analysis) does not consume this conversation\'s context.',
18
+ delegate_fork: 'Delegate a task to a subagent that inherits this conversation: a child seeded with all completed turns so far '
19
+ + '(not the current in-flight turn). Use it when the subtask builds on this conversation\'s context, such as a follow-up '
20
+ + 'analysis, a review, or a continuation, without consuming this conversation\'s context for the work itself.',
21
+ }
22
+
23
+ /** How a started child reports back and how to keep working meanwhile. */
24
+ const LIFECYCLE = 'It returns the subagent\'s id at once; the runtime notifies you with its result when it finishes. '
25
+ + 'Use `send_message` to steer it while it runs or to continue its conversation afterwards. '
26
+ + 'Start independent delegations together in one message and keep working; when only waiting remains, end your turn instead of polling.'
27
+
28
+ /** The sub-workspace rules every delegation tool states. */
29
+ const SUB_WORKSPACES = [
30
+ 'Sub-workspaces: the `cwd` you pass becomes the child\'s sub-workspace, created if missing, and the only place where it may modify files '
31
+ + 'besides temporary directories and `writable_paths`. Without a `cwd`, or with one outside your own writable area, the child can read but not modify the workspace.',
32
+ `A child that needs more sends you a "[write-access request wr-…]" message and is paused until you answer with \`${ANSWER_TOOL}\`. `
33
+ + `You can also change a child's access at any time with \`${GRANT_TOOL}\` and \`${REVOKE_TOOL}\`. `
34
+ + 'You can grant only paths you can modify yourself, and whatever your child starts is confined the same way.',
35
+ ].join(' ')
36
+
37
+ /**
38
+ * The description of one delegation tool.
39
+ * @param tool - which tool.
40
+ * @param models - the model-selection paragraph from `describeModels`.
41
+ * @returns the full description.
42
+ */
43
+ export function delegateDescription(tool: DelegateTool, models: string): string {
44
+ const cache = tool === 'delegate_fork'
45
+ ? ' Choosing another model loses the provider-side reuse of the inherited conversation.'
46
+ : ''
47
+ return `${PURPOSE[tool]} ${LIFECYCLE}\n\n${SUB_WORKSPACES}\n\n${models}${cache}`
48
+ }
49
+
50
+ /** The `prompt` parameter, by whether the child inherits this conversation. */
51
+ export const PROMPT_DESCRIPTION: Readonly<Record<DelegateTool, string>> = {
52
+ delegate: 'The complete, self-contained task for the subagent. It does not share this conversation\'s context, so include everything it needs.',
53
+ delegate_fork: 'The task for the subagent. It already sees this conversation\'s completed turns, so build on them and state only what is new.',
54
+ }
55
+
56
+ /** The `cwd` parameter. */
57
+ export const CWD_DESCRIPTION = 'The child\'s sub-workspace and initial directory; relative paths use your current directory. '
58
+ + 'It is created if missing, and the child may modify files only there (plus temporary directories and `writable_paths`). '
59
+ + 'Omit it, or name a directory outside your own writable area, and the child can read but not modify the workspace. '
60
+ + 'Later directory changes in either agent are independent.'
61
+
62
+ /** The `writable_paths` parameter. */
63
+ export const WRITABLE_PATHS_DESCRIPTION = 'Paths outside the sub-workspace that the child may also modify from the start, '
64
+ + 'relative to your current directory or absolute. End a path with "/" (or name an existing directory) to grant the whole directory '
65
+ + 'to every tool, including shell commands; a single file is writable through the write and edit tools only. '
66
+ + 'You can grant only what you can modify yourself; the child asks you for anything else.'
67
+
68
+ /** The `model` parameter. */
69
+ export const MODEL_DESCRIPTION = 'The child\'s model as "provider/model", one of the listed choices. Omit it to use your own model.'
70
+
71
+ /** The `model` parameter when the child cannot run the parent's model. */
72
+ export const LISTED_MODEL_DESCRIPTION = 'The child\'s model as "provider/model", one of the listed choices. Omit it to use the first.'
73
+
74
+ /** The `reasoning_effort` parameter. */
75
+ export const EFFORT_DESCRIPTION = 'The child\'s reasoning effort id, such as "low", "high", or "max", among those its model allows. '
76
+ + 'Use lower efforts for simple, mechanical work and higher ones for hard reasoning.'
77
+
78
+ /**
79
+ * Runtime context for a bound child.
80
+ * @param binding - the child's binding in force (inherited access already resolved).
81
+ * @returns the context text.
82
+ */
83
+ export function childContext(binding: Binding, shellReachesGrants = true): string {
84
+ const lines = [
85
+ binding.workspace === null
86
+ ? 'Sub-workspace: none. You can read the workspace, but you may modify files only in temporary directories.'
87
+ : `Sub-workspace: ${binding.workspace}. You may modify files only under this directory and temporary directories.`,
88
+ ]
89
+ const directories = binding.grants.filter(grant => grant.kind === 'dir').map(grant => grant.path)
90
+ const files = binding.grants.filter(grant => grant.kind === 'file').map(grant => grant.path)
91
+ const from = binding.inherited === true ? 'to the agent above you' : 'by your parent'
92
+ const fileToolsOnly = '(write and edit tools only, not shell commands)'
93
+ if (directories.length > 0) lines.push(`Also granted ${from} ${shellReachesGrants ? '(any tool)' : fileToolsOnly}: ${directories.join(', ')}`)
94
+ if (files.length > 0) lines.push(`Also granted ${from} ${fileToolsOnly}: ${files.join(', ')}`)
95
+ lines.push(binding.inherited === true
96
+ ? 'Your parent is a confined subagent, so you share its access and cannot ask for more. If the task needs other paths, report that back instead.'
97
+ : `To modify anything else, call \`${REQUEST_TOOL}\` with the exact paths and a short reason, and wait for the answer. `
98
+ + 'This replaces approval: do not set `sandbox_permissions`.')
99
+ return lines.join('\n')
100
+ }
101
+
102
+ /**
103
+ * Runtime context for a parent with open requests.
104
+ * @param requests - its open requests.
105
+ * @returns the context text, or '' when none are open.
106
+ */
107
+ export function pendingContext(requests: readonly WriteRequest[]): string {
108
+ if (requests.length === 0) return ''
109
+ return [
110
+ `Write-access requests waiting for your \`${ANSWER_TOOL}\` answer (the subagents are paused):`,
111
+ ...requests.map(request => `- ${request.id} from ${request.child}: ${request.paths.map(item => item.directory ? `${item.path}/` : item.path).join(', ')} — ${request.reason}`),
112
+ ].join('\n')
113
+ }