PerryLink/dsh-os--packages-kernel ↗★ 1
@perrylink/dsh-os-kernel
Thin capability kernel for dsh-os: descriptor protocol, registry, legacy tool bridge, six os_* verbs, Allow grant bridge and optional idempotency journal.
安裝
npx -p @deepseek-ai/dsh dsh plugin --profile web add 'github:PerryLink/dsh-os#fba8f0735f2a4971f3650e800835439172e81b30&path:packages/kernel'說明文件
閱讀完整 README ↗@perrylink/dsh-os-kernel
A thin capability kernel for dsh-os. It is a routing and protocol layer, not an OS implementation: it stores no clipboard, opens no window, runs no check and writes no file. Modules keep their own services, storage and tests; they remain independently installable and removable.
descriptor -> registry -> six agent verbs
^ | |
modules register | os_find / os_do / os_request
or fromTool | os_observe / os_help / os_status
|
ctx.tools.schemas/get -> refreshLegacy()
What it owns
- Descriptor protocol —
validateDescriptor()/normalizeDescriptor()over the architecture §2 fields (id,title,summary,whenToUse,whenNotToUse,inputSchema,outputSchema,risk,permissions,cost,idempotency,examples,returns,errors,version,tags,handler,ui,aliases,deprecated,audience). - Registry —
register/list/search/resolve/invoke; filters by namespace (capability),riskandtags; lazy{ id, meta, load }entries;E_CONFLICTon id/alias/version collisions; handler errors normalized to the nineE_*classes. - KernelService — the registry plus
refreshLegacy({scope})andstats()(see below). - Gateway — six plain host
ToolDefinitions:os_find({intent, riskMax?, limit?})→ compact capability cards;os_do({id, args, preview?, idempotencyKey?, grant?})→os.result/v1;write/execute/destructivecapabilities without a grant returnE_DENIEDwithremediationandnextTools: [os_request];os_request({id, args, reason})→ctx.allow.requestfor capabilitycap:(orE_UNAVAILABLEwhen Allow is absent);os_observe({requestId?, jobId?, handle?})→ refreshes a request from Allow, and when approved consumes the Grant once and caches it;os_help({task})→ 4 steps + candidate capabilities + risks;os_status({})→ modules,legacy/capabilitiescounts, health, version.
Permission bridge
One name crosses the bridge in both directions: cap: (for
example cap:act.fs.write). os_request asks Allow for it, allowedByHost
checks it, and the grant cached by os_observe is issued for it. A plain
`` grant does not match; module-owned grants stay separate (Act uses
act:invoke:).
The recovery loop is closed inside the kernel:
os_doon a gated capability returnsE_DENIED+nextTools: [os_request].os_requestcreates a one-use Allow Request and records the subject and an args fingerprint in memory (never the args).os_observepulls the latest request from Allow; whenapproved, it callsallow.checkonce, consumes the Grant and caches it (grantAvailable).- The next
os_dowith the same id, args and subject uses that cache — no host injection. The approval is gone, so a replay or exhausted Grant staysE_DENIED. The cache is bound tosubject + id + args fingerprint, and the Allow check omitsscopeso a narrowed approval still works.
Idempotency journal
os_do reuses idempotencyKey in memory; config.stateFile makes it survive
a restart:
apply(ctx, { stateFile: '/absolute/path/kernel-idempotency.json' })
The journal stores { argsHash, result } per subject + capability + key,
writes atomically with mode 0600, and is bounded to 500 entries. Args are
never stored. A replay returns the original OsResult before consuming a new
grant; different args under the same key return E_CONFLICT. A write failure
keeps the result and appends a warning instead of claiming persistence.
Gateway-only mount
config.gatewayOnly: true hides every inherited non-os_* tool for one agent
scope via ctx.tools.restrict({ deny: [...] }). It requires a scoped mount (an
agent preset or agent.ctx); a global mount fails closed because it would mask
every agent. The legacy bridge keeps enumerating the global view, so hidden
tools remain reachable as legacy. capabilities through
os_find/os_do.
See docs/presets/os-gateway.md and
docs/presets/os-gateway.cordis.yml.
DSH presets are plugin lists; toolFilter (ToolRestriction) is the
subagent-level restriction, not a preset YAML key.
Mount
import { apply } from '@perrylink/dsh-os-kernel'
// ctx.tools must exist (inject: ['tools']); apply() provides ctx.kernel
const kernel = apply(ctx) // six tools registered into ctx.tools
// Optional: apply(ctx, { gatewayOnly: true }) inside an agent preset,
// or apply(ctx, { stateFile: '/abs/kernel-idempotency.json' }).
await kernel.refreshLegacy() // optional: os_find/os_status do this lazily
kernel.register({
id: 'snip.search', title: 'Search clippings', summary: 'Find a copied item.',
whenToUse: ['The user refers to something copied earlier.'],
whenNotToUse: ['The user wants the current clipboard.'],
inputSchema: { type: 'object', additionalProperties: false, required: ['query'], properties: { query: { type: 'string' } } },
risk: 'read', handler: async ({ query }) => ctx.snip.search(query),
})
Legacy tools (73+)
KernelService.refreshLegacy({scope}) bridges the old tool surface without
touching any module:
- Enumerates visible schemas with
ctx.tools.schemas(scope)and fetches each definition withctx.tools.get(name, scope). - Skips
os_*(the kernel's own verbs) and adapts every other tool withfromTool()aslegacy.(riskinferred from name/description;legacyOptionsoverrides it). - Is idempotent: repeated refreshes keep the existing entry. An occupied
legacy.id is never overwritten, and an alias already owned by a descriptor is not stolen — descriptors always win, the legacy entry keeps itslegacy.namespace. - Silently does nothing when
ctx.toolsexposes noschemas/get(older hosts);config.legacyToolsstill works as an explicit fallback.
apply() does not enumerate eagerly. The first os_find or os_status calls
refreshLegacy({ scope: exec.agent }); a direct os_do on an unknown
legacy.* id does the same. Under gatewayOnly the bridge enumerates the
global view instead, because the agent's own tool view is intentionally
restricted to the six verbs. After that the gateway searches descriptors and
legacy tools together, so os_find returns top-k cards from both surfaces and
os_status reports { legacy: N, capabilities: M, total }.
Legacy payloads are normalized through the kernel's local ok() / err()
pair (the same os.result/v1 / OsError envelope as the contract): a returned
{ ok: true, ... } is unwrapped, { ok: false, error } becomes an OsError,
and raw values are wrapped. Unknown error codes are aliased to the nine
classes with details.legacyCode.
Boundary
- Kernel is thin. It has no business modules and no network. The only optional persistence is the idempotency journal above.
- Modules stay independent. A module may register a descriptor when the
kernel is present (
ctx.get('kernel')?.register) and must still work when it is absent. The kernel never imports a module. - Zero runtime dependencies, plain ESM.
lib/state.jsuses only Node built-ins (node:fs,node:path) and only whenconfig.stateFileis set;lib/envelope.jsmirrors@perrylink/dsh-os-contract'sok()/err()helpers instead of importing them, so the package stays standalone. Its success schema remains the publishedos.result/v1. - No publish in this package's scripts; release is owned by the monorepo.
Tests
node --test
Covers descriptors, registry CRUD/conflict/search/lazy invoke, fromTool,
the six verbs, legacy bridge and envelopes, the permission bridge against the
real dsh-allow service (cap:, observe refresh, one-shot grant, args
binding), idempotency across a restart, gatewayOnly and the shipped preset.