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.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Local `ok()` / `err()` envelopes for the OsResult and OsError protocols.
3
+ *
4
+ * Mirrors dsh-os-contract's result/error helpers on purpose: the
5
+ * kernel stays zero-dependency and keeps its published `os.result/v1` schema.
6
+ * Unknown or legacy error codes are aliased to the nine classes, with the
7
+ * original kept in `details.legacyCode`.
8
+ */
9
+ import { fingerprint } from './registry.js'
10
+
11
+ export const RESULT_SCHEMA = 'os.result/v1'
12
+ export const VERSION = '0.4.0'
13
+ export const ERROR_CLASSES = Object.freeze([
14
+ 'E_INVALID_ARGUMENT', 'E_DENIED', 'E_NOT_FOUND', 'E_CONFLICT', 'E_UNAVAILABLE',
15
+ 'E_LIMIT', 'E_STATE', 'E_TIMEOUT', 'E_INTERNAL',
16
+ ])
17
+
18
+ const CLASSES = new Set(ERROR_CLASSES)
19
+ const RETRYABLE = Object.freeze({ E_UNAVAILABLE: true, E_LIMIT: true, E_TIMEOUT: true })
20
+ const ALIASES = Object.freeze({
21
+ E_INPUT: ['E_INVALID_ARGUMENT', 'invalid_argument'],
22
+ E_STATE_INVALID: ['E_STATE', 'version_mismatch'],
23
+ state_invalid: ['E_STATE', 'version_mismatch'],
24
+ grant_required: ['E_DENIED', 'grant_required'],
25
+ E_UNAUTHORIZED: ['E_DENIED', 'unauthenticated'],
26
+ E_RATE_LIMITED: ['E_LIMIT', 'rate_limited'],
27
+ E_RATE_LIMIT: ['E_LIMIT', 'rate_limited'],
28
+ E_QUOTA_EXCEEDED: ['E_LIMIT', 'quota_exceeded'],
29
+ E_REQUEST_EXPIRED: ['E_TIMEOUT', 'approval_expired'],
30
+ aborted: ['E_TIMEOUT', 'cancelled'],
31
+ ABORT_ERR: ['E_TIMEOUT', 'cancelled'],
32
+ action_failed: ['E_INTERNAL', 'tool_failed'],
33
+ })
34
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
35
+ const slim = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text
36
+ const uid = kind => `${kind}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
37
+
38
+ /** Map any code to `{ code, subcode, legacyCode }`; never throws. */
39
+ export function resolveCode(code, subcode) {
40
+ if (CLASSES.has(code)) return { code, subcode: subcode ?? null, legacyCode: null }
41
+ if (typeof code !== 'string' || code === '') return { code: 'E_INTERNAL', subcode: subcode ?? 'tool_failed', legacyCode: null }
42
+ if (ALIASES[code]) return { code: ALIASES[code][0], subcode: subcode ?? ALIASES[code][1], legacyCode: code }
43
+ if (code.startsWith('invalid_')) return { code: 'E_INVALID_ARGUMENT', subcode: subcode ?? code, legacyCode: code }
44
+ if (code.startsWith('E_')) return { code: 'E_INVALID_ARGUMENT', subcode: subcode ?? 'invalid_argument', legacyCode: code }
45
+ if (code.endsWith('_not_found')) return { code: 'E_NOT_FOUND', subcode: subcode ?? code, legacyCode: code }
46
+ if (code.endsWith('_exists')) return { code: 'E_CONFLICT', subcode: subcode ?? 'already_exists', legacyCode: code }
47
+ if (code.endsWith('_timeout') || code === 'timeout') return { code: 'E_TIMEOUT', subcode: subcode ?? 'timeout', legacyCode: code }
48
+ if (code.endsWith('_failed')) return { code: 'E_INTERNAL', subcode: subcode ?? 'tool_failed', legacyCode: code }
49
+ return { code: 'E_INTERNAL', subcode: subcode ?? 'tool_failed', legacyCode: code }
50
+ }
51
+
52
+ /** Build the canonical failure envelope `{ ok: false, error }`. */
53
+ export function err(code, message, options = {}) {
54
+ const resolved = resolveCode(code, options.subcode)
55
+ const legacyCode = options.legacyCode ?? resolved.legacyCode
56
+ const details = { ...(isObject(options.details) ? options.details : {}) }
57
+ if (legacyCode !== null && details.legacyCode === undefined) details.legacyCode = legacyCode
58
+ const retryable = options.retryable ?? RETRYABLE[resolved.code] === true
59
+ const text = typeof message === 'string' && message.trim() !== '' ? message : `${resolved.code}: the call failed.`
60
+ return {
61
+ ok: false,
62
+ error: {
63
+ code: resolved.code,
64
+ subcode: resolved.subcode,
65
+ message: slim(text, 240),
66
+ retryable,
67
+ retryAfterMs: retryable ? (options.retryAfterMs ?? 0) : null,
68
+ remediation: options.remediation ?? 'Report the requestId to the maintainer.',
69
+ nextTools: (Array.isArray(options.nextTools) ? options.nextTools : [])
70
+ .filter(item => isObject(item) && typeof item.tool === 'string' && item.tool !== '').slice(0, 3),
71
+ requestId: options.requestId ?? uid('req'),
72
+ auditId: options.auditId ?? null,
73
+ details,
74
+ cause: null,
75
+ },
76
+ }
77
+ }
78
+
79
+ /** Build a bounded `os.result/v1` success envelope. */
80
+ export function ok(tool, value, options = {}) {
81
+ const items = Array.isArray(value) ? value.slice(0, 20) : Array.isArray(value?.items) ? value.items.slice(0, 20) : []
82
+ const total = Array.isArray(value) ? value.length : Number.isInteger(value?.total) ? value.total : items.length
83
+ const data = value === undefined || Array.isArray(value) ? undefined : value
84
+ const summary = slim(options.summary ?? (typeof value?.summary === 'string' ? value.summary
85
+ : Array.isArray(value) ? `Returned ${items.length} item(s) from ${tool}.` : `${tool} completed.`), 200)
86
+ const page = {
87
+ limit: items.length || 0, returned: items.length, total, totalKnown: true,
88
+ hasMore: total > items.length, nextCursor: null, sort: 'none',
89
+ }
90
+ const payload = { items, page, data }
91
+ const result = {
92
+ schema: RESULT_SCHEMA,
93
+ ok: true,
94
+ tool,
95
+ requestId: options.requestId ?? uid('req'),
96
+ auditId: null,
97
+ summary,
98
+ items,
99
+ page,
100
+ handles: Array.isArray(value?.handles) ? value.handles.slice(0, 5) : [],
101
+ truncated: false,
102
+ warnings: Array.isArray(value?.warnings) ? value.warnings.slice(0, 20) : [],
103
+ cost: {
104
+ tokens: Math.ceil(JSON.stringify(payload).length / 4),
105
+ tokensEstimated: true,
106
+ latencyMs: options.latencyMs ?? 0,
107
+ money: { usd: 0, estimated: false },
108
+ },
109
+ next: Array.isArray(options.next) ? options.next.slice(0, 3) : Array.isArray(value?.next) ? value.next.slice(0, 3) : [],
110
+ provenance: {
111
+ source: 'kernel', sourceVersion: VERSION, observedAt: Date.now(), freshness: 'live',
112
+ hash: `fnv1a:${fingerprint(payload)}`, hashScope: 'items+page+data',
113
+ },
114
+ }
115
+ if (data !== undefined) result.data = data
116
+ if (isObject(value?.job)) result.job = value.job
117
+ return result
118
+ }
119
+
120
+ /**
121
+ * Read a legacy tool outcome. Returns `null` for a plain value, otherwise
122
+ * `{ ok: true, value }` with the `ok` flag stripped, or `{ ok: false, error }`.
123
+ * @param {unknown} value
124
+ * @returns {{ok: true, value: any}|{ok: false, error: any}|null}
125
+ */
126
+ export function legacyOutcome(value) {
127
+ if (!isObject(value) || typeof value.ok !== 'boolean') return null
128
+ if (value.ok === false) {
129
+ const error = isObject(value.error) ? value.error
130
+ : typeof value.error === 'string' ? { message: value.error }
131
+ : value
132
+ return { ok: false, error }
133
+ }
134
+ const { ok: _ok, ...rest } = value
135
+ const keys = Object.keys(rest)
136
+ return { ok: true, value: keys.length === 1 && keys[0] === 'data' ? rest.data : rest }
137
+ }
138
+
139
+ export default { ok, err, legacyOutcome, resolveCode, RESULT_SCHEMA, VERSION, ERROR_CLASSES }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Legacy ToolDefinition -> capability descriptor adapter.
3
+ * Migration only: the module keeps working unchanged; the registry can list it.
4
+ */
5
+ import { normalizeDescriptor } from './descriptor.js'
6
+
7
+ const EXECUTE = ['exec', 'execute', 'invoke', 'run', 'spawn', 'shell', 'fire', 'apply', 'move', 'resize', 'undo', 'capture', 'start', 'stop', 'trigger', 'kill']
8
+ const WRITE = ['write', 'set', 'add', 'remove', 'delete', 'forget', 'clear', 'issue', 'revoke', 'send', 'raise', 'ack', 'escalate', 'register', 'import', 'restore', 'snapshot', 'budget', 'remember', 'open', 'close', 'create', 'update', 'save', 'put', 'notify', 'layout']
9
+
10
+ const firstLine = text => String(text ?? '').trim().split(/\r?\n/)[0].trim()
11
+ const clip = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text
12
+ const titleize = name => name.replace(/[_.]+/g, ' ').replace(/^\w/, char => char.toUpperCase())
13
+
14
+ /** Infer read/write/execute from the tool name first, then its description. */
15
+ export function inferRisk(tool) {
16
+ const name = String(tool?.name ?? '').toLowerCase()
17
+ const words = `${name} ${String(tool?.description ?? '').toLowerCase()}`
18
+ const tokens = name.split(/[^a-z0-9]+/).filter(Boolean)
19
+ const hit = list => list.some(word => tokens.includes(word) || new RegExp(`\\b${word}\\b`).test(words))
20
+ if (hit(EXECUTE)) return 'execute'
21
+ if (hit(WRITE)) return 'write'
22
+ return 'read'
23
+ }
24
+
25
+ /**
26
+ * Adapt a host ToolDefinition into a normalized descriptor.
27
+ * The id is always `legacy.<tool.name>`; `handler` forwards to `tool.execute`.
28
+ * @param {any} tool
29
+ * @param {any} [options] risk/permissions/cost/tags overrides
30
+ * @returns {any}
31
+ */
32
+ export function fromTool(tool, options = {}) {
33
+ if (!tool || typeof tool.name !== 'string' || tool.name === '') {
34
+ throw Object.assign(new TypeError('tool.name must be a non-empty string'), { code: 'E_INVALID_ARGUMENT' })
35
+ }
36
+ if (typeof tool.execute !== 'function') {
37
+ throw Object.assign(new TypeError(`tool ${tool.name} must have execute()`), { code: 'E_INVALID_ARGUMENT' })
38
+ }
39
+ const risk = options.risk ?? inferRisk(tool)
40
+ const summary = clip(firstLine(tool.description) || `Legacy tool ${tool.name}.`, 120)
41
+ const descriptor = {
42
+ id: `legacy.${tool.name}`,
43
+ title: clip(options.title ?? titleize(tool.name), 40),
44
+ summary,
45
+ whenToUse: options.whenToUse ?? [`Use when the task needs the legacy ${tool.name} tool.`],
46
+ whenNotToUse: options.whenNotToUse ?? ['Prefer a registered capability that covers the same intent.'],
47
+ inputSchema: tool.parameters ?? { type: 'object', additionalProperties: true },
48
+ outputSchema: tool.output?.schema ?? { type: 'object', additionalProperties: true },
49
+ risk: Array.isArray(risk) ? risk : [risk],
50
+ permissions: options.permissions ?? [],
51
+ cost: { tokens: 0, latencyMs: 0, moneyUsd: 0, ...(options.cost ?? {}) },
52
+ idempotency: options.idempotency ?? ((Array.isArray(risk) ? risk : [risk]).includes('read') ? 'pure' : 'non-idempotent'),
53
+ examples: options.examples ?? [],
54
+ returns: options.returns ?? `${summary} Returns the legacy tool payload.`,
55
+ errors: options.errors ?? [],
56
+ version: options.version ?? '0.0.0',
57
+ tags: [...new Set(['legacy', ...(options.tags ?? [])])],
58
+ handler: async (args, _ctx, exec) => tool.execute(args, exec ?? {}),
59
+ ui: null,
60
+ aliases: options.aliases ?? [tool.name],
61
+ deprecated: options.deprecated ?? null,
62
+ audience: options.audience ?? ['agent', 'human', 'cli'],
63
+ legacy: true,
64
+ }
65
+ return normalizeDescriptor(descriptor)
66
+ }
67
+
68
+ export default fromTool