dsh-os-kernel 0.0.0-stage → 0.4.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/CHANGELOG.md +124 -0
- package/LICENSE +21 -0
- package/README.md +201 -2
- package/cordis.patch.yml +4 -0
- package/index.js +90 -0
- package/lib/descriptor.js +95 -0
- package/lib/envelope.js +139 -0
- package/lib/from-tool.js +68 -0
- package/lib/gateway.js +670 -0
- package/lib/registry.js +258 -0
- package/lib/service.js +79 -0
- package/lib/state.js +65 -0
- package/lib/taint.js +139 -0
- package/package.json +82 -4
package/lib/gateway.js
ADDED
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent gateway: six plain ToolDefinitions over the capability registry.
|
|
3
|
+
* os_find / os_do / os_request / os_observe / os_help / os_status.
|
|
4
|
+
*/
|
|
5
|
+
import { RISKS } from './descriptor.js'
|
|
6
|
+
import { fingerprint } from './registry.js'
|
|
7
|
+
import { VERSION, RESULT_SCHEMA, ok as makeResult, err as failure, legacyOutcome } from './envelope.js'
|
|
8
|
+
import { createStateStore } from './state.js'
|
|
9
|
+
import { TaintRegistry, sha256 } from './taint.js'
|
|
10
|
+
|
|
11
|
+
export { VERSION, RESULT_SCHEMA }
|
|
12
|
+
export const TOOL_NAMES = Object.freeze(['os_find', 'os_do', 'os_request', 'os_observe', 'os_help', 'os_status'])
|
|
13
|
+
/**
|
|
14
|
+
* Permission names are namespaced `cap:<descriptor.id>` on BOTH sides of the
|
|
15
|
+
* Allow bridge: `os_request` asks for this exact string and `allowedByHost`
|
|
16
|
+
* checks it. The prefix keeps kernel capability grants distinct from a
|
|
17
|
+
* module's own grants (for example Act's `act:invoke:<action>`).
|
|
18
|
+
*/
|
|
19
|
+
export const CAPABILITY_PREFIX = 'cap:'
|
|
20
|
+
export const capabilityName = id => `${CAPABILITY_PREFIX}${id}`
|
|
21
|
+
|
|
22
|
+
const RISK_RANK = Object.freeze({ read: 0, write: 1, execute: 2, network: 2, approval: 2, secret: 3 })
|
|
23
|
+
const OUTPUT = {
|
|
24
|
+
schema: { type: 'object', additionalProperties: true },
|
|
25
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
26
|
+
}
|
|
27
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
28
|
+
const textOf = value => typeof value === 'string' && value.trim() ? value.trim() : null
|
|
29
|
+
const subjectOf = exec => textOf(exec?.subject)
|
|
30
|
+
?? textOf(exec?.agent?.session?.id)
|
|
31
|
+
?? textOf(exec?.agent?.id)
|
|
32
|
+
const maxRisk = risk => Math.max(...risk.map(item => RISK_RANK[item] ?? 0))
|
|
33
|
+
const isRisky = descriptor =>
|
|
34
|
+
descriptor.risk.some(risk => risk === 'write' || risk === 'execute') || descriptor.idempotency === 'destructive'
|
|
35
|
+
|
|
36
|
+
/** Capability ids whose tainted-write gate is enforced by the kernel. */
|
|
37
|
+
const TAINT_WRITE_IDS = new Set(['act.fs.write'])
|
|
38
|
+
const taintTarget = (id, args) => {
|
|
39
|
+
if (TAINT_WRITE_IDS.has(id)) return id
|
|
40
|
+
if (id === 'legacy.act_invoke' && isObject(args) && args.id === 'fs.write') return 'act.fs.write'
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
const taintedCapability = (id, args) => {
|
|
44
|
+
const target = taintTarget(id, args)
|
|
45
|
+
return `${capabilityName(target ?? id)}:tainted`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Exact write text plus the optional token carried in args or nested act args. */
|
|
49
|
+
function taintProbe(id, args) {
|
|
50
|
+
const target = taintTarget(id, args)
|
|
51
|
+
if (target === null || !isObject(args)) return null
|
|
52
|
+
const nested = id === 'legacy.act_invoke' && isObject(args.args) ? args.args : args
|
|
53
|
+
const pick = value => typeof value?.text === 'string' && value.text !== '' ? value.text
|
|
54
|
+
: typeof value?.content === 'string' && value.content !== '' ? value.content : null
|
|
55
|
+
const text = pick(nested) ?? (nested === args ? null : pick(args))
|
|
56
|
+
if (text === null) return null
|
|
57
|
+
const token = typeof args.taintToken === 'string' && args.taintToken !== '' ? args.taintToken
|
|
58
|
+
: typeof nested.taintToken === 'string' && nested.taintToken !== '' ? nested.taintToken : null
|
|
59
|
+
return { target, hash: sha256(text), token }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Drop taint evidence before invoking; the kernel has already evaluated it. */
|
|
63
|
+
function withoutTaint(id, args) {
|
|
64
|
+
const copy = { ...args }
|
|
65
|
+
delete copy.tainted
|
|
66
|
+
delete copy.taintToken
|
|
67
|
+
if (id === 'legacy.act_invoke' && isObject(copy.args)) {
|
|
68
|
+
const nested = { ...copy.args }
|
|
69
|
+
delete nested.tainted
|
|
70
|
+
delete nested.taintToken
|
|
71
|
+
copy.args = nested
|
|
72
|
+
}
|
|
73
|
+
return copy
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const notFound = (id, requestId) => failure('E_NOT_FOUND', `No capability named "${id}".`, {
|
|
77
|
+
subcode: 'unknown_capability',
|
|
78
|
+
remediation: 'Call os_find with a short intent to discover the right capability, then retry os_do.',
|
|
79
|
+
nextTools: [{ tool: 'os_find', args: { intent: id }, why: 'find the closest capability id' }],
|
|
80
|
+
requestId,
|
|
81
|
+
details: { id },
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
const isGrant = grant => {
|
|
85
|
+
if (!grant) return false
|
|
86
|
+
if (typeof grant === 'string') return grant.length > 0
|
|
87
|
+
if (typeof grant !== 'object') return false
|
|
88
|
+
if (grant.revoked === true) return false
|
|
89
|
+
if (typeof grant.status === 'string' && !['active', 'granted', 'issued', 'approved'].includes(grant.status)) return false
|
|
90
|
+
if (typeof grant.expiresAt === 'number' && grant.expiresAt <= Date.now()) return false
|
|
91
|
+
if (typeof grant.uses === 'number' && Number.isFinite(grant.maxUses) && grant.uses >= grant.maxUses) return false
|
|
92
|
+
return true
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function card(descriptor) {
|
|
96
|
+
return {
|
|
97
|
+
id: descriptor.id,
|
|
98
|
+
title: descriptor.title,
|
|
99
|
+
summary: descriptor.summary,
|
|
100
|
+
risk: [...descriptor.risk],
|
|
101
|
+
permissions: [...descriptor.permissions],
|
|
102
|
+
cost: { ...descriptor.cost },
|
|
103
|
+
example: descriptor.examples?.[0] ?? null,
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Build a gateway over one registry.
|
|
109
|
+
* @param {any} registry
|
|
110
|
+
* @param {{ctx?: any, stateFile?: string, gatewayOnly?: boolean, taint?: any}} [options]
|
|
111
|
+
*/
|
|
112
|
+
export function createGateway(registry, options = {}) {
|
|
113
|
+
if (!registry || typeof registry.resolve !== 'function') throw new TypeError('createGateway needs a registry')
|
|
114
|
+
const ctx = options.ctx ?? null
|
|
115
|
+
const stateFile = options.stateFile
|
|
116
|
+
const requests = new Map()
|
|
117
|
+
const jobs = new Map()
|
|
118
|
+
const handles = new Map()
|
|
119
|
+
const idempotency = new Map()
|
|
120
|
+
const autoGrants = new Map()
|
|
121
|
+
const taint = options.taint instanceof TaintRegistry ? options.taint : new TaintRegistry(options.taint)
|
|
122
|
+
let idempotencyStore = null
|
|
123
|
+
try {
|
|
124
|
+
idempotencyStore = createStateStore(stateFile)
|
|
125
|
+
} catch (error) {
|
|
126
|
+
throw new TypeError(error?.message ?? String(error))
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Resolve the Allow service once per call; a throwing getter fails closed. */
|
|
130
|
+
function allowService() {
|
|
131
|
+
// Prefer the injected getter; the direct property is a test/host fallback.
|
|
132
|
+
// Cordis throws on an uninjected read, so it stays inside try/catch.
|
|
133
|
+
try { if (ctx?.allow) return ctx.allow } catch { /* not injected */ }
|
|
134
|
+
if (typeof ctx?.get !== 'function') return null
|
|
135
|
+
try { return ctx.get('allow') ?? null } catch { return null }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Pull the newest request snapshot from the host Allow service. */
|
|
139
|
+
async function latestRequest(requestId, subject) {
|
|
140
|
+
const allow = allowService()
|
|
141
|
+
if (!allow) return null
|
|
142
|
+
if (typeof allow.requests === 'function') {
|
|
143
|
+
for (const filter of subject ? [{ subject }] : [{}]) {
|
|
144
|
+
try {
|
|
145
|
+
const list = await allow.requests(filter)
|
|
146
|
+
const items = Array.isArray(list) ? list : Array.isArray(list?.requests) ? list.requests : []
|
|
147
|
+
const found = items.find(item => item?.id === requestId || item?.requestId === requestId)
|
|
148
|
+
if (found) return found
|
|
149
|
+
} catch { /* try the next seam */ }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (typeof allow.wait === 'function') {
|
|
153
|
+
try { return await allow.wait(requestId, { timeoutMs: 0, ...(subject ? { subject } : {}) }) } catch { /* not visible */ }
|
|
154
|
+
}
|
|
155
|
+
for (const method of ['get', 'status', 'observe']) {
|
|
156
|
+
if (typeof allow[method] !== 'function') continue
|
|
157
|
+
try { const found = await allow[method](requestId); if (found) return found } catch { /* keep local */ }
|
|
158
|
+
}
|
|
159
|
+
return null
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Consume one approved Grant exactly once and remember it for the matching
|
|
164
|
+
* `os_do` call. The Allow check is the atomic use(), and it deliberately
|
|
165
|
+
* omits scope so an approval narrowed by the human still authorizes.
|
|
166
|
+
*/
|
|
167
|
+
async function cacheAutoGrant(requestId, local) {
|
|
168
|
+
const existing = autoGrants.get(requestId)
|
|
169
|
+
if (existing) return { grant: existing.grant, reason: null }
|
|
170
|
+
const allow = allowService()
|
|
171
|
+
if (!allow || typeof allow.check !== 'function') return { grant: null, reason: 'check_unavailable' }
|
|
172
|
+
try {
|
|
173
|
+
const decision = await allow.check({ subject: local.subject, capability: local.capability })
|
|
174
|
+
if (decision?.allowed !== true) return { grant: null, reason: decision?.reason ?? 'no-grant' }
|
|
175
|
+
const grant = decision.grant ?? { id: `grant_auto_${requestId}`, status: 'active' }
|
|
176
|
+
autoGrants.set(requestId, {
|
|
177
|
+
requestId, id: local.capabilityId, argsHash: local.argsHash, subject: local.subject,
|
|
178
|
+
capability: local.capability, grant, at: Date.now(),
|
|
179
|
+
})
|
|
180
|
+
return { grant, reason: null }
|
|
181
|
+
} catch (error) {
|
|
182
|
+
return { grant: null, reason: error?.code ?? 'check_failed' }
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Peek at a cached approval bound to this subject/id/args/capability. */
|
|
187
|
+
function findAutoGrant(subject, id, argsHash, capability) {
|
|
188
|
+
if (!subject || !argsHash) return null
|
|
189
|
+
for (const item of autoGrants.values()) {
|
|
190
|
+
if (item.id === id && item.subject === subject && item.argsHash === argsHash
|
|
191
|
+
&& (capability === undefined || item.capability === capability)) return item
|
|
192
|
+
}
|
|
193
|
+
return null
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Take (and thus consume) the cached approval found by `findAutoGrant`. */
|
|
197
|
+
function takeAutoGrant(item) {
|
|
198
|
+
if (!item) return null
|
|
199
|
+
return autoGrants.get(item.requestId) === item ? (autoGrants.delete(item.requestId), item) : null
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function remember(value) {
|
|
203
|
+
if (!isObject(value)) return
|
|
204
|
+
const job = value.job ?? value.data?.job
|
|
205
|
+
if (job && typeof job.id === 'string') jobs.set(job.id, job)
|
|
206
|
+
for (const handle of value.handles ?? []) if (handle?.ref) handles.set(handle.ref, handle)
|
|
207
|
+
for (const handle of value.data?.handles ?? []) if (handle?.ref) handles.set(handle.ref, handle)
|
|
208
|
+
const ref = value.handle ?? value.data?.handle
|
|
209
|
+
if (typeof ref === 'string' && ref.startsWith('dsh://')) handles.set(ref, { ref })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Lazy legacy bridge: the first os_find/os_status adapts the host tools that
|
|
213
|
+
// are visible to the calling agent. Hosts without schemas/get are skipped.
|
|
214
|
+
let legacyReady = false
|
|
215
|
+
const refreshLegacy = typeof registry.refreshLegacy === 'function' ? registry.refreshLegacy.bind(registry) : null
|
|
216
|
+
async function ensureLegacy(exec) {
|
|
217
|
+
if (legacyReady || !refreshLegacy) return
|
|
218
|
+
const tools = ctx?.tools
|
|
219
|
+
if (!tools || typeof tools.schemas !== 'function' || typeof tools.get !== 'function') return
|
|
220
|
+
// gatewayOnly restricts the agent's *tool* view; the kernel still needs the
|
|
221
|
+
// global view so those tools remain reachable as os_find/os_do capabilities.
|
|
222
|
+
const scope = options.gatewayOnly === true ? undefined : exec?.agent
|
|
223
|
+
try { await refreshLegacy({ scope }) } catch { return }
|
|
224
|
+
legacyReady = true
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function find(input = {}, exec = {}) {
|
|
228
|
+
await ensureLegacy(exec)
|
|
229
|
+
const intent = textOf(input.intent)
|
|
230
|
+
if (!intent) return failure('E_INVALID_ARGUMENT', 'intent must be a non-empty string.', {
|
|
231
|
+
remediation: 'Pass a short task intent, for example "search clipboard history".',
|
|
232
|
+
nextTools: [{ tool: 'os_help', args: { task: intent ?? 'discover capabilities' }, why: 'get task-level guidance' }],
|
|
233
|
+
})
|
|
234
|
+
const limit = Math.min(Math.max(Number.isInteger(input.limit) ? input.limit : 5, 1), 10)
|
|
235
|
+
const riskMax = input.riskMax === undefined ? null : RISKS.includes(input.riskMax) ? input.riskMax : undefined
|
|
236
|
+
if (riskMax === undefined) return failure('E_INVALID_ARGUMENT', `riskMax must be one of ${RISKS.join(', ')}.`)
|
|
237
|
+
let matches = registry.search(intent, { limit: 200 })
|
|
238
|
+
if (riskMax) matches = matches.filter(descriptor => maxRisk(descriptor.risk) <= RISK_RANK[riskMax])
|
|
239
|
+
return { ok: true, intent, items: matches.slice(0, limit).map(card), total: matches.length, truncated: matches.length > limit }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function allowedByHost(exec, descriptor) {
|
|
243
|
+
const subject = subjectOf(exec)
|
|
244
|
+
const allow = allowService()
|
|
245
|
+
if (!subject || !allow || typeof allow.check !== 'function') return false
|
|
246
|
+
try {
|
|
247
|
+
const decision = await allow.check({ subject, capability: capabilityName(descriptor.id) })
|
|
248
|
+
return decision?.allowed === true
|
|
249
|
+
} catch {
|
|
250
|
+
return false
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const denied = (descriptor, args, exec) => failure('E_DENIED',
|
|
255
|
+
`Capability "${descriptor.id}" needs a grant for ${descriptor.risk.join('/')} access.`, {
|
|
256
|
+
subcode: 'grant_required',
|
|
257
|
+
remediation: 'Call os_request with the same id and args, then call os_observe to refresh and consume the approved grant.',
|
|
258
|
+
nextTools: [
|
|
259
|
+
{ tool: 'os_request', args: { id: descriptor.id, args, reason: `Grant ${descriptor.risk.join('/')} access to ${descriptor.id}.` }, why: 'create the pending approval' },
|
|
260
|
+
{ tool: 'os_find', args: { intent: descriptor.id }, why: 'read the capability card and its risk' },
|
|
261
|
+
],
|
|
262
|
+
requestId: exec?.requestId,
|
|
263
|
+
details: { capability: descriptor.id, permission: capabilityName(descriptor.id), risk: descriptor.risk, permissions: descriptor.permissions },
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
/** Ask Allow for a tainted-write capability without consuming a cached grant. */
|
|
267
|
+
async function taintedAllowed(exec, capability) {
|
|
268
|
+
const subject = subjectOf(exec)
|
|
269
|
+
const allow = allowService()
|
|
270
|
+
if (!subject || !allow || typeof allow.check !== 'function') return false
|
|
271
|
+
try {
|
|
272
|
+
return (await allow.check({ subject, capability }))?.allowed === true
|
|
273
|
+
} catch {
|
|
274
|
+
return false
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const taintDenied = (descriptor, args, probe, record, exec) => failure('E_DENIED',
|
|
279
|
+
`Writing content from a tainted source to "${probe.target}" needs a separate tainted Grant.`, {
|
|
280
|
+
subcode: 'grant_required',
|
|
281
|
+
remediation: 'Call os_request with tainted:true and the same id and args, then os_observe; or pass a fresh taintToken from the read.',
|
|
282
|
+
nextTools: [
|
|
283
|
+
{ tool: 'os_request', args: { id: descriptor.id, args, reason: `Grant tainted-write access to ${probe.target}.`, tainted: true }, why: 'create the pending tainted-write approval' },
|
|
284
|
+
{ tool: 'os_find', args: { intent: probe.target }, why: 'read the capability card and its tainted permission' },
|
|
285
|
+
],
|
|
286
|
+
requestId: exec?.requestId,
|
|
287
|
+
details: {
|
|
288
|
+
capability: descriptor.id,
|
|
289
|
+
permission: `${capabilityName(probe.target)}:tainted`,
|
|
290
|
+
tainted: true,
|
|
291
|
+
taintSource: record?.source ?? null,
|
|
292
|
+
reason: probe.token ? 'invalid_taint_token' : 'taint_required',
|
|
293
|
+
},
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
async function execute(input = {}, exec = {}) {
|
|
297
|
+
const id = textOf(input.id)
|
|
298
|
+
if (!id) return failure('E_INVALID_ARGUMENT', 'id must be a non-empty capability id.', {
|
|
299
|
+
remediation: 'Call os_find first; pass the id from a returned card.',
|
|
300
|
+
nextTools: [{ tool: 'os_find', args: { intent: 'capabilities' }, why: 'discover capability ids' }],
|
|
301
|
+
requestId: exec?.requestId,
|
|
302
|
+
})
|
|
303
|
+
let args = input.args === undefined ? {} : input.args
|
|
304
|
+
const providedGrant = input.grant ?? exec?.grant ?? (isObject(args) ? args.grant : undefined)
|
|
305
|
+
if (providedGrant && isObject(args) && Object.prototype.hasOwnProperty.call(args, 'grant')) {
|
|
306
|
+
const { grant: _ignored, ...rest } = args
|
|
307
|
+
args = rest
|
|
308
|
+
}
|
|
309
|
+
if (!isObject(args)) return failure('E_INVALID_ARGUMENT', 'args must be an object.', {
|
|
310
|
+
remediation: 'Pass args as a JSON object matching the capability inputSchema.',
|
|
311
|
+
requestId: exec?.requestId,
|
|
312
|
+
})
|
|
313
|
+
if (id.startsWith('legacy.')) await ensureLegacy(exec)
|
|
314
|
+
const descriptor = await registry.resolve(id)
|
|
315
|
+
if (!descriptor) return notFound(id, exec?.requestId)
|
|
316
|
+
const gated = isRisky(descriptor)
|
|
317
|
+
const argsHash = fingerprint(args)
|
|
318
|
+
const subject = subjectOf(exec)
|
|
319
|
+
// A grant cached by os_observe is bound to the exact subject/id/args triple.
|
|
320
|
+
const auto = gated && !isGrant(providedGrant)
|
|
321
|
+
? findAutoGrant(subject, descriptor.id, argsHash, capabilityName(descriptor.id)) : null
|
|
322
|
+
const grant = providedGrant ?? auto?.grant ?? undefined
|
|
323
|
+
const authorized = !gated || Boolean(auto) || isGrant(grant)
|
|
324
|
+
if (input.preview === true) {
|
|
325
|
+
if (!authorized && !(await allowedByHost(exec, descriptor))) return denied(descriptor, args, exec)
|
|
326
|
+
return makeResult(descriptor.id, { preview: true, id: descriptor.id, args, risk: descriptor.risk, gated }, {
|
|
327
|
+
summary: `Preview only: ${descriptor.id} was not executed.`,
|
|
328
|
+
requestId: exec?.requestId,
|
|
329
|
+
next: gated ? [{ tool: 'os_request', args: { id: descriptor.id, args }, why: 'request approval before executing' }] : [],
|
|
330
|
+
})
|
|
331
|
+
}
|
|
332
|
+
const key = textOf(input.idempotencyKey)
|
|
333
|
+
const slot = key ? `${subject ?? ''}\0${descriptor.id}\0${key}` : null
|
|
334
|
+
if (slot) {
|
|
335
|
+
const previous = idempotency.get(slot) ?? idempotencyStore?.get(slot)
|
|
336
|
+
if (previous) {
|
|
337
|
+
if (previous.argsHash !== argsHash) {
|
|
338
|
+
return failure('E_CONFLICT', 'This idempotencyKey was used with different args.', {
|
|
339
|
+
subcode: 'idempotency_reuse',
|
|
340
|
+
remediation: 'Retry with a fresh idempotencyKey, or replay the original args.',
|
|
341
|
+
requestId: exec?.requestId,
|
|
342
|
+
details: { capability: descriptor.id },
|
|
343
|
+
})
|
|
344
|
+
}
|
|
345
|
+
return previous.result
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (!authorized && !(await allowedByHost(exec, descriptor))) return denied(descriptor, args, exec)
|
|
349
|
+
// Content-hash taint gate: the model no longer decides by writing
|
|
350
|
+
// `tainted:true`; a digest registered from snip_get/seek_resolve/
|
|
351
|
+
// trigger_runs (or any result carrying a taintToken) forces the extra
|
|
352
|
+
// :tainted Grant. A fresh, hash-bound token is the one-time alternative.
|
|
353
|
+
let callArgs = args
|
|
354
|
+
let taintAuto = null
|
|
355
|
+
const probe = taintProbe(descriptor.id, args)
|
|
356
|
+
if (probe) {
|
|
357
|
+
const record = taint.lookup(probe.hash)
|
|
358
|
+
if (record !== undefined || probe.token !== null) {
|
|
359
|
+
let cleared = record !== undefined && probe.token !== null && taint.consume(probe.hash, probe.token)
|
|
360
|
+
if (!cleared) {
|
|
361
|
+
const capability = taintedCapability(descriptor.id, args)
|
|
362
|
+
const cached = findAutoGrant(subject, descriptor.id, argsHash, capability)
|
|
363
|
+
if (cached) {
|
|
364
|
+
taintAuto = cached
|
|
365
|
+
cleared = true
|
|
366
|
+
} else {
|
|
367
|
+
cleared = await taintedAllowed(exec, capability)
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (!cleared) return taintDenied(descriptor, args, probe, record, exec)
|
|
371
|
+
callArgs = withoutTaint(descriptor.id, args)
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// Consume only after every check and after the idempotency replay path, so
|
|
375
|
+
// a replayed call never burns a fresh approval and an approval is used once.
|
|
376
|
+
if (auto) takeAutoGrant(auto)
|
|
377
|
+
if (taintAuto) takeAutoGrant(taintAuto)
|
|
378
|
+
const callRequestId = auto?.requestId ?? taintAuto?.requestId ?? exec?.requestId
|
|
379
|
+
const started = Date.now()
|
|
380
|
+
let outcome
|
|
381
|
+
try {
|
|
382
|
+
outcome = await registry.invoke(descriptor.id, callArgs, {
|
|
383
|
+
ctx, subject: subjectOf(exec), agent: exec?.agent, signal: exec?.signal, grant, requestId: callRequestId,
|
|
384
|
+
})
|
|
385
|
+
} catch (error) {
|
|
386
|
+
return failure('E_INTERNAL', error?.message ?? String(error), {
|
|
387
|
+
remediation: 'Report requestId to the maintainer; do not retry blindly.',
|
|
388
|
+
requestId: callRequestId,
|
|
389
|
+
details: { capability: descriptor.id },
|
|
390
|
+
})
|
|
391
|
+
}
|
|
392
|
+
if (!outcome.ok) {
|
|
393
|
+
return failure(outcome.legacyCode ?? outcome.code, outcome.message ?? `Capability ${descriptor.id} failed.`, {
|
|
394
|
+
subcode: outcome.code === 'E_DENIED' ? 'grant_required' : null,
|
|
395
|
+
remediation: outcome.code === 'E_DENIED'
|
|
396
|
+
? 'Call os_request with the same id and args, then call os_observe to refresh the approval.'
|
|
397
|
+
: 'Call os_find to inspect the capability card, fix the args if needed, then retry.',
|
|
398
|
+
nextTools: outcome.code === 'E_DENIED'
|
|
399
|
+
? [{ tool: 'os_request', args: { id: descriptor.id, args }, why: 'request a grant' }]
|
|
400
|
+
: [{ tool: 'os_find', args: { intent: descriptor.id }, why: 'inspect the capability card' }],
|
|
401
|
+
requestId: callRequestId,
|
|
402
|
+
details: { capability: descriptor.id },
|
|
403
|
+
})
|
|
404
|
+
}
|
|
405
|
+
// Legacy tools often return their own `{ ok, error }` envelope; normalize it
|
|
406
|
+
// through the kernel's err()/ok() pair instead of nesting it as data.
|
|
407
|
+
const normalized = descriptor.legacy === true ? legacyOutcome(outcome.value) : null
|
|
408
|
+
if (normalized?.ok === false) {
|
|
409
|
+
const legacy = normalized.error
|
|
410
|
+
const code = legacy.code ?? 'E_INTERNAL'
|
|
411
|
+
const denied = code === 'E_DENIED' || code === 'grant_required'
|
|
412
|
+
return failure(code, legacy.message ?? `Legacy capability ${descriptor.id} failed.`, {
|
|
413
|
+
subcode: legacy.subcode ?? (denied ? 'grant_required' : null),
|
|
414
|
+
retryable: legacy.retryable,
|
|
415
|
+
retryAfterMs: legacy.retryAfterMs,
|
|
416
|
+
remediation: legacy.remediation ?? (denied
|
|
417
|
+
? 'Call os_request with the same id and args, then call os_observe to refresh the approval.'
|
|
418
|
+
: undefined),
|
|
419
|
+
nextTools: Array.isArray(legacy.nextTools) ? legacy.nextTools : denied
|
|
420
|
+
? [{ tool: 'os_request', args: { id: descriptor.id, args }, why: 'request a grant' }]
|
|
421
|
+
: undefined,
|
|
422
|
+
requestId: callRequestId,
|
|
423
|
+
details: { capability: descriptor.id, ...(isObject(legacy.details) ? legacy.details : {}) },
|
|
424
|
+
})
|
|
425
|
+
}
|
|
426
|
+
const value = normalized?.ok === true ? normalized.value : outcome.value
|
|
427
|
+
const result = makeResult(descriptor.id, value, { requestId: callRequestId, latencyMs: Date.now() - started })
|
|
428
|
+
remember(value)
|
|
429
|
+
taint.observe(descriptor.id, value)
|
|
430
|
+
if (slot) {
|
|
431
|
+
const entry = { argsHash, result }
|
|
432
|
+
idempotency.set(slot, entry)
|
|
433
|
+
if (idempotencyStore) {
|
|
434
|
+
try {
|
|
435
|
+
idempotencyStore.set(slot, entry)
|
|
436
|
+
} catch (error) {
|
|
437
|
+
result.warnings.push(`idempotency result was not persisted: ${error?.message ?? String(error)}`)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return result
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function request(input = {}, exec = {}) {
|
|
445
|
+
const id = textOf(input.id)
|
|
446
|
+
if (!id) return failure('E_INVALID_ARGUMENT', 'id must be a non-empty capability id.', {
|
|
447
|
+
remediation: 'Call os_find first; pass the id from a returned card.',
|
|
448
|
+
nextTools: [{ tool: 'os_find', args: { intent: 'capabilities' }, why: 'discover capability ids' }],
|
|
449
|
+
requestId: exec?.requestId,
|
|
450
|
+
})
|
|
451
|
+
const reason = textOf(input.reason)
|
|
452
|
+
if (!reason) return failure('E_INVALID_ARGUMENT', 'reason must be a non-empty string.', {
|
|
453
|
+
remediation: 'Describe why this action is needed in one short sentence.',
|
|
454
|
+
requestId: exec?.requestId,
|
|
455
|
+
})
|
|
456
|
+
const args = input.args === undefined ? {} : input.args
|
|
457
|
+
if (!isObject(args)) return failure('E_INVALID_ARGUMENT', 'args must be an object.', { requestId: exec?.requestId })
|
|
458
|
+
const descriptor = await registry.resolve(id)
|
|
459
|
+
if (!descriptor) return notFound(id, exec?.requestId)
|
|
460
|
+
const allow = allowService()
|
|
461
|
+
if (!allow || typeof allow.request !== 'function') {
|
|
462
|
+
return failure('E_UNAVAILABLE', 'No Allow request service is available, so nothing can be approved.', {
|
|
463
|
+
subcode: 'dependency_missing',
|
|
464
|
+
remediation: 'Install/enable dsh-allow (ctx.allow.request) and retry os_request.',
|
|
465
|
+
nextTools: [{ tool: 'os_status', why: 'check installed modules and health' }],
|
|
466
|
+
requestId: exec?.requestId,
|
|
467
|
+
details: { service: 'allow.request' },
|
|
468
|
+
})
|
|
469
|
+
}
|
|
470
|
+
// os_do treats an `args.grant` shortcut as a grant, not capability input,
|
|
471
|
+
// so the approval fingerprint must use the same normalized args.
|
|
472
|
+
const requestArgs = isObject(args) && Object.prototype.hasOwnProperty.call(args, 'grant')
|
|
473
|
+
? Object.fromEntries(Object.entries(args).filter(([key]) => key !== 'grant')) : args
|
|
474
|
+
// `tainted:true` asks for `<target>:tainted` instead of the base capability;
|
|
475
|
+
// legacy.act_invoke maps to act.fs.write so both verbs share one approval.
|
|
476
|
+
const capability = input.tainted === true
|
|
477
|
+
? taintedCapability(descriptor.id, requestArgs)
|
|
478
|
+
: capabilityName(descriptor.id)
|
|
479
|
+
const subject = subjectOf(exec)
|
|
480
|
+
if (!subject) {
|
|
481
|
+
return failure('E_INVALID_ARGUMENT', 'os_request needs an executing subject.', {
|
|
482
|
+
remediation: 'Call os_request from an agent turn; the host supplies exec.subject or exec.agent.session.id.',
|
|
483
|
+
requestId: exec?.requestId,
|
|
484
|
+
})
|
|
485
|
+
}
|
|
486
|
+
let response
|
|
487
|
+
try {
|
|
488
|
+
response = await allow.request({
|
|
489
|
+
subject, capability, scope: '*', maxUses: 1, reason,
|
|
490
|
+
})
|
|
491
|
+
} catch (error) {
|
|
492
|
+
return failure(error?.code, error?.message ?? String(error), {
|
|
493
|
+
remediation: 'Fix the request args, or inspect Allow with os_status, then retry os_request.',
|
|
494
|
+
requestId: exec?.requestId,
|
|
495
|
+
})
|
|
496
|
+
}
|
|
497
|
+
const requestId = typeof response === 'string' ? response : response?.requestId ?? response?.id ?? response?.request?.id
|
|
498
|
+
if (typeof requestId !== 'string' || requestId === '') {
|
|
499
|
+
return failure('E_INTERNAL', 'Allow returned no requestId.', {
|
|
500
|
+
remediation: 'Report this to the maintainer; do not retry automatically.',
|
|
501
|
+
requestId: exec?.requestId,
|
|
502
|
+
})
|
|
503
|
+
}
|
|
504
|
+
const status = response?.status ?? response?.state ?? 'pending'
|
|
505
|
+
const hint = response?.hint ?? response?.approvalHint
|
|
506
|
+
?? 'A human must decide; then call os_observe with this requestId and retry os_do with the same id and args.'
|
|
507
|
+
requests.set(requestId, {
|
|
508
|
+
requestId, capabilityId: descriptor.id, capability, argsHash: fingerprint(requestArgs), subject,
|
|
509
|
+
reason, status, scope: '*', createdAt: Date.now(), response,
|
|
510
|
+
})
|
|
511
|
+
return { ok: true, requestId, status, hint, id: descriptor.id, capability }
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async function observe(input = {}, exec = {}) {
|
|
515
|
+
const requestId = textOf(input.requestId)
|
|
516
|
+
const jobId = textOf(input.jobId)
|
|
517
|
+
const handle = textOf(input.handle)
|
|
518
|
+
if (!requestId && !jobId && !handle) {
|
|
519
|
+
return failure('E_INVALID_ARGUMENT', 'Pass one of requestId, jobId or handle.', {
|
|
520
|
+
remediation: 'Use the requestId from os_request, a jobId from a job result, or a dsh:// handle.',
|
|
521
|
+
requestId: exec?.requestId,
|
|
522
|
+
})
|
|
523
|
+
}
|
|
524
|
+
if (requestId) {
|
|
525
|
+
const local = requests.get(requestId)
|
|
526
|
+
if (local && subjectOf(exec) && local.subject !== subjectOf(exec)) {
|
|
527
|
+
return failure('E_NOT_FOUND', `No request named "${requestId}".`, {
|
|
528
|
+
subcode: 'request_not_found', requestId: exec?.requestId,
|
|
529
|
+
})
|
|
530
|
+
}
|
|
531
|
+
const remote = await latestRequest(requestId, local?.subject ?? subjectOf(exec))
|
|
532
|
+
if (!local && !remote) return failure('E_NOT_FOUND', `No request named "${requestId}".`, {
|
|
533
|
+
subcode: 'request_not_found',
|
|
534
|
+
remediation: 'Call os_request to create a pending request, then observe its requestId.',
|
|
535
|
+
requestId: exec?.requestId,
|
|
536
|
+
})
|
|
537
|
+
const state = remote?.state ?? remote?.status ?? local?.status ?? 'pending'
|
|
538
|
+
let grant = null
|
|
539
|
+
let grantReason = null
|
|
540
|
+
if (state === 'approved') {
|
|
541
|
+
if (local) ({ grant, reason: grantReason } = await cacheAutoGrant(requestId, local))
|
|
542
|
+
else grantReason = 'request_not_created_by_kernel'
|
|
543
|
+
} else {
|
|
544
|
+
autoGrants.delete(requestId)
|
|
545
|
+
}
|
|
546
|
+
if (local) local.status = state
|
|
547
|
+
return {
|
|
548
|
+
ok: true, kind: 'request', requestId, state, status: state,
|
|
549
|
+
id: local?.capabilityId ?? null,
|
|
550
|
+
capability: local?.capability ?? remote?.capability ?? null,
|
|
551
|
+
request: { ...(local ?? {}), ...(isObject(remote) ? remote : {}) },
|
|
552
|
+
result: grant ?? remote?.grant ?? remote?.result ?? null,
|
|
553
|
+
grantAvailable: Boolean(grant),
|
|
554
|
+
...(grantReason ? { grantReason } : {}),
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (jobId) {
|
|
558
|
+
let job = jobs.get(jobId)
|
|
559
|
+
if (!job && typeof ctx?.jobs?.get === 'function') {
|
|
560
|
+
try { job = await ctx.jobs.get(jobId) } catch { /* not found */ }
|
|
561
|
+
}
|
|
562
|
+
if (!job) return failure('E_NOT_FOUND', `No job named "${jobId}".`, {
|
|
563
|
+
subcode: 'job_not_found',
|
|
564
|
+
remediation: 'Use the jobId returned in an OsResult job field; jobs expire with the session.',
|
|
565
|
+
requestId: exec?.requestId,
|
|
566
|
+
})
|
|
567
|
+
const state = job.state ?? job.status ?? 'unknown'
|
|
568
|
+
return { ok: true, kind: 'job', jobId, state, job, progress: job.progress ?? null, result: job.result ?? null }
|
|
569
|
+
}
|
|
570
|
+
let entry = handles.get(handle)
|
|
571
|
+
if (!entry && typeof ctx?.handles?.resolve === 'function') {
|
|
572
|
+
try { entry = await ctx.handles.resolve(handle) } catch { /* not found */ }
|
|
573
|
+
}
|
|
574
|
+
if (!entry && typeof ctx?.handles?.get === 'function') {
|
|
575
|
+
try { entry = await ctx.handles.get(handle) } catch { /* not found */ }
|
|
576
|
+
}
|
|
577
|
+
if (!entry) return failure('E_NOT_FOUND', `No handle named "${handle}".`, {
|
|
578
|
+
subcode: 'handle_not_found',
|
|
579
|
+
remediation: 'Handles expire; rerun the capability that produced the handle.',
|
|
580
|
+
requestId: exec?.requestId,
|
|
581
|
+
})
|
|
582
|
+
return { ok: true, kind: 'handle', handle, state: 'available', result: entry }
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
async function help(input = {}) {
|
|
586
|
+
const task = textOf(input.task)
|
|
587
|
+
if (!task) return failure('E_INVALID_ARGUMENT', 'task must be a non-empty string.', {
|
|
588
|
+
remediation: 'Pass the user task in one short sentence.',
|
|
589
|
+
})
|
|
590
|
+
const matches = registry.search(task, { limit: 5 })
|
|
591
|
+
const steps = [
|
|
592
|
+
`Call os_find with intent "${task}" to see the top matching capability cards.`,
|
|
593
|
+
'Call os_do with the chosen id and args. Read ok before using any other field.',
|
|
594
|
+
'If os_do returns E_DENIED, call os_request with the same id and args, then wait for a human decision.',
|
|
595
|
+
'Call os_observe with the requestId; once approved it consumes the Grant and os_do can run without an injected grant.',
|
|
596
|
+
]
|
|
597
|
+
return {
|
|
598
|
+
ok: true,
|
|
599
|
+
task,
|
|
600
|
+
steps,
|
|
601
|
+
capabilities: matches.map(descriptor => ({ id: descriptor.id, title: descriptor.title, risk: [...descriptor.risk] })),
|
|
602
|
+
risks: [...new Set(matches.flatMap(descriptor => descriptor.risk))],
|
|
603
|
+
example: matches[0]?.examples?.[0] ?? null,
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
async function status(_input = {}, exec = {}) {
|
|
608
|
+
await ensureLegacy(exec)
|
|
609
|
+
const all = registry.list({ includeDeprecated: true, limit: 200 })
|
|
610
|
+
const legacy = all.filter(descriptor => descriptor.legacy === true).length
|
|
611
|
+
const counts = typeof registry.stats === 'function' ? registry.stats() : { legacy, capabilities: all.length - legacy, total: all.length }
|
|
612
|
+
const modules = [...new Set(all.filter(descriptor => descriptor.legacy !== true).map(descriptor => descriptor.id.split('.')[0]))].sort()
|
|
613
|
+
return {
|
|
614
|
+
ok: true,
|
|
615
|
+
version: VERSION,
|
|
616
|
+
modules,
|
|
617
|
+
...counts,
|
|
618
|
+
health: {
|
|
619
|
+
status: 'ok', ...counts,
|
|
620
|
+
namespaces: modules.length, deprecated: all.filter(descriptor => descriptor.deprecated).length,
|
|
621
|
+
},
|
|
622
|
+
tools: [...TOOL_NAMES],
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const defineTool = (name, description, properties, required, run) => ({
|
|
627
|
+
name,
|
|
628
|
+
description,
|
|
629
|
+
parameters: { type: 'object', additionalProperties: false, properties, required },
|
|
630
|
+
output: OUTPUT,
|
|
631
|
+
execute: run,
|
|
632
|
+
})
|
|
633
|
+
|
|
634
|
+
const tools = [
|
|
635
|
+
defineTool('os_find', 'Find the top matching dsh-os capabilities for an intent; returns compact capability cards. Read-only.', {
|
|
636
|
+
intent: { type: 'string', description: 'What the user wants to do, in natural language.' },
|
|
637
|
+
riskMax: { type: 'string', enum: [...RISKS], description: 'Only return capabilities at or below this risk.' },
|
|
638
|
+
limit: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum cards (default 5).' },
|
|
639
|
+
}, ['intent'], find),
|
|
640
|
+
defineTool('os_do', 'Execute a resolved capability. Returns an OsResult; write/execute capabilities need a grant. After os_observe reports the request approved, retry with the same id and args and the cached grant is consumed automatically. Writing text previously returned by snip_get/seek_resolve/trigger_runs also needs the `<id>:tainted` Grant, or a fresh taintToken bound to that text.', {
|
|
641
|
+
id: { type: 'string', description: 'Capability id from os_find, for example "snip.search".' },
|
|
642
|
+
args: { type: 'object', additionalProperties: true, description: 'Capability input matching its inputSchema. For act.fs.write/legacy.act_invoke, text/content is hashed against the taint registry.' },
|
|
643
|
+
preview: { type: 'boolean', description: 'Validate and preview without running the handler.' },
|
|
644
|
+
idempotencyKey: { type: 'string', description: 'Reuse on retries so a write happens at most once; with config.stateFile it survives a restart.' },
|
|
645
|
+
grant: { description: 'Optional grant object or id; normally omitted because os_observe caches the approved one.' },
|
|
646
|
+
}, ['id'], execute),
|
|
647
|
+
defineTool('os_request', 'Create a pending approval request for capability "cap:<id>"; never approves it. Needs ctx.allow.request. Pass tainted:true to request the extra tainted-write Grant.', {
|
|
648
|
+
id: { type: 'string', description: 'Capability id that needs approval.' },
|
|
649
|
+
args: { type: 'object', additionalProperties: true, description: 'Exact args that will be executed later.' },
|
|
650
|
+
reason: { type: 'string', description: 'One-sentence reason shown to the human approver.' },
|
|
651
|
+
tainted: { type: 'boolean', description: 'Request "cap:<id>:tainted" for content from a taint source.' },
|
|
652
|
+
}, ['id', 'args', 'reason'], request),
|
|
653
|
+
defineTool('os_observe', 'Observe a request, job or dsh:// handle. For a request it refreshes state from Allow, consumes grantAvailable and lets the next matching os_do run.', {
|
|
654
|
+
requestId: { type: 'string', description: 'requestId returned by os_request.' },
|
|
655
|
+
jobId: { type: 'string', description: 'jobId returned in an OsResult job field.' },
|
|
656
|
+
handle: { type: 'string', description: 'dsh:// handle from an OsResult.' },
|
|
657
|
+
}, [], observe),
|
|
658
|
+
defineTool('os_help', 'Get a 3-5 step task plan plus candidate capabilities and their risks. Read-only.', {
|
|
659
|
+
task: { type: 'string', description: 'The user task to plan for.' },
|
|
660
|
+
}, ['task'], help),
|
|
661
|
+
defineTool('os_status', 'Report installed kernel modules, capability count, gateway version and health. Read-only.', {}, [], status),
|
|
662
|
+
]
|
|
663
|
+
|
|
664
|
+
return { tools, find, do: execute, request, observe, help, status, state: { requests, jobs, handles, idempotency, autoGrants, taint } }
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** Six plain ToolDefinitions bound to `registry`. */
|
|
668
|
+
export const createTools = (registry, options) => createGateway(registry, options).tools
|
|
669
|
+
export const gatewayTools = createTools
|
|
670
|
+
export default createGateway
|