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/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 +676 -0
- package/lib/registry.js +258 -0
- package/lib/service.js +132 -0
- package/lib/state.js +65 -0
- package/lib/taint.js +139 -0
- package/package.json +82 -4
package/lib/registry.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/** Capability registry: Map + filters, lazy handlers, conflicts and invoke. */
|
|
2
|
+
import { normalizeDescriptor } from './descriptor.js'
|
|
3
|
+
|
|
4
|
+
const CODES = new Set(['E_INVALID_ARGUMENT', 'E_DENIED', 'E_NOT_FOUND', 'E_CONFLICT', 'E_UNAVAILABLE', 'E_LIMIT', 'E_STATE', 'E_TIMEOUT', 'E_INTERNAL'])
|
|
5
|
+
const META_KEYS = ['id', 'title', 'summary', 'whenToUse', 'whenNotToUse', 'risk', 'tags', 'cost']
|
|
6
|
+
const META_HANDLER = async () => { throw new Error('meta handler must never run') }
|
|
7
|
+
const obj = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
8
|
+
|
|
9
|
+
function conflict(message) {
|
|
10
|
+
const error = new Error(message)
|
|
11
|
+
error.code = 'E_CONFLICT'
|
|
12
|
+
throw error
|
|
13
|
+
}
|
|
14
|
+
function canonical(value, seen = new WeakSet()) {
|
|
15
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'
|
|
16
|
+
if (seen.has(value)) return '"[circular]"'
|
|
17
|
+
seen.add(value)
|
|
18
|
+
if (Array.isArray(value)) return `[${value.map(item => canonical(item, seen)).join(',')}]`
|
|
19
|
+
const keys = Object.keys(value).filter(key => value[key] !== undefined).sort()
|
|
20
|
+
return `{${keys.map(key => `${JSON.stringify(key)}:${canonical(value[key], seen)}`).join(',')}}`
|
|
21
|
+
}
|
|
22
|
+
function fnv(text) {
|
|
23
|
+
let hash = 0x811c9dc5
|
|
24
|
+
for (let index = 0; index < text.length; index += 1) { hash ^= text.charCodeAt(index); hash = Math.imul(hash, 0x01000193) }
|
|
25
|
+
return (hash >>> 0).toString(16)
|
|
26
|
+
}
|
|
27
|
+
const fingerprint = (value, handler) => fnv(`${handler ? Function.prototype.toString.call(handler) : ''}\n${canonical(value)}`)
|
|
28
|
+
const pickMeta = descriptor => Object.fromEntries(META_KEYS.map(key => [key, descriptor[key]]))
|
|
29
|
+
const sameMeta = (left, right) => canonical(pickMeta(left)) === canonical(pickMeta(right))
|
|
30
|
+
const summaryOf = descriptor => typeof descriptor.toJSON === 'function' ? descriptor.toJSON() : { ...descriptor }
|
|
31
|
+
|
|
32
|
+
function normalizeMeta(raw) {
|
|
33
|
+
if (!obj(raw)) conflict('lazy capability needs a meta object')
|
|
34
|
+
return summaryOf(normalizeDescriptor({ ...raw, whenToUse: raw.whenToUse ?? [], whenNotToUse: raw.whenNotToUse ?? [], handler: META_HANDLER }))
|
|
35
|
+
}
|
|
36
|
+
function compareVersion(left, right) {
|
|
37
|
+
const a = String(left).split('-')[0].split('.').map(Number)
|
|
38
|
+
const b = String(right).split('-')[0].split('.').map(Number)
|
|
39
|
+
for (let index = 0; index < 3; index += 1) if (a[index] !== b[index]) return a[index] - b[index]
|
|
40
|
+
return 0
|
|
41
|
+
}
|
|
42
|
+
function checkInput(schema, value) {
|
|
43
|
+
if (!obj(schema) || schema.type === undefined) return null
|
|
44
|
+
if (schema.type === 'object') {
|
|
45
|
+
if (!obj(value)) return 'must be an object'
|
|
46
|
+
for (const key of schema.required ?? []) if (value[key] === undefined) return `missing required property "${key}"`
|
|
47
|
+
const properties = obj(schema.properties) ? schema.properties : {}
|
|
48
|
+
for (const key of Object.keys(value)) {
|
|
49
|
+
if (!Object.prototype.hasOwnProperty.call(properties, key)) {
|
|
50
|
+
if (schema.additionalProperties === false) return `unknown property "${key}"`
|
|
51
|
+
continue
|
|
52
|
+
}
|
|
53
|
+
const error = checkInput(properties[key], value[key])
|
|
54
|
+
if (error) return `${key}: ${error}`
|
|
55
|
+
}
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
58
|
+
if (schema.type === 'array') {
|
|
59
|
+
if (!Array.isArray(value)) return 'must be an array'
|
|
60
|
+
if (schema.minItems !== undefined && value.length < schema.minItems) return 'has too few items'
|
|
61
|
+
if (schema.maxItems !== undefined && value.length > schema.maxItems) return 'has too many items'
|
|
62
|
+
for (const item of value) { const error = checkInput(schema.items, item); if (error) return error }
|
|
63
|
+
return null
|
|
64
|
+
}
|
|
65
|
+
if (schema.type === 'string') {
|
|
66
|
+
if (typeof value !== 'string') return 'must be a string'
|
|
67
|
+
if (schema.minLength !== undefined && value.length < schema.minLength) return 'is too short'
|
|
68
|
+
if (schema.maxLength !== undefined && value.length > schema.maxLength) return 'is too long'
|
|
69
|
+
} else if (schema.type === 'integer') { if (!Number.isInteger(value)) return 'must be an integer' }
|
|
70
|
+
else if (schema.type === 'number') { if (typeof value !== 'number' || !Number.isFinite(value)) return 'must be a number' }
|
|
71
|
+
else if (schema.type === 'boolean') { if (typeof value !== 'boolean') return 'must be a boolean' }
|
|
72
|
+
if (schema.enum !== undefined && !schema.enum.includes(value)) return 'is not an allowed value'
|
|
73
|
+
if (schema.minimum !== undefined && value < schema.minimum) return `must be >= ${schema.minimum}`
|
|
74
|
+
if (schema.maximum !== undefined && value > schema.maximum) return `must be <= ${schema.maximum}`
|
|
75
|
+
return null
|
|
76
|
+
}
|
|
77
|
+
function score(descriptor, word) {
|
|
78
|
+
if (!word) return 0
|
|
79
|
+
const fields = [
|
|
80
|
+
[String(descriptor.id).toLowerCase(), 5], [String(descriptor.title).toLowerCase(), 3],
|
|
81
|
+
[String(descriptor.summary).toLowerCase(), 2], [descriptor.tags.join(' ').toLowerCase(), 2],
|
|
82
|
+
[(descriptor.whenToUse ?? []).join(' ').toLowerCase(), 1],
|
|
83
|
+
]
|
|
84
|
+
let total = 0
|
|
85
|
+
for (const [text, weight] of fields) {
|
|
86
|
+
if (!text) continue
|
|
87
|
+
if (text === word) total += weight * 2
|
|
88
|
+
else if (text.includes(word)) total += weight
|
|
89
|
+
}
|
|
90
|
+
return total
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Ordered capability map with filters, lazy entries and normalized invoke results. */
|
|
94
|
+
export class CapabilityRegistry {
|
|
95
|
+
constructor({ authorize, ctx = null, strict = false, allowDowngrade = false, override = false } = {}) {
|
|
96
|
+
this.authorize = typeof authorize === 'function' ? authorize : null
|
|
97
|
+
this.ctx = ctx
|
|
98
|
+
this.strict = strict === true
|
|
99
|
+
this.allowDowngrade = allowDowngrade === true
|
|
100
|
+
this.override = override === true
|
|
101
|
+
this.entries = new Map()
|
|
102
|
+
this.aliases = new Map()
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Register one descriptor, an array, or `{ id, meta, load }`; returns unregister(). */
|
|
106
|
+
register(input, options = {}) {
|
|
107
|
+
if (Array.isArray(input)) { const undo = input.map(item => this.register(item, options)); return () => { for (const fn of undo) fn() } }
|
|
108
|
+
if (!obj(input)) throw Object.assign(new TypeError('descriptor must be an object'), { code: 'E_INVALID_ARGUMENT' })
|
|
109
|
+
return typeof input.load === 'function' && input.meta ? this.#lazy(input, options) : this.#descriptor(input, options)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
#aliases(descriptor) {
|
|
113
|
+
if (new Set(descriptor.aliases).size !== descriptor.aliases.length) conflict(`duplicate aliases on ${descriptor.id}`)
|
|
114
|
+
for (const alias of descriptor.aliases) {
|
|
115
|
+
if (alias !== descriptor.id && (this.entries.has(alias) || (this.aliases.has(alias) && this.aliases.get(alias) !== descriptor.id))) {
|
|
116
|
+
conflict(`alias "${alias}" of ${descriptor.id} collides with an existing entry`)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
#store(entry, descriptor) {
|
|
122
|
+
this.entries.set(descriptor.id, entry)
|
|
123
|
+
for (const alias of descriptor.aliases) if (alias !== descriptor.id) this.aliases.set(alias, descriptor.id)
|
|
124
|
+
return () => this.entries.get(entry.id) === entry ? this.unregister(entry.id, entry.owner) : false
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
#descriptor(raw, options) {
|
|
128
|
+
const descriptor = normalizeDescriptor(raw)
|
|
129
|
+
this.#aliases(descriptor)
|
|
130
|
+
const owner = options.owner ?? descriptor.owner ?? 'default'
|
|
131
|
+
const existing = this.entries.get(descriptor.id)
|
|
132
|
+
if (existing && !(this.override || options.override)) {
|
|
133
|
+
if (existing.owner !== owner) conflict(`${descriptor.id} is owned by ${existing.owner}`)
|
|
134
|
+
const order = compareVersion(descriptor.version, existing.version)
|
|
135
|
+
if (order === 0) {
|
|
136
|
+
if (existing.fingerprint !== fingerprint(descriptor, descriptor.handler)) conflict(`${descriptor.id}@${descriptor.version} is already registered with a different handler`)
|
|
137
|
+
return () => false
|
|
138
|
+
}
|
|
139
|
+
if (order < 0 && !(this.allowDowngrade || options.allowDowngrade)) conflict(`${descriptor.id}@${descriptor.version} would downgrade ${existing.version}`)
|
|
140
|
+
}
|
|
141
|
+
if (existing) for (const [alias, target] of this.aliases) if (target === descriptor.id) this.aliases.delete(alias)
|
|
142
|
+
const entry = { id: descriptor.id, owner, version: descriptor.version, descriptor, fingerprint: fingerprint(descriptor, descriptor.handler), lazy: false }
|
|
143
|
+
return this.#store(entry, descriptor)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#lazy(input, options) {
|
|
147
|
+
const meta = normalizeMeta(input.meta)
|
|
148
|
+
const owner = options.owner ?? meta.owner ?? 'default'
|
|
149
|
+
const existing = this.entries.get(meta.id)
|
|
150
|
+
if (existing && !(this.override || options.override)) {
|
|
151
|
+
if (existing.owner !== owner) conflict(`${meta.id} is owned by ${existing.owner}`)
|
|
152
|
+
if (existing.version === meta.version && existing.fingerprint === fingerprint(meta)) return () => false
|
|
153
|
+
if (compareVersion(meta.version, existing.version) < 0 && !this.allowDowngrade) conflict(`${meta.id} would downgrade ${existing.version}`)
|
|
154
|
+
if (existing.version === meta.version) conflict(`${meta.id}@${meta.version} is already registered with different metadata`)
|
|
155
|
+
}
|
|
156
|
+
const entry = { id: meta.id, owner, version: meta.version, meta, load: input.load, descriptor: null, promise: null, fingerprint: fingerprint(meta), lazy: true }
|
|
157
|
+
this.entries.set(meta.id, entry)
|
|
158
|
+
return () => this.entries.get(entry.id) === entry ? this.unregister(entry.id, owner) : false
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Remove by id; only the owner may remove it. */
|
|
162
|
+
unregister(id, owner) {
|
|
163
|
+
const entry = this.entries.get(id)
|
|
164
|
+
if (!entry || (owner !== undefined && entry.owner !== owner)) return false
|
|
165
|
+
this.entries.delete(id)
|
|
166
|
+
for (const [alias, target] of this.aliases) if (target === id) this.aliases.delete(alias)
|
|
167
|
+
return true
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Resolve an id or alias: descriptor, Promise for a lazy entry, or null. */
|
|
171
|
+
resolve(idOrAlias) {
|
|
172
|
+
const entry = this.entries.get(this.aliases.get(idOrAlias) ?? idOrAlias)
|
|
173
|
+
if (!entry) return null
|
|
174
|
+
return entry.descriptor ?? this.#load(entry)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async #load(entry) {
|
|
178
|
+
if (entry.descriptor) return entry.descriptor
|
|
179
|
+
if (!entry.promise) {
|
|
180
|
+
entry.promise = Promise.resolve().then(entry.load).then(raw => {
|
|
181
|
+
const descriptor = normalizeDescriptor(raw)
|
|
182
|
+
if (!sameMeta(descriptor, entry.meta)) conflict(`${entry.id} loaded descriptor does not match its metadata`)
|
|
183
|
+
entry.descriptor = descriptor
|
|
184
|
+
entry.promise = null
|
|
185
|
+
return descriptor
|
|
186
|
+
}).catch(error => { entry.promise = null; throw error })
|
|
187
|
+
}
|
|
188
|
+
return entry.promise
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Filtered, id-sorted summaries. Namespace/risk/tag/q plus limit and offset cursor. */
|
|
192
|
+
list(filter = {}) {
|
|
193
|
+
const limit = Math.min(Math.max(Number.isInteger(filter.limit) ? filter.limit : 50, 1), 200)
|
|
194
|
+
const offset = Math.max(Number.isInteger(filter.cursor) ? filter.cursor : Number(filter.cursor) || 0, 0)
|
|
195
|
+
const caps = filter.capability === undefined ? null : Array.isArray(filter.capability) ? filter.capability : [filter.capability]
|
|
196
|
+
const risks = filter.risk === undefined ? null : Array.isArray(filter.risk) ? filter.risk : [filter.risk]
|
|
197
|
+
const tagFilter = filter.tag ?? filter.tags
|
|
198
|
+
const tags = tagFilter === undefined ? null : Array.isArray(tagFilter) ? tagFilter : [tagFilter]
|
|
199
|
+
const items = []
|
|
200
|
+
for (const entry of this.entries.values()) {
|
|
201
|
+
const descriptor = entry.descriptor ?? entry.meta
|
|
202
|
+
if (filter.includeDeprecated !== true && descriptor.deprecated) continue
|
|
203
|
+
if (caps && !caps.includes(descriptor.id.split('.')[0])) continue
|
|
204
|
+
if (risks && !descriptor.risk.some(risk => risks.includes(risk))) continue
|
|
205
|
+
if (tags && !tags.every(tag => descriptor.tags.includes(tag))) continue
|
|
206
|
+
if (filter.q && score(descriptor, filter.q) === 0) continue
|
|
207
|
+
items.push(descriptor)
|
|
208
|
+
}
|
|
209
|
+
return items.sort((left, right) => left.id.localeCompare(right.id)).slice(offset, offset + limit).map(summaryOf)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Weighted substring search over id/title/summary/tags/whenToUse. */
|
|
213
|
+
search(query, { limit = 5 } = {}) {
|
|
214
|
+
const text = String(query ?? '').trim().toLowerCase()
|
|
215
|
+
if (!text) return []
|
|
216
|
+
const scored = []
|
|
217
|
+
for (const entry of this.entries.values()) {
|
|
218
|
+
const descriptor = entry.descriptor ?? entry.meta
|
|
219
|
+
const value = text.split(/\s+/).reduce((total, word) => total + score(descriptor, word), 0)
|
|
220
|
+
if (value > 0) scored.push({ descriptor, value: value + (score(descriptor, text) > 0 ? 2 : 0) })
|
|
221
|
+
}
|
|
222
|
+
return scored.sort((left, right) => right.value - left.value || left.descriptor.id.localeCompare(right.descriptor.id))
|
|
223
|
+
.slice(0, Math.min(Math.max(limit, 1), 200)).map(item => summaryOf(item.descriptor))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Sorted ids (aliases excluded). */
|
|
227
|
+
names() { return [...this.entries.keys()].sort() }
|
|
228
|
+
|
|
229
|
+
/** Resolve, validate, authorize, run, and normalize errors. */
|
|
230
|
+
async invoke(id, input = {}, options = {}) {
|
|
231
|
+
const descriptor = await this.resolve(id)
|
|
232
|
+
if (!descriptor) return { ok: false, code: 'E_NOT_FOUND', message: `no capability named "${id}"` }
|
|
233
|
+
if (!obj(input)) return { ok: false, code: 'E_INVALID_ARGUMENT', message: 'input must be an object' }
|
|
234
|
+
const invalid = checkInput(descriptor.inputSchema, input)
|
|
235
|
+
if (invalid) return { ok: false, code: 'E_INVALID_ARGUMENT', message: `invalid input: ${invalid}` }
|
|
236
|
+
if (this.authorize) {
|
|
237
|
+
try {
|
|
238
|
+
const decision = await this.authorize(descriptor, { ...options, input })
|
|
239
|
+
if (decision === false || decision?.allowed === false) return { ok: false, code: 'E_DENIED', message: `not authorized to invoke ${descriptor.id}` }
|
|
240
|
+
} catch (error) { return { ok: false, code: typeof error?.code === 'string' ? error.code : 'E_INTERNAL', message: error?.message ?? String(error) } }
|
|
241
|
+
}
|
|
242
|
+
const exec = { subject: options.subject ?? null, agent: options.agent ?? null, signal: options.signal, requestId: options.requestId, grant: options.grant, ctx: options.ctx ?? this.ctx }
|
|
243
|
+
try {
|
|
244
|
+
const value = await descriptor.handler(input, exec.ctx, exec)
|
|
245
|
+
if (value === undefined) return { ok: false, code: 'E_STATE', message: `${descriptor.id} handler returned undefined` }
|
|
246
|
+
if (this.strict) {
|
|
247
|
+
const bad = checkInput(descriptor.outputSchema, value)
|
|
248
|
+
if (bad) return { ok: false, code: 'E_STATE', message: `output does not match outputSchema: ${bad}` }
|
|
249
|
+
}
|
|
250
|
+
return { ok: true, value }
|
|
251
|
+
} catch (error) {
|
|
252
|
+
return { ok: false, code: CODES.has(error?.code) ? error.code : 'E_UNAVAILABLE', message: error?.message ?? String(error), legacyCode: error?.code }
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export { fingerprint, canonical, checkInput as validateInput }
|
|
258
|
+
export const createRegistry = options => new CapabilityRegistry(options)
|
package/lib/service.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* KernelService: the registry plus a lazy bridge to the host's legacy tools.
|
|
3
|
+
*
|
|
4
|
+
* DSH exposes `ctx.tools.schemas(scope)` (visible schemas) and
|
|
5
|
+
* `ctx.tools.get(name, scope)` (the definition with `execute`). The service
|
|
6
|
+
* enumerates them, skips `os_*` and occupied ids, and adapts the rest with
|
|
7
|
+
* `fromTool` as `legacy.<tool name>`. Repeated or concurrent calls are safe:
|
|
8
|
+
* an occupied id is kept, not overwritten.
|
|
9
|
+
*/
|
|
10
|
+
import { CapabilityRegistry } from './registry.js'
|
|
11
|
+
import { fromTool } from './from-tool.js'
|
|
12
|
+
|
|
13
|
+
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
14
|
+
const nameOf = value => typeof value === 'string' ? value : isObject(value) && typeof value.name === 'string' ? value.name : null
|
|
15
|
+
|
|
16
|
+
/** Registry plus `refreshLegacy()` and `stats()`. */
|
|
17
|
+
export class KernelService extends CapabilityRegistry {
|
|
18
|
+
constructor(options = {}) {
|
|
19
|
+
super(options)
|
|
20
|
+
this.legacyOptions = isObject(options.legacyOptions) ? options.legacyOptions : {}
|
|
21
|
+
this.lastLegacyRefresh = null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Count aliased-by-`legacy` entries separately from real capabilities. */
|
|
25
|
+
stats() {
|
|
26
|
+
let legacy = 0
|
|
27
|
+
for (const entry of this.entries.values()) if ((entry.descriptor ?? entry.meta).legacy === true) legacy += 1
|
|
28
|
+
const total = this.entries.size
|
|
29
|
+
return { legacy, capabilities: total - legacy, total }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The tools seam, or null when the host does not expose enumeration. */
|
|
33
|
+
#seam() {
|
|
34
|
+
const tools = this.ctx?.tools
|
|
35
|
+
return tools && typeof tools.schemas === 'function' && typeof tools.get === 'function' ? tools : null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Adapt every host tool visible in `scope` into the registry.
|
|
40
|
+
* Without the tools seam this is a silent no-op; id collisions keep the
|
|
41
|
+
* existing descriptor (the legacy entry is always `legacy.<name>`).
|
|
42
|
+
* @param {{scope?: any}} [options]
|
|
43
|
+
* @returns {Promise<{ok: true, available: boolean, scanned: number, added: number, deduped: number, skipped: number, legacy: number, capabilities: number, total: number}>}
|
|
44
|
+
*/
|
|
45
|
+
async refreshLegacy({ scope } = {}) {
|
|
46
|
+
const tools = this.#seam()
|
|
47
|
+
const counts = this.stats()
|
|
48
|
+
const report = { ok: true, available: tools !== null, scanned: 0, added: 0, deduped: 0, skipped: 0, ...counts }
|
|
49
|
+
if (!tools) return report
|
|
50
|
+
let schemas
|
|
51
|
+
try { schemas = await tools.schemas(scope) } catch { return { ...report, available: false } }
|
|
52
|
+
const names = [...new Set((Array.isArray(schemas) ? schemas : []).map(nameOf).filter(name => name && !name.startsWith('os_')))]
|
|
53
|
+
for (const name of names) {
|
|
54
|
+
report.scanned += 1
|
|
55
|
+
const id = `legacy.${name}`
|
|
56
|
+
if (this.entries.has(id)) { report.deduped += 1; continue }
|
|
57
|
+
let tool
|
|
58
|
+
try { tool = await tools.get(name, scope) } catch { report.skipped += 1; continue }
|
|
59
|
+
if (!tool || typeof tool.execute !== 'function') { report.skipped += 1; continue }
|
|
60
|
+
const toolName = nameOf(tool) ?? name
|
|
61
|
+
if (toolName.startsWith('os_')) { report.deduped += 1; continue }
|
|
62
|
+
let descriptor
|
|
63
|
+
try { descriptor = fromTool(tool, this.legacyOptions) } catch { report.skipped += 1; continue }
|
|
64
|
+
if (descriptor.id !== id) {
|
|
65
|
+
if (this.entries.has(descriptor.id)) { report.deduped += 1; continue }
|
|
66
|
+
report.skipped += 1
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
const aliases = descriptor.aliases.filter(alias => alias !== descriptor.id && !this.entries.has(alias) && !this.aliases.has(alias))
|
|
70
|
+
if (aliases.length !== descriptor.aliases.length) descriptor = { ...descriptor, aliases }
|
|
71
|
+
try { this.register(descriptor); report.added += 1 } catch { report.skipped += 1 }
|
|
72
|
+
}
|
|
73
|
+
this.lastLegacyRefresh = Date.now()
|
|
74
|
+
return { ...report, ...this.stats() }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Project Act's registered actions as `act.<id>` capabilities. */
|
|
78
|
+
async refreshAct() {
|
|
79
|
+
const act = typeof this.ctx?.get === 'function' ? this.ctx.get('act') : null
|
|
80
|
+
if (!act || typeof act.list !== 'function' || typeof act.invoke !== 'function') {
|
|
81
|
+
return { ok: true, available: false, added: 0, ...this.stats() }
|
|
82
|
+
}
|
|
83
|
+
let actions
|
|
84
|
+
try { actions = act.list() } catch { return { ok: true, available: false, added: 0, ...this.stats() } }
|
|
85
|
+
if (!Array.isArray(actions)) return { ok: true, available: false, added: 0, ...this.stats() }
|
|
86
|
+
let added = 0
|
|
87
|
+
for (const action of actions) {
|
|
88
|
+
if (!action || typeof action.id !== 'string') continue
|
|
89
|
+
const id = `act.${action.id}`
|
|
90
|
+
if (this.entries.has(id) || this.aliases.has(id)) continue
|
|
91
|
+
const risk = action.risk === 'danger' ? ['execute'] : action.risk === 'write' ? ['write'] : ['read']
|
|
92
|
+
try {
|
|
93
|
+
this.register({
|
|
94
|
+
id,
|
|
95
|
+
title: (action.title ?? action.id).slice(0, 40),
|
|
96
|
+
summary: (action.description ?? `Act action ${action.id}`).slice(0, 120),
|
|
97
|
+
whenToUse: [`Use when the task needs the ${action.id} action.`],
|
|
98
|
+
whenNotToUse: [],
|
|
99
|
+
inputSchema: { type: 'object', additionalProperties: true },
|
|
100
|
+
outputSchema: { type: 'object', additionalProperties: true },
|
|
101
|
+
risk,
|
|
102
|
+
permissions: [`act:invoke:${action.id}`],
|
|
103
|
+
cost: { tokens: 0, latencyMs: 0, moneyUsd: 0 },
|
|
104
|
+
idempotency: risk[0] === 'read' ? 'pure' : 'non-idempotent',
|
|
105
|
+
examples: [],
|
|
106
|
+
errors: [],
|
|
107
|
+
version: '0.1.0',
|
|
108
|
+
tags: ['act'],
|
|
109
|
+
handler: async (args, _ctx, exec) => {
|
|
110
|
+
const subject = exec?.subject ?? exec?.agent?.session?.id ?? exec?.agent?.id
|
|
111
|
+
const result = await act.invoke(action.id, args, {
|
|
112
|
+
subject,
|
|
113
|
+
agent: exec?.agent,
|
|
114
|
+
signal: exec?.signal,
|
|
115
|
+
})
|
|
116
|
+
if (!result || result.ok !== true) {
|
|
117
|
+
const error = new Error(result?.message ?? `act.${action.id} failed`)
|
|
118
|
+
error.code = result?.code ?? 'E_UNAVAILABLE'
|
|
119
|
+
throw error
|
|
120
|
+
}
|
|
121
|
+
return result.result ?? result
|
|
122
|
+
},
|
|
123
|
+
})
|
|
124
|
+
added += 1
|
|
125
|
+
} catch { /* occupied or invalid; keep going */ }
|
|
126
|
+
}
|
|
127
|
+
return { ok: true, available: true, added, ...this.stats() }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const createKernelService = options => new KernelService(options)
|
|
132
|
+
export default KernelService
|
package/lib/state.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional idempotency journal for `os_do`.
|
|
3
|
+
*
|
|
4
|
+
* Only the request fingerprint and the finished OsResult are stored — never
|
|
5
|
+
* the capability args. The file is read once at mount and rewritten atomically
|
|
6
|
+
* after every successful keyed execution, so a restarted kernel can return the
|
|
7
|
+
* original result for the same capability + key.
|
|
8
|
+
*/
|
|
9
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
10
|
+
import { dirname, resolve } from 'node:path'
|
|
11
|
+
|
|
12
|
+
export const STATE_VERSION = 1
|
|
13
|
+
/** Bound the journal so a busy session cannot grow it without limit. */
|
|
14
|
+
export const MAX_ENTRIES = 500
|
|
15
|
+
|
|
16
|
+
const isEntry = entry => entry !== null && typeof entry === 'object'
|
|
17
|
+
&& typeof entry.argsHash === 'string'
|
|
18
|
+
&& entry.result !== null && typeof entry.result === 'object'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Open a journal at `stateFile`, or return null when the option is absent.
|
|
22
|
+
* @param {string|undefined|null} stateFile
|
|
23
|
+
* @returns {{file: string, get: Function, set: Function, size: Function}|null}
|
|
24
|
+
*/
|
|
25
|
+
export function createStateStore(stateFile) {
|
|
26
|
+
if (stateFile === undefined || stateFile === null) return null
|
|
27
|
+
if (typeof stateFile !== 'string' || stateFile.trim() === '') {
|
|
28
|
+
throw new TypeError('config.stateFile must be a non-empty path string')
|
|
29
|
+
}
|
|
30
|
+
const file = resolve(stateFile)
|
|
31
|
+
const entries = new Map()
|
|
32
|
+
try {
|
|
33
|
+
const raw = JSON.parse(readFileSync(file, 'utf8'))
|
|
34
|
+
if (raw === null || typeof raw !== 'object' || raw.version !== STATE_VERSION
|
|
35
|
+
|| raw.entries === null || typeof raw.entries !== 'object' || Array.isArray(raw.entries)) {
|
|
36
|
+
throw new Error('unsupported state file shape')
|
|
37
|
+
}
|
|
38
|
+
for (const [key, entry] of Object.entries(raw.entries)) {
|
|
39
|
+
if (!isEntry(entry)) continue
|
|
40
|
+
entries.set(key, { argsHash: entry.argsHash, result: entry.result, at: Number(entry.at) || 0 })
|
|
41
|
+
}
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error?.code !== 'ENOENT') throw new Error(`cannot read kernel state file ${file}: ${error.message}`)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function persist() {
|
|
47
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
48
|
+
const temp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`
|
|
49
|
+
writeFileSync(temp, `${JSON.stringify({ version: STATE_VERSION, entries: Object.fromEntries(entries) }, null, 2)}\n`, { mode: 0o600 })
|
|
50
|
+
renameSync(temp, file)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
file,
|
|
55
|
+
get: key => entries.get(key),
|
|
56
|
+
set(key, entry) {
|
|
57
|
+
const stored = { argsHash: entry.argsHash, result: entry.result, at: Date.now() }
|
|
58
|
+
entries.set(key, stored)
|
|
59
|
+
while (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value)
|
|
60
|
+
persist()
|
|
61
|
+
return stored
|
|
62
|
+
},
|
|
63
|
+
size: () => entries.size,
|
|
64
|
+
}
|
|
65
|
+
}
|
package/lib/taint.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content-hash taint registry for dsh-os-kernel 0.4.0.
|
|
3
|
+
*
|
|
4
|
+
* The gateway records the SHA-256 of text returned by taint sources
|
|
5
|
+
* (`snip_get`, `seek_resolve`, `trigger_runs`) and of any result carrying a
|
|
6
|
+
* `taintToken`. A later write of the same text can then require the extra
|
|
7
|
+
* `:tainted` Grant or a one-time, hash-bound token instead of trusting the
|
|
8
|
+
* model to self-report `tainted: true`.
|
|
9
|
+
*
|
|
10
|
+
* Only digests, source ids, tokens and timestamps are stored — never the
|
|
11
|
+
* original text. Tokens expire after five minutes and are cleared on first
|
|
12
|
+
* successful use; the digest stays registered (bounded) so the content keeps
|
|
13
|
+
* requiring the tainted Grant after its token is gone.
|
|
14
|
+
*
|
|
15
|
+
* This is an exact-text gate, not taint tracking: a model that edits the
|
|
16
|
+
* content before writing produces a different digest and passes the gate. See
|
|
17
|
+
* the package README for the limits.
|
|
18
|
+
* @module dsh-os-kernel/taint
|
|
19
|
+
*/
|
|
20
|
+
import { createHash, timingSafeEqual } from 'node:crypto'
|
|
21
|
+
|
|
22
|
+
export const TAINT_TTL_MS = 5 * 60 * 1000
|
|
23
|
+
export const MAX_TAINT_RECORDS = 256
|
|
24
|
+
export const TOKEN_PATTERN = /^[0-9a-f]{64}$/
|
|
25
|
+
export const TAINT_SOURCES = Object.freeze([
|
|
26
|
+
'snip.get', 'legacy.snip_get', 'snip_get',
|
|
27
|
+
'seek.resolve', 'legacy.seek_resolve', 'seek_resolve',
|
|
28
|
+
'trigger.runs', 'legacy.trigger_runs', 'trigger_runs',
|
|
29
|
+
])
|
|
30
|
+
|
|
31
|
+
const SOURCE_IDS = new Set(TAINT_SOURCES)
|
|
32
|
+
const TEXT_KEYS = new Set(['text', 'content', 'body', 'markdown', 'snippet'])
|
|
33
|
+
const MAX_DEPTH = 8
|
|
34
|
+
|
|
35
|
+
const isObject = value => value !== null && typeof value === 'object'
|
|
36
|
+
const isToken = value => typeof value === 'string' && TOKEN_PATTERN.test(value)
|
|
37
|
+
const sameToken = (left, right) => isToken(left) && isToken(right)
|
|
38
|
+
&& timingSafeEqual(Buffer.from(left), Buffer.from(right))
|
|
39
|
+
|
|
40
|
+
/** True when a capability id is one whose text starts a taint flow. */
|
|
41
|
+
export const isTaintSource = id => SOURCE_IDS.has(id)
|
|
42
|
+
|
|
43
|
+
/** SHA-256 hex digest of one text value. */
|
|
44
|
+
export const sha256 = text => createHash('sha256').update(text, 'utf8').digest('hex')
|
|
45
|
+
|
|
46
|
+
/** Collect `{ hash -> token }` for every text/content field in a result value. */
|
|
47
|
+
function collectTexts(value, token, found, depth = 0) {
|
|
48
|
+
if (!isObject(value) || depth > MAX_DEPTH) return
|
|
49
|
+
const local = typeof value.taintToken === 'string' && value.taintToken !== '' ? value.taintToken : token
|
|
50
|
+
for (const [key, child] of Object.entries(value)) {
|
|
51
|
+
if (TEXT_KEYS.has(key) && typeof child === 'string' && child !== '') {
|
|
52
|
+
const hash = sha256(child)
|
|
53
|
+
if (local !== null || !found.has(hash)) found.set(hash, local)
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
if (isObject(child)) collectTexts(child, local, found, depth + 1)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class TaintRegistry {
|
|
61
|
+
#records = new Map()
|
|
62
|
+
#now
|
|
63
|
+
#ttlMs
|
|
64
|
+
#max
|
|
65
|
+
|
|
66
|
+
constructor(options = {}) {
|
|
67
|
+
this.#now = typeof options?.now === 'function' ? options.now : Date.now
|
|
68
|
+
this.#ttlMs = Number.isSafeInteger(options?.ttlMs) && options.ttlMs > 0 ? options.ttlMs : TAINT_TTL_MS
|
|
69
|
+
this.#max = Number.isSafeInteger(options?.max) && options.max > 0 ? options.max : MAX_TAINT_RECORDS
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Register one text digest. The text itself is hashed and discarded. */
|
|
73
|
+
record(text, options = {}) {
|
|
74
|
+
if (typeof text !== 'string' || text === '') return null
|
|
75
|
+
return this.#store(sha256(text), options)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Observe one capability result. Text from a taint source is always
|
|
80
|
+
* registered; other results are registered only when they carry a token.
|
|
81
|
+
*/
|
|
82
|
+
observe(capabilityId, value) {
|
|
83
|
+
const found = new Map()
|
|
84
|
+
collectTexts(value, null, found)
|
|
85
|
+
const source = isTaintSource(capabilityId)
|
|
86
|
+
if (!source && ![...found.values()].some(token => typeof token === 'string' && token !== '')) return 0
|
|
87
|
+
for (const [hash, token] of found) this.#store(hash, { source: capabilityId, token })
|
|
88
|
+
return found.size
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
#store(hash, { source = 'unknown', token = null } = {}) {
|
|
92
|
+
const previous = this.#records.get(hash)
|
|
93
|
+
const incoming = typeof token === 'string' && token !== '' ? token : null
|
|
94
|
+
const nextToken = incoming ?? previous?.token ?? null
|
|
95
|
+
const at = this.#now()
|
|
96
|
+
const record = {
|
|
97
|
+
hash, source, token: nextToken, at,
|
|
98
|
+
tokenExpiresAt: incoming !== null ? at + this.#ttlMs
|
|
99
|
+
: nextToken === null ? null : previous?.tokenExpiresAt ?? at + this.#ttlMs,
|
|
100
|
+
usedAt: previous?.usedAt ?? null,
|
|
101
|
+
}
|
|
102
|
+
if (!this.#records.has(hash)) {
|
|
103
|
+
while (this.#records.size >= this.#max) this.#records.delete(this.#records.keys().next().value)
|
|
104
|
+
}
|
|
105
|
+
this.#records.set(hash, record)
|
|
106
|
+
return { ...record }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Look up a digest without consuming its token. */
|
|
110
|
+
lookup(hash) {
|
|
111
|
+
return typeof hash === 'string' ? this.#records.get(hash) : undefined
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** True when this exact text was registered (token already used or not). */
|
|
115
|
+
matches(text) {
|
|
116
|
+
return typeof text === 'string' && text !== '' && this.#records.has(sha256(text))
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Check a token for a digest and burn it on success. */
|
|
120
|
+
consume(hash, token) {
|
|
121
|
+
const record = this.lookup(hash)
|
|
122
|
+
if (record === undefined || !isToken(token) || !sameToken(record.token, token)) return false
|
|
123
|
+
if (!(record.tokenExpiresAt > this.#now())) return false
|
|
124
|
+
record.token = null
|
|
125
|
+
record.usedAt = this.#now()
|
|
126
|
+
return true
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Copy of the registry metadata; never contains plaintext. */
|
|
130
|
+
snapshot() {
|
|
131
|
+
return [...this.#records.values()].map(record => ({ ...record }))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
get size() {
|
|
135
|
+
return this.#records.size
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export default TaintRegistry
|