@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.
- package/AGENTS.md +52 -0
- package/LICENSE +21 -0
- package/README.md +166 -2
- package/cordis.patch.yml +11 -0
- package/lib/client.js +439 -0
- package/lib/client.modules.txt +8 -0
- package/lib/host/access.d.ts +46 -0
- package/lib/host/access.js +54 -0
- package/lib/host/call-scope.d.ts +21 -0
- package/lib/host/call-scope.js +26 -0
- package/lib/host/delegate.d.ts +47 -0
- package/lib/host/delegate.js +129 -0
- package/lib/host/grants.d.ts +51 -0
- package/lib/host/grants.js +62 -0
- package/lib/host/legacy.d.ts +57 -0
- package/lib/host/legacy.js +85 -0
- package/lib/host/models.d.ts +59 -0
- package/lib/host/models.js +139 -0
- package/lib/host/paths.d.ts +51 -0
- package/lib/host/paths.js +100 -0
- package/lib/host/policy.d.ts +72 -0
- package/lib/host/policy.js +169 -0
- package/lib/host/prompt.d.ts +41 -0
- package/lib/host/prompt.js +100 -0
- package/lib/host/requests.d.ts +82 -0
- package/lib/host/requests.js +109 -0
- package/lib/host/scope.d.ts +33 -0
- package/lib/host/scope.js +46 -0
- package/lib/host/store.d.ts +89 -0
- package/lib/host/store.js +128 -0
- package/lib/host/tools.d.ts +58 -0
- package/lib/host/tools.js +298 -0
- package/lib/host/types.d.ts +176 -0
- package/lib/host/types.js +26 -0
- package/lib/index.d.ts +55 -0
- package/lib/index.js +245 -0
- package/lib/shared/settings.d.ts +69 -0
- package/lib/shared/settings.js +86 -0
- package/locale/AGENTS.md +22 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +87 -4
- package/src/AGENTS.md +26 -0
- package/src/client/AGENTS.md +28 -0
- package/src/client/css.d.ts +5 -0
- package/src/client/host.ts +82 -0
- package/src/client/index.ts +81 -0
- package/src/client/locales.ts +61 -0
- package/src/client/settings.tsx +222 -0
- package/src/client/styles.css +44 -0
- package/src/host/AGENTS.md +51 -0
- package/src/host/access.ts +82 -0
- package/src/host/call-scope.ts +31 -0
- package/src/host/delegate.ts +162 -0
- package/src/host/grants.ts +82 -0
- package/src/host/legacy.ts +86 -0
- package/src/host/models.ts +155 -0
- package/src/host/paths.ts +100 -0
- package/src/host/policy.ts +169 -0
- package/src/host/prompt.ts +113 -0
- package/src/host/requests.ts +149 -0
- package/src/host/scope.ts +54 -0
- package/src/host/store.ts +159 -0
- package/src/host/tools.ts +318 -0
- package/src/host/types.ts +183 -0
- package/src/index.ts +316 -0
- package/src/shared/AGENTS.md +20 -0
- package/src/shared/settings.ts +104 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Write-access requests waiting for a parent's answer.
|
|
3
|
+
*
|
|
4
|
+
* A request lives only in memory, from the child's `request_write_access` call
|
|
5
|
+
* until the parent answers, the timeout passes, or the child's call is
|
|
6
|
+
* cancelled. If the process exits, the child's call ends with it, so nothing
|
|
7
|
+
* needs to survive a restart; the grants an answer produces are stored by the
|
|
8
|
+
* caller in the binding store.
|
|
9
|
+
* @module complete-subagent/host/requests
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { randomBytes } from 'node:crypto'
|
|
13
|
+
|
|
14
|
+
/** One requested path. */
|
|
15
|
+
export interface RequestedPath {
|
|
16
|
+
/** Canonical absolute path. */
|
|
17
|
+
readonly path: string
|
|
18
|
+
/** Whether the whole directory is asked for (an existing directory, or a `dir/` spelling). */
|
|
19
|
+
readonly directory: boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** What a child's call returns. */
|
|
23
|
+
export interface WriteAnswer {
|
|
24
|
+
readonly decision: 'allow' | 'deny'
|
|
25
|
+
readonly granted: { path: string; kind: 'dir' | 'file' }[]
|
|
26
|
+
readonly message?: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One open request. */
|
|
30
|
+
export interface WriteRequest {
|
|
31
|
+
readonly id: string
|
|
32
|
+
/** Child session id. */
|
|
33
|
+
readonly child: string
|
|
34
|
+
/** Parent session id: the only agent that may answer. */
|
|
35
|
+
readonly parent: string
|
|
36
|
+
/** The child's sub-workspace, for the parent's message. */
|
|
37
|
+
readonly workspace: string | null
|
|
38
|
+
readonly paths: readonly RequestedPath[]
|
|
39
|
+
readonly reason: string
|
|
40
|
+
readonly at: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface Entry {
|
|
44
|
+
readonly request: WriteRequest
|
|
45
|
+
readonly answered: Promise<WriteAnswer>
|
|
46
|
+
readonly answer: (answer: WriteAnswer) => void
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The open requests of this process. */
|
|
50
|
+
export class RequestBroker {
|
|
51
|
+
private readonly entries = new Map<string, Entry>()
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Open a request.
|
|
55
|
+
* @param fields - everything but the id and time.
|
|
56
|
+
* @returns the open request.
|
|
57
|
+
*/
|
|
58
|
+
open(fields: Omit<WriteRequest, 'id' | 'at'>): WriteRequest {
|
|
59
|
+
let id: string
|
|
60
|
+
do id = `wr-${randomBytes(3).toString('hex')}`
|
|
61
|
+
while (this.entries.has(id))
|
|
62
|
+
const request: WriteRequest = { ...fields, id, at: Date.now() }
|
|
63
|
+
let answer!: (answer: WriteAnswer) => void
|
|
64
|
+
const answered = new Promise<WriteAnswer>((resolve) => {
|
|
65
|
+
answer = resolve
|
|
66
|
+
})
|
|
67
|
+
this.entries.set(id, { request, answered, answer })
|
|
68
|
+
return request
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* An open request by id.
|
|
73
|
+
* @param id - request id.
|
|
74
|
+
* @returns the request, or undefined once answered, expired, or cancelled.
|
|
75
|
+
*/
|
|
76
|
+
get(id: string): WriteRequest | undefined {
|
|
77
|
+
return this.entries.get(id)?.request
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The open requests addressed to one parent, oldest first.
|
|
82
|
+
* @param parent - parent session id.
|
|
83
|
+
* @returns its requests.
|
|
84
|
+
*/
|
|
85
|
+
pendingFor(parent: string): WriteRequest[] {
|
|
86
|
+
return [...this.entries.values()].map(entry => entry.request).filter(request => request.parent === parent)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Answer an open request and close it.
|
|
91
|
+
* @param id - request id.
|
|
92
|
+
* @param answer - the decision the child receives.
|
|
93
|
+
* @returns false when the request was no longer open.
|
|
94
|
+
*/
|
|
95
|
+
settle(id: string, answer: WriteAnswer): boolean {
|
|
96
|
+
const entry = this.entries.get(id)
|
|
97
|
+
if (entry === undefined) return false
|
|
98
|
+
this.entries.delete(id)
|
|
99
|
+
entry.answer(answer)
|
|
100
|
+
return true
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Close a request without an answer (the message to the parent failed).
|
|
105
|
+
* @param id - request id.
|
|
106
|
+
*/
|
|
107
|
+
close(id: string): void {
|
|
108
|
+
this.entries.delete(id)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Wait for the answer. A timeout closes the request as denied; cancellation
|
|
113
|
+
* closes it and rejects with the signal's reason.
|
|
114
|
+
* @param id - request id.
|
|
115
|
+
* @param timeoutMs - how long the parent has.
|
|
116
|
+
* @param signal - the child's call cancellation.
|
|
117
|
+
* @returns the parent's answer, or a denial on timeout.
|
|
118
|
+
*/
|
|
119
|
+
wait(id: string, timeoutMs: number, signal: AbortSignal): Promise<WriteAnswer> {
|
|
120
|
+
const entry = this.entries.get(id)
|
|
121
|
+
if (entry === undefined) return Promise.resolve({ decision: 'deny', granted: [], message: 'The request was closed before it could be answered.' })
|
|
122
|
+
return new Promise<WriteAnswer>((resolve, reject) => {
|
|
123
|
+
const finish = (): void => {
|
|
124
|
+
clearTimeout(timer)
|
|
125
|
+
signal.removeEventListener('abort', onAbort)
|
|
126
|
+
}
|
|
127
|
+
const onAbort = (): void => {
|
|
128
|
+
finish()
|
|
129
|
+
this.entries.delete(id)
|
|
130
|
+
reject(signal.reason ?? new Error('aborted'))
|
|
131
|
+
}
|
|
132
|
+
const timer = setTimeout(() => {
|
|
133
|
+
finish()
|
|
134
|
+
this.entries.delete(id)
|
|
135
|
+
resolve({ decision: 'deny', granted: [], message: `Your parent did not answer within ${Math.round(timeoutMs / 1000)} seconds; nothing was granted.` })
|
|
136
|
+
}, timeoutMs)
|
|
137
|
+
timer.unref?.()
|
|
138
|
+
if (signal.aborted) {
|
|
139
|
+
onAbort()
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
143
|
+
void entry.answered.then((answer) => {
|
|
144
|
+
finish()
|
|
145
|
+
resolve(answer)
|
|
146
|
+
})
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which agents the plugin serves: every agent, or only those whose session
|
|
3
|
+
* runs one of the configured agent presets.
|
|
4
|
+
*
|
|
5
|
+
* A bundle that mounts this plugin for its own preset sets `presets`, so the
|
|
6
|
+
* tools and prompt texts stay out of every other preset's sessions. A child
|
|
7
|
+
* records its parent's preset unless it was started with one of its own, so a
|
|
8
|
+
* served agent's children are served too.
|
|
9
|
+
* @module complete-subagent/host/scope
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { AgentPresetsLike, SessionLike, SessionProjectionsLike } from './types.ts'
|
|
13
|
+
|
|
14
|
+
/** Where a session's preset can be read, each looked up at call time because both are optional. */
|
|
15
|
+
export interface PresetSources {
|
|
16
|
+
readonly agentPresets: () => AgentPresetsLike | undefined
|
|
17
|
+
readonly sessionProjections: () => SessionProjectionsLike | undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The preset a session runs. The registry's method comes first because newer
|
|
22
|
+
* hosts deprecate reading its projection directly; 0.2.1-rc.5 has no such
|
|
23
|
+
* method, and the projection is how that host reads it too.
|
|
24
|
+
* @param session - the session.
|
|
25
|
+
* @param sources - the host services to read.
|
|
26
|
+
* @returns the preset id, or undefined when none can be read.
|
|
27
|
+
*/
|
|
28
|
+
export function sessionPreset(session: SessionLike, sources: PresetSources): string | undefined {
|
|
29
|
+
const registry = sources.agentPresets()
|
|
30
|
+
const preset: unknown = typeof registry?.presetForSession === 'function'
|
|
31
|
+
? registry.presetForSession(session)
|
|
32
|
+
: sources.sessionProjections()?.stateOf(session, 'agentPreset')
|
|
33
|
+
return typeof preset === 'string' ? preset : undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Build the "does the plugin serve this session" check.
|
|
38
|
+
* @param presets - the configured preset ids; empty serves every session.
|
|
39
|
+
* @param sources - the host services a session's preset is read from.
|
|
40
|
+
* @returns the check. With presets configured, a session whose preset cannot be
|
|
41
|
+
* read (no service, none recorded, a failure) is not served.
|
|
42
|
+
*/
|
|
43
|
+
export function presetScope(presets: readonly string[], sources: PresetSources): (session: SessionLike) => boolean {
|
|
44
|
+
if (presets.length === 0) return () => true
|
|
45
|
+
const allowed = new Set(presets)
|
|
46
|
+
return (session) => {
|
|
47
|
+
try {
|
|
48
|
+
const preset = sessionPreset(session, sources)
|
|
49
|
+
return preset !== undefined && allowed.has(preset)
|
|
50
|
+
} catch {
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable bindings: which sub-workspace a child owns and what its parent granted.
|
|
3
|
+
*
|
|
4
|
+
* One JSON file per child session under
|
|
5
|
+
* `$DSH_HOME/plugin-data/complete-subagent/children/`. A child keeps its session
|
|
6
|
+
* id when it is cold-resumed (a finished child woken by `send_message`, or any
|
|
7
|
+
* child after a restart), so the same file applies again. Reads are synchronous
|
|
8
|
+
* and cached, because the sandbox policy is resolved synchronously on every
|
|
9
|
+
* capability call; writes replace the file atomically.
|
|
10
|
+
* @module complete-subagent/host/store
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
14
|
+
import { homedir } from 'node:os'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
|
|
17
|
+
/** One path a parent let its child modify. */
|
|
18
|
+
export interface Grant {
|
|
19
|
+
/** Canonical absolute path. */
|
|
20
|
+
readonly path: string
|
|
21
|
+
/** A directory grant covers its subtree for every tool; a file grant covers the file for `write`/`edit`. */
|
|
22
|
+
readonly kind: 'dir' | 'file'
|
|
23
|
+
/** The request that produced it. */
|
|
24
|
+
readonly requestId: string
|
|
25
|
+
/** Unix epoch milliseconds. */
|
|
26
|
+
readonly at: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Everything the fence needs to know about one child. */
|
|
30
|
+
export interface Binding {
|
|
31
|
+
readonly version: 1
|
|
32
|
+
/** Child session id. */
|
|
33
|
+
readonly child: string
|
|
34
|
+
/** Parent session id. */
|
|
35
|
+
readonly parent: string
|
|
36
|
+
/** Canonical sub-workspace, or null when the child has none. */
|
|
37
|
+
readonly workspace: string | null
|
|
38
|
+
readonly grants: readonly Grant[]
|
|
39
|
+
/**
|
|
40
|
+
* Set for a child that a confined agent started some other way (the official
|
|
41
|
+
* subagent tools, a workflow): it holds whatever access its parent holds now,
|
|
42
|
+
* and `workspace` / `grants` stay empty.
|
|
43
|
+
*/
|
|
44
|
+
readonly inherited?: true
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The default store directory, following the host's home rule: `DSH_HOME`, then
|
|
49
|
+
* `~/.dsh`.
|
|
50
|
+
* @param env - environment to read.
|
|
51
|
+
* @returns the absolute directory holding one file per child.
|
|
52
|
+
*/
|
|
53
|
+
export function defaultStoreDirectory(env: NodeJS.ProcessEnv = process.env): string {
|
|
54
|
+
const home = env.DSH_HOME !== undefined && env.DSH_HOME !== '' ? env.DSH_HOME : join(homedir(), '.dsh')
|
|
55
|
+
return join(home, 'plugin-data', 'complete-subagent', 'children')
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** File-backed binding store with a synchronous read cache. */
|
|
59
|
+
export class BindingStore {
|
|
60
|
+
private readonly cache = new Map<string, Binding | null>()
|
|
61
|
+
|
|
62
|
+
/** @param directory - where the per-child files live; created on first write. */
|
|
63
|
+
constructor(readonly directory: string) {}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The binding of one child, or undefined when it was not bound by this plugin.
|
|
67
|
+
* @param child - child session id.
|
|
68
|
+
* @returns the stored binding.
|
|
69
|
+
*/
|
|
70
|
+
get(child: string): Binding | undefined {
|
|
71
|
+
const cached = this.cache.get(child)
|
|
72
|
+
if (cached !== undefined) return cached ?? undefined
|
|
73
|
+
const loaded = this.load(child)
|
|
74
|
+
this.cache.set(child, loaded ?? null)
|
|
75
|
+
return loaded
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Store a binding, replacing any earlier one for the same child. The cache is
|
|
80
|
+
* updated first, so a failed write still fences the child for the life of
|
|
81
|
+
* this process; the failure is rethrown for the caller to report.
|
|
82
|
+
* @param binding - the complete binding.
|
|
83
|
+
*/
|
|
84
|
+
set(binding: Binding): void {
|
|
85
|
+
this.cache.set(binding.child, binding)
|
|
86
|
+
mkdirSync(this.directory, { recursive: true })
|
|
87
|
+
const file = this.fileOf(binding.child)
|
|
88
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
89
|
+
writeFileSync(temp, `${JSON.stringify(binding, null, 2)}\n`)
|
|
90
|
+
renameSync(temp, file)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Forget a child, for a delegation that failed to start.
|
|
95
|
+
* @param child - child session id.
|
|
96
|
+
*/
|
|
97
|
+
delete(child: string): void {
|
|
98
|
+
this.cache.set(child, null)
|
|
99
|
+
rmSync(this.fileOf(child), { force: true })
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Add grants to a bound child, skipping ones it already holds.
|
|
104
|
+
* @param child - child session id.
|
|
105
|
+
* @param grants - new grants.
|
|
106
|
+
* @returns the updated binding.
|
|
107
|
+
* @throws when the child is not bound.
|
|
108
|
+
*/
|
|
109
|
+
addGrants(child: string, grants: readonly Grant[]): Binding {
|
|
110
|
+
const binding = this.get(child)
|
|
111
|
+
if (binding === undefined) throw new Error(`child ${child} has no binding`)
|
|
112
|
+
const held = new Set(binding.grants.map(grant => `${grant.kind}:${grant.path}`))
|
|
113
|
+
const added = grants.filter(grant => !held.has(`${grant.kind}:${grant.path}`))
|
|
114
|
+
const next: Binding = { ...binding, grants: [...binding.grants, ...added] }
|
|
115
|
+
this.set(next)
|
|
116
|
+
return next
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Remove a bound child's grants on the given paths, of either kind.
|
|
121
|
+
* @param child - child session id.
|
|
122
|
+
* @param paths - canonical paths to take back.
|
|
123
|
+
* @returns the removed grants.
|
|
124
|
+
* @throws when the child is not bound.
|
|
125
|
+
*/
|
|
126
|
+
removeGrants(child: string, paths: readonly string[]): Grant[] {
|
|
127
|
+
const binding = this.get(child)
|
|
128
|
+
if (binding === undefined) throw new Error(`child ${child} has no binding`)
|
|
129
|
+
const targets = new Set(paths)
|
|
130
|
+
const removed = binding.grants.filter(grant => targets.has(grant.path))
|
|
131
|
+
if (removed.length > 0) this.set({ ...binding, grants: binding.grants.filter(grant => !targets.has(grant.path)) })
|
|
132
|
+
return removed
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private fileOf(child: string): string {
|
|
136
|
+
return join(this.directory, `${encodeURIComponent(child)}.json`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private load(child: string): Binding | undefined {
|
|
140
|
+
let text: string
|
|
141
|
+
try {
|
|
142
|
+
text = readFileSync(this.fileOf(child), 'utf8')
|
|
143
|
+
} catch {
|
|
144
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
const value = JSON.parse(text) as Partial<Binding>
|
|
148
|
+
if (value.version !== 1 || value.child !== child || typeof value.parent !== 'string') return undefined
|
|
149
|
+
if (value.workspace !== null && typeof value.workspace !== 'string') return undefined
|
|
150
|
+
const grants = Array.isArray(value.grants)
|
|
151
|
+
? value.grants.filter((grant): grant is Grant =>
|
|
152
|
+
typeof grant?.path === 'string' && (grant.kind === 'dir' || grant.kind === 'file'))
|
|
153
|
+
: []
|
|
154
|
+
return { version: 1, child, parent: value.parent, workspace: value.workspace, grants, ...value.inherited === true ? { inherited: true } : {} }
|
|
155
|
+
} catch {
|
|
156
|
+
return undefined
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The model-facing write-access tools: a bound child's `request_write_access`,
|
|
3
|
+
* and its parent's `answer_write_request`, `grant_write_access`, and
|
|
4
|
+
* `revoke_write_access`.
|
|
5
|
+
*
|
|
6
|
+
* A request reaches the parent through the host's adjacent-agent channel
|
|
7
|
+
* (`ctx.subagents.sendMessage`): a running parent sees it at its next step, an
|
|
8
|
+
* idle parent starts a turn. The child's call then waits for the answer, so a
|
|
9
|
+
* granted child continues in the same turn. A parent can also grant or revoke
|
|
10
|
+
* without a request; the child reads its current access in its runtime context
|
|
11
|
+
* at every step, and the fence applies it to the next capability call.
|
|
12
|
+
* @module complete-subagent/host/tools
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
16
|
+
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
|
17
|
+
import { grantLine, issueGrants, requestedPaths } from './grants.ts'
|
|
18
|
+
import type { Fence } from './policy.ts'
|
|
19
|
+
import type { RequestBroker, WriteAnswer, WriteRequest } from './requests.ts'
|
|
20
|
+
import type { BindingStore } from './store.ts'
|
|
21
|
+
import { ANSWER_TOOL, GRANT_TOOL, REQUEST_TOOL, REVOKE_TOOL } from './types.ts'
|
|
22
|
+
import type { AgentLike, SandboxPolicy, SessionLike, SubagentsLike, WorkingDirectoryLike } from './types.ts'
|
|
23
|
+
|
|
24
|
+
export { ANSWER_TOOL, GRANT_TOOL, REQUEST_TOOL, REVOKE_TOOL }
|
|
25
|
+
|
|
26
|
+
/** What the tools read. */
|
|
27
|
+
export interface ToolDeps {
|
|
28
|
+
readonly store: BindingStore
|
|
29
|
+
readonly fence: Fence
|
|
30
|
+
readonly broker: RequestBroker
|
|
31
|
+
readonly subagents: SubagentsLike
|
|
32
|
+
readonly workingDirectory: WorkingDirectoryLike
|
|
33
|
+
/** The session's enforced (already narrowed) sandbox policy. */
|
|
34
|
+
readonly resolvePolicy: (session: SessionLike) => SandboxPolicy
|
|
35
|
+
/** How long a parent has to answer. */
|
|
36
|
+
readonly timeoutMs: () => number
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const GRANTED_SCHEMA = {
|
|
40
|
+
type: 'array',
|
|
41
|
+
required: true,
|
|
42
|
+
items: {
|
|
43
|
+
type: 'object',
|
|
44
|
+
additionalProperties: false,
|
|
45
|
+
properties: {
|
|
46
|
+
path: { type: 'string', required: true },
|
|
47
|
+
kind: { type: 'string', required: true, enum: ['dir', 'file'] },
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
} as const
|
|
51
|
+
|
|
52
|
+
const PATHS_DESCRIPTION = 'Relative to your current directory or absolute. End a path with "/" for a whole directory '
|
|
53
|
+
+ '(every tool, including shell commands); a single file is writable through the write and edit tools only.'
|
|
54
|
+
|
|
55
|
+
/** The message the parent receives. */
|
|
56
|
+
export function requestMessage(request: WriteRequest, timeoutMs: number): string {
|
|
57
|
+
const where = request.workspace === null ? 'it has no sub-workspace' : `its sub-workspace is ${request.workspace}`
|
|
58
|
+
return [
|
|
59
|
+
`[write-access request ${request.id}] Subagent ${request.child} asks to modify paths outside its sub-workspace (${where}):`,
|
|
60
|
+
...request.paths.map(item => item.directory ? `- ${item.path}/ (directory)` : `- ${item.path}`),
|
|
61
|
+
`Reason: ${request.reason}`,
|
|
62
|
+
`It is paused until you answer with \`${ANSWER_TOOL}\` (request_id "${request.id}", decision "allow" or "deny"; `
|
|
63
|
+
+ `optional \`paths\` to grant a narrower set, optional \`message\` for the subagent). `
|
|
64
|
+
+ `Unanswered, it is denied after ${Math.round(timeoutMs / 60_000)} minutes.`,
|
|
65
|
+
].join('\n')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Render an answer for the child. */
|
|
69
|
+
function renderAnswer(answer: WriteAnswer): string {
|
|
70
|
+
const lines = answer.decision === 'allow'
|
|
71
|
+
? ['Allowed. You may now modify:', ...answer.granted.map(grantLine)]
|
|
72
|
+
: ['Denied. Do not modify these paths; continue within your sub-workspace or report back to your parent.']
|
|
73
|
+
if (answer.message !== undefined && answer.message !== '') lines.push(`Parent's note: ${answer.message}`)
|
|
74
|
+
return lines.join('\n')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The calling agent, which every tool here needs. */
|
|
78
|
+
function callerOf(exec: { agent?: unknown }, tool: string): AgentLike {
|
|
79
|
+
const agent = exec.agent as AgentLike | undefined
|
|
80
|
+
if (agent === undefined) throw new Error(`${tool} requires a calling agent`)
|
|
81
|
+
return agent
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The caller's own bound child.
|
|
86
|
+
* @returns the child session id.
|
|
87
|
+
* @throws when the id is not a child the caller started through the delegation tools.
|
|
88
|
+
*/
|
|
89
|
+
function ownChild(deps: ToolDeps, parent: AgentLike, agentId: string): string {
|
|
90
|
+
const id = agentId.trim()
|
|
91
|
+
const binding = deps.store.get(id)
|
|
92
|
+
if (binding?.parent !== parent.id || binding.inherited === true) {
|
|
93
|
+
throw new Error(`"${id}" is not a subagent you started with \`delegate\` or \`delegate_fork\`.`)
|
|
94
|
+
}
|
|
95
|
+
return id
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The child-side tool.
|
|
100
|
+
* @param deps - shared state and services.
|
|
101
|
+
* @returns a registry-ready definition.
|
|
102
|
+
*/
|
|
103
|
+
export function createRequestTool(deps: ToolDeps): ToolDefinition {
|
|
104
|
+
return defineTool({
|
|
105
|
+
name: REQUEST_TOOL,
|
|
106
|
+
description: 'Ask your parent agent for permission to modify paths outside your sub-workspace. '
|
|
107
|
+
+ 'You are paused until it answers; on "allow" the listed paths become writable for the rest of your work. '
|
|
108
|
+
+ 'End a path with "/" to ask for a whole directory (every tool, including shell commands); '
|
|
109
|
+
+ 'a single file is granted to the write and edit tools only.',
|
|
110
|
+
parameters: {
|
|
111
|
+
paths: {
|
|
112
|
+
type: 'array',
|
|
113
|
+
required: true,
|
|
114
|
+
items: { type: 'string' },
|
|
115
|
+
description: 'Paths to modify, relative to your current directory or absolute. Ask only for what the task needs.',
|
|
116
|
+
},
|
|
117
|
+
reason: {
|
|
118
|
+
type: 'string',
|
|
119
|
+
required: true,
|
|
120
|
+
description: 'One or two sentences: what you will change there and why.',
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
output: {
|
|
124
|
+
schema: {
|
|
125
|
+
type: 'object',
|
|
126
|
+
additionalProperties: false,
|
|
127
|
+
properties: {
|
|
128
|
+
decision: { type: 'string', required: true, enum: ['allow', 'deny'] },
|
|
129
|
+
granted: GRANTED_SCHEMA,
|
|
130
|
+
message: { type: 'string' },
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
render: (_args, value) => [{ type: 'text', text: renderAnswer(value as WriteAnswer) }],
|
|
134
|
+
},
|
|
135
|
+
isConcurrencySafe: () => true,
|
|
136
|
+
async execute(args, exec): Promise<WriteAnswer> {
|
|
137
|
+
const child = callerOf(exec, REQUEST_TOOL)
|
|
138
|
+
const binding = deps.store.get(child.id)
|
|
139
|
+
if (binding === undefined || binding.inherited === true) {
|
|
140
|
+
throw new Error(`${REQUEST_TOOL} is only for subagents started with \`delegate\` or \`delegate_fork\``)
|
|
141
|
+
}
|
|
142
|
+
if (args.paths.length === 0) throw new Error('List at least one path')
|
|
143
|
+
const base = await deps.workingDirectory.ensure(child, exec.signal)
|
|
144
|
+
const request = deps.broker.open({
|
|
145
|
+
child: child.id,
|
|
146
|
+
parent: binding.parent,
|
|
147
|
+
workspace: binding.workspace,
|
|
148
|
+
paths: requestedPaths(base, args.paths),
|
|
149
|
+
reason: args.reason.trim(),
|
|
150
|
+
})
|
|
151
|
+
try {
|
|
152
|
+
await deps.subagents.sendMessage(child, binding.parent, [{ type: 'text', text: requestMessage(request, deps.timeoutMs()) }], { signal: exec.signal })
|
|
153
|
+
} catch (error) {
|
|
154
|
+
deps.broker.close(request.id)
|
|
155
|
+
if (exec.signal.aborted) throw error
|
|
156
|
+
return { decision: 'deny', granted: [], message: `Your parent agent could not be reached (${error instanceof Error ? error.message : String(error)}); nothing was granted.` }
|
|
157
|
+
}
|
|
158
|
+
return await deps.broker.wait(request.id, deps.timeoutMs(), exec.signal)
|
|
159
|
+
},
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The parent-side answer.
|
|
165
|
+
* @param deps - shared state and services.
|
|
166
|
+
* @returns a registry-ready definition.
|
|
167
|
+
*/
|
|
168
|
+
export function createAnswerTool(deps: ToolDeps): ToolDefinition {
|
|
169
|
+
return defineTool({
|
|
170
|
+
name: ANSWER_TOOL,
|
|
171
|
+
description: 'Answer a write-access request from one of your subagents (a message tagged "[write-access request wr-…]"). '
|
|
172
|
+
+ 'The subagent is paused until you answer. You can grant only paths you can modify yourself.',
|
|
173
|
+
parameters: {
|
|
174
|
+
request_id: { type: 'string', required: true, description: 'The id from the request, like "wr-1a2b3c".' },
|
|
175
|
+
decision: { type: 'string', required: true, enum: ['allow', 'deny'] },
|
|
176
|
+
paths: {
|
|
177
|
+
type: 'array',
|
|
178
|
+
items: { type: 'string' },
|
|
179
|
+
description: `Allow only: the paths to grant instead of the requested ones. ${PATHS_DESCRIPTION} Omit to grant exactly what was requested.`,
|
|
180
|
+
},
|
|
181
|
+
message: { type: 'string', description: 'Optional note for the subagent, such as why you denied or narrowed the request.' },
|
|
182
|
+
},
|
|
183
|
+
output: {
|
|
184
|
+
schema: {
|
|
185
|
+
type: 'object',
|
|
186
|
+
additionalProperties: false,
|
|
187
|
+
properties: {
|
|
188
|
+
request_id: { type: 'string', required: true },
|
|
189
|
+
decision: { type: 'string', required: true, enum: ['allow', 'deny'] },
|
|
190
|
+
granted: GRANTED_SCHEMA,
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
render: (_args, value) => [{
|
|
194
|
+
type: 'text',
|
|
195
|
+
text: value.decision === 'allow'
|
|
196
|
+
? [`Allowed ${value.request_id}. The subagent may now modify:`, ...value.granted.map(grant => grantLine(grant as { path: string; kind: 'dir' | 'file' }))].join('\n')
|
|
197
|
+
: `Denied ${value.request_id}.`,
|
|
198
|
+
}],
|
|
199
|
+
},
|
|
200
|
+
isConcurrencySafe: () => true,
|
|
201
|
+
async execute(args, exec) {
|
|
202
|
+
const parent = callerOf(exec, ANSWER_TOOL)
|
|
203
|
+
const id = args.request_id.trim()
|
|
204
|
+
const open = (): WriteRequest => {
|
|
205
|
+
const request = deps.broker.get(id)
|
|
206
|
+
if (request === undefined) throw new Error(`No open write-access request "${id}": it was already answered, timed out, or was cancelled.`)
|
|
207
|
+
if (request.parent !== parent.id) throw new Error(`Request "${id}" was sent to another agent.`)
|
|
208
|
+
return request
|
|
209
|
+
}
|
|
210
|
+
const request = open()
|
|
211
|
+
const message = args.message?.trim()
|
|
212
|
+
const note = message === undefined || message === '' ? {} : { message }
|
|
213
|
+
if (args.decision === 'deny') {
|
|
214
|
+
deps.broker.settle(id, { decision: 'deny', granted: [], ...note })
|
|
215
|
+
return { request_id: id, decision: 'deny' as const, granted: [] }
|
|
216
|
+
}
|
|
217
|
+
const targets = args.paths === undefined
|
|
218
|
+
? request.paths
|
|
219
|
+
: requestedPaths(await deps.workingDirectory.ensure(parent, exec.signal), args.paths)
|
|
220
|
+
if (targets.length === 0) throw new Error('Grant at least one path, or deny the request')
|
|
221
|
+
open()
|
|
222
|
+
const grants = issueGrants({ fence: deps.fence, store: deps.store, grantor: parent, policy: deps.resolvePolicy(parent.session), targets, requestId: id })
|
|
223
|
+
deps.store.addGrants(request.child, grants)
|
|
224
|
+
const granted = grants.map(grant => ({ path: grant.path, kind: grant.kind }))
|
|
225
|
+
deps.broker.settle(id, { decision: 'allow', granted, ...note })
|
|
226
|
+
return { request_id: id, decision: 'allow' as const, granted }
|
|
227
|
+
},
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The parent-side grant without a request.
|
|
233
|
+
* @param deps - shared state and services.
|
|
234
|
+
* @returns a registry-ready definition.
|
|
235
|
+
*/
|
|
236
|
+
export function createGrantTool(deps: ToolDeps): ToolDefinition {
|
|
237
|
+
return defineTool({
|
|
238
|
+
name: GRANT_TOOL,
|
|
239
|
+
description: 'Let one of your subagents modify more paths without waiting for it to ask, for example when you give it follow-up work. '
|
|
240
|
+
+ 'A running subagent sees the new access at its next step. You can grant only paths you can modify yourself.',
|
|
241
|
+
parameters: {
|
|
242
|
+
agent_id: { type: 'string', required: true, description: 'The subagent id returned when you started it.' },
|
|
243
|
+
paths: { type: 'array', required: true, items: { type: 'string' }, description: `Paths to grant. ${PATHS_DESCRIPTION}` },
|
|
244
|
+
},
|
|
245
|
+
output: {
|
|
246
|
+
schema: {
|
|
247
|
+
type: 'object',
|
|
248
|
+
additionalProperties: false,
|
|
249
|
+
properties: {
|
|
250
|
+
agent_id: { type: 'string', required: true },
|
|
251
|
+
granted: GRANTED_SCHEMA,
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
render: (_args, value) => [{
|
|
255
|
+
type: 'text',
|
|
256
|
+
text: [`Granted to ${value.agent_id}:`, ...value.granted.map(grant => grantLine(grant as { path: string; kind: 'dir' | 'file' }))].join('\n'),
|
|
257
|
+
}],
|
|
258
|
+
},
|
|
259
|
+
isConcurrencySafe: () => true,
|
|
260
|
+
async execute(args, exec) {
|
|
261
|
+
const parent = callerOf(exec, GRANT_TOOL)
|
|
262
|
+
const child = ownChild(deps, parent, args.agent_id)
|
|
263
|
+
if (args.paths.length === 0) throw new Error('List at least one path')
|
|
264
|
+
const targets = requestedPaths(await deps.workingDirectory.ensure(parent, exec.signal), args.paths)
|
|
265
|
+
const grants = issueGrants({ fence: deps.fence, store: deps.store, grantor: parent, policy: deps.resolvePolicy(parent.session), targets, requestId: 'grant' })
|
|
266
|
+
deps.store.addGrants(child, grants)
|
|
267
|
+
return { agent_id: child, granted: grants.map(grant => ({ path: grant.path, kind: grant.kind })) }
|
|
268
|
+
},
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The parent-side revocation.
|
|
274
|
+
* @param deps - shared state and services.
|
|
275
|
+
* @returns a registry-ready definition.
|
|
276
|
+
*/
|
|
277
|
+
export function createRevokeTool(deps: ToolDeps): ToolDefinition {
|
|
278
|
+
return defineTool({
|
|
279
|
+
name: REVOKE_TOOL,
|
|
280
|
+
description: 'Take back paths you granted to one of your subagents. It takes effect at once, also for a running subagent. '
|
|
281
|
+
+ 'The sub-workspace itself cannot be revoked.',
|
|
282
|
+
parameters: {
|
|
283
|
+
agent_id: { type: 'string', required: true, description: 'The subagent id returned when you started it.' },
|
|
284
|
+
paths: { type: 'array', required: true, items: { type: 'string' }, description: 'Granted paths to take back, relative to your current directory or absolute.' },
|
|
285
|
+
},
|
|
286
|
+
output: {
|
|
287
|
+
schema: {
|
|
288
|
+
type: 'object',
|
|
289
|
+
additionalProperties: false,
|
|
290
|
+
properties: {
|
|
291
|
+
agent_id: { type: 'string', required: true },
|
|
292
|
+
revoked: GRANTED_SCHEMA,
|
|
293
|
+
not_granted: { type: 'array', required: true, items: { type: 'string' } },
|
|
294
|
+
},
|
|
295
|
+
},
|
|
296
|
+
render: (_args, value) => {
|
|
297
|
+
const lines = value.revoked.length === 0
|
|
298
|
+
? [`Nothing revoked from ${value.agent_id}.`]
|
|
299
|
+
: [`Revoked from ${value.agent_id}:`, ...value.revoked.map(grant => grantLine(grant as { path: string; kind: 'dir' | 'file' }))]
|
|
300
|
+
if (value.not_granted.length > 0) lines.push(`Not granted, so nothing to revoke: ${value.not_granted.join(', ')}`)
|
|
301
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
302
|
+
},
|
|
303
|
+
},
|
|
304
|
+
isConcurrencySafe: () => true,
|
|
305
|
+
async execute(args, exec) {
|
|
306
|
+
const parent = callerOf(exec, REVOKE_TOOL)
|
|
307
|
+
const child = ownChild(deps, parent, args.agent_id)
|
|
308
|
+
const paths = requestedPaths(await deps.workingDirectory.ensure(parent, exec.signal), args.paths).map(target => target.path)
|
|
309
|
+
const removed = deps.store.removeGrants(child, paths)
|
|
310
|
+
const gone = new Set(removed.map(grant => grant.path))
|
|
311
|
+
return {
|
|
312
|
+
agent_id: child,
|
|
313
|
+
revoked: removed.map(grant => ({ path: grant.path, kind: grant.kind })),
|
|
314
|
+
not_granted: paths.filter(path => !gone.has(path)),
|
|
315
|
+
}
|
|
316
|
+
},
|
|
317
|
+
})
|
|
318
|
+
}
|