dsh-os-kernel 0.0.0-stage → 0.5.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/lib/gateway.js ADDED
@@ -0,0 +1,676 @@
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
+ let actReady = false
216
+ const refreshLegacy = typeof registry.refreshLegacy === 'function' ? registry.refreshLegacy.bind(registry) : null
217
+ const refreshAct = typeof registry.refreshAct === 'function' ? registry.refreshAct.bind(registry) : null
218
+ async function ensureLegacy(exec) {
219
+ if (!actReady && refreshAct) {
220
+ try { await refreshAct() } catch { /* Act is optional */ }
221
+ actReady = true
222
+ }
223
+ if (legacyReady || !refreshLegacy) return
224
+ const tools = ctx?.tools
225
+ if (!tools || typeof tools.schemas !== 'function' || typeof tools.get !== 'function') return
226
+ // gatewayOnly restricts the agent's *tool* view; the kernel still needs the
227
+ // global view so those tools remain reachable as os_find/os_do capabilities.
228
+ const scope = options.gatewayOnly === true ? undefined : exec?.agent
229
+ try { await refreshLegacy({ scope }) } catch { return }
230
+ legacyReady = true
231
+ }
232
+
233
+ async function find(input = {}, exec = {}) {
234
+ await ensureLegacy(exec)
235
+ const intent = textOf(input.intent)
236
+ if (!intent) return failure('E_INVALID_ARGUMENT', 'intent must be a non-empty string.', {
237
+ remediation: 'Pass a short task intent, for example "search clipboard history".',
238
+ nextTools: [{ tool: 'os_help', args: { task: intent ?? 'discover capabilities' }, why: 'get task-level guidance' }],
239
+ })
240
+ const limit = Math.min(Math.max(Number.isInteger(input.limit) ? input.limit : 5, 1), 10)
241
+ const riskMax = input.riskMax === undefined ? null : RISKS.includes(input.riskMax) ? input.riskMax : undefined
242
+ if (riskMax === undefined) return failure('E_INVALID_ARGUMENT', `riskMax must be one of ${RISKS.join(', ')}.`)
243
+ let matches = registry.search(intent, { limit: 200 })
244
+ if (riskMax) matches = matches.filter(descriptor => maxRisk(descriptor.risk) <= RISK_RANK[riskMax])
245
+ return { ok: true, intent, items: matches.slice(0, limit).map(card), total: matches.length, truncated: matches.length > limit }
246
+ }
247
+
248
+ async function allowedByHost(exec, descriptor) {
249
+ const subject = subjectOf(exec)
250
+ const allow = allowService()
251
+ if (!subject || !allow || typeof allow.check !== 'function') return false
252
+ try {
253
+ const decision = await allow.check({ subject, capability: capabilityName(descriptor.id) })
254
+ return decision?.allowed === true
255
+ } catch {
256
+ return false
257
+ }
258
+ }
259
+
260
+ const denied = (descriptor, args, exec) => failure('E_DENIED',
261
+ `Capability "${descriptor.id}" needs a grant for ${descriptor.risk.join('/')} access.`, {
262
+ subcode: 'grant_required',
263
+ remediation: 'Call os_request with the same id and args, then call os_observe to refresh and consume the approved grant.',
264
+ nextTools: [
265
+ { tool: 'os_request', args: { id: descriptor.id, args, reason: `Grant ${descriptor.risk.join('/')} access to ${descriptor.id}.` }, why: 'create the pending approval' },
266
+ { tool: 'os_find', args: { intent: descriptor.id }, why: 'read the capability card and its risk' },
267
+ ],
268
+ requestId: exec?.requestId,
269
+ details: { capability: descriptor.id, permission: capabilityName(descriptor.id), risk: descriptor.risk, permissions: descriptor.permissions },
270
+ })
271
+
272
+ /** Ask Allow for a tainted-write capability without consuming a cached grant. */
273
+ async function taintedAllowed(exec, capability) {
274
+ const subject = subjectOf(exec)
275
+ const allow = allowService()
276
+ if (!subject || !allow || typeof allow.check !== 'function') return false
277
+ try {
278
+ return (await allow.check({ subject, capability }))?.allowed === true
279
+ } catch {
280
+ return false
281
+ }
282
+ }
283
+
284
+ const taintDenied = (descriptor, args, probe, record, exec) => failure('E_DENIED',
285
+ `Writing content from a tainted source to "${probe.target}" needs a separate tainted Grant.`, {
286
+ subcode: 'grant_required',
287
+ remediation: 'Call os_request with tainted:true and the same id and args, then os_observe; or pass a fresh taintToken from the read.',
288
+ nextTools: [
289
+ { 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' },
290
+ { tool: 'os_find', args: { intent: probe.target }, why: 'read the capability card and its tainted permission' },
291
+ ],
292
+ requestId: exec?.requestId,
293
+ details: {
294
+ capability: descriptor.id,
295
+ permission: `${capabilityName(probe.target)}:tainted`,
296
+ tainted: true,
297
+ taintSource: record?.source ?? null,
298
+ reason: probe.token ? 'invalid_taint_token' : 'taint_required',
299
+ },
300
+ })
301
+
302
+ async function execute(input = {}, exec = {}) {
303
+ const id = textOf(input.id)
304
+ if (!id) return failure('E_INVALID_ARGUMENT', 'id must be a non-empty capability id.', {
305
+ remediation: 'Call os_find first; pass the id from a returned card.',
306
+ nextTools: [{ tool: 'os_find', args: { intent: 'capabilities' }, why: 'discover capability ids' }],
307
+ requestId: exec?.requestId,
308
+ })
309
+ let args = input.args === undefined ? {} : input.args
310
+ const providedGrant = input.grant ?? exec?.grant ?? (isObject(args) ? args.grant : undefined)
311
+ if (providedGrant && isObject(args) && Object.prototype.hasOwnProperty.call(args, 'grant')) {
312
+ const { grant: _ignored, ...rest } = args
313
+ args = rest
314
+ }
315
+ if (!isObject(args)) return failure('E_INVALID_ARGUMENT', 'args must be an object.', {
316
+ remediation: 'Pass args as a JSON object matching the capability inputSchema.',
317
+ requestId: exec?.requestId,
318
+ })
319
+ if (id.startsWith('legacy.')) await ensureLegacy(exec)
320
+ const descriptor = await registry.resolve(id)
321
+ if (!descriptor) return notFound(id, exec?.requestId)
322
+ const gated = isRisky(descriptor)
323
+ const argsHash = fingerprint(args)
324
+ const subject = subjectOf(exec)
325
+ // A grant cached by os_observe is bound to the exact subject/id/args triple.
326
+ const auto = gated && !isGrant(providedGrant)
327
+ ? findAutoGrant(subject, descriptor.id, argsHash, capabilityName(descriptor.id)) : null
328
+ const grant = providedGrant ?? auto?.grant ?? undefined
329
+ const authorized = !gated || Boolean(auto) || isGrant(grant)
330
+ if (input.preview === true) {
331
+ if (!authorized && !(await allowedByHost(exec, descriptor))) return denied(descriptor, args, exec)
332
+ return makeResult(descriptor.id, { preview: true, id: descriptor.id, args, risk: descriptor.risk, gated }, {
333
+ summary: `Preview only: ${descriptor.id} was not executed.`,
334
+ requestId: exec?.requestId,
335
+ next: gated ? [{ tool: 'os_request', args: { id: descriptor.id, args }, why: 'request approval before executing' }] : [],
336
+ })
337
+ }
338
+ const key = textOf(input.idempotencyKey)
339
+ const slot = key ? `${subject ?? ''}\0${descriptor.id}\0${key}` : null
340
+ if (slot) {
341
+ const previous = idempotency.get(slot) ?? idempotencyStore?.get(slot)
342
+ if (previous) {
343
+ if (previous.argsHash !== argsHash) {
344
+ return failure('E_CONFLICT', 'This idempotencyKey was used with different args.', {
345
+ subcode: 'idempotency_reuse',
346
+ remediation: 'Retry with a fresh idempotencyKey, or replay the original args.',
347
+ requestId: exec?.requestId,
348
+ details: { capability: descriptor.id },
349
+ })
350
+ }
351
+ return previous.result
352
+ }
353
+ }
354
+ if (!authorized && !(await allowedByHost(exec, descriptor))) return denied(descriptor, args, exec)
355
+ // Content-hash taint gate: the model no longer decides by writing
356
+ // `tainted:true`; a digest registered from snip_get/seek_resolve/
357
+ // trigger_runs (or any result carrying a taintToken) forces the extra
358
+ // :tainted Grant. A fresh, hash-bound token is the one-time alternative.
359
+ let callArgs = args
360
+ let taintAuto = null
361
+ const probe = taintProbe(descriptor.id, args)
362
+ if (probe) {
363
+ const record = taint.lookup(probe.hash)
364
+ if (record !== undefined || probe.token !== null) {
365
+ let cleared = record !== undefined && probe.token !== null && taint.consume(probe.hash, probe.token)
366
+ if (!cleared) {
367
+ const capability = taintedCapability(descriptor.id, args)
368
+ const cached = findAutoGrant(subject, descriptor.id, argsHash, capability)
369
+ if (cached) {
370
+ taintAuto = cached
371
+ cleared = true
372
+ } else {
373
+ cleared = await taintedAllowed(exec, capability)
374
+ }
375
+ }
376
+ if (!cleared) return taintDenied(descriptor, args, probe, record, exec)
377
+ callArgs = withoutTaint(descriptor.id, args)
378
+ }
379
+ }
380
+ // Consume only after every check and after the idempotency replay path, so
381
+ // a replayed call never burns a fresh approval and an approval is used once.
382
+ if (auto) takeAutoGrant(auto)
383
+ if (taintAuto) takeAutoGrant(taintAuto)
384
+ const callRequestId = auto?.requestId ?? taintAuto?.requestId ?? exec?.requestId
385
+ const started = Date.now()
386
+ let outcome
387
+ try {
388
+ outcome = await registry.invoke(descriptor.id, callArgs, {
389
+ ctx, subject: subjectOf(exec), agent: exec?.agent, signal: exec?.signal, grant, requestId: callRequestId,
390
+ })
391
+ } catch (error) {
392
+ return failure('E_INTERNAL', error?.message ?? String(error), {
393
+ remediation: 'Report requestId to the maintainer; do not retry blindly.',
394
+ requestId: callRequestId,
395
+ details: { capability: descriptor.id },
396
+ })
397
+ }
398
+ if (!outcome.ok) {
399
+ return failure(outcome.legacyCode ?? outcome.code, outcome.message ?? `Capability ${descriptor.id} failed.`, {
400
+ subcode: outcome.code === 'E_DENIED' ? 'grant_required' : null,
401
+ remediation: outcome.code === 'E_DENIED'
402
+ ? 'Call os_request with the same id and args, then call os_observe to refresh the approval.'
403
+ : 'Call os_find to inspect the capability card, fix the args if needed, then retry.',
404
+ nextTools: outcome.code === 'E_DENIED'
405
+ ? [{ tool: 'os_request', args: { id: descriptor.id, args }, why: 'request a grant' }]
406
+ : [{ tool: 'os_find', args: { intent: descriptor.id }, why: 'inspect the capability card' }],
407
+ requestId: callRequestId,
408
+ details: { capability: descriptor.id },
409
+ })
410
+ }
411
+ // Legacy tools often return their own `{ ok, error }` envelope; normalize it
412
+ // through the kernel's err()/ok() pair instead of nesting it as data.
413
+ const normalized = descriptor.legacy === true ? legacyOutcome(outcome.value) : null
414
+ if (normalized?.ok === false) {
415
+ const legacy = normalized.error
416
+ const code = legacy.code ?? 'E_INTERNAL'
417
+ const denied = code === 'E_DENIED' || code === 'grant_required'
418
+ return failure(code, legacy.message ?? `Legacy capability ${descriptor.id} failed.`, {
419
+ subcode: legacy.subcode ?? (denied ? 'grant_required' : null),
420
+ retryable: legacy.retryable,
421
+ retryAfterMs: legacy.retryAfterMs,
422
+ remediation: legacy.remediation ?? (denied
423
+ ? 'Call os_request with the same id and args, then call os_observe to refresh the approval.'
424
+ : undefined),
425
+ nextTools: Array.isArray(legacy.nextTools) ? legacy.nextTools : denied
426
+ ? [{ tool: 'os_request', args: { id: descriptor.id, args }, why: 'request a grant' }]
427
+ : undefined,
428
+ requestId: callRequestId,
429
+ details: { capability: descriptor.id, ...(isObject(legacy.details) ? legacy.details : {}) },
430
+ })
431
+ }
432
+ const value = normalized?.ok === true ? normalized.value : outcome.value
433
+ const result = makeResult(descriptor.id, value, { requestId: callRequestId, latencyMs: Date.now() - started })
434
+ remember(value)
435
+ taint.observe(descriptor.id, value)
436
+ if (slot) {
437
+ const entry = { argsHash, result }
438
+ idempotency.set(slot, entry)
439
+ if (idempotencyStore) {
440
+ try {
441
+ idempotencyStore.set(slot, entry)
442
+ } catch (error) {
443
+ result.warnings.push(`idempotency result was not persisted: ${error?.message ?? String(error)}`)
444
+ }
445
+ }
446
+ }
447
+ return result
448
+ }
449
+
450
+ async function request(input = {}, exec = {}) {
451
+ const id = textOf(input.id)
452
+ if (!id) return failure('E_INVALID_ARGUMENT', 'id must be a non-empty capability id.', {
453
+ remediation: 'Call os_find first; pass the id from a returned card.',
454
+ nextTools: [{ tool: 'os_find', args: { intent: 'capabilities' }, why: 'discover capability ids' }],
455
+ requestId: exec?.requestId,
456
+ })
457
+ const reason = textOf(input.reason)
458
+ if (!reason) return failure('E_INVALID_ARGUMENT', 'reason must be a non-empty string.', {
459
+ remediation: 'Describe why this action is needed in one short sentence.',
460
+ requestId: exec?.requestId,
461
+ })
462
+ const args = input.args === undefined ? {} : input.args
463
+ if (!isObject(args)) return failure('E_INVALID_ARGUMENT', 'args must be an object.', { requestId: exec?.requestId })
464
+ const descriptor = await registry.resolve(id)
465
+ if (!descriptor) return notFound(id, exec?.requestId)
466
+ const allow = allowService()
467
+ if (!allow || typeof allow.request !== 'function') {
468
+ return failure('E_UNAVAILABLE', 'No Allow request service is available, so nothing can be approved.', {
469
+ subcode: 'dependency_missing',
470
+ remediation: 'Install/enable dsh-allow (ctx.allow.request) and retry os_request.',
471
+ nextTools: [{ tool: 'os_status', why: 'check installed modules and health' }],
472
+ requestId: exec?.requestId,
473
+ details: { service: 'allow.request' },
474
+ })
475
+ }
476
+ // os_do treats an `args.grant` shortcut as a grant, not capability input,
477
+ // so the approval fingerprint must use the same normalized args.
478
+ const requestArgs = isObject(args) && Object.prototype.hasOwnProperty.call(args, 'grant')
479
+ ? Object.fromEntries(Object.entries(args).filter(([key]) => key !== 'grant')) : args
480
+ // `tainted:true` asks for `<target>:tainted` instead of the base capability;
481
+ // legacy.act_invoke maps to act.fs.write so both verbs share one approval.
482
+ const capability = input.tainted === true
483
+ ? taintedCapability(descriptor.id, requestArgs)
484
+ : capabilityName(descriptor.id)
485
+ const subject = subjectOf(exec)
486
+ if (!subject) {
487
+ return failure('E_INVALID_ARGUMENT', 'os_request needs an executing subject.', {
488
+ remediation: 'Call os_request from an agent turn; the host supplies exec.subject or exec.agent.session.id.',
489
+ requestId: exec?.requestId,
490
+ })
491
+ }
492
+ let response
493
+ try {
494
+ response = await allow.request({
495
+ subject, capability, scope: '*', maxUses: 1, reason,
496
+ })
497
+ } catch (error) {
498
+ return failure(error?.code, error?.message ?? String(error), {
499
+ remediation: 'Fix the request args, or inspect Allow with os_status, then retry os_request.',
500
+ requestId: exec?.requestId,
501
+ })
502
+ }
503
+ const requestId = typeof response === 'string' ? response : response?.requestId ?? response?.id ?? response?.request?.id
504
+ if (typeof requestId !== 'string' || requestId === '') {
505
+ return failure('E_INTERNAL', 'Allow returned no requestId.', {
506
+ remediation: 'Report this to the maintainer; do not retry automatically.',
507
+ requestId: exec?.requestId,
508
+ })
509
+ }
510
+ const status = response?.status ?? response?.state ?? 'pending'
511
+ const hint = response?.hint ?? response?.approvalHint
512
+ ?? 'A human must decide; then call os_observe with this requestId and retry os_do with the same id and args.'
513
+ requests.set(requestId, {
514
+ requestId, capabilityId: descriptor.id, capability, argsHash: fingerprint(requestArgs), subject,
515
+ reason, status, scope: '*', createdAt: Date.now(), response,
516
+ })
517
+ return { ok: true, requestId, status, hint, id: descriptor.id, capability }
518
+ }
519
+
520
+ async function observe(input = {}, exec = {}) {
521
+ const requestId = textOf(input.requestId)
522
+ const jobId = textOf(input.jobId)
523
+ const handle = textOf(input.handle)
524
+ if (!requestId && !jobId && !handle) {
525
+ return failure('E_INVALID_ARGUMENT', 'Pass one of requestId, jobId or handle.', {
526
+ remediation: 'Use the requestId from os_request, a jobId from a job result, or a dsh:// handle.',
527
+ requestId: exec?.requestId,
528
+ })
529
+ }
530
+ if (requestId) {
531
+ const local = requests.get(requestId)
532
+ if (local && subjectOf(exec) && local.subject !== subjectOf(exec)) {
533
+ return failure('E_NOT_FOUND', `No request named "${requestId}".`, {
534
+ subcode: 'request_not_found', requestId: exec?.requestId,
535
+ })
536
+ }
537
+ const remote = await latestRequest(requestId, local?.subject ?? subjectOf(exec))
538
+ if (!local && !remote) return failure('E_NOT_FOUND', `No request named "${requestId}".`, {
539
+ subcode: 'request_not_found',
540
+ remediation: 'Call os_request to create a pending request, then observe its requestId.',
541
+ requestId: exec?.requestId,
542
+ })
543
+ const state = remote?.state ?? remote?.status ?? local?.status ?? 'pending'
544
+ let grant = null
545
+ let grantReason = null
546
+ if (state === 'approved') {
547
+ if (local) ({ grant, reason: grantReason } = await cacheAutoGrant(requestId, local))
548
+ else grantReason = 'request_not_created_by_kernel'
549
+ } else {
550
+ autoGrants.delete(requestId)
551
+ }
552
+ if (local) local.status = state
553
+ return {
554
+ ok: true, kind: 'request', requestId, state, status: state,
555
+ id: local?.capabilityId ?? null,
556
+ capability: local?.capability ?? remote?.capability ?? null,
557
+ request: { ...(local ?? {}), ...(isObject(remote) ? remote : {}) },
558
+ result: grant ?? remote?.grant ?? remote?.result ?? null,
559
+ grantAvailable: Boolean(grant),
560
+ ...(grantReason ? { grantReason } : {}),
561
+ }
562
+ }
563
+ if (jobId) {
564
+ let job = jobs.get(jobId)
565
+ if (!job && typeof ctx?.jobs?.get === 'function') {
566
+ try { job = await ctx.jobs.get(jobId) } catch { /* not found */ }
567
+ }
568
+ if (!job) return failure('E_NOT_FOUND', `No job named "${jobId}".`, {
569
+ subcode: 'job_not_found',
570
+ remediation: 'Use the jobId returned in an OsResult job field; jobs expire with the session.',
571
+ requestId: exec?.requestId,
572
+ })
573
+ const state = job.state ?? job.status ?? 'unknown'
574
+ return { ok: true, kind: 'job', jobId, state, job, progress: job.progress ?? null, result: job.result ?? null }
575
+ }
576
+ let entry = handles.get(handle)
577
+ if (!entry && typeof ctx?.handles?.resolve === 'function') {
578
+ try { entry = await ctx.handles.resolve(handle) } catch { /* not found */ }
579
+ }
580
+ if (!entry && typeof ctx?.handles?.get === 'function') {
581
+ try { entry = await ctx.handles.get(handle) } catch { /* not found */ }
582
+ }
583
+ if (!entry) return failure('E_NOT_FOUND', `No handle named "${handle}".`, {
584
+ subcode: 'handle_not_found',
585
+ remediation: 'Handles expire; rerun the capability that produced the handle.',
586
+ requestId: exec?.requestId,
587
+ })
588
+ return { ok: true, kind: 'handle', handle, state: 'available', result: entry }
589
+ }
590
+
591
+ async function help(input = {}) {
592
+ const task = textOf(input.task)
593
+ if (!task) return failure('E_INVALID_ARGUMENT', 'task must be a non-empty string.', {
594
+ remediation: 'Pass the user task in one short sentence.',
595
+ })
596
+ const matches = registry.search(task, { limit: 5 })
597
+ const steps = [
598
+ `Call os_find with intent "${task}" to see the top matching capability cards.`,
599
+ 'Call os_do with the chosen id and args. Read ok before using any other field.',
600
+ 'If os_do returns E_DENIED, call os_request with the same id and args, then wait for a human decision.',
601
+ 'Call os_observe with the requestId; once approved it consumes the Grant and os_do can run without an injected grant.',
602
+ ]
603
+ return {
604
+ ok: true,
605
+ task,
606
+ steps,
607
+ capabilities: matches.map(descriptor => ({ id: descriptor.id, title: descriptor.title, risk: [...descriptor.risk] })),
608
+ risks: [...new Set(matches.flatMap(descriptor => descriptor.risk))],
609
+ example: matches[0]?.examples?.[0] ?? null,
610
+ }
611
+ }
612
+
613
+ async function status(_input = {}, exec = {}) {
614
+ await ensureLegacy(exec)
615
+ const all = registry.list({ includeDeprecated: true, limit: 200 })
616
+ const legacy = all.filter(descriptor => descriptor.legacy === true).length
617
+ const counts = typeof registry.stats === 'function' ? registry.stats() : { legacy, capabilities: all.length - legacy, total: all.length }
618
+ const modules = [...new Set(all.filter(descriptor => descriptor.legacy !== true).map(descriptor => descriptor.id.split('.')[0]))].sort()
619
+ return {
620
+ ok: true,
621
+ version: VERSION,
622
+ modules,
623
+ ...counts,
624
+ health: {
625
+ status: 'ok', ...counts,
626
+ namespaces: modules.length, deprecated: all.filter(descriptor => descriptor.deprecated).length,
627
+ },
628
+ tools: [...TOOL_NAMES],
629
+ }
630
+ }
631
+
632
+ const defineTool = (name, description, properties, required, run) => ({
633
+ name,
634
+ description,
635
+ parameters: { type: 'object', additionalProperties: false, properties, required },
636
+ output: OUTPUT,
637
+ execute: run,
638
+ })
639
+
640
+ const tools = [
641
+ defineTool('os_find', 'Find the top matching dsh-os capabilities for an intent; returns compact capability cards. Read-only.', {
642
+ intent: { type: 'string', description: 'What the user wants to do, in natural language.' },
643
+ riskMax: { type: 'string', enum: [...RISKS], description: 'Only return capabilities at or below this risk.' },
644
+ limit: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum cards (default 5).' },
645
+ }, ['intent'], find),
646
+ 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.', {
647
+ id: { type: 'string', description: 'Capability id from os_find, for example "snip.search".' },
648
+ 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.' },
649
+ preview: { type: 'boolean', description: 'Validate and preview without running the handler.' },
650
+ idempotencyKey: { type: 'string', description: 'Reuse on retries so a write happens at most once; with config.stateFile it survives a restart.' },
651
+ grant: { description: 'Optional grant object or id; normally omitted because os_observe caches the approved one.' },
652
+ }, ['id'], execute),
653
+ 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.', {
654
+ id: { type: 'string', description: 'Capability id that needs approval.' },
655
+ args: { type: 'object', additionalProperties: true, description: 'Exact args that will be executed later.' },
656
+ reason: { type: 'string', description: 'One-sentence reason shown to the human approver.' },
657
+ tainted: { type: 'boolean', description: 'Request "cap:<id>:tainted" for content from a taint source.' },
658
+ }, ['id', 'args', 'reason'], request),
659
+ 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.', {
660
+ requestId: { type: 'string', description: 'requestId returned by os_request.' },
661
+ jobId: { type: 'string', description: 'jobId returned in an OsResult job field.' },
662
+ handle: { type: 'string', description: 'dsh:// handle from an OsResult.' },
663
+ }, [], observe),
664
+ defineTool('os_help', 'Get a 3-5 step task plan plus candidate capabilities and their risks. Read-only.', {
665
+ task: { type: 'string', description: 'The user task to plan for.' },
666
+ }, ['task'], help),
667
+ defineTool('os_status', 'Report installed kernel modules, capability count, gateway version and health. Read-only.', {}, [], status),
668
+ ]
669
+
670
+ return { tools, find, do: execute, request, observe, help, status, state: { requests, jobs, handles, idempotency, autoGrants, taint } }
671
+ }
672
+
673
+ /** Six plain ToolDefinitions bound to `registry`. */
674
+ export const createTools = (registry, options) => createGateway(registry, options).tools
675
+ export const gatewayTools = createTools
676
+ export default createGateway