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 ADDED
@@ -0,0 +1,124 @@
1
+ # Changelog
2
+
3
+ ## 0.4.0 — 2026-11-21
4
+
5
+ ### Added
6
+
7
+ - **Content-hash taint gate.** The gateway keeps an in-process
8
+ `TaintRegistry` of `sha256(text)` for every `text`/`content` field returned
9
+ by `snip_get`, `seek_resolve` and `trigger_runs`, and for any result that
10
+ carries a `taintToken`. Only digests, source ids, tokens and timestamps are
11
+ stored; the original text is never kept or logged.
12
+ - `os_do` on `act.fs.write` (or `legacy.act_invoke` with `args.id ===
13
+ "fs.write"`) hashes `args.text`/`args.content`. A registered digest requires
14
+ the base Grant **and** `cap:act.fs.write:tainted` through `ctx.allow.check`,
15
+ or a fresh `taintToken` bound to that digest. A miss returns `E_DENIED`,
16
+ `subcode: "grant_required"`, `details.permission:
17
+ "cap:act.fs.write:tainted"` and `nextTools: [os_request]`.
18
+ - Tokens are single-use, hash-bound and expire after five minutes
19
+ (`TAINT_TTL_MS`). A used or expired token cannot authorize another write,
20
+ but the digest stays registered (bounded to 256 entries) so the tainted
21
+ Grant is still required. Taint evidence is stripped before the handler runs.
22
+ - `os_request({ ..., tainted: true })` requests the mapped `:tainted`
23
+ capability, closing the two-approval loop through `os_observe`/`os_do`:
24
+ `legacy.act_invoke` maps to `cap:act.fs.write:tainted`.
25
+ - `config.taint` (`{ ttlMs, max, now }`) for hosts/tests; exports
26
+ `TaintRegistry`, `TAINT_TTL_MS`, `MAX_TAINT_RECORDS` and the taint helpers.
27
+ - Tests: blocked verbatim reuse, base+tainted Grants, one-shot and stripped
28
+ tokens, forged/expired tokens, ordinary content, `seek_resolve` and legacy
29
+ `snip_get` sources, and the real `dsh-allow` recovery loop.
30
+
31
+ ### Changed
32
+
33
+ - `VERSION` and the package version are `0.4.0`. `os_do`/`os_request` schemas
34
+ document the taint behaviour; `os_request` gains the optional `tainted`
35
+ field.
36
+
37
+ ### Limit
38
+
39
+ - The digest gate prevents verbatim reuse only. Rewritten content, substrings
40
+ or a different fetch path produce a different digest and pass. Full
41
+ provenance still requires host metadata; this is not taint tracking.
42
+
43
+ ## 0.3.0 — 2026-11-21
44
+
45
+ ### Added
46
+
47
+ - **Permission bridge closes the loop.** `os_observe({requestId})` pulls the
48
+ latest request from Allow (`ctx.allow.requests`, then `wait`/`get`), and on
49
+ `approved` calls `ctx.allow.check` once, caches the consumed Grant and
50
+ reports `grantAvailable`. The next `os_do` with the same id, args and subject
51
+ uses it automatically; no host-injected grant is needed. Replays and
52
+ exhausted Grants stay `E_DENIED`. Cached approvals are bound to
53
+ `subject + capability + args fingerprint`; `os_request` records only the
54
+ fingerprint, never the args.
55
+ - **Optional idempotency journal.** `apply(ctx, { stateFile })` persists
56
+ `{ argsHash, result }` per subject + capability + key, returns the original
57
+ `OsResult` after a restart, and rejects key reuse with different args as
58
+ `E_CONFLICT`. Atomic writes, mode `0600`, 500-entry bound, no args stored.
59
+ - **`config.gatewayOnly`.** In a scoped agent/preset mount it registers the six
60
+ verbs and calls `ctx.tools.restrict({ deny: [...] })` for every inherited
61
+ non-`os_*` tool; a global mount fails closed. The legacy bridge enumerates
62
+ the global view under this mode, so hidden tools remain reachable as
63
+ capabilities.
64
+ - `docs/presets/os-gateway.md` + `.cordis.yml`: copyable preset row and the
65
+ `toolFilter` vs. `ctx.tools.restrict` distinction.
66
+ - Exports `capabilityName()`, `CAPABILITY_PREFIX`, `createStateStore`,
67
+ `STATE_VERSION`, `MAX_ENTRIES`; tests for the real `dsh-allow` bridge,
68
+ observe refresh, one-shot replay, args binding, restart-safe idempotency,
69
+ gatewayOnly and the preset.
70
+
71
+ ### Changed
72
+
73
+ - **Capability naming is unified to `cap:<descriptor.id>`.** `os_request` used
74
+ to ask for `<id>` while `allowedByHost` checked `cap:<id>`; both now use
75
+ `cap:<id>`, matching what `os_observe` consumes. Plain `<id>` grants no
76
+ longer match (module grants such as `act:invoke:<action>` are unaffected).
77
+ - `os_do` checks the idempotency journal before authorization, so a restart
78
+ replay needs no fresh Grant; entries are scoped by subject + capability + key.
79
+ - The Allow check omits `scope`, so a human-narrowed approval still authorizes
80
+ its one use. `isGrant()` rejects `used` or exhausted Grants.
81
+ - `VERSION` and the package version are `0.3.0`.
82
+
83
+ ### Compatibility
84
+
85
+ - The result schema remains `os.result/v1`; `legacyTools`, explicit `grant`
86
+ args and in-memory idempotency are unchanged.
87
+ - `stateFile` and `gatewayOnly` are opt-in; without them 0.2.0 behavior is
88
+ unchanged apart from the capability name.
89
+
90
+ ## 0.2.0 — 2026-11-21
91
+
92
+ ### Added
93
+
94
+ - `KernelService` (extends `CapabilityRegistry`) with `refreshLegacy({scope})`
95
+ and `stats()`. `apply()` now provides it as `ctx.kernel` while returning the
96
+ same object.
97
+ - Legacy bridge: enumerates `ctx.tools.schemas(scope)`, fetches definitions
98
+ with `ctx.tools.get(name, scope)`, excludes `os_*`, and registers the rest
99
+ with `fromTool()` as `legacy.<tool name>`. Repeated refreshes are idempotent;
100
+ existing ids and aliases are kept, so descriptors are never shadowed.
101
+ - Lazy refresh on the first `os_find`/`os_status` (scope = `exec.agent`), and
102
+ on a direct `os_do` for an unknown `legacy.*` id. Hosts without a
103
+ `schemas`/`get` seam are silently skipped.
104
+ - `os_do` normalizes legacy outcomes: unwraps `{ok:true,...}`, converts
105
+ `{ok:false,error}` to an OsError, aliases unknown codes to the nine classes
106
+ and keeps the original in `details.legacyCode`.
107
+ - `os_status` now reports `{ legacy, capabilities, total }`; legacy descriptors
108
+ are excluded from `modules`.
109
+ - Local `ok()` / `err()` / `legacyOutcome()` envelope helpers
110
+ (`./envelope` export), mirroring `dsh-os-contract` without adding
111
+ a dependency.
112
+ - `fromTool()` recognizes `execute` in names/descriptions as execute risk.
113
+
114
+ ### Changed
115
+
116
+ - `VERSION` is `0.2.0`; the package version is `0.2.0`.
117
+ - `os_find`/`os_status` are now async-refresh aware; both still return the
118
+ same shapes as before, apart from the new `os_status` counters.
119
+
120
+ ### Compatibility
121
+
122
+ - `config.legacyTools` remains supported for hosts that cannot enumerate.
123
+ - The published result schema remains `os.result/v1`, not the contract's
124
+ `dsh.os.result/v1`; field shapes are unchanged.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PerryLink contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,202 @@
1
- # Temporary Holding Version
1
+ # dsh-os-kernel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **A thin capability kernel for dsh-os.** It is a routing and protocol layer,
4
+ not an OS implementation: it stores no clipboard, opens no window, runs no
5
+ check and writes no file. Modules keep their own services, storage and tests;
6
+ they remain independently installable and removable.
7
+
8
+ ```
9
+ descriptor -> registry -> six agent verbs
10
+ ^ | |
11
+ modules register | os_find / os_do / os_request
12
+ or fromTool | os_observe / os_help / os_status
13
+ |
14
+ ctx.tools.schemas/get -> refreshLegacy()
15
+ ```
16
+
17
+ ## What it owns
18
+
19
+ 1. **Descriptor protocol** — `validateDescriptor()` / `normalizeDescriptor()`
20
+ over the architecture §2 fields (`id`, `title`, `summary`, `whenToUse`,
21
+ `whenNotToUse`, `inputSchema`, `outputSchema`, `risk`, `permissions`,
22
+ `cost`, `idempotency`, `examples`, `returns`, `errors`, `version`, `tags`,
23
+ `handler`, `ui`, `aliases`, `deprecated`, `audience`).
24
+ 2. **Registry** — `register` / `list` / `search` / `resolve` / `invoke`;
25
+ filters by namespace (`capability`), `risk` and `tags`; lazy
26
+ `{ id, meta, load }` entries; `E_CONFLICT` on id/alias/version collisions;
27
+ handler errors normalized to the nine `E_*` classes.
28
+ 3. **KernelService** — the registry plus `refreshLegacy({scope})` and
29
+ `stats()` (see below).
30
+ 4. **Gateway** — six plain host `ToolDefinition`s:
31
+ - `os_find({intent, riskMax?, limit?})` → compact capability cards;
32
+ - `os_do({id, args, preview?, idempotencyKey?, grant?})` → `os.result/v1`;
33
+ `write`/`execute`/`destructive` capabilities without a grant return
34
+ `E_DENIED` with `remediation` and `nextTools: [os_request]`; writes of
35
+ previously-seen taint-source text also need the `:tainted` Grant (below);
36
+ - `os_request({id, args, reason, tainted?})` → `ctx.allow.request` for
37
+ capability `cap:<descriptor.id>` (or `cap:<id>:tainted` when
38
+ `tainted:true`; `E_UNAVAILABLE` when Allow is absent);
39
+ - `os_observe({requestId?, jobId?, handle?})` → refreshes a request from
40
+ Allow, and when approved consumes the Grant once and caches it;
41
+ - `os_help({task})` → 4 steps + candidate capabilities + risks;
42
+ - `os_status({})` → modules, `legacy` / `capabilities` counts, health,
43
+ version.
44
+
45
+ ## Permission bridge
46
+
47
+ One name crosses the bridge in both directions: `cap:<descriptor.id>` (for
48
+ example `cap:act.fs.write`). `os_request` asks Allow for it, `allowedByHost`
49
+ checks it, and the grant cached by `os_observe` is issued for it. A plain
50
+ `<id>` grant does not match; module-owned grants stay separate (Act uses
51
+ `act:invoke:<action>`).
52
+
53
+ The recovery loop is closed inside the kernel:
54
+
55
+ 1. `os_do` on a gated capability returns `E_DENIED` + `nextTools: [os_request]`.
56
+ 2. `os_request` creates a one-use Allow Request and records the subject and an
57
+ args fingerprint in memory (never the args).
58
+ 3. `os_observe` pulls the latest request from Allow; when `approved`, it calls
59
+ `allow.check` once, consumes the Grant and caches it (`grantAvailable`).
60
+ 4. The next `os_do` with the same id, args and subject uses that cache — no
61
+ host injection. The approval is gone, so a replay or exhausted Grant stays
62
+ `E_DENIED`. The cache is bound to `subject + id + args fingerprint`, and
63
+ the Allow check omits `scope` so a narrowed approval still works.
64
+
65
+ ## Content-hash taint gate (0.4.0)
66
+
67
+ `tainted: true` is a claim, not evidence. The gateway instead records the
68
+ SHA-256 of every `text`/`content` field returned by a taint source —
69
+ `snip_get`, `seek_resolve`, `trigger_runs` — and of text in any result that
70
+ carries a `taintToken`. Only the digest, source id, token and timestamps are
71
+ kept; the text is hashed and discarded, and no plaintext is logged.
72
+
73
+ For `act.fs.write` (or `legacy.act_invoke` with `args.id === "fs.write"`), the
74
+ gateway hashes `args.text` / `args.content` (nested under `args.args` for
75
+ `act_invoke`). If the digest is registered, the write needs **the base Grant
76
+ plus one of**:
77
+
78
+ - `ctx.allow.check({ subject, capability: "cap:act.fs.write:tainted" })`,
79
+ normally through `os_request({ id, args, reason, tainted: true })` →
80
+ `os_observe` → `os_do`; or
81
+ - a fresh `taintToken` returned with that exact text — single use, bound to
82
+ the digest, valid for five minutes.
83
+
84
+ Otherwise `os_do` returns `E_DENIED` with `subcode: "grant_required"`,
85
+ `details.permission: "cap:act.fs.write:tainted"` and `nextTools:
86
+ [os_request]`. Taint evidence is stripped before the handler runs. The digest
87
+ stays registered after its token is used or expires, so later writes still
88
+ need the tainted Grant. The registry is in-process and bounded to 256
89
+ digests.
90
+
91
+ **Limit: exact-text reuse only.** Rewriting the content, copying a substring,
92
+ or re-fetching it through another path yields a different digest and passes
93
+ this gate. Full provenance needs host-supplied source metadata carried with
94
+ the content; the kernel does not inspect model reasoning, and a module remains
95
+ callable outside the gateway. The gate raises the cost of replaying a
96
+ prompt-injected snippet; it is not a sandbox. Ordinary reads such as
97
+ `act.fs.read` do not seed the registry.
98
+
99
+ ## Idempotency journal
100
+
101
+ `os_do` reuses `idempotencyKey` in memory; `config.stateFile` makes it survive
102
+ a restart:
103
+
104
+ ```js
105
+ apply(ctx, { stateFile: '/absolute/path/kernel-idempotency.json' })
106
+ ```
107
+
108
+ The journal stores `{ argsHash, result }` per subject + capability + key,
109
+ writes atomically with mode `0600`, and is bounded to 500 entries. Args are
110
+ never stored. A replay returns the original `OsResult` before consuming a new
111
+ grant; different args under the same key return `E_CONFLICT`. A write failure
112
+ keeps the result and appends a warning instead of claiming persistence.
113
+
114
+ ## Gateway-only mount
115
+
116
+ `config.gatewayOnly: true` hides every inherited non-`os_*` tool for one agent
117
+ scope via `ctx.tools.restrict({ deny: [...] })`. It requires a scoped mount (an
118
+ agent preset or `agent.ctx`); a global mount fails closed because it would mask
119
+ every agent. The legacy bridge keeps enumerating the global view, so hidden
120
+ tools remain reachable as `legacy.<tool>` capabilities through
121
+ `os_find`/`os_do`.
122
+
123
+ See [`docs/presets/os-gateway.md`](../../docs/presets/os-gateway.md) and
124
+ [`docs/presets/os-gateway.cordis.yml`](../../docs/presets/os-gateway.cordis.yml).
125
+ DSH presets are plugin lists; `toolFilter` (`ToolRestriction`) is the
126
+ subagent-level restriction, not a preset YAML key.
127
+
128
+ ## Mount
129
+
130
+ ```js
131
+ import { apply } from 'dsh-os-kernel'
132
+ // ctx.tools must exist (inject: ['tools']); apply() provides ctx.kernel
133
+ const kernel = apply(ctx) // six tools registered into ctx.tools
134
+ // Optional: apply(ctx, { gatewayOnly: true }) inside an agent preset,
135
+ // or apply(ctx, { stateFile: '/abs/kernel-idempotency.json' }).
136
+ await kernel.refreshLegacy() // optional: os_find/os_status do this lazily
137
+ kernel.register({
138
+ id: 'snip.search', title: 'Search clippings', summary: 'Find a copied item.',
139
+ whenToUse: ['The user refers to something copied earlier.'],
140
+ whenNotToUse: ['The user wants the current clipboard.'],
141
+ inputSchema: { type: 'object', additionalProperties: false, required: ['query'], properties: { query: { type: 'string' } } },
142
+ risk: 'read', handler: async ({ query }) => ctx.snip.search(query),
143
+ })
144
+ ```
145
+
146
+ ## Legacy tools (73+)
147
+
148
+ `KernelService.refreshLegacy({scope})` bridges the old tool surface without
149
+ touching any module:
150
+
151
+ 1. Enumerates visible schemas with `ctx.tools.schemas(scope)` and fetches each
152
+ definition with `ctx.tools.get(name, scope)`.
153
+ 2. Skips `os_*` (the kernel's own verbs) and adapts every other tool with
154
+ `fromTool()` as `legacy.<tool name>` (`risk` inferred from name/description;
155
+ `legacyOptions` overrides it).
156
+ 3. Is idempotent: repeated refreshes keep the existing entry. An occupied
157
+ `legacy.<name>` id is never overwritten, and an alias already owned by a
158
+ descriptor is not stolen — descriptors always win, the legacy entry keeps
159
+ its `legacy.` namespace.
160
+ 4. Silently does nothing when `ctx.tools` exposes no `schemas`/`get` (older
161
+ hosts); `config.legacyTools` still works as an explicit fallback.
162
+
163
+ `apply()` does not enumerate eagerly. The first `os_find` or `os_status` calls
164
+ `refreshLegacy({ scope: exec.agent })`; a direct `os_do` on an unknown
165
+ `legacy.*` id does the same. Under `gatewayOnly` the bridge enumerates the
166
+ global view instead, because the agent's own tool view is intentionally
167
+ restricted to the six verbs. After that the gateway searches descriptors and
168
+ legacy tools together, so `os_find` returns top-k cards from both surfaces and
169
+ `os_status` reports `{ legacy: N, capabilities: M, total }`.
170
+
171
+ Legacy payloads are normalized through the kernel's local `ok()` / `err()`
172
+ pair (the same `os.result/v1` / OsError envelope as the contract): a returned
173
+ `{ ok: true, ... }` is unwrapped, `{ ok: false, error }` becomes an `OsError`,
174
+ and raw values are wrapped. Unknown error codes are aliased to the nine
175
+ classes with `details.legacyCode`.
176
+
177
+ ## Boundary
178
+
179
+ - **Kernel is thin.** It has no business modules and no network. The only
180
+ optional persistence is the idempotency journal above.
181
+ - **Modules stay independent.** A module may register a descriptor when the
182
+ kernel is present (`ctx.get('kernel')?.register`) and must still work when it
183
+ is absent. The kernel never imports a module.
184
+ - **Zero runtime dependencies**, plain ESM. `lib/state.js` uses only Node
185
+ built-ins (`node:fs`, `node:path`) and only when `config.stateFile` is set;
186
+ `lib/envelope.js` mirrors `dsh-os-contract`'s `ok()`/`err()`
187
+ helpers instead of importing them, so the package stays standalone. Its
188
+ success schema remains the published `os.result/v1`.
189
+ - **No publish** in this package's scripts; release is owned by the monorepo.
190
+
191
+ ## Tests
192
+
193
+ ```sh
194
+ node --test
195
+ ```
196
+
197
+ Covers descriptors, registry CRUD/conflict/search/lazy invoke, `fromTool`,
198
+ the six verbs, legacy bridge and envelopes, the permission bridge against the
199
+ real `dsh-allow` service (`cap:<id>`, observe refresh, one-shot grant, args
200
+ binding), the content-hash taint gate (blocked/dual-grant/token/forged/expired/
201
+ ordinary/recovery loop), idempotency across a restart, `gatewayOnly` and the
202
+ shipped preset.
@@ -0,0 +1,4 @@
1
+ # dsh-os-kernel bundle patch: mount the plugin.
2
+ - insert:
3
+ - id: dsh-os-kernel
4
+ name: "dsh-os-kernel"
package/index.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * dsh-os-kernel — the thin capability kernel for dsh-os.
3
+ *
4
+ * It owns a registry, six agent verbs and the descriptor protocol. It owns no
5
+ * business logic: every capability stays in its own module and is registered
6
+ * here (or adapted from a legacy ToolDefinition with fromTool).
7
+ */
8
+ import { KernelService } from './lib/service.js'
9
+ import { createTools, TOOL_NAMES } from './lib/gateway.js'
10
+ import { fromTool } from './lib/from-tool.js'
11
+
12
+ export { CapabilityRegistry, createRegistry } from './lib/registry.js'
13
+ export { KernelService, createKernelService } from './lib/service.js'
14
+ export { validateDescriptor, normalizeDescriptor, RISKS, IDEMPOTENCY } from './lib/descriptor.js'
15
+ export { fromTool } from './lib/from-tool.js'
16
+ export {
17
+ createGateway, createTools, gatewayTools, VERSION, TOOL_NAMES, CAPABILITY_PREFIX, capabilityName,
18
+ } from './lib/gateway.js'
19
+ export { createStateStore, STATE_VERSION, MAX_ENTRIES } from './lib/state.js'
20
+ export { TaintRegistry, TAINT_TTL_MS, MAX_TAINT_RECORDS, TOKEN_PATTERN, TAINT_SOURCES, isTaintSource, sha256 } from './lib/taint.js'
21
+ export { ok, err, legacyOutcome, resolveCode, ERROR_CLASSES, RESULT_SCHEMA } from './lib/envelope.js'
22
+
23
+ /** Cordis plugin name. */
24
+ export const name = 'dsh-os-kernel'
25
+ /** The kernel registers six agent tools through the host registry. */
26
+ export const inject = ['tools']
27
+
28
+ /**
29
+ * Hide every inherited global tool except the six `os_*` verbs. This only
30
+ * works in a scoped context (an agent preset / agent.ctx): a global
31
+ * `tools.restrict()` would mask every agent, so DSH rejects it.
32
+ * @param {any} ctx
33
+ * @returns {Function|null} the restriction disposer, or null when nothing was inherited
34
+ */
35
+ function restrictToGateway(ctx) {
36
+ const tools = ctx?.tools
37
+ if (!tools || typeof tools.restrict !== 'function' || typeof tools.schemas !== 'function') {
38
+ throw new Error('config.gatewayOnly requires ctx.tools.restrict() and ctx.tools.schemas()')
39
+ }
40
+ let schemas
41
+ try { schemas = tools.schemas() } catch (error) {
42
+ throw new Error(`config.gatewayOnly cannot read ctx.tools.schemas(): ${error?.message ?? String(error)}`)
43
+ }
44
+ if (!Array.isArray(schemas)) throw new Error('config.gatewayOnly requires synchronous ctx.tools.schemas()')
45
+ const own = new Set(TOOL_NAMES)
46
+ const names = schemas.map(item => typeof item === 'string' ? item : item?.name)
47
+ const deny = [...new Set(names.filter(name => typeof name === 'string' && name !== 'run_code' && !own.has(name)))]
48
+ if (deny.length === 0) return null
49
+ try {
50
+ return tools.restrict({ deny })
51
+ } catch (error) {
52
+ throw new Error(
53
+ `config.gatewayOnly needs a scoped agent/preset mount because ctx.tools.restrict() rejected the mask: ${error?.message ?? String(error)}. `
54
+ + 'Mount the kernel inside an agent preset; see docs/presets/os-gateway.md.',
55
+ )
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Mount the kernel: provide `ctx.kernel`, adapt legacy tools, register six verbs.
61
+ * `config.legacyTools` remains for hosts that cannot enumerate tools; when
62
+ * `ctx.tools.schemas/get` exist, the first `os_find`/`os_status` lazily adapts
63
+ * every visible non-`os_*` tool as `legacy.<tool name>`.
64
+ * @param {any} ctx
65
+ * @param {{authorize?: Function, strict?: boolean, legacyTools?: any[], legacyOptions?: any, capabilities?: any[], stateFile?: string, gatewayOnly?: boolean, taint?: {ttlMs?: number, max?: number, now?: Function}}} [config]
66
+ * @returns {KernelService}
67
+ */
68
+ export function apply(ctx, config = {}) {
69
+ const registry = new KernelService({
70
+ authorize: config.authorize,
71
+ ctx,
72
+ strict: config.strict,
73
+ legacyOptions: config.legacyOptions ?? {},
74
+ })
75
+ ctx.provide('kernel', registry)
76
+ for (const descriptor of Array.isArray(config.capabilities) ? config.capabilities : []) registry.register(descriptor)
77
+ for (const tool of Array.isArray(config.legacyTools) ? config.legacyTools : []) registry.register(fromTool(tool, config.legacyOptions ?? {}))
78
+ const tools = createTools(registry, {
79
+ ctx,
80
+ stateFile: config.stateFile,
81
+ gatewayOnly: config.gatewayOnly === true,
82
+ taint: config.taint,
83
+ })
84
+ if (ctx.tools && typeof ctx.tools.register === 'function') for (const tool of tools) ctx.tools.register(tool)
85
+ if (config.gatewayOnly === true) {
86
+ const restriction = restrictToGateway(ctx)
87
+ if (typeof restriction === 'function') registry.gatewayRestriction = restriction
88
+ }
89
+ return registry
90
+ }
@@ -0,0 +1,95 @@
1
+ /** Capability descriptor validation and normalization (architecture §2). Pure ESM. */
2
+ export const RISKS = Object.freeze(['read', 'write', 'execute', 'network', 'secret', 'approval'])
3
+ export const IDEMPOTENCY = Object.freeze(['pure', 'idempotent', 'non-idempotent', 'destructive'])
4
+ export const AUDIENCES = Object.freeze(['agent', 'human', 'cli'])
5
+
6
+ const ID = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/
7
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
8
+ const KEYS = new Set(['id', 'title', 'summary', 'whenToUse', 'whenNotToUse', 'inputSchema', 'outputSchema',
9
+ 'risk', 'permissions', 'cost', 'idempotency', 'examples', 'returns', 'errors', 'version', 'tags',
10
+ 'handler', 'ui', 'aliases', 'deprecated', 'audience', 'legacy', 'owner'])
11
+ const obj = value => value !== null && typeof value === 'object' && !Array.isArray(value)
12
+
13
+ function fail(message) {
14
+ const error = new TypeError(message)
15
+ error.code = 'E_INVALID_ARGUMENT'
16
+ throw error
17
+ }
18
+ const str = (value, field, max) => {
19
+ if (typeof value !== 'string' || value.trim() === '') fail(`${field} must be a non-empty string`)
20
+ if (max !== undefined && value.length > max) fail(`${field} must be at most ${max} characters`)
21
+ }
22
+ const strings = (value, field) => {
23
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || item === '')) fail(`${field} must be an array of non-empty strings`)
24
+ }
25
+ const optionalStrings = (value, field) => { if (value !== undefined) strings(value, field) }
26
+
27
+ /** Validate a descriptor without mutating it; returns the same object. */
28
+ export function validateDescriptor(descriptor) {
29
+ if (!obj(descriptor)) fail('descriptor must be a plain object')
30
+ for (const key of Object.keys(descriptor)) {
31
+ if (!KEYS.has(key) && !key.startsWith('x-')) fail(`unknown descriptor field: ${key}`)
32
+ }
33
+ if (!ID.test(String(descriptor.id))) fail('id must look like "namespace.verb"')
34
+ str(descriptor.title, 'title', 40)
35
+ str(descriptor.summary, 'summary', 120)
36
+ for (const field of ['whenToUse', 'whenNotToUse', 'permissions', 'tags', 'aliases', 'audience']) optionalStrings(descriptor[field], field)
37
+ for (const field of ['inputSchema', 'outputSchema']) if (descriptor[field] !== undefined && !obj(descriptor[field])) fail(`${field} must be an object`)
38
+ const risks = Array.isArray(descriptor.risk) ? descriptor.risk : [descriptor.risk]
39
+ if (risks.length === 0 || risks.some(risk => !RISKS.includes(risk))) fail(`risk must contain only ${RISKS.join(', ')}`)
40
+ if (descriptor.idempotency !== undefined && !IDEMPOTENCY.includes(descriptor.idempotency)) fail(`idempotency must be one of ${IDEMPOTENCY.join(', ')}`)
41
+ if (descriptor.version !== undefined && !SEMVER.test(descriptor.version)) fail('version must be semver')
42
+ if (descriptor.cost !== undefined) {
43
+ if (!obj(descriptor.cost)) fail('cost must be an object')
44
+ for (const field of ['tokens', 'latencyMs', 'moneyUsd']) {
45
+ const value = descriptor.cost[field]
46
+ if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value) || value < 0)) fail(`cost.${field} must be a non-negative number`)
47
+ }
48
+ }
49
+ if (descriptor.examples !== undefined && !Array.isArray(descriptor.examples)) fail('examples must be an array')
50
+ if (descriptor.errors !== undefined) {
51
+ if (!Array.isArray(descriptor.errors)) fail('errors must be an array')
52
+ for (const item of descriptor.errors) if (!obj(item) || typeof item.code !== 'string' || !item.code) fail('errors[] needs a string code')
53
+ }
54
+ if (descriptor.ui !== undefined && descriptor.ui !== null && !obj(descriptor.ui)) fail('ui must be an object or null')
55
+ if (descriptor.deprecated !== undefined && descriptor.deprecated !== null && !obj(descriptor.deprecated)) fail('deprecated must be an object or null')
56
+ if (descriptor.audience !== undefined) for (const item of descriptor.audience) if (!AUDIENCES.includes(item)) fail(`audience must contain only ${AUDIENCES.join(', ')}`)
57
+ if (typeof descriptor.handler !== 'function') fail('handler must be a function')
58
+ return descriptor
59
+ }
60
+
61
+ const freeze = (value, seen = new WeakSet()) => {
62
+ if (value === null || typeof value !== 'object' || seen.has(value)) return value
63
+ seen.add(value)
64
+ for (const key of Object.keys(value)) freeze(value[key], seen)
65
+ return Object.freeze(value)
66
+ }
67
+ const copy = value => Array.isArray(value) ? value.map(copy)
68
+ : obj(value) ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copy(item)])) : value
69
+
70
+ /** Validate, fill defaults, detach and freeze. `toJSON()` strips the handler. */
71
+ export function normalizeDescriptor(descriptor) {
72
+ validateDescriptor(descriptor)
73
+ const out = copy(descriptor)
74
+ out.risk = [...new Set(Array.isArray(descriptor.risk) ? descriptor.risk : [descriptor.risk])]
75
+ out.whenToUse = [...(descriptor.whenToUse ?? [])]
76
+ out.whenNotToUse = [...(descriptor.whenNotToUse ?? [])]
77
+ out.inputSchema = copy(descriptor.inputSchema ?? { type: 'object', additionalProperties: true })
78
+ out.outputSchema = copy(descriptor.outputSchema ?? { type: 'object', additionalProperties: true })
79
+ out.permissions = [...(descriptor.permissions ?? [])]
80
+ const cost = descriptor.cost ?? {}
81
+ out.cost = { tokens: cost.tokens ?? 0, latencyMs: cost.latencyMs ?? 0, moneyUsd: cost.moneyUsd ?? cost.money ?? 0 }
82
+ out.idempotency = descriptor.idempotency ?? 'pure'
83
+ out.examples = copy(descriptor.examples ?? [])
84
+ out.returns = descriptor.returns ?? descriptor.summary
85
+ out.errors = copy(descriptor.errors ?? [])
86
+ out.version = descriptor.version ?? '1.0.0'
87
+ out.tags = [...(descriptor.tags ?? [])]
88
+ out.ui = copy(descriptor.ui ?? null)
89
+ out.aliases = [...(descriptor.aliases ?? [])]
90
+ out.deprecated = copy(descriptor.deprecated ?? null)
91
+ out.audience = [...(descriptor.audience ?? AUDIENCES)]
92
+ if (descriptor.legacy === true) out.legacy = true
93
+ Object.defineProperty(out, 'toJSON', { enumerable: false, value() { const plain = { ...this }; delete plain.handler; return plain } })
94
+ return freeze(out)
95
+ }