@tinycloud/operations 0.4.0-beta.9 → 0.4.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../../../node_modules/ms/index.js","../../sdk-core/src/manifest.ts","../../sdk-core/src/capabilities.ts","../src/authority.ts","../src/state.ts","../src/artifacts.ts","../src/secrets.ts","../src/operations/auth.ts","../src/operations/exploration.ts","../src/operations/secrets-get.ts","../src/operations/sql.ts","../src/delegation-binding.ts","../src/operations/status.ts","../src/registry.ts","../src/profile.ts","../src/runtime.ts","../src/invoke.ts","../../sdk-core/src/policy/errors.ts","../../sdk-core/src/policy/jcs.ts","../src/safe-values.ts","../src/redaction.ts","../src/cli-runtime.ts"],"sourcesContent":["export const OPERATION_ERROR_CODES = [\n \"INPUT_INVALID\",\n \"OPERATION_NOT_FOUND\",\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"PROFILE_NOT_FOUND\",\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"AUTH_REQUIRED\",\n \"PERMISSION_DENIED\",\n \"SESSION_NOT_FOUND\",\n \"PERMISSION_HINT_INVALID\",\n \"DELEGATION_ARTIFACT_INVALID\",\n \"DELEGATION_EXPIRED\",\n \"DELEGATION_AUDIENCE_MISMATCH\",\n \"DELEGATION_HOST_MISMATCH\",\n \"DELEGATION_REJECTED\",\n \"ENCRYPTION_NETWORK_UNRESOLVED\",\n \"NODE_UNREACHABLE\",\n \"NODE_ERROR\",\n \"KV_NOT_FOUND\",\n \"KV_PRECONDITION_FAILED\",\n \"KV_CONFLICT\",\n \"KV_RESPONSE_TOO_LARGE\",\n \"SQL_QUERY_INVALID\",\n \"SQL_EXECUTION_FAILED\",\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"SQL_VALUE_UNSAFE\",\n \"SECRET_READ_FAILED\",\n \"SECRET_DECRYPT_FAILED\",\n \"OUTPUT_INVALID\",\n \"INTERNAL_ERROR\",\n] as const;\n\nexport type OperationErrorCode = (typeof OPERATION_ERROR_CODES)[number];\n\nexport interface OperationError {\n readonly code: OperationErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport function operationError(\n code: OperationErrorCode,\n message: string,\n options: Readonly<{\n retryable?: boolean;\n details?: Readonly<Record<string, unknown>>;\n }> = {},\n): OperationError {\n return {\n code,\n message,\n retryable: options.retryable ?? false,\n ...(options.details === undefined ? {} : { details: options.details }),\n };\n}\n\n/**\n * Internal operations and profile resolution use this for expected failures.\n * Generic exceptions are never exposed at the projection boundary.\n */\nexport class OperationInvocationError extends Error {\n public readonly operationError: OperationError;\n\n constructor(operationError: OperationError) {\n super(operationError.message);\n this.name = \"OperationInvocationError\";\n this.operationError = operationError;\n }\n}\n\nexport function isOperationErrorCode(value: unknown): value is OperationErrorCode {\n return typeof value === \"string\" && OPERATION_ERROR_CODES.includes(value as OperationErrorCode);\n}\n\nexport function internalOperationError(): OperationError {\n return operationError(\n \"INTERNAL_ERROR\",\n \"The operation could not be completed.\",\n );\n}\n\nexport function sanitizeThrownOperationError(error: unknown): OperationError {\n if (error instanceof OperationInvocationError) {\n return sanitizeOperationError(error.operationError);\n }\n\n return internalOperationError();\n}\n\nexport function sanitizeOperationError(error: unknown): OperationError {\n if (\n typeof error !== \"object\" ||\n error === null ||\n !isOperationErrorCode((error as { code?: unknown }).code) ||\n typeof (error as { message?: unknown }).message !== \"string\" ||\n typeof (error as { retryable?: unknown }).retryable !== \"boolean\"\n ) {\n return internalOperationError();\n }\n\n const candidate = error as OperationError;\n return operationError(candidate.code, candidate.message, {\n retryable: candidate.retryable,\n ...(candidate.details === undefined ? {} : { details: candidate.details }),\n });\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/**\n * TinyCloud App Manifest\n *\n * A declarative description of an app's identity and the capabilities it\n * needs. The manifest drives the SIWE recap at sign-in time, enabling a\n * single wallet prompt that covers the app's own permissions plus any\n * pre-declared delegations.\n *\n * The SDK does NOT fetch external manifests. Apps compose their own manifest\n * (optionally including backend or agent addenda) before handing it to the\n * SDK.\n *\n * Canonical spec: `.claude/specs/manifest.md`.\n *\n * @packageDocumentation\n */\n\nimport ms from \"ms\";\nimport { ACCOUNT_MANIFEST_PERMISSIONS } from \"@tinycloud/bootstrap\";\nimport { resolveSecretPath, SECRET_NAME_RE } from \"@tinycloud/sdk-services\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A single permission entry inside a manifest. This is the shape apps write\n * in their `manifest.json` and the shape we compare against when performing\n * the capability-subset derivability check in the delegation flow.\n *\n * `service` uses the long form (e.g. `\"tinycloud.kv\"`, `\"tinycloud.sql\"`).\n * `\"tinycloud.vault\"` is an SDK-only shorthand that expands to the KV\n * resources the vault service uses; it is never encoded as a recap service.\n */\nexport interface PermissionEntry {\n /** Service namespace, e.g. \"tinycloud.kv\", \"tinycloud.sql\", \"tinycloud.duckdb\", \"tinycloud.capabilities\". */\n service: string;\n /** Space name or full space URI. Defaults to \"applications\" inside manifests. */\n space?: string;\n /**\n * Service-specific path.\n * - tinycloud.kv: hierarchical prefix. \"/\" = all, \"foo/\" = prefix match, \"foo\" = exact key\n * - tinycloud.sql: database name/file (e.g. \"data.sqlite\") or \"/\" for all\n * - tinycloud.duckdb: database name/file\n * - tinycloud.capabilities: capability key URI or \"/\" for all\n */\n path: string;\n /**\n * Short action names (e.g. \"get\", \"put\", \"read\", \"schema\"). The SDK expands\n * these to full URNs (e.g. `tinycloud.kv/get`) during resolution.\n * Already-expanded URNs are passed through unchanged.\n */\n actions: string[];\n /** Exact ReCap caveat branches when this authority came from a signed ReCap. */\n caveats?: Record<string, unknown>[];\n /** When true, the manifest prefix is NOT prepended to `path`. Default false. */\n skipPrefix?: boolean;\n /** Per-entry expiry override, ms-format. */\n expiry?: string;\n /** User/agent-facing context for why this permission is requested. */\n description?: string;\n}\n\nexport type ManifestSecretActions =\n | true\n | string\n | string[]\n | {\n /** Actual vault secret name. Defaults to the manifest object key. */\n name?: string;\n /** Optional scoped secret namespace. Omit for global secrets. */\n scope?: string;\n actions?: string | string[];\n expiry?: string;\n description?: string;\n };\n\n/**\n * The valid values for `Manifest.defaults`.\n *\n * - `false` → no auto-included permissions\n * - `true` → standard tier (KV + SQL read/write + capabilities:read)\n * - `\"admin\"` → standard + SQL schema\n * - `\"all\"` → everything the SDK supports (including DuckDB)\n *\n * Unknown string values silently fall back to `true`. Values are normalized\n * (lowercase + trim) before matching.\n */\nexport type ManifestDefaults = boolean | \"admin\" | \"all\";\n\n/**\n * Agent-readable app knowledge bundle pointer.\n *\n * - `true` means the default root: `knowledge/index.md`\n * - string values must point at a markdown root under `knowledge/`\n */\nexport type ManifestKnowledge = true | string;\n\n/** Default root used when `manifest.knowledge === true`. */\nexport const DEFAULT_KNOWLEDGE_ROOT = \"knowledge/index.md\";\n\n/**\n * The raw manifest shape an app declares. See `.claude/specs/manifest.md`.\n */\nexport interface Manifest {\n /** Schema version. Optional, defaults to 1. */\n manifest_version?: 1;\n /** Application identifier / namespace prefix. Required. */\n app_id: string;\n /** Display name. Required. */\n name: string;\n /** Description of what the app or delegate does. Optional. */\n description?: string;\n /** DID of this manifest's delegate target. Optional. Required only for delegation materialization. */\n did?: string;\n /** URL to app icon. Optional. */\n icon?: string;\n /** App version string. Optional. */\n appVersion?: string;\n /** Default expiry for permissions. ms-format (\"30d\", \"2h\", \"1y\"). Default \"30d\". */\n expiry?: string;\n /** Space name or full space URI. Optional, defaults to \"applications\". */\n space?: string;\n /**\n * Path prefix auto-prepended to permission paths. Optional, defaults to\n * `app_id`. Set to `\"\"` to disable entirely. Individual permissions can opt\n * out with `skipPrefix: true`.\n */\n prefix?: string;\n /**\n * Default permission set to auto-include. Optional, defaults to `true`.\n * See {@link ManifestDefaults}.\n */\n defaults?: ManifestDefaults | string;\n /** Whether to include the public-space companion delegation. Default `true`. */\n includePublicSpace?: boolean;\n /** Agent-readable knowledge bundle root. `true` means `knowledge/index.md`. */\n knowledge?: ManifestKnowledge;\n /**\n * Additional permissions beyond the defaults. Use for cross-space access,\n * DuckDB (opt-in), or `skipPrefix: true` entries.\n */\n permissions?: PermissionEntry[];\n /**\n * Secret name shorthand. Entries resolve to encrypted vault KV resources in\n * the `secrets` space.\n */\n secrets?: Record<string, ManifestSecretActions>;\n}\n\n/**\n * A resolved permission entry with fully-expanded paths and action URNs.\n * This is the shape the delegation flow compares against parsed recap\n * capabilities, and the shape the session-key delegation path actually uses.\n */\nexport interface ResourceCapability {\n /** Long-form service, e.g. \"tinycloud.kv\". */\n service: string;\n /** Space name or URI. Short names are resolved to full SpaceIds at sign-in time. */\n space: string;\n /** Path with the manifest prefix applied (or skipped per `skipPrefix`). */\n path: string;\n /** Full-URN actions, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: string[];\n /** Per-entry expiry override in milliseconds. */\n expiryMs?: number;\n /** User/agent-facing context copied from the source permission entry. */\n description?: string;\n}\n\n/**\n * A resolved delegation entry with fully-expanded permissions.\n */\nexport interface ResolvedDelegate {\n /** DID of the delegate. */\n did: string;\n /** Informational display name. Optional. */\n name?: string;\n /** Expiry in milliseconds (per-delegation > manifest default > 30 days). */\n expiryMs: number;\n /** Fully resolved permissions. */\n permissions: ResourceCapability[];\n}\n\n/**\n * The output of {@link resolveManifest}: a fully-expanded capability set\n * ready to drive the SIWE recap.\n */\nexport interface ResolvedCapabilities {\n /** Application identifier copied from manifest.app_id. */\n app_id: string;\n /** Delegate DID copied from manifest.did, when present. */\n did?: string;\n /** Effective default space for this manifest. */\n space: string;\n /** All session-key resources with paths fully resolved (prefix applied). */\n resources: ResourceCapability[];\n /** Default expiry for the session, in milliseconds. */\n expiryMs: number;\n /** Whether to include the public-space companion. */\n includePublicSpace: boolean;\n /** Delegate targets derived from manifests that declare `did`. */\n additionalDelegates: ResolvedDelegate[];\n}\n\nexport interface ManifestRegistryRecord {\n /** KV key inside the account space. */\n key: string;\n /** App id this record describes. */\n app_id: string;\n /** Latest manifest payloads composed for this app id. */\n manifests: Manifest[];\n}\n\nexport interface ComposeManifestOptions {\n /** Include implicit account-space registry permissions. Default true. */\n includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface ComposedManifestRequest {\n /** Validated manifests that were composed. */\n manifests: Manifest[];\n /** Full permission union requested from the user in one SIWE. */\n resources: ResourceCapability[];\n /** Delegations that can be materialized after sign-in. */\n delegationTargets: ResolvedDelegate[];\n /** Account-space registry records to write after successful sign-in. */\n registryRecords: ManifestRegistryRecord[];\n /** Effective session expiry, using the longest composed manifest expiry. */\n expiryMs: number;\n /** Whether to include the public-space companion behavior. */\n includePublicSpace: boolean;\n}\n\n/**\n * Thrown when the manifest fails validation (missing id/name, bad expiry,\n * empty actions on a permission, etc).\n */\nexport class ManifestValidationError extends Error {\n constructor(message: string) {\n super(`Manifest validation failed: ${message}`);\n this.name = \"ManifestValidationError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default expiry when neither the manifest, delegation, nor permission\n * specifies one. APP tier — see `expiry.ts`. Spec: 30 days.\n *\n * Kept as an ms-format string because the manifest schema stores expiry\n * as a string and the parser is shared between this default and\n * caller-provided values; converting `EXPIRY.APP_MS` back to a string\n * here would duplicate that same `30d` literal in another form.\n */\nexport const DEFAULT_EXPIRY = \"30d\";\n\n/**\n * Default `defaults` value when the manifest omits it. Spec: standard tier.\n */\nexport const DEFAULT_DEFAULTS: ManifestDefaults = true;\n\n/** Default manifest schema version. */\nexport const DEFAULT_MANIFEST_VERSION = 1;\n\n/** Default space for manifest-declared app data. */\nexport const DEFAULT_MANIFEST_SPACE = \"applications\";\n\n/** Account-space name used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_SPACE = \"account\";\n\n/** Account-space KV prefix used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_PATH = \"applications/\";\n\nexport const SECRETS_SPACE = \"secrets\";\n\n/** SDK-only permission service for encrypted vault resources. */\nexport const VAULT_PERMISSION_SERVICE = \"tinycloud.vault\";\n\ntype VaultKVBase = \"vault\";\n\ninterface VaultActionExpansion {\n bases: readonly VaultKVBase[];\n action: string;\n}\n\n/**\n * Known services and their short-form (recap URI) names. The TinyCloud\n * node encodes the recap resource URI with the short service name, while\n * action URNs and manifest entries use the long `tinycloud.<short>` form.\n * This table is the canonical bridge between the two.\n */\nexport const SERVICE_SHORT_TO_LONG: Readonly<Record<string, string>> =\n Object.freeze({\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n capabilities: \"tinycloud.capabilities\",\n hooks: \"tinycloud.hooks\",\n encryption: \"tinycloud.encryption\",\n delegation: \"tinycloud.delegation\",\n });\n\n/**\n * Manifest service identifier for TinyCloud encryption network grants.\n *\n * Encryption permissions live on a network id URN\n * (`urn:tinycloud:encryption:<ownerDid>:<network>`), not on a space.\n * The `path` field is the literal networkId; `actions` are\n * `[\"decrypt\"]` (expanded to `[\"tinycloud.encryption/decrypt\"]`).\n *\n * Apps should omit `space` for encryption permissions. The SDK may emit\n * an internal `\"encryption\"` compatibility label after expansion so the\n * older `PermissionEntry`/`ResourceCapability` shape can still carry the\n * raw network URN through subset checks.\n */\nexport const ENCRYPTION_PERMISSION_SERVICE = \"tinycloud.encryption\";\n\n/** Synthetic space label used by encryption manifest entries. */\nexport const ENCRYPTION_MANIFEST_SPACE = \"encryption\";\n\n/**\n * Inverse of {@link SERVICE_SHORT_TO_LONG}.\n */\nexport const SERVICE_LONG_TO_SHORT: Readonly<Record<string, string>> =\n Object.freeze(\n Object.fromEntries(\n Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s]),\n ),\n );\n\n/**\n * Default permission entries for the `true` / standard tier.\n *\n * `tinycloud.capabilities/read` is added separately for every requested\n * space, without the app path prefix. That keeps capability introspection\n * space-scoped instead of app-data scoped.\n */\nconst DEFAULT_STANDARD_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n/**\n * Default permission entries for the `\"admin\"` tier: standard + sql/schema.\n */\nconst DEFAULT_ADMIN_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n];\n\n/**\n * Default permission entries for the `\"all\"` tier: admin + DuckDB.\n *\n * DuckDB is opt-in and only appears in this tier or in explicit manifest\n * `permissions` entries.\n */\nconst DEFAULT_ALL_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n {\n service: \"tinycloud.duckdb\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ms-format duration string (e.g. \"30d\", \"2h\", \"1y\") into\n * milliseconds.\n *\n * @throws {ManifestValidationError} on empty string, non-string input, or\n * any input `ms()` cannot parse.\n */\nexport function parseExpiry(duration: string): number {\n if (typeof duration !== \"string\" || duration.length === 0) {\n throw new ManifestValidationError(\n `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`,\n );\n }\n // `ms` returns `undefined` for unparseable input and can return a number\n // or a string depending on the call signature; cast explicitly.\n const parsed = (ms as unknown as (v: string) => number | undefined)(duration);\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new ManifestValidationError(\n `invalid expiry duration: ${JSON.stringify(duration)}`,\n );\n }\n return parsed;\n}\n\n/**\n * Expand a list of action short names (or already-expanded URNs) into full\n * ability URNs of the form `<service>/<action>`.\n *\n * Examples:\n * `expandActionShortNames(\"tinycloud.kv\", [\"get\", \"put\"])`\n * → `[\"tinycloud.kv/get\", \"tinycloud.kv/put\"]`\n * `expandActionShortNames(\"tinycloud.kv\", [\"tinycloud.kv/get\"])`\n * → `[\"tinycloud.kv/get\"]` (passed through unchanged)\n */\nexport function expandActionShortNames(\n service: string,\n actions: readonly string[],\n): string[] {\n return actions.map((a) => {\n if (a.includes(\"/\")) {\n // Already a full URN — pass through.\n return a;\n }\n return `${service}/${a}`;\n });\n}\n\n/**\n * Expand SDK virtual permission services into concrete recap-capable services.\n *\n * Today this handles `\"tinycloud.vault\"`, which is backed by inline\n * network-encrypted KV records:\n * - read/get: `vault/<path>` with `tinycloud.kv/get`\n * - write/put: `vault/<path>` with `tinycloud.kv/put`\n * - delete/del: `vault/<path>` with `tinycloud.kv/del`\n * - list: `vault/<path>` with `tinycloud.kv/list`\n * - head: `vault/<path>` with `tinycloud.kv/get`\n * - metadata: `vault/<path>` with `tinycloud.kv/metadata`\n */\nexport function expandPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {\n return expandEncryptionPermissionEntry(entry);\n }\n if (entry.service !== VAULT_PERMISSION_SERVICE) {\n return [\n {\n ...entry,\n actions: expandActionShortNames(entry.service, entry.actions),\n },\n ];\n }\n\n return expandVaultPermissionEntry(entry);\n}\n\n/**\n * Expand a `tinycloud.encryption` manifest entry.\n *\n * - `path` MUST be a networkId URN (`urn:tinycloud:encryption:...`).\n * The manifest prefix is always skipped — network ids are top-level\n * owner-scoped resources, not space-scoped paths.\n * - `actions` must be `decrypt`, `network.create`, or `network.revoke`\n * (or their already-expanded `tinycloud.encryption/*` forms).\n *\n * The returned entry uses an internal `space = \"encryption\"` compatibility\n * label so old manifest grouping code does not collapse it into the app's\n * data space, and `skipPrefix` is forced to `true` so the prefix application\n * step is a no-op.\n */\nfunction expandEncryptionPermissionEntry(\n entry: PermissionEntry,\n): PermissionEntry[] {\n if (\n typeof entry.path !== \"string\" ||\n !entry.path.startsWith(\"urn:tinycloud:encryption:\")\n ) {\n throw new ManifestValidationError(\n `tinycloud.encryption entries require path to be a networkId URN ` +\n `(got ${JSON.stringify(entry.path)})`,\n );\n }\n const normalizedActions: string[] = [];\n for (const action of entry.actions) {\n if (action === \"decrypt\" || action === \"tinycloud.encryption/decrypt\") {\n normalizedActions.push(\"tinycloud.encryption/decrypt\");\n continue;\n }\n if (\n action === \"network.create\" ||\n action === \"tinycloud.encryption/network.create\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.create\");\n continue;\n }\n if (\n action === \"network.revoke\" ||\n action === \"tinycloud.encryption/network.revoke\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.revoke\");\n continue;\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n // Dedupe while preserving order\n const dedupedActions: string[] = [];\n const seen = new Set<string>();\n for (const a of normalizedActions) {\n if (!seen.has(a)) {\n dedupedActions.push(a);\n seen.add(a);\n }\n }\n // Encryption resources are network-scoped, not space-scoped. We\n // always emit the synthetic \"encryption\" space label so manifest\n // grouping can deal with it uniformly without collapsing the\n // networkId URN into an app data space.\n return [\n {\n service: ENCRYPTION_PERMISSION_SERVICE,\n space: ENCRYPTION_MANIFEST_SPACE,\n path: entry.path,\n actions: dedupedActions,\n skipPrefix: true,\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n },\n ];\n}\n\n/**\n * Expand a list of permission entries using {@link expandPermissionEntry}.\n */\nexport function expandPermissionEntries(\n entries: readonly PermissionEntry[],\n): PermissionEntry[] {\n return entries.flatMap(expandPermissionEntry);\n}\n\n/**\n * Apply the manifest prefix to a permission path per the spec rules.\n *\n * - `skipPrefix: true` → path is returned as-is\n * - `prefix === \"\"` → path is returned as-is\n * - path starts with \"/\" → `prefix + path` (e.g. \"com.listen.app\" + \"/\" → \"com.listen.app/\")\n * - otherwise → `prefix + \"/\" + path` (e.g. \"com.listen.app\" + \"data.sqlite\" → \"com.listen.app/data.sqlite\")\n */\nexport function applyPrefix(\n prefix: string,\n path: string,\n skipPrefix: boolean,\n): string {\n if (skipPrefix) {\n return path;\n }\n if (prefix === \"\") {\n return path;\n }\n if (path.startsWith(\"/\")) {\n return `${prefix}${path}`;\n }\n return `${prefix}/${path}`;\n}\n\n/**\n * Fetch and parse a manifest from a URL (browser) or file path (node).\n * The runtime decides the fetch strategy via `globalThis.fetch`; this is\n * platform-agnostic. Callers that want custom loading should JSON.parse a\n * Manifest themselves and skip this helper.\n *\n * @throws if the fetch fails, the JSON is invalid, or the manifest fails\n * validation.\n */\nexport async function loadManifest(url: string): Promise<Manifest> {\n const fetchFn: typeof fetch | undefined = (\n globalThis as { fetch?: typeof fetch }\n ).fetch;\n if (typeof fetchFn !== \"function\") {\n throw new ManifestValidationError(\n \"loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch\",\n );\n }\n const res = await fetchFn(url);\n if (!res.ok) {\n throw new ManifestValidationError(\n `failed to fetch manifest from ${url}: HTTP ${res.status}`,\n );\n }\n const json = (await res.json()) as unknown;\n return validateManifest(json);\n}\n\n/**\n * Validate a manifest-shaped object and return it strongly-typed.\n * Throws {@link ManifestValidationError} on any hard failure.\n */\nexport function validateManifest(input: unknown): Manifest {\n if (input === null || typeof input !== \"object\") {\n throw new ManifestValidationError(\"manifest must be an object\");\n }\n const m = input as Manifest;\n if (\n m.manifest_version !== undefined &&\n m.manifest_version !== DEFAULT_MANIFEST_VERSION\n ) {\n throw new ManifestValidationError(\n `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`,\n );\n }\n if (typeof m.app_id !== \"string\" || m.app_id.length === 0) {\n throw new ManifestValidationError(\n \"manifest.app_id is required and must be a non-empty string\",\n );\n }\n if (typeof m.name !== \"string\" || m.name.length === 0) {\n throw new ManifestValidationError(\n \"manifest.name is required and must be a non-empty string\",\n );\n }\n if (\n m.did !== undefined &&\n (typeof m.did !== \"string\" || m.did.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.did must be a non-empty DID string\",\n );\n }\n if (\n m.space !== undefined &&\n (typeof m.space !== \"string\" || m.space.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.space must be a non-empty string\",\n );\n }\n if (m.expiry !== undefined) {\n // Will throw with a clear error if invalid.\n parseExpiry(m.expiry);\n }\n if (m.knowledge !== undefined) {\n resolveManifestKnowledgeRoot(m.knowledge);\n }\n if (m.permissions !== undefined) {\n if (!Array.isArray(m.permissions)) {\n throw new ManifestValidationError(\n \"manifest.permissions must be an array\",\n );\n }\n m.permissions.forEach((p, i) =>\n validatePermissionEntry(p, `permissions[${i}]`),\n );\n }\n if (m.secrets !== undefined) {\n validateManifestSecrets(m.secrets);\n }\n return m;\n}\n\n/**\n * Resolve a manifest knowledge pointer to its root markdown file.\n *\n * This is metadata only; app knowledge does not create capabilities.\n */\nexport function resolveManifestKnowledgeRoot(\n knowledge: Manifest[\"knowledge\"] | undefined,\n): string | undefined {\n if (knowledge === undefined) {\n return undefined;\n }\n if (knowledge === true) {\n return DEFAULT_KNOWLEDGE_ROOT;\n }\n if (typeof knowledge !== \"string\" || knowledge.length === 0) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n if (!/^knowledge\\/.+\\.md$/.test(knowledge)) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n return knowledge;\n}\n\nfunction validateManifestSecrets(secrets: unknown): void {\n if (secrets === null || typeof secrets !== \"object\" || Array.isArray(secrets)) {\n throw new ManifestValidationError(\"manifest.secrets must be an object\");\n }\n\n for (const [name, spec] of Object.entries(secrets)) {\n if (!SECRET_NAME_RE.test(name)) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`,\n );\n }\n try {\n resolveSecretPath(\n secretNameFromSpec(name, spec as ManifestSecretActions),\n { scope: secretScopeFromSpec(spec as ManifestSecretActions) },\n );\n } catch (error) {\n throw new ManifestValidationError(\n `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const actions = secretActionsFromSpec(name, spec as ManifestSecretActions);\n if (actions.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty`,\n );\n }\n for (const action of actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty strings`,\n );\n }\n }\n if (\n spec !== null &&\n typeof spec === \"object\" &&\n !Array.isArray(spec) &&\n (spec as { expiry?: unknown }).expiry !== undefined\n ) {\n parseExpiry((spec as { expiry: string }).expiry);\n }\n }\n}\n\nfunction validatePermissionEntry(p: unknown, path: string): void {\n if (p === null || typeof p !== \"object\") {\n throw new ManifestValidationError(`${path} must be an object`);\n }\n const entry = p as PermissionEntry;\n if (typeof entry.service !== \"string\" || entry.service.length === 0) {\n throw new ManifestValidationError(`${path}.service is required`);\n }\n if (\n entry.space !== undefined &&\n (typeof entry.space !== \"string\" || entry.space.length === 0)\n ) {\n throw new ManifestValidationError(\n `${path}.space must be a non-empty string`,\n );\n }\n if (typeof entry.path !== \"string\") {\n throw new ManifestValidationError(\n `${path}.path is required (use \"\" or \"/\" for root)`,\n );\n }\n if (!Array.isArray(entry.actions) || entry.actions.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must be a non-empty array`,\n );\n }\n for (const action of entry.actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must contain non-empty strings`,\n );\n }\n if (entry.service === VAULT_PERMISSION_SERVICE) {\n vaultActionExpansion(action);\n }\n }\n if (entry.caveats !== undefined &&\n (!Array.isArray(entry.caveats) || entry.caveats.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n ))\n ) {\n throw new ManifestValidationError(`${path}.caveats must be an array of objects`);\n }\n if (entry.expiry !== undefined) {\n parseExpiry(entry.expiry);\n }\n}\n\n/**\n * Normalize a `defaults` value: lowercase + trim, then match against known\n * tiers. Unknown string values silently fall back to `true` (standard).\n * Boolean values pass through.\n */\nexport function normalizeDefaults(\n value: Manifest[\"defaults\"] | undefined,\n): ManifestDefaults {\n if (value === undefined) {\n return DEFAULT_DEFAULTS;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value !== \"string\") {\n // Spec says unknown values silently fall back to `true`.\n return true;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"admin\" || normalized === \"all\") {\n return normalized;\n }\n // Anything else, including \"true\"/\"false\"/\"standard\"/garbage, falls back\n // to the standard tier per spec.\n return true;\n}\n\n/**\n * Return the default permission entries for the given tier. Entries are\n * deep-cloned so callers can mutate them without affecting the constants.\n */\nfunction defaultEntriesForTier(tier: ManifestDefaults): PermissionEntry[] {\n if (tier === false) {\n return [];\n }\n const source =\n tier === \"admin\"\n ? DEFAULT_ADMIN_ENTRIES\n : tier === \"all\"\n ? DEFAULT_ALL_ENTRIES\n : DEFAULT_STANDARD_ENTRIES;\n return source.map((e) => ({\n service: e.service,\n space: e.space,\n path: e.path,\n actions: [...e.actions],\n ...(e.skipPrefix !== undefined ? { skipPrefix: e.skipPrefix } : {}),\n }));\n}\n\n/**\n * Resolve a raw manifest into a {@link ResolvedCapabilities} object: expand\n * shortform actions, apply the prefix, merge defaults, and compute effective\n * expiries. Pure function — does no I/O.\n *\n * Resolution semantics (spec):\n * - `prefix` defaults to `app_id`; set to `\"\"` to disable prefix application entirely.\n * - `space` defaults to `applications`; per-permission `space` overrides it.\n * - `defaults` defaults to `true` (standard tier); unknown string values fall back to `true`.\n * - Per-entry expiry overrides per-delegation overrides manifest > `DEFAULT_EXPIRY`.\n * - Default entries use `skipPrefix: false` so they inherit the manifest prefix.\n */\nexport function resolveManifest(input: Manifest): ResolvedCapabilities {\n const manifest = validateManifest(input);\n\n const prefix =\n manifest.prefix !== undefined ? manifest.prefix : manifest.app_id;\n const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;\n const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);\n const includePublicSpace = manifest.includePublicSpace ?? true;\n const tier = normalizeDefaults(manifest.defaults);\n\n const defaultEntries = defaultEntriesForTier(tier);\n const explicitEntries = manifest.permissions ?? [];\n const secretEntries = secretEntriesForManifest(manifest.secrets);\n\n // Merge order: defaults first, then explicit entries, so explicit entries\n // for the same (service, space, path) tuple override defaults.\n const allEntries: PermissionEntry[] = [\n ...defaultEntries,\n ...explicitEntries,\n ...secretEntries,\n ];\n\n const resources: ResourceCapability[] = withCapabilitiesReadForSpaces(\n allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space)),\n );\n\n const additionalDelegates: ResolvedDelegate[] =\n manifest.did === undefined\n ? []\n : [\n {\n did: manifest.did,\n name: manifest.name,\n expiryMs,\n permissions: resources.map(cloneResourceCapability),\n },\n ];\n\n return {\n app_id: manifest.app_id,\n ...(manifest.did !== undefined ? { did: manifest.did } : {}),\n space,\n resources,\n expiryMs,\n includePublicSpace,\n additionalDelegates,\n };\n}\n\nfunction normalizeSecretActions(actions: readonly string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const add = (action: string) => {\n if (!seen.has(action)) {\n out.push(action);\n seen.add(action);\n }\n };\n\n for (const action of actions) {\n if (action === \"read\") {\n add(\"get\");\n continue;\n }\n if (action === \"write\") {\n add(\"put\");\n continue;\n }\n if (action === \"delete\") {\n add(\"del\");\n continue;\n }\n if (\n action === \"get\" ||\n action === \"put\" ||\n action === \"del\" ||\n action === \"list\" ||\n action === \"metadata\"\n ) {\n add(action);\n continue;\n }\n if (\n action === \"tinycloud.kv/get\" ||\n action === \"tinycloud.kv/put\" ||\n action === \"tinycloud.kv/del\" ||\n action === \"tinycloud.kv/list\" ||\n action === \"tinycloud.kv/metadata\"\n ) {\n add(action);\n continue;\n }\n throw new ManifestValidationError(\n `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`,\n );\n }\n\n return out;\n}\n\nfunction secretNameFromSpec(\n fallbackName: string,\n spec: ManifestSecretActions,\n): string {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.name ?? fallbackName;\n }\n return fallbackName;\n}\n\nfunction secretScopeFromSpec(\n spec: ManifestSecretActions,\n): string | undefined {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.scope;\n }\n return undefined;\n}\n\nfunction secretActionsFromSpec(\n name: string,\n spec: ManifestSecretActions,\n): string[] {\n if (spec === true) {\n return [\"read\"];\n }\n if (typeof spec === \"string\") {\n return [spec];\n }\n if (Array.isArray(spec)) {\n return spec;\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must be true, a string action, an actions array, or an object`,\n );\n }\n if (spec.actions === undefined) {\n return [\"read\"];\n }\n if (typeof spec.actions === \"string\") {\n return [spec.actions];\n }\n if (Array.isArray(spec.actions)) {\n return spec.actions;\n }\n throw new ManifestValidationError(\n `manifest.secrets.${name}.actions must be a string or array`,\n );\n}\n\nfunction secretEntriesForManifest(\n secrets: Manifest[\"secrets\"] | undefined,\n): PermissionEntry[] {\n if (secrets === undefined) {\n return [];\n }\n\n const entries: PermissionEntry[] = [];\n for (const [name, spec] of Object.entries(secrets)) {\n const actions = secretActionsFromSpec(name, spec);\n const secretPath = resolveSecretPath(\n secretNameFromSpec(name, spec),\n { scope: secretScopeFromSpec(spec) },\n );\n const extra: { expiry?: string; description?: string } =\n spec !== true && typeof spec === \"object\" && !Array.isArray(spec)\n ? spec\n : {};\n entries.push({\n service: VAULT_PERMISSION_SERVICE,\n space: SECRETS_SPACE,\n path: secretPath.vaultKey,\n actions: normalizeSecretActions(actions),\n skipPrefix: true,\n ...(extra.expiry !== undefined ? { expiry: extra.expiry } : {}),\n ...(extra.description !== undefined\n ? { description: extra.description }\n : {}),\n });\n }\n return entries;\n}\n\n/**\n * Expand a single permission entry into a {@link ResourceCapability}:\n * apply the prefix to the path and expand short actions into full URNs.\n */\nfunction resolveEntry(\n entry: PermissionEntry,\n prefix: string,\n _inheritedExpiryMs: number,\n inheritedSpace: string,\n): ResourceCapability[] {\n // Encryption permissions reference a networkId URN as their resource\n // — the manifest prefix is meaningless against a top-level\n // owner-scoped resource and would corrupt the URN. Always skip.\n const skipPrefixForEntry =\n entry.skipPrefix === true ||\n entry.service === ENCRYPTION_PERMISSION_SERVICE;\n const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);\n const entryExpiryMs =\n entry.expiry !== undefined ? parseExpiry(entry.expiry) : undefined;\n return expandPermissionEntry({\n ...entry,\n space: entry.space ?? inheritedSpace,\n path: resolvedPath,\n skipPrefix: true,\n }).map((expanded) => ({\n service: expanded.service,\n space: expanded.space ?? inheritedSpace,\n path: expanded.path,\n actions: expanded.actions,\n // Only populate `expiryMs` when the entry had its own expiry override.\n // When absent, callers use the parent (delegation or manifest) expiry\n // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.\n ...(entryExpiryMs !== undefined ? { expiryMs: entryExpiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n }));\n}\n\nfunction expandVaultPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n const byBase = new Map<VaultKVBase, string[]>();\n\n for (const action of entry.actions) {\n const expansion = vaultActionExpansion(action);\n for (const base of expansion.bases) {\n const actions = byBase.get(base) ?? [];\n if (!actions.includes(expansion.action)) {\n actions.push(expansion.action);\n }\n byBase.set(base, actions);\n }\n }\n\n return [...byBase.entries()].map(([base, actions]) => ({\n ...entry,\n service: \"tinycloud.kv\",\n path: vaultKVPath(base, entry.path),\n actions,\n skipPrefix: true,\n }));\n}\n\nfunction vaultActionExpansion(action: string): VaultActionExpansion {\n const normalized = normalizeVaultAction(action);\n if (normalized === \"read\" || normalized === \"get\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"write\" || normalized === \"put\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/put\" };\n }\n if (normalized === \"delete\" || normalized === \"del\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/del\" };\n }\n if (normalized === \"list\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/list\" };\n }\n if (normalized === \"head\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"metadata\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/metadata\" };\n }\n\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`,\n );\n}\n\nfunction normalizeVaultAction(action: string): string {\n if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {\n return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);\n }\n if (action.startsWith(\"tinycloud.kv/\")) {\n return action.slice(\"tinycloud.kv/\".length);\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`,\n );\n }\n return action;\n}\n\nfunction vaultKVPath(base: VaultKVBase, path: string): string {\n const normalized = path.startsWith(\"/\") ? path.slice(1) : path;\n return `${base}/${normalized}`;\n}\n\nfunction cloneResourceCapability(\n entry: ResourceCapability,\n): ResourceCapability {\n return {\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.expiryMs !== undefined ? { expiryMs: entry.expiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction clonePermissionEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction dedupeResources(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n const byKey = new Map<string, ResourceCapability>();\n\n for (const resource of resources) {\n const key = `${resource.service}\\u0000${resource.space}\\u0000${resource.path}\\u0000${resource.expiryMs ?? \"\"}`;\n const existing = byKey.get(key);\n if (existing === undefined) {\n byKey.set(key, cloneResourceCapability(resource));\n continue;\n }\n\n const seen = new Set(existing.actions);\n for (const action of resource.actions) {\n if (!seen.has(action)) {\n existing.actions.push(action);\n seen.add(action);\n }\n }\n if (\n existing.description === undefined &&\n resource.description !== undefined\n ) {\n existing.description = resource.description;\n }\n }\n\n return [...byKey.values()];\n}\n\nfunction capabilitiesReadPermission(space: string): ResourceCapability {\n return {\n service: \"tinycloud.capabilities\",\n space,\n path: \"\",\n actions: [\"tinycloud.capabilities/read\"],\n };\n}\n\nfunction withCapabilitiesReadForSpaces(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n if (resources.length === 0) {\n return [];\n }\n\n const spaces = new Set(\n resources\n .filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE)\n .map((resource) => resource.space),\n );\n return dedupeResources([\n ...resources,\n ...[...spaces].map(capabilitiesReadPermission),\n ]);\n}\n\n/**\n * Compose one or more manifests into the single capability request that should\n * be signed. Fetching manifests is intentionally out of band; callers pass the\n * already-loaded manifest objects.\n */\nexport function composeManifestRequest(\n inputs: readonly Manifest[],\n options: ComposeManifestOptions = {},\n): ComposedManifestRequest {\n if (!Array.isArray(inputs) || inputs.length === 0) {\n throw new ManifestValidationError(\n \"composeManifestRequest requires at least one manifest\",\n );\n }\n\n const includeAccountRegistryPermissions =\n options.includeAccountRegistryPermissions ?? true;\n const manifests = inputs.map(validateManifest);\n const resolved = manifests.map(resolveManifest);\n const resources = resolved.flatMap((entry) => entry.resources);\n const delegationTargets = resolved.flatMap((entry) =>\n entry.additionalDelegates.map((delegate) => ({\n ...delegate,\n permissions: dedupeResources(delegate.permissions),\n })),\n );\n\n if (includeAccountRegistryPermissions) {\n resources.push(\n ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n );\n }\n const resourcesWithImplicitCapabilities =\n withCapabilitiesReadForSpaces(resources);\n\n const manifestsByAppId = new Map<string, Manifest[]>();\n for (const manifest of manifests) {\n const current = manifestsByAppId.get(manifest.app_id);\n if (current === undefined) {\n manifestsByAppId.set(manifest.app_id, [manifest]);\n } else {\n current.push(manifest);\n }\n }\n\n const registryRecords: ManifestRegistryRecord[] =\n includeAccountRegistryPermissions\n ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({\n key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,\n app_id,\n manifests: appManifests.map((manifest) => ({\n ...manifest,\n permissions: manifest.permissions?.map(clonePermissionEntry),\n })),\n }))\n : [];\n\n return {\n manifests,\n resources: resourcesWithImplicitCapabilities,\n delegationTargets,\n registryRecords,\n expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),\n includePublicSpace: resolved.some((entry) => entry.includePublicSpace),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abilities map construction (bridge to WASM prepareSession / createDelegation)\n// ---------------------------------------------------------------------------\n\n/**\n * The shape `prepareSession` and the multi-resource `createDelegation` WASM\n * export both accept:\n *\n * ```\n * { [shortService]: { [path]: [fullUrnAction, ...] } }\n * ```\n *\n * - `shortService` is the recap-level service segment (`\"kv\"`, `\"sql\"`,\n * `\"duckdb\"`, `\"capabilities\"`, `\"hooks\"`) — not the manifest long form.\n * - `path` is the fully-resolved path (prefix already applied). An empty\n * string means \"no path segment\" on the resource URI.\n * - Action strings are full URNs like `\"tinycloud.kv/get\"`.\n *\n * This is a single source of truth for both the session's own recap (at\n * sign-in) and the delegations it can derive (post sign-in). We re-use it\n * for both so one manifest drives both sides.\n */\nexport type AbilitiesMap = Record<string, Record<string, string[]>>;\n\n/**\n * Per-space abilities map accepted by the newer WASM session config:\n *\n * ```\n * { [spaceIdOrName]: { [shortService]: { [path]: [fullUrnAction, ...] } } }\n * ```\n */\nexport type SpaceAbilitiesMap = Record<string, AbilitiesMap>;\n\n/**\n * Convert a list of {@link ResourceCapability} entries (manifest\n * long-form service, full-URN actions) into the {@link AbilitiesMap}\n * shape the WASM layer expects.\n *\n * When multiple entries target the same `(service, path)` pair, their\n * action lists are merged and deduped. Entries whose service has no\n * short-form mapping in {@link SERVICE_LONG_TO_SHORT} are rejected with\n * a {@link ManifestValidationError} — the SDK does not silently drop\n * unknown services because the recap encoding would lose them.\n *\n * Paths are kept verbatim: this function does NOT collapse\n * `\"com.listen.app/\"` and `\"com.listen.app\"` or reinterpret empty /\n * slash strings. Callers that care about path canonicalization should\n * normalize before calling.\n */\nexport function resourceCapabilitiesToAbilitiesMap(\n resources: readonly ResourceCapability[],\n): AbilitiesMap {\n const out: AbilitiesMap = {};\n for (const r of resources) {\n const shortService = SERVICE_LONG_TO_SHORT[r.service];\n if (shortService === undefined) {\n throw new ManifestValidationError(\n `unknown service '${r.service}' — no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(\", \")}`,\n );\n }\n if (out[shortService] === undefined) {\n out[shortService] = {};\n }\n const pathsMap = out[shortService];\n const existing = pathsMap[r.path];\n if (existing === undefined) {\n // Copy so downstream mutation can't leak back into the input.\n pathsMap[r.path] = [...r.actions];\n } else {\n // Merge + dedupe while preserving first-seen order.\n const seen = new Set(existing);\n for (const action of r.actions) {\n if (!seen.has(action)) {\n existing.push(action);\n seen.add(action);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Group resolved capabilities by `space`, then convert each group into a WASM\n * abilities map. Short space names are left as-is here; platform layers that\n * know the wallet address and chain id turn them into full SpaceIds.\n */\nexport function resourceCapabilitiesToSpaceAbilitiesMap(\n resources: readonly ResourceCapability[],\n): SpaceAbilitiesMap {\n const grouped = new Map<string, ResourceCapability[]>();\n for (const resource of resources) {\n const entries = grouped.get(resource.space);\n if (entries === undefined) {\n grouped.set(resource.space, [resource]);\n } else {\n entries.push(resource);\n }\n }\n\n const out: SpaceAbilitiesMap = {};\n for (const [space, entries] of grouped.entries()) {\n out[space] = resourceCapabilitiesToAbilitiesMap(entries);\n }\n return out;\n}\n\n/**\n * Build the {@link AbilitiesMap} that a session should be signed with,\n * given a {@link ResolvedCapabilities} (i.e. the output of\n * {@link resolveManifest}).\n *\n * The resulting map is the **union** of:\n * 1. the app's own resources (`resolved.resources`), and\n * 2. every permission declared in every `additionalDelegates[*]` entry.\n *\n * The union is what makes the manifest's delegations ergonomic: at\n * sign-in, the session key acquires recap coverage for both the app's\n * runtime needs and every downstream delegation target. Post sign-in,\n * `delegateTo(backendDID, backendPermissions)` can then issue the\n * sub-delegation via the session key (no wallet prompt) because the\n * caps are already part of the granted set.\n *\n * Duplicate `(service, path, action)` triples across resources and\n * delegations are merged and deduped — the session SIWE doesn't need\n * them repeated.\n */\nexport function manifestAbilitiesUnion(\n resolved: ResolvedCapabilities,\n): AbilitiesMap {\n const all: ResourceCapability[] = [...resolved.resources];\n for (const delegate of resolved.additionalDelegates) {\n for (const perm of delegate.permissions) {\n all.push(perm);\n }\n }\n return resourceCapabilitiesToAbilitiesMap(all);\n}\n","/**\n * Capability subset checking and recap parsing.\n *\n * This module powers the capability-chain delegation flow. The key decision\n * a `delegateTo` call has to make is: \"are the requested capabilities a\n * subset of what the current session already grants?\"\n *\n * - If yes → issue the delegation via the session-key UCAN path (no wallet prompt).\n * - If no → raise {@link PermissionNotInManifestError} so the caller can\n * trigger an escalation flow via `requestPermissions`.\n *\n * Canonical spec: `.claude/specs/capability-chain.md`.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_MANIFEST_SPACE,\n type PermissionEntry,\n SERVICE_SHORT_TO_LONG,\n expandActionShortNames,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a `delegateTo` call requests capabilities that the current\n * session does not already grant. The caller can catch this and trigger\n * `requestPermissions(missing)` to show an escalation modal.\n */\nexport class PermissionNotInManifestError extends Error {\n public readonly missing: PermissionEntry[];\n public readonly granted: PermissionEntry[];\n\n constructor(missing: PermissionEntry[], granted: PermissionEntry[]) {\n super(\n `Requested capabilities exceed current session. Missing ${missing.length} entries.`\n );\n this.name = \"PermissionNotInManifestError\";\n this.missing = missing;\n this.granted = granted;\n }\n}\n\n/**\n * Thrown when the current session has expired (or will expire within the\n * safety margin). The caller should trigger a fresh sign-in.\n */\nexport class SessionExpiredError extends Error {\n public readonly expiredAt: Date;\n\n constructor(expiredAt: Date) {\n super(`Session expired at ${expiredAt.toISOString()}`);\n this.name = \"SessionExpiredError\";\n this.expiredAt = expiredAt;\n }\n}\n\n/**\n * Thrown when the installed WASM delegation boundary cannot encode every\n * constrained ReCap branch in a requested child delegation.\n */\nexport class CaveatedDelegationUnsupportedError extends Error {\n /** Stable machine-readable error code for fail-closed caveated delegation. */\n code = \"CAVEATED_DELEGATION_UNSUPPORTED\" as const;\n /** Requested entries whose constrained ReCap branches cannot be preserved. */\n entries: PermissionEntry[];\n\n constructor(entries: PermissionEntry[]) {\n super(\n \"Cannot create a caveated delegation because this WASM delegation boundary cannot preserve every ReCap caveat branch exactly.\"\n );\n this.name = \"CaveatedDelegationUnsupportedError\";\n this.entries = entries.map(cloneEntry);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space normalization\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a space identifier to its short-name form.\n *\n * Recap resource URIs in a signed SIWE encode the space as a full URI of the\n * form `tinycloud:pkh:eip155:{chainId}:{address}:{name}` (e.g.\n * `tinycloud:pkh:eip155:1:0xd559...:default`). Manifest permissions and\n * backend-advertised permissions use the short `{name}` form (e.g.\n * `\"default\"`).\n *\n * Strict string comparison between these two forms would always fail, so we\n * normalize both sides to the short name before comparing. The trailing\n * segment after the last `:` in a `tinycloud:` URI is the space name.\n *\n * Short names (`\"default\"`, `\"work-space\"`) are returned unchanged.\n * Any non-`tinycloud:` string is returned unchanged. A malformed URI with a\n * trailing colon is returned unchanged (so the check degrades to a strict\n * mismatch rather than collapsing to an empty string).\n *\n * @internal\n */\nexport function normalizeSpace(space: string): string {\n if (!space.startsWith(\"tinycloud:\")) {\n return space;\n }\n const lastColon = space.lastIndexOf(\":\");\n if (lastColon === -1 || lastColon === space.length - 1) {\n return space;\n }\n return space.slice(lastColon + 1);\n}\n\n// ---------------------------------------------------------------------------\n// Subset check\n// ---------------------------------------------------------------------------\n\nexport interface SubsetCheckResult {\n /** True when every requested entry is covered by a granted entry. */\n subset: boolean;\n /** Entries the granted set does not cover (empty when `subset` is true). */\n missing: PermissionEntry[];\n}\n\n/**\n * Check whether `requested` is a strict subset of `granted`.\n *\n * Matching rules for each `requested[i]`:\n * - `service` matches exactly.\n * - `space` matches exactly.\n * - Path containment:\n * - If `granted.path` ends with `/`, it covers any `requested.path` that\n * starts with `granted.path`.\n * - Otherwise, the paths must match exactly.\n * - Action containment: every requested URN must be matched exactly or by a\n * service-scoped wildcard such as `tinycloud.kv/*`.\n *\n * Grant entries with the same service, space, path coverage, and caveats are\n * considered together. This matters because ReCap parsers may return one\n * entry per action even when the original manifest grouped those actions.\n * Any `requested` entry whose actions are not collectively covered is added\n * to `missing` and the overall result is non-subset.\n *\n * Both sides are expected to be in the canonical long-form shape (service\n * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}\n * or `expandActionShortNames` to normalize inputs first.\n */\nexport function isCapabilitySubset(\n requested: readonly PermissionEntry[],\n granted: readonly PermissionEntry[]\n): SubsetCheckResult {\n const missing: PermissionEntry[] = [];\n\n for (const req of requested) {\n const matchingScope = granted.filter((entry) =>\n canonicalizeEntryScopeMatches(req, entry)\n );\n const requestedActions = expandActionShortNames(\n req.service,\n req.actions\n );\n const grantedActions = matchingScope.flatMap((entry) =>\n expandActionShortNames(entry.service, entry.actions)\n );\n const covered = requestedActions.every((requestedAction) =>\n grantedActions.some((grantedAction) =>\n actionContains(grantedAction, requestedAction)\n )\n );\n if (!covered) {\n missing.push(cloneEntry(req));\n }\n }\n\n return { subset: missing.length === 0, missing };\n}\n\n/**\n * Returns true when `granted` fully covers `requested` — same service, same\n * space, path containment per spec, and action set containment.\n */\nfunction canonicalizeEntryScopeMatches(\n requested: PermissionEntry,\n granted: PermissionEntry\n): boolean {\n if (requested.service !== granted.service) {\n return false;\n }\n // Normalize both sides so callers passing short names (`\"default\"`) match\n // recap-parsed full URIs (`\"tinycloud:pkh:eip155:1:0xd559...:default\"`) and\n // vice versa. Idempotent for short names.\n if (\n normalizeSpace(requested.space ?? DEFAULT_MANIFEST_SPACE) !==\n normalizeSpace(granted.space ?? DEFAULT_MANIFEST_SPACE)\n ) {\n return false;\n }\n if (!pathContains(granted.path, requested.path)) {\n return false;\n }\n // There is no safe general partial ordering for arbitrary ReCap caveat\n // objects. A caveated authority therefore only covers the same caveat set;\n // treating it as uncaveated would authorize a broader child delegation.\n if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {\n return false;\n }\n return true;\n}\n\n/**\n * Compare ReCap caveat branch sets without losing signed branch structure.\n *\n * ReCap represents an unconstrained ability as `[{}]`, while SDK callers can\n * represent that same authority as `undefined` or `[]`. Those three forms are\n * equivalent. Every other branch, including an unconstrained branch mixed\n * with a constrained one, remains part of the canonical comparison.\n */\nexport function recapCaveatsEqual(\n left: readonly Record<string, unknown>[] | undefined,\n right: readonly Record<string, unknown>[] | undefined,\n): boolean {\n return canonicalizeRecapCaveats(left) === canonicalizeRecapCaveats(right);\n}\n\n/**\n * Canonicalize a ReCap caveat branch set for exact equality checks.\n *\n * Object keys and branch order do not affect equality. A lone unconstrained\n * branch is normalized to the SDK's empty-caveat representation, but an\n * unconstrained branch in a mixed set is deliberately retained.\n */\nexport function canonicalizeRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): string {\n const canonicalize = (value: unknown): string => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return JSON.stringify(value);\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(\",\")}]`;\n if (typeof value === \"object\") {\n const object = value as Record<string, unknown>;\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n return `{${Object.keys(object).sort().map((key) =>\n `${JSON.stringify(key)}:${canonicalize(object[key])}`,\n ).join(\",\")}}`;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n const branches = (caveats ?? []).map(canonicalize).sort();\n if (branches.length === 0 || (branches.length === 1 && branches[0] === \"{}\")) {\n return \"[]\";\n }\n return `[${branches.join(\",\")}]`;\n}\n\n/** Return whether a granted action pattern covers one requested action. */\nexport function actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === \"*\" || grantedAction === requestedAction) return true;\n if (!grantedAction.endsWith(\"/*\")) return false;\n const service = grantedAction.slice(0, -2);\n return requestedAction === service || requestedAction.startsWith(`${service}/`);\n}\n\n/**\n * Path containment per spec:\n * - `granted.path` ends with `/` → prefix match (requested starts with granted)\n * - otherwise → exact string match\n *\n * The empty string is treated as \"no path constraint\" and matches anything.\n * The single-character `\"/\"` also matches anything (it is a trailing-slash\n * prefix of zero-length).\n */\nfunction pathContains(grantedPath: string, requestedPath: string): boolean {\n if (grantedPath === \"\" || grantedPath === \"/\") {\n return true;\n }\n if (grantedPath.endsWith(\"/\")) {\n return requestedPath.startsWith(grantedPath);\n }\n return requestedPath === grantedPath;\n}\n\nfunction cloneEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Recap parsing (WASM wrapper)\n// ---------------------------------------------------------------------------\n\n/**\n * The raw shape returned from the WASM `parseRecapFromSiwe` export. The\n * Rust layer encodes the service in the short form (e.g. `\"kv\"`) because\n * that is what the SIWE recap resource URI actually contains. We normalize\n * to the manifest long form (`\"tinycloud.kv\"`) in {@link parseRecapCapabilities}.\n *\n * @internal\n */\nexport interface WasmRecapEntry {\n service: string;\n space: string;\n path: string;\n actions: string[];\n /** Exact ReCap caveats shared by every action in this entry. */\n caveats?: Record<string, unknown>[];\n}\n\n/**\n * Signature of the WASM `parseRecapFromSiwe` export. Accepts the signed\n * SIWE message string and returns an array of raw recap entries. Throws if\n * the SIWE is malformed or the recap statement has been tampered.\n *\n * Exposed as an interface so the SDK can inject the web or node binding\n * without `capabilities.ts` needing to know which.\n */\nexport type ParseRecapFromSiwe = (siweString: string) => WasmRecapEntry[];\n\n/**\n * Parse a signed SIWE message into an array of {@link PermissionEntry}\n * objects in the canonical long-form manifest shape.\n *\n * This is a thin wrapper around the WASM `parseRecapFromSiwe` export that:\n * 1. Normalizes short-form services (`\"kv\"`) to long-form (`\"tinycloud.kv\"`).\n * 2. Returns entries in a deterministic order (sorted by space, then service,\n * then path) so downstream equality checks are stable.\n *\n * Returns an empty array when the SIWE has no recap resource (plain auth\n * SIWE); this matches the WASM function's behavior and the spec.\n *\n * @param parseWasm The WASM `parseRecapFromSiwe` binding.\n * @param siwe The signed SIWE message string (exactly what `session.siwe` stores).\n */\nexport function parseRecapCapabilities(\n parseWasm: ParseRecapFromSiwe,\n siwe: string\n): PermissionEntry[] {\n const raw = parseWasm(siwe);\n if (!Array.isArray(raw)) {\n throw new Error(\n \"parseRecapFromSiwe returned a non-array value; wasm binding may be out of sync\"\n );\n }\n const normalized: PermissionEntry[] = raw.map((entry) => {\n const longService =\n SERVICE_SHORT_TO_LONG[entry.service] ??\n // Unknown short names pass through. If the recap already contained a\n // long-form service (e.g. a future tinycloud-node version emits long\n // form directly), don't double-prefix.\n (entry.service.startsWith(\"tinycloud.\")\n ? entry.service\n : `tinycloud.${entry.service}`);\n return {\n service: longService,\n // The Rust layer emits the space as a full `tinycloud:pkh:...:name`\n // URI (the recap target URI). Normalize to the short name so the\n // returned entries match the shape manifests use.\n space: normalizeSpace(entry.space),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats === undefined\n ? {}\n : { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }),\n };\n });\n\n // Sort for determinism (callers do equality checks on arrays of entries\n // in tests; deterministic ordering keeps those stable).\n normalized.sort((a, b) => {\n const aSpace = a.space ?? DEFAULT_MANIFEST_SPACE;\n const bSpace = b.space ?? DEFAULT_MANIFEST_SPACE;\n if (aSpace !== bSpace) return aSpace < bSpace ? -1 : 1;\n if (a.service !== b.service) return a.service < b.service ? -1 : 1;\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return 0;\n });\n\n return normalized;\n}\n","import {\n canonicalizeRecapCaveats,\n isCapabilitySubset,\n type PermissionEntry,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * A capability in the canonical form persisted in a v1 request artifact.\n *\n * The SDK remains the semantic authority for containment. This module only\n * establishes deterministic exact identity for persistence and display.\n */\nexport type CanonicalPermissionEntry = Readonly<PermissionEntry>;\n\nexport interface AuthorityEvaluation {\n readonly satisfied: boolean;\n readonly missing: readonly CanonicalPermissionEntry[];\n}\n\n/**\n * Operation-owned space resolution. The SDK's general capability evaluator\n * intentionally preserves its historical short/full-space compatibility; the\n * operation kernel supplies this narrower resolver when a space identifies a\n * remote owner's resource.\n */\nexport type OperationSpaceResolver = (space: string) => string;\n\nconst EXACT_PERMISSION_KEYS = new Set([\n \"service\",\n \"space\",\n \"path\",\n \"actions\",\n \"skipPrefix\",\n \"expiry\",\n \"description\",\n]);\n\n/**\n * Validate requirements that can be represented without semantic broadening in\n * a v1 artifact. Caveated authority is intentionally rejected: the v1 request\n * schema and grant path cannot preserve those signed branches end-to-end.\n */\nexport function validateExactCapabilities(value: unknown): PermissionEntry[] | undefined {\n if (!Array.isArray(value)) return undefined;\n\n const permissions: PermissionEntry[] = [];\n for (const candidate of value) {\n if (!isExactPermission(candidate)) return undefined;\n permissions.push(candidate);\n }\n return canonicalizeCapabilities(permissions);\n}\n\n/**\n * Evaluates required authority with the SDK's public subset primitive.\n *\n * In particular, this intentionally does not implement matching rules or\n * manufacture wildcards. A wildcard can cover a requirement only when it was\n * already present in the supplied granted authority and the SDK says so.\n */\nexport function evaluateAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeCapabilities(granted);\n const canonicalRequired = canonicalizeCapabilities(required);\n const result = isCapabilitySubset(canonicalRequired, canonicalGranted);\n\n return {\n satisfied: result.subset,\n missing: canonicalizeCapabilities(result.missing),\n };\n}\n\n/**\n * Evaluate operation capabilities without allowing two owners' same-named\n * spaces to compare equal. Path and action containment still come from the\n * SDK primitive; only the operation space identity is made owner-exact.\n */\nexport function evaluateOperationAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeOperationCapabilities(granted, resolveSpace);\n const canonicalRequired = canonicalizeOperationCapabilities(required, resolveSpace);\n const missing: CanonicalPermissionEntry[] = [];\n\n for (const requested of canonicalRequired) {\n const covered = canonicalGranted.some((candidate) =>\n candidate.service === requested.service &&\n operationSpacesEqual(candidate.space, requested.space) &&\n isCapabilitySubset([requested], [candidate]).subset,\n );\n if (!covered) missing.push(requested);\n }\n\n return {\n satisfied: missing.length === 0,\n missing: canonicalizeCapabilities(missing),\n };\n}\n\n/**\n * Whether a delegation's signed capabilities stay inside the stored request\n * it answers. `tinycloud.auth.import` and runtime replay share this check, so\n * a delegation import accepts is never one replay discards.\n */\nexport function delegationWithinRequest(\n requested: readonly PermissionEntry[],\n effective: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n return requested.length > 0 &&\n evaluateOperationAuthority(requested, canonicalizeCapabilities(effective), resolveSpace).satisfied;\n}\n\n/**\n * Validate a runtime hint as an exact member of the registered plan. Runtime\n * nodes may report the one phase that failed, but they may not introduce a\n * broader, differently-owned, caveated, or otherwise new capability.\n */\nexport function isExactCapabilityMemberSubset(\n hinted: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n const canonicalHinted = canonicalizeOperationCapabilities(hinted, resolveSpace);\n const canonicalPlanned = canonicalizeOperationCapabilities(planned, resolveSpace);\n return canonicalHinted.length > 0 && canonicalHinted.every((hint) => canonicalPlanned.some((plan) =>\n JSON.stringify(hint) === JSON.stringify(plan),\n ));\n}\n\n/** Canonical identity used by operation preflight, hints, and artifacts. */\nexport function canonicalizeOperationCapabilities(\n permissions: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): CanonicalPermissionEntry[] {\n return canonicalizeCapabilities(permissions.map((permission) => {\n const canonicalPath = canonicalizeOperationPath(permission);\n if (permission.space === undefined || resolveSpace === undefined) {\n return canonicalPath;\n }\n try {\n return { ...canonicalPath, space: resolveSpace(permission.space) };\n } catch {\n // An unresolvable identity remains a non-matching literal. It must never\n // be widened to a wildcard or to another authenticated owner.\n return canonicalPath;\n }\n }));\n}\n\nfunction canonicalizeOperationPath(permission: PermissionEntry): PermissionEntry {\n if (permission.service !== \"tinycloud.encryption\") return permission;\n const match = permission.path.match(\n /^(urn:tinycloud:encryption:did:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.*)$/,\n );\n if (!match) return permission;\n return { ...permission, path: `${match[1]}${match[2]!.toLowerCase()}${match[3]}` };\n}\n\nfunction operationSpacesEqual(\n granted: string | undefined,\n requested: string | undefined,\n): boolean {\n return granted === requested;\n}\n\n/** Returns a stable exact identity for one capability without containment. */\nexport function permissionIdentity(permission: PermissionEntry): string {\n return JSON.stringify(canonicalizeCapability(permission));\n}\n\n/**\n * Sorts actions and entries and removes only exactly-identical capabilities.\n * It does not coalesce paths, services, spaces, or actions into a broader\n * capability.\n */\nexport function canonicalizeCapabilities(\n permissions: readonly PermissionEntry[],\n): CanonicalPermissionEntry[] {\n const byIdentity = new Map<string, CanonicalPermissionEntry>();\n for (const permission of permissions) {\n const canonical = canonicalizeCapability(permission);\n byIdentity.set(permissionIdentityFromCanonical(canonical), canonical);\n }\n\n return [...byIdentity.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, permission]) => permission);\n}\n\nfunction canonicalizeCapability(permission: PermissionEntry): CanonicalPermissionEntry {\n const actions = [...new Set(permission.actions)].sort((left, right) => left.localeCompare(right));\n return {\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined\n ? {}\n : { caveats: canonicalizeCaveats(permission.caveats) }),\n };\n}\n\nfunction permissionIdentityFromCanonical(permission: CanonicalPermissionEntry): string {\n return JSON.stringify({\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions: permission.actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n });\n}\n\nfunction isExactPermission(value: unknown): value is PermissionEntry {\n if (\n !isExactRecord(value) ||\n Object.getOwnPropertyNames(value).some((key) => !EXACT_PERMISSION_KEYS.has(key)) ||\n Object.getOwnPropertySymbols(value).length > 0\n ) {\n return false;\n }\n if (\n !isExactText(value.service) ||\n !isExactPath(value.path, value.actions) ||\n (value.space !== undefined && !isExactText(value.space)) ||\n !Array.isArray(value.actions) ||\n value.actions.length === 0 ||\n !value.actions.every(isExactText) ||\n new Set(value.actions).size !== value.actions.length ||\n value.skipPrefix === true ||\n (value.skipPrefix !== undefined && value.skipPrefix !== false) ||\n (value.expiry !== undefined && !isExactText(value.expiry)) ||\n (value.description !== undefined && !isExactText(value.description))\n ) {\n return false;\n }\n return !(\"caveats\" in value);\n}\n\nfunction isExactRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isExactText(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && !value.includes(\"*\");\n}\n\nfunction isExactPath(value: unknown, actions: unknown): value is string {\n if (typeof value !== \"string\" || value === \"/\" || value.includes(\"*\")) return false;\n if (value === \"\" || value.endsWith(\"/\")) {\n return Array.isArray(actions) && actions.includes(\"tinycloud.kv/list\");\n }\n return true;\n}\n\nfunction canonicalizeCaveats(\n caveats: readonly Record<string, unknown>[],\n): Record<string, unknown>[] {\n return [...caveats]\n .map((caveat) => ({\n identity: canonicalizeRecapCaveats([caveat]),\n value: JSON.parse(JSON.stringify(caveat)) as Record<string, unknown>,\n }))\n .sort((left, right) => left.identity.localeCompare(right.identity))\n .map(({ value }) => value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n readdir,\n rename,\n rmdir,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\nconst DEFAULT_PROFILE = \"default\";\nconst DEFAULT_LOCK_TIMEOUT_MS = 2_000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\nconst DEFAULT_STALE_LOCK_MS = 30_000;\nconst TEST_LOCK_CONTENTION_SIGNAL_PATH = \"TC_TEST_PROFILE_LOCK_CONTENTION_SIGNAL_PATH\";\n// Profile state holds keys, sessions and delegations: owner-only access.\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIR_MODE = 0o700;\nconst TEST_LOCK_RECOVERY_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RECOVERY_BARRIER_DIR\";\nconst TEST_LOCK_OWNERLESS_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_OWNERLESS_BARRIER_DIR\";\nconst TEST_LOCK_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_RELEASE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RELEASE_BARRIER_DIR\";\nconst TEST_LOCK_CLAIM_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIM_BARRIER_DIR\";\nconst TEST_LOCK_CLAIMED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIMED_BARRIER_DIR\";\nconst TEST_LOCK_VERIFIED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_VERIFIED_BARRIER_DIR\";\nconst TEST_LOCK_MOVED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_MOVED_BARRIER_DIR\";\nconst TEST_LOCK_TURN_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_TURN_SETTLE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_SETTLE_BARRIER_DIR\";\nconst TEST_LOCK_TURN_COLLECT_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_COLLECT_BARRIER_DIR\";\n/** One acquisition of a profile lock; `active` is cleared before release. */\ninterface HeldProfileLock {\n readonly lockPath: string;\n /** The number of the turn this acquisition holds (see acquireTurn). */\n readonly turnSlot: number;\n /** A deletion of the profile ran while this acquisition waited for the lock. */\n readonly deletedWhileWaiting: boolean;\n active: boolean;\n}\n/**\n * Async context shared by every copy of this module in the process. Each\n * bundled operations entry point (`state`, `delegation-binding`, the root)\n * carries its own copy, so module-level context would make lock reentrancy and\n * the invocation state root stop at an entry-point boundary.\n * Each key is independently versioned for the shape and meaning of the\n * value it stores. Held-lock entries gained `turnSlot` and\n * `deletedWhileWaiting` in TC-633, so `.v2` must not read TC-602's `.v1`\n * entries. The invocation root remains a string path with unchanged\n * semantics and stays `.v1`. Relinquished turn tokens use a separate\n * versioned process-wide key: only an explicitly given-up turn of this PID\n * may be settled across separately bundled entry points.\n */\nfunction processWideContext<T>(key: string): AsyncLocalStorage<T> {\n const registry = globalThis as unknown as Record<symbol, AsyncLocalStorage<T> | undefined>;\n return registry[Symbol.for(key)] ??= new AsyncLocalStorage<T>();\n}\nconst invocationStateRoot = processWideContext<string>(\"tinycloud.operations.invocationStateRoot.v1\");\n/** Profile lock acquisitions held by the current async call chain (see withProfileLock). */\nconst heldProfileLocks = processWideContext<readonly HeldProfileLock[]>(\"tinycloud.operations.heldProfileLocks.v2\");\n\nexport type ProfileStoreName =\n | \"session\"\n | \"additional-delegations\"\n | \"auth-requests\";\n\nexport interface StoreMetadata {\n formatVersion: number;\n}\n\nexport interface ProfileStoreContents<T> {\n formatVersion: number;\n records: T[];\n}\n\nexport interface ProfileLockOptions {\n timeoutMs?: number;\n retryMs?: number;\n staleAfterMs?: number;\n}\n\nexport class ProfileLockTimeoutError extends Error {\n readonly code = \"PROFILE_LOCK_TIMEOUT\";\n\n /** `detail` names the cause when it is not simply another process holding the lock. */\n constructor(profile: string, timeoutMs: number, detail?: string) {\n super(`Timed out waiting for the profile lock for \"${profile}\" after ${timeoutMs}ms.${detail ? ` ${detail}` : \"\"}`);\n this.name = \"ProfileLockTimeoutError\";\n }\n}\n\n/**\n * A store write that waited for the profile lock while a deletion of that\n * profile held it, and found no profile settings once it got the lock. The\n * write is refused rather than recreating a profile with only a session or\n * store in it.\n */\nexport class ProfileDeletedError extends Error {\n readonly code = \"PROFILE_NOT_FOUND\";\n\n constructor(profile: string) {\n super(`Profile \"${profile}\" was deleted while this change waited for its lock, so the change was not written.`);\n this.name = \"ProfileDeletedError\";\n }\n}\n\n/**\n * The CLI's delegated-secret path treats TC_HOME as a home directory, rather\n * than a direct TinyCloud directory. Keep the shared store on that convention.\n */\nexport function tinycloudHomePath(): string {\n const home = invocationStateRoot.getStore() ??\n process.env.TC_HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n homedir();\n return join(home, \".tinycloud\");\n}\n\n/** Run one operation against an isolated TinyCloud home directory. */\nexport function withTinyCloudStateRoot<T>(\n stateRoot: string | undefined,\n action: () => Promise<T>,\n): Promise<T> {\n if (stateRoot === undefined) return action();\n if (!isAbsolute(stateRoot) || stateRoot.includes(\"\\0\")) {\n throw new TypeError(\"The TinyCloud state root must be an absolute path.\");\n }\n return invocationStateRoot.run(resolve(stateRoot), action);\n}\n\nexport function tinycloudConfigPath(): string {\n return join(tinycloudHomePath(), \"config.json\");\n}\n\nexport function profilesPath(): string {\n return join(tinycloudHomePath(), \"profiles\");\n}\n\nexport function profilePath(profile: string): string {\n return join(profilesPath(), validateProfileName(profile));\n}\n\nexport function profileConfigPath(profile: string): string {\n return join(profilePath(profile), \"profile.json\");\n}\n\nexport function sessionPath(profile: string): string {\n return profileStorePath(profile, \"session\");\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n return profileStorePath(profile, \"additional-delegations\");\n}\n\nexport function authRequestsPath(profile: string): string {\n return profileStorePath(profile, \"auth-requests\");\n}\n\nexport function profileStorePath(profile: string, store: ProfileStoreName): string {\n return join(profilePath(profile), `${store}.json`);\n}\n\n/** The format record is deliberately separate from each legacy JSON payload. */\nexport function profileStoreMetadataPath(profile: string, store: ProfileStoreName): string {\n return `${profileStorePath(profile, store)}.metadata.json`;\n}\n\nexport function profileLockPath(profile: string): string {\n return join(profilePath(profile), \".lock\");\n}\n\nexport function profileLockMetadataPath(profile: string): string {\n return join(profileLockPath(profile), \"owner.json\");\n}\n\n/**\n * The turn lock of a profile (see acquireTurn). It lives outside the profile\n * directory, so neither a profile deletion nor an older release's cleanup\n * removes it.\n */\nexport function profileTurnLockPath(profile: string): string {\n return join(tinycloudHomePath(), \"profile-locks\", validateProfileName(profile));\n}\n\n/**\n * Reads JSON without hiding malformed or inaccessible files. A missing file is\n * the only condition represented as null.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(filePath, \"utf8\")) as T;\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return null;\n throw error;\n }\n}\n\n/**\n * Writes the same pretty-printed, trailing-newline JSON shape used by the CLI,\n * but publishes it with an atomic rename from the same directory.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n await replaceJson(filePath, value, false);\n}\n\n/**\n * writeJsonAtomic; `durable` also flushes the data to disk before the rename,\n * so a crash or power loss leaves the old record or the new one, never a\n * truncated one (for lock records, whose damage would stop every writer).\n */\nasync function replaceJson(filePath: string, value: unknown, durable: boolean): Promise<void> {\n const directory = dirname(filePath);\n const temporaryPath = join(\n directory,\n `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,\n );\n const contents = `${JSON.stringify(value, null, 2)}\\n`;\n\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n try {\n if (durable) await writeFileDurably(temporaryPath, contents);\n else await writeFile(temporaryPath, contents, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE });\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Creates a file (exclusively) and, when it has contents, flushes them to disk. */\nasync function writeFileDurably(path: string, contents: string): Promise<void> {\n const handle = await open(path, \"wx\", PRIVATE_FILE_MODE);\n try {\n if (contents) {\n await handle.writeFile(contents, \"utf8\");\n await handle.datasync();\n }\n } finally {\n await handle.close();\n }\n}\n\nexport async function readProfile<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n return readJson<T>(profileConfigPath(profile));\n}\n\nexport async function readSession<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n await readStoreMetadata(profile, \"session\");\n return readJson<T>(sessionPath(profile));\n}\n\nexport async function readAdditionalDelegations<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"additional-delegations\")).records;\n}\n\nexport async function readAuthRequests<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"auth-requests\")).records;\n}\n\nexport async function readStoreMetadata(\n profile: string,\n store: ProfileStoreName,\n): Promise<StoreMetadata> {\n const metadata = await readJson<StoreMetadata>(profileStoreMetadataPath(profile, store));\n if (metadata === null) return { formatVersion: 1 };\n if (\n typeof metadata !== \"object\" ||\n metadata.formatVersion !== 1\n ) {\n throw new TypeError(`Unsupported store format for \"${store}\".`);\n }\n return metadata;\n}\n\nexport async function readProfileStore<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n): Promise<ProfileStoreContents<T>> {\n const [metadata, raw] = await Promise.all([\n readStoreMetadata(profile, store),\n readJson<unknown>(profileStorePath(profile, store)),\n ]);\n return {\n formatVersion: metadata.formatVersion,\n records: Array.isArray(raw) ? raw as T[] : [],\n };\n}\n\n/**\n * Runs a small critical section under the one lock shared by all profile\n * stores (see acquireProfileLock). Lock release verifies its ownership token\n * before removing the exact metadata instance it acquired.\n *\n * Reentrant within one async call chain: a critical section that already\n * holds a profile's lock (for example a login's compare-and-commit) can call\n * store writers that take the same lock without deadlocking. Ownership is\n * keyed by the resolved lock path (so switching state roots inside a lock\n * still takes the other root's lock) and lasts exactly as long as the\n * acquisition: it is revoked before release, so work deferred past the\n * critical section waits for the lock like any other caller.\n */\nexport async function withProfileLock<T>(\n profile: string,\n action: () => Promise<T>,\n options: ProfileLockOptions = {},\n): Promise<T> {\n const normalizedProfile = validateProfileName(profile);\n const lockPath = profileLockPath(normalizedProfile);\n const held = (heldProfileLocks.getStore() ?? []).filter((ownership) => ownership.active);\n if (held.some((ownership) => ownership.lockPath === lockPath)) return action();\n const acquired = await acquireProfileLock(normalizedProfile, options);\n const ownership: HeldProfileLock = {\n lockPath,\n turnSlot: acquired.turnSlot,\n deletedWhileWaiting: acquired.deletedWhileWaiting,\n active: true,\n };\n try {\n return await heldProfileLocks.run([...held, ownership], action);\n } finally {\n ownership.active = false;\n await acquired.release();\n // Taking the lock recreated the deleted profile's directory; remove it\n // again unless something was written into it (rmdir needs it empty).\n if (acquired.deletedWhileWaiting) await rmdir(profilePath(normalizedProfile)).catch(() => undefined);\n }\n}\n\n/**\n * Records, inside a profile deletion's critical section and after its files\n * are gone, that the profile was deleted, with the number of the deleting\n * turn. A store write whose wait overlapped that turn (it arrived before the\n * deletion released the lock, whether before or after this record) then\n * refuses (ProfileDeletedError) instead of recreating a profile with only a\n * session or store in it. The caller must hold the profile's lock.\n */\nexport async function recordProfileDeletion(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership) throw new Error(`Recording the deletion of profile \"${profile}\" requires holding its lock.`);\n await replaceJson(join(profileTurnLockPath(profile), \"deleted.json\"), { slot: ownership.turnSlot }, true);\n}\n\n/**\n * Refuses a write that would recreate a profile deleted while this critical\n * section waited for the lock (ProfileDeletedError). Every writer of profile\n * state other than the profile settings themselves calls this inside its\n * critical section, before writing. The caller must hold the profile's lock.\n */\nexport async function refuseWriteToDeletedProfile(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership?.deletedWhileWaiting) return;\n // Recreated meanwhile (or by this critical section): writing is fine.\n if (await exists(profileConfigPath(profile))) return;\n throw new ProfileDeletedError(profile);\n}\n\n/**\n * Appends a record or replaces the existing record with the supplied explicit\n * key. The extractor is supplied by the owning store so state.ts never needs\n * to know permission-request or delegation record shapes.\n */\nexport async function upsertProfileRecord<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n key: string,\n record: T,\n getKey: (candidate: T) => string | undefined,\n options: ProfileLockOptions = {},\n): Promise<T[]> {\n if (!key) throw new TypeError(\"A non-empty record key is required.\");\n\n return withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n const current = (await readProfileStore<T>(profile, store)).records;\n const next = current.filter((candidate) => getKey(candidate) !== key);\n next.push(record);\n await writeJsonAtomic(profileStorePath(profile, store), next);\n await writeFormatOneMetadata(profile, store);\n return next;\n }, options);\n}\n\n/**\n * Performs a typed read-modify-write of a legacy array store under the one\n * per-profile lock. The payload stays an array and the sibling metadata stays\n * format 1, so existing CLI readers keep their byte/layout contract.\n */\nexport async function updateProfileStore<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n options: ProfileLockOptions = {},\n): Promise<Result> {\n return withProfileLock(\n profile,\n () => updateProfileStoreWhileLocked(profile, store, update),\n options,\n );\n}\n\n/** The caller must already own this profile's lock. */\nasync function updateProfileStoreWhileLocked<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n): Promise<Result> {\n await refuseWriteToDeletedProfile(profile);\n const current = await readProfileStore<T>(profile, store);\n const next = await update(current.records);\n await writeJsonAtomic(profileStorePath(profile, store), next.records);\n await writeFormatOneMetadata(profile, store);\n return next.result;\n}\n\nexport async function writeSession<T extends object>(\n profile: string,\n session: T,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n await readStoreMetadata(profile, \"session\");\n await writeJsonAtomic(sessionPath(profile), session);\n await writeFormatOneMetadata(profile, \"session\");\n }, options);\n}\n\nexport async function removeSession(\n profile: string,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await readStoreMetadata(profile, \"session\");\n await rm(sessionPath(profile), { force: true });\n }, options);\n}\n\nasync function writeFormatOneMetadata(profile: string, store: ProfileStoreName): Promise<void> {\n await writeJsonAtomic(profileStoreMetadataPath(profile, store), { formatVersion: 1 });\n}\n\ninterface AcquiredProfileLock {\n readonly deletedWhileWaiting: boolean;\n readonly turnSlot: number;\n release(): Promise<void>;\n}\n\ninterface LockDeadline {\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly retryMs: number;\n}\n\n/**\n * Takes a profile's lock in two layers:\n *\n * 1. The turn lock (acquireTurn), used by this release and later ones. It\n * decides nothing from elapsed time, so a process paused anywhere, for\n * any length of time, cannot let a second holder in.\n * 2. Holding a turn, the `.lock` directory every older release uses\n * (publishProfileLock), so they keep excluding this release and it them.\n * Only one process of this release at a time acquires, recovers or\n * releases `.lock`.\n *\n * Also reports whether a profile deletion (recordProfileDeletion) ran while\n * this acquisition waited.\n */\nasync function acquireProfileLock(\n profile: string,\n options: ProfileLockOptions,\n): Promise<AcquiredProfileLock> {\n const deadline: LockDeadline = {\n startedAt: Date.now(),\n timeoutMs: options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS,\n retryMs: options.retryMs ?? DEFAULT_LOCK_RETRY_MS,\n };\n const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_LOCK_MS;\n const lockPath = profileLockPath(profile);\n const turnDirectory = profileTurnLockPath(profile);\n\n const directory = profilePath(profile);\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n await mkdir(dirname(turnDirectory), { recursive: true, mode: PRIVATE_DIR_MODE });\n // Every store write takes this lock: tighten the tree older releases\n // created 0775 before writing sessions or delegations into it.\n for (const path of [tinycloudHomePath(), profilesPath(), directory]) {\n await chmod(path, PRIVATE_DIR_MODE).catch((error: unknown) => {\n // A profile deletion can remove the profile directory right after the\n // mkdir above; the lock attempt below recreates it 0700.\n if (path !== directory || !isErrno(error, \"ENOENT\")) throw error;\n });\n }\n\n const { turn, firstWaitedTurn } = await acquireTurn(profile, turnDirectory, deadline);\n try {\n // An unreadable deletion record is ignored rather than failing every\n // acquisition; it is written durably, so only damage makes it so.\n const deletion = await readJson<{ slot?: unknown }>(join(turnDirectory, \"deleted.json\")).catch(() => null);\n const deletedWhileWaiting = typeof deletion?.slot === \"number\" && deletion.slot >= firstWaitedTurn;\n while (true) {\n const token = randomUUID();\n if (await publishProfileLock(profile, lockPath, token)) {\n return {\n deletedWhileWaiting,\n turnSlot: turn.slot,\n release: async () => {\n try {\n await releaseProfileLock(profile, lockPath, token);\n } finally {\n await releaseTurn(profile, turn);\n }\n },\n };\n }\n await signalTestLockContention(profile);\n if (await recoverStaleLock(profile, lockPath, staleAfterMs)) continue;\n await waitOrTimeOut(profile, deadline);\n }\n } catch (error) {\n await releaseTurn(profile, turn);\n throw error;\n }\n}\n\n/** Throws once the acquisition's time is up; `detail` explains a damaged turn lock. */\nfunction checkDeadline(profile: string, deadline: LockDeadline, detail?: string): void {\n if (Date.now() - deadline.startedAt >= deadline.timeoutMs) {\n throw new ProfileLockTimeoutError(profile, deadline.timeoutMs, detail);\n }\n}\n\n/** Sleeps one retry interval, or throws once the acquisition's time is up. */\nasync function waitOrTimeOut(profile: string, deadline: LockDeadline, detail?: string): Promise<void> {\n checkDeadline(profile, deadline, detail);\n await sleep(Math.min(deadline.retryMs, deadline.timeoutMs - (Date.now() - deadline.startedAt)));\n}\n\n/** One granted turn of the turn lock. */\ninterface Turn {\n readonly directory: string;\n readonly slot: number;\n readonly token: string;\n}\n\n/** A turn as recorded on disk. */\ninterface TurnState {\n readonly slot: number;\n readonly token: string;\n readonly pid: number;\n /** The token of the turn before it that its creator observed; null for turn 0. */\n readonly after: string | null;\n readonly held: boolean;\n readonly done: boolean;\n}\n\n/** Turn directory names: decimal turn numbers. */\nconst TURN = /^(?:0|[1-9][0-9]*)$/;\n\n/**\n * Tokens of turns this process published and then gave up (a marker write or\n * a read failed after publication): the positive evidence that lets this\n * process settle a turn of its own PID. A live process's turn that is not in\n * here is never settled by it, so a module instance that cannot see another\n * instance's set (another bundled copy of this package) waits rather than\n * settling a turn that copy still holds.\n *\n * One set per process, not per module instance: the package's entry points\n * (state, index, artifacts, cli-runtime; ESM and CJS) each bundle their own\n * copy of this module, and one process may load several. The key is\n * versioned so that a release changing what the set holds uses a new one.\n */\nconst relinquishedTurns: Set<string> =\n (globalThis as unknown as Record<symbol, Set<string> | undefined>)[Symbol.for(\"tinycloud.operations.relinquishedProfileTurns.v1\")] ??=\n new Set<string>();\n\n/** Marker writes are retried this many times, after these delays (ms), before giving up. */\nconst MARKER_RETRY_DELAYS_MS = [10, 50, 250];\n/** A given-up turn is settled in the background every second for up to five minutes. */\nconst SETTLE_RETRY_MS = 1_000;\nconst SETTLE_RETRIES = 300;\n\n/**\n * The turn lock: mutual exclusion among processes of this release that does\n * not depend on how long any of them is paused. It uses only `mkdir`,\n * `rename`, exclusive file creation, and a check that a holder's PID is gone\n * (as `.lock` recovery always has), so it needs no hard links.\n *\n * Turns are numbered directories in profileTurnLockPath(profile). Turn n has\n * `owner.json` ({ pid, createdAt, token, after }), where `after` is the token\n * of the turn n-1 its creator observed, and gains `<token>.held` when granted\n * and `<token>.done` when over. Markers name the turn's own token, so one\n * written late into a recreated directory of the same number means nothing.\n *\n * - A turn is published by renaming a fully written staging directory to\n * `n`, which fails while `n` exists (rename never replaces a non-empty\n * directory, and turn directories are never empty). The turn directory\n * itself is published the same way, with a granted, finished turn 0.\n * - A process takes turn n only after reading turn n-1 granted and done.\n * Once `n` is published it checks that turn n-1 is still the one it read\n * (same token, granted, done) and only then writes `held`; otherwise the\n * turn is void: it writes `done` alone and starts over.\n * - Turns are removed by renaming them aside: a void turn at any time, a\n * granted one only once no older turn is left and turn n+1 is granted and\n * done. The latest turn is never removed.\n *\n * Why at most one granted turn is ever not done: a removed number can be\n * published again, but turn n-1 is always removed before turn n, so a\n * process whose stale read led it to republish n finds n-1 gone or holding\n * another token, and its turn is void. A process that finds n-1 as it read\n * it published `n` for the first time, so it is the only process granted n,\n * and n-1 was done before. A turn is marked done only by its holder, or by\n * another process once the holder's PID is gone (or by its own process,\n * once it has explicitly given that turn up); a paused holder is alive.\n * A turn is voided only on definite evidence (the turn it follows is gone or\n * holds another token), never because a read failed. Nothing above is\n * decided from elapsed time.\n *\n * Returns the turn and the number of the first turn this acquisition waited\n * on: the latest turn when it first looked if that was not done yet, else\n * the next one.\n */\nasync function acquireTurn(\n profile: string,\n directory: string,\n deadline: LockDeadline,\n): Promise<{ turn: Turn; firstWaitedTurn: number }> {\n let firstWaitedTurn: number | undefined;\n // Why the turn lock looks damaged, as of the last look, for the timeout message.\n let problem: string | undefined;\n const damaged = (what: string) =>\n `The turn lock ${directory} ${what}, so no process can take it. ` +\n `If no tc or MCP process is using profile \"${profile}\", remove that directory.`;\n for (let first = true; ; first = false) {\n if (!first) checkDeadline(profile, deadline, problem);\n problem = undefined;\n const latest = await readLatestTurn(directory);\n if (latest === \"missing\") {\n await createTurnDirectory(directory);\n continue;\n }\n if (latest === \"empty\") {\n // Usually a listing that straddled a turn's publication and an older\n // turn's removal (readdir is not a snapshot); damaged if it persists.\n problem = damaged(\"has no turns\");\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n if (latest === null) continue;\n if (typeof latest === \"number\") {\n problem = damaged(`has an unreadable turn ${latest}`);\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n firstWaitedTurn ??= latest.done ? latest.slot + 1 : latest.slot;\n if (latest.held && latest.done) {\n const turn = await takeTurn(profile, directory, latest);\n if (turn !== null) return { turn, firstWaitedTurn };\n await waitOrTimeOut(profile, deadline);\n } else if (latest.done) {\n problem = damaged(`ends with turn ${latest.slot}, which was never granted`);\n await waitOrTimeOut(profile, deadline, problem);\n } else if (latest.pid === process.pid ? relinquishedTurns.has(latest.token) : !isProcessAlive(latest.pid)) {\n await waitForTestBarrier(TEST_LOCK_TURN_SETTLE_BARRIER_DIR, profile);\n await settleAbandonedTurn(directory, latest);\n relinquishedTurns.delete(latest.token);\n } else {\n await signalTestLockContention(profile);\n await waitOrTimeOut(profile, deadline);\n }\n }\n}\n\n/**\n * The highest-numbered turn: its state, its number if it is damaged, null if\n * it went away while being read.\n */\nasync function readLatestTurn(directory: string): Promise<TurnState | number | \"missing\" | \"empty\" | null> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return \"missing\";\n throw error;\n }\n const slots = names.filter((name) => TURN.test(name)).map(Number);\n if (slots.length === 0) return \"empty\";\n const slot = Math.max(...slots);\n const turn = await readTurn(directory, slot);\n return turn === \"damaged\" ? slot : turn;\n}\n\n/**\n * Turn `slot` as recorded now; null if it is gone; \"damaged\" if its owner\n * record is missing or unreadable (turns are renamed into place and aside\n * whole, with their owner record written durably). Any other read error is\n * thrown: it says nothing about the turn. `done` is read before `held`,\n * which every writer creates first, so a turn read as done is never misread\n * as void.\n */\nasync function readTurn(directory: string, slot: number): Promise<TurnState | \"damaged\" | null> {\n const path = join(directory, String(slot));\n let text: string;\n try {\n text = await readFile(join(path, \"owner.json\"), \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\") && !isErrno(error, \"ENOTDIR\")) throw error;\n return await exists(path) ? \"damaged\" : null;\n }\n let owner: { pid?: unknown; token?: unknown; after?: unknown } | null;\n try {\n owner = JSON.parse(text) as typeof owner;\n } catch {\n return \"damaged\";\n }\n if (owner === null || typeof owner !== \"object\" || typeof owner.token !== \"string\" || typeof owner.pid !== \"number\") {\n return \"damaged\";\n }\n const done = await exists(join(path, `${owner.token}.done`));\n const held = await exists(join(path, `${owner.token}.held`));\n return {\n slot,\n token: owner.token,\n pid: owner.pid,\n after: typeof owner.after === \"string\" ? owner.after : null,\n held,\n done,\n };\n}\n\n/**\n * Whether turn `slot` is still the granted, finished turn with `token`. False\n * only on definite evidence: it is gone, or holds another token. Throws if it\n * cannot be read, or is damaged, so the caller leaves its own turn undecided.\n */\nasync function isFinishedTurn(directory: string, slot: number, token: string): Promise<boolean> {\n const turn = await readTurn(directory, slot);\n if (turn === \"damaged\") throw new Error(`Turn ${slot} of the turn lock ${directory} is unreadable.`);\n return turn !== null && turn.token === token && turn.held && turn.done;\n}\n\n/**\n * Publishes the turn after `latest` and claims it. Null if another process\n * published that number first, or the turn is void. If a step after\n * publication fails, the turn is handed to settleOwnTurn and the error thrown.\n */\nasync function takeTurn(profile: string, directory: string, latest: TurnState): Promise<Turn | null> {\n const token = randomUUID();\n const slot = latest.slot + 1;\n const path = join(directory, String(slot));\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: latest.token };\n let published = false;\n try {\n published = await publishDirectory(\n join(directory, `.stage-${process.pid}-${token}`),\n path,\n { \"owner.json\": `${JSON.stringify(owner, null, 2)}\\n` },\n () => waitForTestBarrier(TEST_LOCK_TURN_PUBLISH_BARRIER_DIR, profile),\n );\n if (published && await isFinishedTurn(directory, latest.slot, latest.token) && await markTurn(path, token, \"held\")) {\n return { directory, slot, token };\n }\n if (published) await markTurn(path, token, \"done\");\n return null;\n } catch (error) {\n if (published) settleOwnTurn(directory, slot, token);\n throw error;\n }\n}\n\n/**\n * Finishes the turn of a process that is gone (or one this process gave up).\n * A turn its creator never got to grant is granted first if the turn before\n * it is still the one its creator read (the check the creator would have\n * made; that turn cannot have been removed, since that needs this turn\n * done), and left void only if it definitely is not.\n */\nasync function settleAbandonedTurn(directory: string, abandoned: TurnState): Promise<void> {\n const path = join(directory, String(abandoned.slot));\n if (!abandoned.held && abandoned.after !== null &&\n await isFinishedTurn(directory, abandoned.slot - 1, abandoned.after)) {\n await markTurn(path, abandoned.token, \"held\");\n }\n await markTurn(path, abandoned.token, \"done\");\n}\n\n/**\n * Settles a turn this process published but could not grant or finish (a\n * marker write or a read failed). Other processes wait on this live PID, so\n * it is retried in the background until it succeeds or the turn is settled\n * otherwise (by this process's next acquisition, or by another process once\n * this one has exited). The timer does not keep the process alive.\n */\nfunction settleOwnTurn(directory: string, slot: number, token: string, retries = SETTLE_RETRIES): void {\n relinquishedTurns.add(token);\n void (async () => {\n try {\n const turn = await readTurn(directory, slot);\n if (turn !== null && turn !== \"damaged\" && turn.token === token && !turn.done) await settleAbandonedTurn(directory, turn);\n relinquishedTurns.delete(token);\n } catch {\n // Still relinquished: this process's next acquisition settles it too.\n if (retries > 0) setTimeout(() => settleOwnTurn(directory, slot, token, retries - 1), SETTLE_RETRY_MS).unref();\n }\n })();\n}\n\n/**\n * Creates `<token>.<kind>` in a turn directory; false if the directory is\n * gone. Other failures (a full disk, a permission error) are retried a few\n * times, then thrown.\n */\nasync function markTurn(path: string, token: string, kind: \"held\" | \"done\"): Promise<boolean> {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(join(path, `${token}.${kind}`), \"\", { mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return true;\n if (isErrno(error, \"ENOENT\")) return false;\n if (attempt >= MARKER_RETRY_DELAYS_MS.length) throw error;\n await sleep(MARKER_RETRY_DELAYS_MS[attempt]!);\n }\n }\n}\n\n/** Creates the turn directory with a granted, finished turn 0, unless another process did. */\nasync function createTurnDirectory(directory: string): Promise<void> {\n const token = randomUUID();\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: null };\n await publishDirectory(join(dirname(directory), `.stage-${basename(directory)}-${process.pid}-${token}`), directory, {\n \"0/owner.json\": `${JSON.stringify(owner, null, 2)}\\n`,\n [`0/${token}.held`]: \"\",\n [`0/${token}.done`]: \"\",\n });\n}\n\n/**\n * Writes `files` (durably, when not empty) into a new staging directory and\n * renames it to `target`. False if `target` already exists (or the turn\n * directory is gone); the caller starts over. Nothing else removes a live\n * process's staging directory (see collectTurns), so `target` never appears\n * incomplete.\n */\nasync function publishDirectory(\n stage: string,\n target: string,\n files: Readonly<Record<string, string>>,\n beforeRename?: () => Promise<void>,\n): Promise<boolean> {\n try {\n for (const [name, contents] of Object.entries(files)) {\n await mkdir(dirname(join(stage, name)), { recursive: true, mode: PRIVATE_DIR_MODE });\n await writeFileDurably(join(stage, name), contents);\n }\n await beforeRename?.();\n await rename(stage, target);\n return true;\n } catch (error) {\n // ENOTEMPTY/EEXIST: `target` exists, though it may be gone again by now.\n // Windows reports an existing target directory as EPERM.\n if ([\"ENOTEMPTY\", \"EEXIST\", \"ENOENT\"].some((code) => isErrno(error, code)) || await exists(target)) return false;\n throw error;\n } finally {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Finishes this process's turn. If `done` cannot be written even after\n * retries, the critical section is still over and its writes stand: the turn\n * is handed to settleOwnTurn rather than failing the caller.\n */\nasync function releaseTurn(profile: string, turn: Turn): Promise<void> {\n try {\n await markTurn(join(turn.directory, String(turn.slot)), turn.token, \"done\");\n } catch {\n settleOwnTurn(turn.directory, turn.slot, turn.token);\n return;\n }\n await collectTurns(profile, turn).catch(() => undefined);\n}\n\n/**\n * Leftovers in a turn directory whose writer is gone: trash (a removed turn\n * renamed aside, garbage from then on), and staging directories and\n * deletion-record temporaries named after their writer's PID.\n */\nfunction isAbandonedTurnEntry(name: string): boolean {\n if (name.startsWith(\".trash-\")) return true;\n const writer = /^\\.(?:stage|deleted\\.json)[-.]([0-9]+)[-.]/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/** A turn directory's staging directory left beside it by a process that is gone. */\nfunction isAbandonedTurnDirectoryStage(name: string): boolean {\n const writer = /^\\.stage-.+-([0-9]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/**\n * Removes the turns before `turn`, which just finished: void turns, and\n * granted ones oldest first, each once no older turn is left and the next is\n * granted and done (see acquireTurn). A turn is renamed aside before it is\n * deleted, so its number is never an empty directory. A turn that is damaged\n * or cannot be read is left alone, and a read error stops the collection.\n * Leftovers of crashed processes go too, judged by PID, never by age:\n * removing a paused process's staging directory could publish an incomplete\n * turn.\n */\nasync function collectTurns(profile: string, turn: Turn): Promise<void> {\n for (const [directory, abandoned] of [\n [turn.directory, isAbandonedTurnEntry],\n [dirname(turn.directory), isAbandonedTurnDirectoryStage],\n ] as const) {\n for (const name of (await readdir(directory)).filter(abandoned)) {\n await rm(join(directory, name), { recursive: true, force: true }).catch(() => undefined);\n }\n }\n const older = (await readdir(turn.directory)).filter((name) => TURN.test(name)).map(Number)\n .filter((slot) => slot < turn.slot)\n .sort((left, right) => left - right);\n for (const slot of older) {\n const candidate = await readTurn(turn.directory, slot);\n if (candidate === null || candidate === \"damaged\" || !candidate.done) continue;\n if (candidate.held) {\n if (await exists(join(turn.directory, String(slot - 1)))) continue;\n const next = await readTurn(turn.directory, slot + 1);\n if (next === null || next === \"damaged\" || !next.held || !next.done) continue;\n }\n await waitForTestBarrier(TEST_LOCK_TURN_COLLECT_BARRIER_DIR, profile);\n const trash = join(turn.directory, `.trash-${randomUUID()}`);\n if (await rename(join(turn.directory, String(slot)), trash).then(() => true, () => false)) {\n await rm(trash, { recursive: true, force: true }).catch(() => undefined);\n }\n }\n}\n\n/**\n * One attempt to take `.lock`, made while holding a turn. Nothing here\n * replaces an existing path:\n *\n * 1. `mkdir(.lock)` (never recursive) is exclusive, and is the primitive\n * older releases use too, so they exclude each other.\n * 2. Ownership is published by `link`ing a fully written owner file (staged\n * beside `.lock`, on the same filesystem) to `.lock/owner.json`. `link`\n * fails with EEXIST if an owner exists, and with ENOENT if the directory\n * was removed meanwhile (an aged ownerless-lock reclaim by an older\n * release). Only a successful link holds the lock; on either failure\n * nothing is released, since nothing was acquired, and the caller retries.\n * On a filesystem without hard links (FAT/exFAT, some SMB mounts) the\n * owner file is created in place with an exclusive create instead, with\n * the same EEXIST/ENOENT outcomes. A reader may then briefly see it\n * incomplete; every release treats an owner file it cannot parse as a\n * held lock, and this release removes one only once it has aged (see\n * isAbandonedOwner).\n *\n * A profile deletion removes the profile directory once it has released its\n * lock, so `mkdir(.lock)` can see ENOENT; the directory is recreated (0700)\n * and the caller retries within its deadline, as for a first write to a new\n * profile.\n *\n * Only one owner.json can exist at the lock path, and it is removed only by\n * its holder's release or by recovery of an abandoned holder, so at most one\n * process holds the lock. Returns false when the lock is not acquired.\n */\nasync function publishProfileLock(profile: string, lockPath: string, token: string): Promise<boolean> {\n try {\n await mkdir(lockPath, { mode: PRIVATE_DIR_MODE });\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return false;\n if (!isErrno(error, \"ENOENT\")) throw error;\n await mkdir(profilePath(profile), { recursive: true, mode: PRIVATE_DIR_MODE });\n return false;\n }\n await waitForTestBarrier(TEST_LOCK_PUBLISH_BARRIER_DIR, profile);\n const ownerPath = join(lockPath, \"owner.json\");\n const staged = join(dirname(lockPath), `.lock-owner-${token}.tmp`);\n const owner = `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString(), token }, null, 2)}\\n`;\n try {\n await writeFile(staged, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n try {\n await link(staged, ownerPath);\n } catch (error) {\n if (!lacksHardLinks(error)) throw error;\n await writeFile(ownerPath, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n }\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\") || isErrno(error, \"ENOENT\")) return false;\n // Do not leave an ownerless lock behind for others to wait out. rmdir\n // removes only an empty directory; anyone who created it after ours went\n // away sees ENOENT on link and retries.\n await rmdir(lockPath).catch(() => undefined);\n throw error;\n } finally {\n await rm(staged, { force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Errors `link` reports on a filesystem without hard links: EPERM (Linux\n * FAT/exFAT), ENOTSUP/EOPNOTSUPP (macOS FAT/exFAT, SMB), ENOSYS, EISDIR\n * (libuv's code for Windows' ERROR_INVALID_FUNCTION on FAT32), and EMLINK\n * (too many links), for which the same fallback is just as correct.\n */\nconst NO_HARD_LINK_ERRORS = new Set([\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\", \"EISDIR\", \"EMLINK\"]);\n\nfunction lacksHardLinks(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n NO_HARD_LINK_ERRORS.has(String((error as { code?: unknown }).code));\n}\n\n/**\n * Releases the lock if `.lock/owner.json` is still this acquisition's. No\n * one else can put an owner record there while it exists (owners are only\n * published into a directory their own `mkdir` created, and recovery\n * removes only an abandoned holder's record), so the record read is the one\n * unlinked.\n */\nasync function releaseProfileLock(profile: string, lockPath: string, token: string): Promise<void> {\n const ownerPath = join(lockPath, \"owner.json\");\n const owner = await readJson<{ token?: unknown }>(ownerPath).catch(() => null);\n if (owner?.token !== token) return;\n await rm(ownerPath, { force: true });\n // `.lock` is empty from here until the rmdir; a contender that removes it\n // and creates its own meanwhile is not harmed: rmdir fails on its owner\n // file, or the contender's link sees ENOENT and retries. If a recoverer's\n // claim file is still inside, rmdir fails and that recoverer removes the\n // directory when it drops its claim.\n await waitForTestBarrier(TEST_LOCK_RELEASE_BARRIER_DIR, profile);\n await rmdir(lockPath).catch(() => undefined);\n}\n\n/**\n * Gives process-level contention tests an event-driven witness that a second\n * writer has reached an already-held lock. This deliberately has no effect\n * outside an explicit test environment, and only creates a new signal file\n * beneath TC_HOME; it never changes lock acquisition or release semantics.\n */\nasync function signalTestLockContention(profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n\n const configuredPath = process.env[TEST_LOCK_CONTENTION_SIGNAL_PATH];\n const configuredHome = process.env.TC_HOME;\n if (!configuredPath || !configuredHome) return;\n\n const home = resolve(configuredHome);\n const signalPath = resolve(configuredPath);\n const pathFromHome = relative(home, signalPath);\n if (\n pathFromHome === \"\" ||\n pathFromHome === \"..\" ||\n pathFromHome.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) ||\n pathFromHome.startsWith(\"../\") ||\n pathFromHome.startsWith(\"..\\\\\")\n ) {\n return;\n }\n\n await writeFile(signalPath, `${profile}\\n`, { encoding: \"utf8\", flag: \"wx\" })\n .catch(() => undefined);\n}\n\n/**\n * Reclaims a `.lock` with no owner record, while holding a turn. A\n * `.recover-*` claim may contain a live legacy owner's record moved by a\n * no-hard-links recoverer just before it crashed. Restore that record first;\n * only orphaned claims holding dead or malformed records can be removed.\n * Otherwise the directory must be older than the stale threshold: one left\n * by a crash, or by an older release, whose `.stale-*` / `.release-*` claim\n * files are removed too. owner.json is never unlinked, and the directory\n * itself is only `rmdir`ed, which succeeds only while it is empty.\n *\n * Holding a turn, no other process of this release reclaims concurrently.\n * That closes the race in which two reclaimers' age checks let the later one\n * remove a directory a 1.0.0-beta.16-or-older release had just created,\n * which holds the lock from its `mkdir`. That race remains only if a\n * 1.0.0-beta.17 … 1.0.1-beta.4 release reclaims at the same moment, or the\n * older process stays paused between its `mkdir` and its owner write for\n * longer than the stale threshold; recoveryFenced bounds how stale this\n * process's age check can be.\n */\nasync function recoverOwnerlessLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n let aged: boolean;\n try {\n const { mtimeMs } = await stat(lockPath);\n aged = Date.now() - mtimeMs >= staleAfterMs;\n } catch {\n return false;\n }\n const checkedAt = performance.now();\n await waitForTestBarrier(TEST_LOCK_OWNERLESS_BARRIER_DIR, profile);\n try {\n const entries = await readdir(lockPath);\n if (entries.includes(\"owner.json\")) return false;\n const onlyOrphanedClaims = entries.length > 0 && entries.every((entry) => RECOVERY_CLAIM.test(entry));\n if (!onlyOrphanedClaims && (!aged || recoveryFenced(checkedAt, staleAfterMs))) return false;\n for (const name of entries.filter((entry) => RECOVERY_CLAIM.test(entry))) {\n const claimPath = join(lockPath, name);\n if (await hasLiveRecoveryOwner(claimPath)) {\n // The claim keeps the directory in place. Only the original mkdir\n // owner could publish owner.json here; never overwrite that record.\n if (!await exists(join(lockPath, \"owner.json\"))) await rename(claimPath, join(lockPath, \"owner.json\"));\n return false;\n }\n await rm(claimPath, { force: true });\n }\n for (const name of entries.filter((entry) => ABANDONED_CLAIM.test(entry))) {\n await rm(join(lockPath, name), { force: true });\n }\n await rmdir(lockPath);\n } catch {\n return false;\n }\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/** A no-hard-links claim may contain a live owner's record moved before a crash. */\nasync function hasLiveRecoveryOwner(claimPath: string): Promise<boolean> {\n let contents: string;\n try {\n contents = await readFile(claimPath, \"utf8\");\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return false;\n throw error; // An I/O failure is not evidence that the holder is gone.\n }\n let owner: unknown;\n try {\n owner = JSON.parse(contents);\n } catch {\n return false;\n }\n const pid = typeof owner === \"object\" && owner !== null && \"pid\" in owner ? owner.pid : null;\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && isProcessAlive(pid);\n}\n\n/**\n * Whether an ownerless-reclaim decision made at `since` (a monotonic\n * timestamp) is too old to act on. The age check is only good for a while:\n * past half the stale threshold the reclaim starts over.\n */\nfunction recoveryFenced(since: number, staleAfterMs: number): boolean {\n return performance.now() - since >= staleAfterMs / 2;\n}\n\n/** Claim files of older releases' stale recovery and (up to 1.0.0-beta.16) release. */\nconst ABANDONED_CLAIM = /^\\.(?:release|stale)-[0-9a-f-]+\\.json$/;\n/**\n * Claim files of this release's stale recovery. Releases up to 1.0.1-beta.4\n * never remove them, which is what makes this recovery safe against them; a\n * recoverer that crashes leaves one that only a release with the turn lock\n * clears (see REFERENCE.md, \"Profile lock\").\n */\nconst RECOVERY_CLAIM = /^\\.recover-[0-9a-f-]+\\.json$/;\n/** Owner files staged by publishProfileLock beside `.lock`. */\nconst STAGED_OWNER = /^\\.lock-owner-[0-9a-f-]+\\.tmp$/;\n/**\n * Removes owner files a crashed acquirer staged beside `.lock`. A live\n * acquirer's staged file exists only for its write and link, so only files\n * older than the stale threshold are removed. Runs after a recovery, never\n * on the uncontended path.\n */\nasync function removeAgedOwnerFiles(lockPath: string, staleAfterMs: number): Promise<void> {\n const directory = dirname(lockPath);\n const names = await readdir(directory).catch(() => []);\n for (const name of names.filter((entry) => STAGED_OWNER.test(entry))) {\n const path = join(directory, name);\n const aged = await stat(path).then(({ mtimeMs }) => Date.now() - mtimeMs >= staleAfterMs, () => false);\n if (aged) await rm(path, { force: true }).catch(() => undefined);\n }\n}\n\n\n/**\n * Removes an abandoned owner record (see isAbandonedOwner) and its `.lock`,\n * while holding a turn, so no other process of this release recovers,\n * reclaims or acquires `.lock` meanwhile.\n *\n * The record is claimed first: hard-linked to `.recover-<uuid>.json`, and the\n * claim compared with the exact bytes read. A record that replaced the\n * observed one is left in place. While the claim is inside `.lock`, the\n * directory cannot be removed and recreated: older releases never remove a\n * `.recover-*` claim (they clean up only their own claim names), and other\n * processes of this release are kept out by the turn lock. So no other owner\n * record can appear in it, and the unlink of owner.json can only remove the\n * claimed, dead record. A live record is never unlinked or moved. `.lock`\n * itself is removed only after this process's claim is unlinked from it,\n * which proves it is still the dead holder's directory; if the claim cannot\n * be made, `.lock` is left alone (it may be a directory a 1.0.0-beta.16-or-\n * older writer just created, which it holds from that `mkdir`). No step\n * depends on how long this process takes.\n *\n * Without hard links (where 1.0.0-beta.17 … 1.0.1-beta.4 cannot run at all),\n * the record is renamed into the claim instead, and put back if it is not\n * the observed one: one a 1.0.0-beta.16-or-older process published after\n * recovering the same lock at the same moment. The claim keeps `.lock` held\n * meanwhile, so no second writer gets in, but if that holder releases\n * between the two renames, the put-back restores a released record, and\n * `.lock` stays held until that PID is gone and the record is 30 s old.\n */\nasync function recoverStaleLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n const ownerPath = join(lockPath, \"owner.json\");\n const observed = await readFile(ownerPath, \"utf8\").catch(() => null);\n if (observed === null) return recoverOwnerlessLock(profile, lockPath, staleAfterMs);\n if (!await isAbandonedOwner(observed, ownerPath, staleAfterMs)) return false;\n\n await waitForTestBarrier(TEST_LOCK_RECOVERY_BARRIER_DIR, profile);\n const claimPath = join(lockPath, `.recover-${randomUUID()}.json`);\n let moved = false;\n try {\n await link(ownerPath, claimPath);\n } catch (error) {\n // Gone or replaced already (another release recovered it): leave `.lock`.\n if (!lacksHardLinks(error)) return false;\n try {\n await rename(ownerPath, claimPath);\n moved = true;\n } catch {\n return false;\n }\n }\n if (moved) await waitForTestBarrier(TEST_LOCK_MOVED_BARRIER_DIR, profile);\n const sameInstance = await readFile(claimPath, \"utf8\").then((claimed) => claimed === observed, () => false);\n await waitForTestBarrier(TEST_LOCK_VERIFIED_BARRIER_DIR, profile);\n if (!sameInstance) {\n if (moved) {\n // No other owner.json can have appeared meanwhile: only a process\n // whose mkdir created this `.lock` publishes one, and it already has.\n await rename(claimPath, ownerPath).catch(() => undefined);\n } else {\n await unlink(claimPath).catch(() => undefined);\n }\n return false;\n }\n if (!moved) await rm(ownerPath, { force: true });\n await waitForTestBarrier(TEST_LOCK_CLAIM_BARRIER_DIR, profile);\n await waitForTestBarrier(TEST_LOCK_CLAIMED_BARRIER_DIR, profile);\n // Drop any claim a crashed recoverer of this release left, then this one.\n for (const name of (await readdir(lockPath).catch(() => [])).filter((entry) => RECOVERY_CLAIM.test(entry))) {\n if (join(lockPath, name) !== claimPath) await rm(join(lockPath, name), { force: true });\n }\n // Empty now, and still the dead holder's directory if this claim was in\n // it: remove it rather than leave an ownerless lock to age out.\n if (await unlink(claimPath).then(() => true, () => false)) await rmdir(lockPath).catch(() => undefined);\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/**\n * Whether an owner record (its exact bytes, read from `ownerPath`) is\n * abandoned: a holder's whose PID is gone, older than the stale threshold;\n * or, if it is not a complete record, a file older than that threshold.\n * Every release publishes complete records (by link or rename) except this\n * one's no-hard-link fallback, which writes in place while holding a turn;\n * so an incomplete record seen while holding a turn was left by a crash.\n */\nasync function isAbandonedOwner(observed: string, ownerPath: string, staleAfterMs: number): Promise<boolean> {\n let owner: unknown;\n try {\n owner = JSON.parse(observed);\n } catch {\n owner = null;\n }\n if (typeof owner === \"object\" && owner !== null && \"pid\" in owner) {\n return isStaleOwner(owner as { pid?: unknown; createdAt?: unknown }, staleAfterMs);\n }\n const modifiedAt = await stat(ownerPath).then(({ mtimeMs }) => mtimeMs, () => Number.NaN);\n return Date.now() - modifiedAt >= staleAfterMs;\n}\n\n/** Test-only rendezvous (NODE_ENV=test and the named barrier directory set). */\nasync function waitForTestBarrier(environmentName: string, profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n const barrierDirectory = process.env[environmentName];\n if (!barrierDirectory) return;\n await mkdir(barrierDirectory, { recursive: true });\n const readyPath = join(barrierDirectory, `ready-${process.pid}-${profile}`);\n await writeFile(readyPath, \"ready\\n\", { encoding: \"utf8\", flag: \"wx\" }).catch(() => undefined);\n const releasePath = join(barrierDirectory, \"release\");\n while (true) {\n try {\n await readFile(releasePath, \"utf8\");\n return;\n } catch {\n await sleep(1);\n }\n }\n}\n\nfunction isStaleOwner(\n owner: { pid?: unknown; createdAt?: unknown } | null,\n staleAfterMs: number,\n): boolean {\n const now = Date.now();\n const createdAt = typeof owner?.createdAt === \"string\"\n ? Date.parse(owner.createdAt)\n : Number.NaN;\n\n // Reclaim only a fully published lock whose owner PID is confirmed dead.\n // A lock without an owner record is handled by recoverOwnerlessLock: a\n // process holds the lock only once its owner.json is linked in.\n if (!Number.isFinite(createdAt) || now - createdAt < staleAfterMs) return false;\n if (typeof owner?.pid !== \"number\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n return false;\n }\n return !isProcessAlive(owner.pid);\n}\n\n/** Whether `path` exists. Only ENOENT/ENOTDIR mean it does not; other errors are thrown. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, \"ENOENT\") || isErrno(error, \"ENOTDIR\")) return false;\n throw error;\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return !isErrno(error, \"ESRCH\");\n }\n}\n\nfunction validateProfileName(profile: string): string {\n if (\n !profile ||\n profile === \".\" ||\n profile === \"..\" ||\n profile.includes(\"/\") ||\n profile.includes(\"\\\\\") ||\n profile.includes(\"\\0\")\n ) {\n throw new TypeError(\"Profile names must be non-empty path segments.\");\n }\n return profile;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n (error as { code?: unknown }).code === code;\n}\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nexport { DEFAULT_PROFILE };\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/sdk-core\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n evaluateOperationAuthority,\n evaluateAuthority,\n} from \"./authority.js\";\nimport type { OperationSpaceResolver } from \"./authority.js\";\nimport type {\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\nimport { readAuthRequests, updateProfileStore } from \"./state.js\";\n\nexport { evaluateAuthority } from \"./authority.js\";\n\nconst THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1_000;\n\n/** The shared wire schema for SDK PermissionEntry values, including signed ReCap caveats. */\nexport const PermissionEntrySchema = z.object({\n service: z.string().min(1),\n space: z.string().min(1).optional(),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n caveats: z.array(z.record(z.unknown())).optional(),\n skipPrefix: z.boolean().optional(),\n expiry: z.string().min(1).optional(),\n description: z.string().optional(),\n}).strict();\n\nconst CommandSchema = z.object({\n argv: z.array(z.string()).min(1),\n cwd: z.string().min(1),\n}).strict();\n\nconst LegacyPermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string(),\n sessionDid: z.string().min(1),\n requested: z.array(PermissionEntrySchema),\n requestedExpiry: z.union([z.string(), z.number().finite()]).optional(),\n}).strict();\n\nconst PortableDelegationSchema: z.ZodType<Record<string, unknown>> = z.lazy(() => z.object({\n cid: z.string().min(1),\n spaceId: z.string().min(1),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n delegateDID: z.string().min(1),\n ownerAddress: z.string().min(1),\n chainId: z.number().int().positive(),\n expiry: z.union([z.string().datetime({ offset: true }), z.date()]),\n delegationHeader: z.object({ Authorization: z.string().min(1) }).strict(),\n host: z.string().min(1).optional(),\n disableSubDelegation: z.boolean().optional(),\n publicDelegation: PortableDelegationSchema.optional(),\n resources: z.array(PermissionEntrySchema).optional(),\n}).passthrough());\n\n/** Canonical wire-format v1 request retained for CLI and OpenKey compatibility. */\nexport const PermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string().min(1), z.number().finite()]).optional(),\n requested: z.array(PermissionEntrySchema),\n command: CommandSchema.optional(),\n}).strict();\n\n/** Canonical structured v1 delegation import accepted by the auth operation. */\nexport const DelegationImportArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.delegation\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n delegationCid: z.string().min(1).optional(),\n delegation: PortableDelegationSchema,\n // This field is presentation metadata only. A later import operation obtains\n // effective permissions from validated, installed delegation authority.\n permissions: z.array(PermissionEntrySchema).optional(),\n expiry: z.string().datetime({ offset: true }).optional(),\n prompted: z.boolean().optional(),\n}).strict();\n\n/**\n * The stored request an imported delegation was checked against, persisted\n * with the delegation. Its fields are exactly the request artifact's, so\n * replay accepts every binding import can write.\n */\nexport const DelegationRequestBindingSchema = PermissionRequestArtifactSchema\n .pick({ requestId: true, requested: true })\n .strict();\nexport type DelegationRequestBinding = z.infer<typeof DelegationRequestBindingSchema>;\n\nexport type PermissionRequestArtifact = z.infer<typeof PermissionRequestArtifactSchema>;\nexport type DelegationImportArtifact = z.infer<typeof DelegationImportArtifactSchema>;\n/** The minimal public node-sdk request shape accepted by the legacy reader. */\nexport type LegacyPermissionRequestArtifact = z.infer<typeof LegacyPermissionRequestArtifactSchema>;\nexport type ArtifactClock = () => Date;\nexport type RequestIdSource = () => string;\n\n/** Invocation-owned values used to safely complete a legacy request record. */\nexport interface LegacyRequestContext {\n readonly profile: string;\n readonly host: string;\n readonly sessionDid: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly now?: Date;\n}\n\nexport interface PermissionRequestIdentityInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly host: string;\n readonly missing: readonly PermissionEntry[];\n}\n\nexport interface BuildPermissionRequestArtifactInput extends PermissionRequestIdentityInput {\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly requestedExpiry?: string | number;\n readonly command?: { readonly argv: readonly string[]; readonly cwd: string };\n readonly now?: ArtifactClock;\n readonly createRequestId?: RequestIdSource;\n}\n\nexport interface CreateOrReusePermissionRequestInput extends BuildPermissionRequestArtifactInput {\n readonly granted: readonly PermissionEntry[];\n /** Owner-aware identity resolver used by registered operation callers. */\n readonly resolveSpace?: OperationSpaceResolver;\n readonly replace?: boolean;\n}\n\nexport type PermissionRequestResolution =\n | Readonly<{ status: \"satisfied\"; reused: false }>\n | Readonly<{ status: \"created\"; reused: boolean; request: PermissionRequestArtifact }>;\n\n/** Parses a request artifact without accepting a newer wire format as v1. */\nexport function validatePermissionRequestArtifact(value: unknown): PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.parse(value);\n}\n\n/** Parses a structured active-session import artifact without accepting a newer wire format as v1. */\nexport function validateDelegationImportArtifact(value: unknown): DelegationImportArtifact {\n return DelegationImportArtifactSchema.parse(value);\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.safeParse(value).success;\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n return DelegationImportArtifactSchema.safeParse(value).success;\n}\n\nfunction normalizeLegacyPermissionRequest(\n value: LegacyPermissionRequestArtifact,\n context: LegacyRequestContext,\n): PermissionRequestArtifact {\n if (principal(value.sessionDid) !== principal(context.sessionDid)) {\n throw new TypeError(\"Stored authority request belongs to a different session.\");\n }\n const createdAt = context.now ?? new Date();\n if (Number.isNaN(createdAt.getTime())) {\n throw new TypeError(\"The legacy authority request has no usable creation time.\");\n }\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: value.requestId,\n createdAt: createdAt.toISOString(),\n profile: context.profile,\n posture: context.posture,\n operatorType: context.operatorType,\n host: context.host,\n sessionDid: context.sessionDid,\n ...(context.ownerDid === undefined ? {} : { ownerDid: context.ownerDid }),\n ...(context.spaceId === undefined ? {} : { spaceId: context.spaceId }),\n ...(value.requestedExpiry === undefined ? {} : { requestedExpiry: value.requestedExpiry }),\n requested: canonicalizeCapabilities(value.requested),\n } as PermissionRequestArtifact;\n}\n\nfunction principal(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\n/**\n * Stable exact identity used only for request reuse. It binds a request to its\n * selected profile, active session DID, host, and canonical missing subset.\n */\nexport function createPermissionRequestIdentity(input: PermissionRequestIdentityInput): string {\n return JSON.stringify({\n profile: input.profile,\n sessionDid: input.sessionDid,\n host: input.host,\n missing: canonicalizeCapabilities(input.missing),\n });\n}\n\n/** Builds an on-disk-compatible v1 record. Omitted values stay omitted. */\nexport function buildPermissionRequestArtifact(\n input: BuildPermissionRequestArtifactInput,\n): PermissionRequestArtifact {\n const now = input.now ?? (() => new Date());\n const createdAt = now();\n if (Number.isNaN(createdAt.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n const requested = canonicalizeCapabilities(input.missing);\n if (requested.length === 0) throw new TypeError(\"Permission requests require at least one missing capability.\");\n\n return validatePermissionRequestArtifact({\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: input.createRequestId?.() ?? defaultRequestId(createdAt),\n createdAt: createdAt.toISOString(),\n profile: input.profile,\n posture: input.posture,\n operatorType: input.operatorType,\n host: input.host,\n sessionDid: input.sessionDid,\n ...(input.ownerDid !== undefined ? { ownerDid: input.ownerDid } : {}),\n ...(input.spaceId !== undefined ? { spaceId: input.spaceId } : {}),\n ...(input.requestedExpiry !== undefined ? { requestedExpiry: input.requestedExpiry } : {}),\n requested,\n ...(input.command !== undefined\n ? { command: { argv: [...input.command.argv], cwd: input.command.cwd } }\n : {}),\n });\n}\n\n/** Reads only valid canonical v1 records and refuses malformed stored artifacts. */\nexport async function listPermissionRequests(\n profile: string,\n context?: LegacyRequestContext,\n): Promise<PermissionRequestArtifact[]> {\n const records: PermissionRequestArtifact[] = [];\n for (const value of await readAuthRequests<unknown>(profile)) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (context !== undefined && principal(canonical.data.sessionDid) !== principal(context.sessionDid)) {\n continue;\n }\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (context === undefined) {\n throw new TypeError(\"Legacy authority requests require the selected invocation context.\");\n }\n if (principal(legacy.data.sessionDid) !== principal(context.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, context));\n }\n return records;\n}\n\nexport async function findPermissionRequest(\n profile: string,\n requestId: string,\n identity: Pick<PermissionRequestIdentityInput, \"sessionDid\" | \"host\"> &\n Partial<Omit<LegacyRequestContext, \"profile\" | \"host\" | \"sessionDid\">>,\n): Promise<PermissionRequestArtifact | null> {\n const records = await listPermissionRequests(profile, {\n profile,\n host: identity.host,\n sessionDid: identity.sessionDid,\n posture: identity.posture ?? \"delegate-session\",\n operatorType: identity.operatorType ?? \"human\",\n ...(identity.ownerDid === undefined ? {} : { ownerDid: identity.ownerDid }),\n ...(identity.spaceId === undefined ? {} : { spaceId: identity.spaceId }),\n });\n return records.find((record) =>\n record.requestId === requestId &&\n record.sessionDid === identity.sessionDid &&\n record.host === identity.host,\n ) ?? null;\n}\n\n/**\n * Atomically returns the newest identical unresolved request, or writes a new\n * v1 record. Retention, stale-session pruning, covered-record pruning, and\n * partial-grant supersession all happen in the same existing profile lock.\n */\nexport async function createOrReusePermissionRequest(\n input: CreateOrReusePermissionRequestInput,\n): Promise<PermissionRequestResolution> {\n // Registered operations already computed this exact missing set during\n // canonical preflight. Do not recompute it with the legacy global matcher:\n // that matcher intentionally treats same-named short/full spaces as equal.\n const missing = input.resolveSpace === undefined\n ? evaluateAuthority(input.granted, input.missing).missing\n : canonicalizeCapabilities(input.missing);\n const now = input.now ?? (() => new Date());\n const observedNow = now();\n if (Number.isNaN(observedNow.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n\n return updateProfileStore<unknown, PermissionRequestResolution>(\n input.profile,\n \"auth-requests\",\n (rawRecords) => {\n const records: PermissionRequestArtifact[] = [];\n for (const value of rawRecords) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (principal(canonical.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (principal(legacy.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, {\n profile: input.profile,\n host: input.host,\n sessionDid: input.sessionDid,\n posture: input.posture,\n operatorType: input.operatorType,\n ...(input.ownerDid === undefined ? {} : { ownerDid: input.ownerDid }),\n ...(input.spaceId === undefined ? {} : { spaceId: input.spaceId }),\n now: observedNow,\n }));\n }\n const retained = prunePermissionRequests(records, {\n profile: input.profile,\n sessionDid: input.sessionDid,\n granted: input.granted,\n resolveSpace: input.resolveSpace,\n now: observedNow,\n });\n\n if (missing.length === 0) {\n return { records: retained, result: { status: \"satisfied\", reused: false } };\n }\n\n const identity = createPermissionRequestIdentity({ ...input, missing });\n const withoutSuperseded = retained.filter((record) => !isSupersededBy(record, input, missing));\n const equivalent = newestEquivalentRequest(withoutSuperseded, identity);\n if (equivalent !== undefined && input.replace !== true) {\n return { records: withoutSuperseded, result: { status: \"created\", reused: true, request: equivalent } };\n }\n\n const next = withoutSuperseded.filter((record) =>\n input.replace !== true || permissionRequestArtifactIdentity(record) !== identity,\n );\n const request = buildPermissionRequestArtifact({ ...input, missing, now: () => observedNow });\n return {\n records: [...next, request],\n result: { status: \"created\", reused: false, request },\n };\n },\n );\n}\n\nexport interface PrunePermissionRequestsInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly granted: readonly PermissionEntry[];\n readonly resolveSpace?: OperationSpaceResolver;\n readonly now: Date;\n}\n\n/** Pure retention policy used by the locked persistence operation. */\nexport function prunePermissionRequests(\n records: readonly PermissionRequestArtifact[],\n input: PrunePermissionRequestsInput,\n): PermissionRequestArtifact[] {\n const cutoff = input.now.getTime() - THIRTY_DAYS_MS;\n return records.filter((record) => {\n const createdAt = Date.parse(record.createdAt);\n if (!Number.isFinite(createdAt) || createdAt < cutoff) return false;\n if (record.profile === input.profile && principal(record.sessionDid) !== principal(input.sessionDid)) return false;\n // Empty request arrays are historical CLI records. They carry no\n // authority, but remain readable and are retained byte-for-byte by the\n // shared format-1 writer for compatibility.\n if (record.requested.length === 0) return true;\n return !evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).satisfied;\n });\n}\n\nfunction newestEquivalentRequest(\n records: readonly PermissionRequestArtifact[],\n identity: string,\n): PermissionRequestArtifact | undefined {\n let newest: PermissionRequestArtifact | undefined;\n for (const record of records) {\n if (permissionRequestArtifactIdentity(record) !== identity) continue;\n if (newest === undefined || record.createdAt >= newest.createdAt) newest = record;\n }\n return newest;\n}\n\nfunction isSupersededBy(\n record: PermissionRequestArtifact,\n input: CreateOrReusePermissionRequestInput,\n missing: readonly PermissionEntry[],\n): boolean {\n if (\n record.profile !== input.profile ||\n record.sessionDid !== input.sessionDid ||\n record.host !== input.host\n ) {\n return false;\n }\n const remaining = evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).missing;\n return remaining.length > 0 &&\n permissionRequestArtifactIdentity(record) !==\n createPermissionRequestIdentity({ ...input, missing }) &&\n createPermissionRequestIdentity({ ...input, missing: remaining }) ===\n createPermissionRequestIdentity({ ...input, missing });\n}\n\nfunction permissionRequestArtifactIdentity(record: PermissionRequestArtifact): string {\n return createPermissionRequestIdentity({\n profile: record.profile,\n sessionDid: record.sessionDid,\n host: record.host,\n missing: record.requested,\n });\n}\n\nfunction evaluateArtifactAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n) {\n return resolveSpace === undefined\n ? evaluateAuthority(granted, required)\n : evaluateOperationAuthority(granted, required, resolveSpace);\n}\n\nfunction defaultRequestId(now: Date): string {\n return `req_${now.getTime().toString(36)}_${randomUUID().replace(/-/g, \"\")}`;\n}\n","// Namespace-shaped so modules that bundle this one stay compatible with\n// lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\n\nimport { OperationInvocationError, operationError } from \"./errors.js\";\n\nconst DEFAULT_SECRETS_SPACE = \"secrets\";\nconst SECRET_MANAGER_BASE_URL = \"https://secrets.tinycloud.xyz\";\nconst SECRET_NAME_RE = /^[A-Z][A-Z0-9_]*$/;\nconst RESERVED_SECRET_SCOPES = new Set([\"default\", \"global\"]);\n\nexport interface SecretsGetInput {\n readonly name: string;\n readonly scope?: string;\n readonly space?: string;\n}\n\nexport interface SecretReference {\n readonly name: string;\n readonly scope?: string;\n readonly space: string;\n readonly vaultKey: string;\n readonly permissionPath: string;\n}\n\nexport function normalizeSecretsGetInput(\n input: SecretsGetInput,\n): SecretsGetInput {\n const reference = resolveSecretReference(input);\n return {\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n // Omission is meaningful: the CLI's default is the literal `secrets`\n // space, while an explicitly supplied short name is resolved later against\n // the authenticated identity.\n ...(input.space === undefined ? {} : { space: reference.space }),\n };\n}\n\n/** Resolves the one canonical backing key/path used by planning and setup. */\nexport function resolveSecretReference(\n input: SecretsGetInput,\n): SecretReference {\n const name = input.name.trim();\n if (!SECRET_NAME_RE.test(name)) {\n throw invalidSecretInput();\n }\n\n const scope = canonicalizeSecretScope(input.scope);\n const space = normalizeSecretsSpace(input.space);\n const vaultKey = scope === undefined\n ? `secrets/${name}`\n : `secrets/scoped/${scope}/${name}`;\n\n return {\n name,\n ...(scope === undefined ? {} : { scope }),\n space,\n vaultKey,\n permissionPath: `vault/${vaultKey}`,\n };\n}\n\n/**\n * Resolve the operation's space against the authenticated identity. The\n * public short-name contract remains `secrets`, while an authenticated\n * operation uses its owner-exact URI for the actual read boundary.\n */\nexport function resolveSecretReferenceForOperation(\n input: SecretsGetInput,\n node: unknown,\n ownerSpace?: string,\n): SecretReference {\n const reference = resolveSecretReference(input);\n if (input.space === undefined && ownerSpace === undefined) return reference;\n return {\n ...reference,\n space: resolveOperationSpace(reference.space, node, ownerSpace),\n };\n}\n\n/** Creates the one owner-aware resolver shared by operation matching paths. */\nexport function operationSpaceResolver(\n node: unknown,\n ownerSpace?: string,\n): (space: string) => string {\n return (space) => resolveOperationSpace(space, node, ownerSpace);\n}\n\nfunction resolveOperationSpace(space: string, node: unknown, ownerSpace?: string): string {\n if (space.startsWith(\"tinycloud:\")) return canonicalizeSpaceUri(space);\n\n const ownerSpaceId = ownerSpace === undefined ? undefined : ownedSpaceForName(ownerSpace, space);\n if (ownerSpaceId !== undefined) return canonicalizeSpaceUri(ownerSpaceId);\n\n const candidate = node as {\n resolveOwnedSpace?: (spaceName: string) => unknown;\n spaceId?: unknown;\n address?: unknown;\n did?: unknown;\n };\n try {\n const resolved = candidate.resolveOwnedSpace?.(space);\n if (typeof resolved === \"string\" && resolved.length > 0) {\n return canonicalizeSpaceUri(resolved);\n }\n } catch {\n // Continue to the identity-derived resolver below.\n }\n\n // A restored delegate session carries the owner's primary space even though\n // node.did is the delegate/session principal. This is the same owner\n // identity used by the CLI space resolver.\n if (typeof candidate.spaceId === \"string\") {\n const resolved = ownedSpaceForName(candidate.spaceId, space);\n if (resolved !== undefined) return canonicalizeSpaceUri(resolved);\n }\n\n const did = typeof candidate.did === \"string\" ? candidate.did : undefined;\n const pkh = did === undefined ? null : nodeSdk.parsePkhDid(did);\n if (pkh === null) {\n throw invalidSecretInput();\n }\n return nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, space);\n}\n\nfunction ownedSpaceForName(ownerSpace: string, name: string): string | undefined {\n const parsed = nodeSdk.parseSpaceUri(ownerSpace);\n if (parsed === null) return undefined;\n try {\n const pkh = nodeSdk.parsePkhDid(parsed.owner);\n return pkh === null ? undefined : nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, name);\n } catch {\n return undefined;\n }\n}\n\nfunction canonicalizeSpaceUri(space: string): string {\n const parts = space.split(\":\");\n const name = parts.at(-1);\n if (parts.length < 3 || name === undefined || name === \"\") {\n throw invalidSecretInput();\n }\n // EIP-155 address casing is interchangeable only in the repository's\n // anchored PKH space form. Other TinyCloud space/DID syntaxes are opaque\n // method-specific identifiers and must remain byte-for-byte unchanged.\n const pkh = space.match(\n /^tinycloud:pkh:eip155:(\\d+):(0x[0-9a-fA-F]{40}):([^:]+)$/,\n );\n if (pkh !== null) {\n return `tinycloud:pkh:eip155:${pkh[1]}:${nodeSdk.canonicalizeAddress(pkh[2]!).toLowerCase()}:${pkh[3]}`;\n }\n return space;\n}\n\n/**\n * Builds a setup action URL without ever accepting a secret value. It opens\n * Secret Manager's app with the secret's name (and scope) filled in.\n */\nexport function buildSecretSetupUrl(reference: SecretReference): string {\n const parameters = [\n [\"secret\", reference.name],\n ...(reference.scope === undefined ? [] : [[\"scope\", reference.scope] as const]),\n [\"space\", reference.space],\n ] as const;\n const query = parameters\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return `${SECRET_MANAGER_BASE_URL}/app?${query}`;\n}\n\nfunction canonicalizeSecretScope(scope: string | undefined): string | undefined {\n if (scope === undefined || scope === \"\") return undefined;\n\n const trimmed = scope.trim();\n if (trimmed === \"\") throw invalidSecretInput();\n\n const canonical = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n if (canonical === \"\" || RESERVED_SECRET_SCOPES.has(canonical)) {\n throw invalidSecretInput();\n }\n return canonical;\n}\n\nfunction normalizeSecretsSpace(space: string | undefined): string {\n if (space === undefined || space === \"\") return DEFAULT_SECRETS_SPACE;\n\n if (space.startsWith(\"tinycloud:\")) {\n const parts = space.split(\":\");\n if (parts.length < 3 || parts.at(-1) === undefined || parts.at(-1) === \"\") {\n throw invalidSecretInput();\n }\n return `tinycloud:${parts.slice(1, -1).join(\":\")}:${parts.at(-1)}`;\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(space)) throw invalidSecretInput();\n return space;\n}\n\nfunction invalidSecretInput(): OperationInvocationError {\n return new OperationInvocationError(\n operationError(\"INPUT_INVALID\", \"The secret reference is invalid.\"),\n );\n}\n","import * as nodeSdk from \"@tinycloud/node-sdk\";\nimport type {\n PermissionEntry,\n PortableDelegation,\n RuntimeDelegationActivator,\n} from \"@tinycloud/node-sdk\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n canonicalizeOperationCapabilities,\n delegationWithinRequest,\n evaluateAuthority,\n validateExactCapabilities,\n} from \"../authority.js\";\nimport {\n createOrReusePermissionRequest,\n DelegationImportArtifactSchema,\n findPermissionRequest,\n listPermissionRequests,\n PermissionEntrySchema,\n type DelegationImportArtifact,\n type DelegationRequestBinding,\n type PermissionRequestArtifact,\n} from \"../artifacts.js\";\nimport type {\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n RuntimeOperationContext,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { operationError } from \"../errors.js\";\nimport { lookupOperation } from \"../registry.js\";\nimport {\n readSession,\n readProfile,\n updateProfileStore,\n} from \"../state.js\";\nimport { operationSpaceResolver } from \"../secrets.js\";\n\ntype CapabilitiesInput = Record<never, never>;\ntype CapabilitiesOutput = { readonly capabilities: readonly PermissionEntry[] };\ntype AuthRequestInput =\n | Readonly<{ requestId: string }>\n | Readonly<{\n operationId: string;\n operationVersion: number;\n input?: unknown;\n }>;\ntype AuthRequestOutput = Readonly<{\n missing: readonly PermissionEntry[];\n request?: PermissionRequestArtifact;\n}>;\ntype AuthImportOutput = Readonly<{\n cid: string;\n effectivePermissions: readonly PermissionEntry[];\n expiry: string;\n audience: string;\n host: string;\n activated: true;\n alreadyPresent: boolean;\n}>;\n\nconst EmptyInputSchema: z.ZodType<CapabilitiesInput> = z.object({}).strict();\nconst CapabilitiesOutputSchema: z.ZodType<CapabilitiesOutput> = z.object({\n capabilities: z.array(PermissionEntrySchema),\n}).strict();\nconst AuthRequestInputSchema: z.ZodType<AuthRequestInput> = z.union([\n z.object({ requestId: z.string().min(1) }).strict(),\n z.object({\n operationId: z.string().min(1),\n operationVersion: z.number().int().positive(),\n input: z.unknown(),\n }).strict().superRefine((value, issue) => {\n if (!Object.prototype.hasOwnProperty.call(value, \"input\")) {\n issue.addIssue({ code: z.ZodIssueCode.custom, message: \"Operation input is required.\" });\n }\n }),\n]);\nconst PermissionRequestOutputSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string(), z.number()]).optional(),\n requested: z.array(PermissionEntrySchema).min(1),\n command: z.object({ argv: z.array(z.string()).min(1), cwd: z.string().min(1) }).strict().optional(),\n}).strict();\nconst AuthRequestOutputSchema: z.ZodType<AuthRequestOutput> = z.object({\n missing: z.array(PermissionEntrySchema),\n request: PermissionRequestOutputSchema.optional(),\n}).strict();\nconst AuthImportOutputSchema: z.ZodType<AuthImportOutput> = z.object({\n cid: z.string().min(1),\n effectivePermissions: z.array(PermissionEntrySchema),\n expiry: z.string().datetime({ offset: true }),\n audience: z.string().min(1),\n host: z.string().min(1),\n activated: z.literal(true),\n alreadyPresent: z.boolean(),\n}).strict();\n\nconst AUTH_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\nconst AUTH_EXPOSURE: OperationExposure = {\n cli: { status: \"required\" },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\nconst AUTH_CAPABILITIES_SENSITIVITY: OperationSensitivity = { input: [], output: [] };\nconst AUTH_REQUEST_SENSITIVITY: OperationSensitivity = { input: [\"/input\"], output: [] };\nconst AUTH_IMPORT_SENSITIVITY: OperationSensitivity = { input: [\"\"], output: [] };\n\n/**\n * Internal I2 auth definitions. Registry integration intentionally owns their\n * registration and root exports remain limited to invokeOperation.\n */\ntype AuthOperationDefinition =\n | OperationDefinition<CapabilitiesInput, CapabilitiesOutput>\n | OperationDefinition<AuthRequestInput, AuthRequestOutput>\n | OperationDefinition<DelegationImportArtifact, AuthImportOutput>;\n\nexport const authOperationDefinitions: readonly AuthOperationDefinition[] = [\n {\n id: \"tinycloud.auth.capabilities\",\n version: 1,\n title: \"TinyCloud active capabilities\",\n description: \"Inspect validated active runtime capabilities for the selected profile.\",\n input: EmptyInputSchema,\n output: CapabilitiesOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTH_POSTURES,\n exposure: AUTH_EXPOSURE,\n sensitivity: AUTH_CAPABILITIES_SENSITIVITY,\n authority: async () => [],\n execute: async (context: OperationContext): Promise<OperationExecutionOutcome<CapabilitiesOutput>> => ({\n status: \"ok\",\n output: {\n capabilities: canonicalizeCapabilities(\n (context.runtime?.granted ?? []) as unknown as PermissionEntry[],\n ),\n },\n }),\n },\n {\n id: \"tinycloud.auth.request\",\n version: 1,\n title: \"Request TinyCloud capabilities\",\n description: \"Create or recover an exact stored request from a canonical operation planner.\",\n input: AuthRequestInputSchema,\n output: AuthRequestOutputSchema,\n effects: [\"local_write\"],\n runtime: \"authenticated\",\n postures: AUTH_POSTURES,\n exposure: AUTH_EXPOSURE,\n sensitivity: AUTH_REQUEST_SENSITIVITY,\n authority: async () => [],\n execute: (context: OperationContext, input: AuthRequestInput) => requestExactAuthority(\n context as RuntimeOperationContext,\n input,\n ),\n },\n {\n id: \"tinycloud.auth.import\",\n version: 1,\n title: \"Import TinyCloud delegation\",\n description: \"Validate, activate, and persist one request-bound runtime delegation.\",\n input: DelegationImportArtifactSchema,\n output: AuthImportOutputSchema,\n effects: [\"local_write\"],\n runtime: \"authenticated\",\n postures: AUTH_POSTURES,\n exposure: AUTH_EXPOSURE,\n sensitivity: AUTH_IMPORT_SENSITIVITY,\n invalidInputErrorCode: \"DELEGATION_ARTIFACT_INVALID\",\n authority: async () => [],\n execute: (context: OperationContext, input: DelegationImportArtifact) => importRequestBoundDelegation(\n context as RuntimeOperationContext,\n input,\n ),\n },\n];\n\nasync function requestExactAuthority(\n context: RuntimeOperationContext,\n input: AuthRequestInput,\n): Promise<OperationExecutionOutcome<AuthRequestOutput>> {\n const sessionDid = context.summary.sessionDid;\n if (sessionDid === undefined) return missingSession();\n\n if (\"requestId\" in input) {\n try {\n const request = await findPermissionRequest(context.summary.profile, input.requestId, {\n sessionDid,\n host: context.summary.host,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n });\n if (request === null) {\n return invalidInput(\"The requested authority request is not available for this session.\");\n }\n if (request.profile !== context.summary.profile) {\n return invalidInput(\"The requested authority request is not available for this profile.\");\n }\n const required = exactCapabilities(request.requested);\n if (required === undefined) {\n return operationFailure(\n \"PERMISSION_HINT_INVALID\",\n \"The stored authority request has invalid capabilities.\",\n );\n }\n const evaluation = evaluateAuthority(\n context.runtime.granted as unknown as PermissionEntry[],\n required,\n );\n if (evaluation.satisfied) {\n return { status: \"ok\", output: { missing: [] } };\n }\n const narrowed = await createOrReusePermissionRequest({\n profile: context.summary.profile,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n host: context.summary.host,\n sessionDid,\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n missing: evaluation.missing,\n granted: context.runtime.granted as unknown as PermissionEntry[],\n });\n if (narrowed.status === \"satisfied\") return { status: \"ok\", output: { missing: [] } };\n return { status: \"ok\", output: { missing: evaluation.missing, request: narrowed.request } };\n } catch {\n return internalFailure();\n }\n }\n\n const target = lookupOperation(input.operationId, input.operationVersion);\n if (target.status === \"operation_not_found\") {\n return operationFailure(\"OPERATION_NOT_FOUND\", \"The requested operation is not registered.\");\n }\n if (target.status === \"operation_version_unsupported\") {\n return operationFailure(\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"The requested operation version is not supported.\",\n );\n }\n if (target.definition.id === \"tinycloud.auth.request\") {\n return invalidInput(\"Authority requests cannot plan themselves.\");\n }\n if (!target.definition.postures.includes(context.summary.posture)) {\n return operationFailure(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The active profile posture cannot execute this operation.\",\n );\n }\n\n const parsed = target.definition.input.safeParse(input.input);\n if (!parsed.success) return invalidInput(\"The operation input is invalid.\");\n\n try {\n const planned = await target.definition.authority(context, parsed.data);\n const required = exactCapabilities(planned);\n if (required === undefined) {\n return operationFailure(\n \"PERMISSION_HINT_INVALID\",\n \"The operation returned an invalid permission requirement.\",\n );\n }\n const evaluation = evaluateAuthority(\n context.runtime.granted as unknown as PermissionEntry[],\n required,\n );\n if (evaluation.satisfied) {\n // Do not call the artifact store: even a retention-only write is not an\n // allowed side effect for an already-authorized request.\n return { status: \"ok\", output: { missing: [] } };\n }\n const request = await createOrReusePermissionRequest({\n profile: context.summary.profile,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n host: context.summary.host,\n sessionDid,\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n missing: evaluation.missing,\n granted: context.runtime.granted as unknown as PermissionEntry[],\n });\n if (request.status === \"satisfied\") return { status: \"ok\", output: { missing: [] } };\n return {\n status: \"ok\",\n output: { missing: evaluation.missing, request: request.request },\n };\n } catch {\n return internalFailure();\n }\n}\n\nasync function importRequestBoundDelegation(\n context: RuntimeOperationContext,\n input: DelegationImportArtifact,\n): Promise<OperationExecutionOutcome<AuthImportOutput>> {\n try {\n const rawDelegation = input.delegation as unknown as Record<string, unknown>;\n if (typeof rawDelegation.delegateDID !== \"string\") return invalidDelegation();\n if (context.summary.sessionDid !== undefined && !samePrincipal(\n rawDelegation.delegateDID,\n context.summary.sessionDid,\n )) {\n return audienceMismatch(context.summary.sessionDid, rawDelegation.delegateDID);\n }\n const initial = await importState(context, input.requestId);\n if (!initial.ok) return initial.result;\n const { request, sessionDid, host } = initial;\n const explicitHost = rawDelegation.host;\n if (explicitHost !== undefined && typeof explicitHost !== \"string\") {\n return invalidDelegation();\n }\n if (typeof explicitHost === \"string\" && normalizeHost(explicitHost) !== normalizeHost(host)) {\n return hostMismatch(host, explicitHost);\n }\n const expiry = normalizeExpiry(rawDelegation.expiry);\n if (expiry === undefined) return invalidDelegation();\n if (expiry.getTime() <= Date.now()) return expiredDelegation();\n if (input.delegationCid !== undefined && input.delegationCid !== rawDelegation.cid) {\n return invalidDelegation();\n }\n if (typeof rawDelegation.delegateDID !== \"string\" || !samePrincipal(rawDelegation.delegateDID, sessionDid)) {\n return audienceMismatch(sessionDid, String(rawDelegation.delegateDID ?? \"unknown\"));\n }\n\n const delegation = {\n ...rawDelegation,\n expiry,\n host: explicitHost ?? host,\n } as PortableDelegation;\n let activated: Awaited<ReturnType<typeof nodeSdk.activateValidatedRuntimeDelegation>>;\n try {\n activated = await nodeSdk.activateValidatedRuntimeDelegation(\n context.runtime.node as RuntimeDelegationActivator,\n delegation,\n { host },\n );\n } catch {\n return operationFailure(\n \"DELEGATION_REJECTED\",\n \"The delegation was rejected by the TinyCloud runtime.\",\n );\n }\n\n const effectivePermissions = canonicalizeCapabilities(activated.effectivePermissions);\n const resolveSpace = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n );\n if (!delegationWithinRequest(request.requested, effectivePermissions, resolveSpace)) {\n return operationFailure(\n \"DELEGATION_REJECTED\",\n \"The delegation exceeds the stored authority request.\",\n );\n }\n\n try {\n return await updateProfileStore<Record<string, unknown>, OperationExecutionOutcome<AuthImportOutput>>(\n context.summary.profile,\n \"additional-delegations\",\n async (records) => {\n const state = await importState(context, input.requestId);\n if (!state.ok) return { records, result: state.result };\n if (state.sessionDid !== sessionDid || normalizeHost(state.host) !== normalizeHost(host)) {\n return {\n records,\n result: audienceMismatch(state.sessionDid, sessionDid),\n };\n }\n if (state.request.profile !== context.summary.profile ||\n !samePrincipal(state.request.sessionDid, sessionDid) ||\n normalizeHost(state.request.host) !== normalizeHost(host) ||\n JSON.stringify(canonicalizeOperationCapabilities(state.request.requested, resolveSpace)) !==\n JSON.stringify(canonicalizeOperationCapabilities(request.requested, resolveSpace))) {\n return {\n records,\n result: operationFailure(\n \"DELEGATION_ARTIFACT_INVALID\",\n \"The delegation does not reference a current stored request.\",\n ),\n };\n }\n // Replay re-checks the delegation against this binding; the stored\n // request itself may later be pruned.\n const record = {\n delegation: activated.delegation,\n permissions: activated.effectivePermissions,\n authorityRequest: {\n requestId: request.requestId,\n requested: request.requested,\n } satisfies DelegationRequestBinding,\n };\n // A validated import replaces every stored row for its CID with this\n // record, whatever binding those rows carried (none, a synthesized\n // one, or one replay cannot use), keeping the first row's position.\n const position = records.findIndex((entry) => delegationCid(entry) === activated.cid);\n const alreadyPresent = position !== -1;\n const others = records.filter((entry) => delegationCid(entry) !== activated.cid);\n return {\n records: alreadyPresent\n ? [...others.slice(0, position), record, ...others.slice(position)]\n : [...records, record],\n result: {\n status: \"ok\",\n output: {\n cid: activated.cid,\n effectivePermissions,\n expiry: activated.expiry.toISOString(),\n audience: activated.audience,\n host: activated.host,\n activated: true,\n alreadyPresent,\n },\n },\n };\n },\n );\n } catch {\n return internalImportFailure();\n }\n } catch {\n return internalImportFailure();\n }\n}\n\nasync function importState(\n context: RuntimeOperationContext,\n requestId: string,\n): Promise<\n | { ok: true; request: PermissionRequestArtifact; sessionDid: string; host: string }\n | { ok: false; result: OperationExecutionOutcome<never> }\n> {\n const sessionDid = await currentSessionDid(context.summary.profile);\n if (sessionDid === undefined) return { ok: false, result: missingSession() };\n if (context.summary.sessionDid === undefined || !samePrincipal(context.summary.sessionDid, sessionDid)) {\n return { ok: false, result: audienceMismatch(sessionDid, context.summary.sessionDid ?? \"unknown\") };\n }\n const current = await readProfile<Record<string, unknown>>(context.summary.profile);\n const host = typeof current?.host === \"string\" ? current.host : context.summary.host;\n if (normalizeHost(host) !== normalizeHost(context.summary.host)) {\n return { ok: false, result: hostMismatch(context.summary.host, host) };\n }\n let requests: PermissionRequestArtifact[];\n try {\n requests = await listPermissionRequests(context.summary.profile, {\n profile: context.summary.profile,\n host: context.summary.host,\n sessionDid,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n });\n } catch {\n return {\n ok: false,\n result: operationFailure(\n \"DELEGATION_ARTIFACT_INVALID\",\n \"The stored authority request is malformed.\",\n ),\n };\n }\n const request = requests.find((candidate) => candidate.requestId === requestId);\n if (request === undefined || request.profile !== context.summary.profile) {\n return {\n ok: false,\n result: operationFailure(\n \"DELEGATION_ARTIFACT_INVALID\",\n \"The delegation does not reference a stored request for this profile.\",\n ),\n };\n }\n if (normalizeHost(request.host) !== normalizeHost(host)) {\n return { ok: false, result: hostMismatch(host, request.host) };\n }\n if (!samePrincipal(request.sessionDid, sessionDid)) {\n return { ok: false, result: audienceMismatch(sessionDid, request.sessionDid) };\n }\n return { ok: true, request, sessionDid, host };\n}\n\nfunction exactCapabilities(value: unknown): PermissionEntry[] | undefined {\n return validateExactCapabilities(value);\n}\n\nfunction normalizeExpiry(value: unknown): Date | undefined {\n const expiry = value instanceof Date ? value : typeof value === \"string\" ? new Date(value) : undefined;\n return expiry !== undefined && !Number.isNaN(expiry.getTime()) ? expiry : undefined;\n}\n\nfunction normalizeHost(host: string): string {\n return host.replace(/\\/+$/, \"\");\n}\n\nfunction samePrincipal(left: string, right: string): boolean {\n return left.split(\"#\", 1)[0] === right.split(\"#\", 1)[0];\n}\n\nfunction delegationCid(value: Record<string, unknown>): string | undefined {\n const delegation = value.delegation;\n if (delegation === null || typeof delegation !== \"object\") return undefined;\n const cid = (delegation as { cid?: unknown }).cid;\n return typeof cid === \"string\" ? cid : undefined;\n}\n\nasync function currentSessionDid(profile: string): Promise<string | undefined> {\n const session = await readSession<Record<string, unknown>>(profile);\n if (session === null || typeof session.verificationMethod !== \"string\") return undefined;\n return session.verificationMethod.split(\"#\", 1)[0] || undefined;\n}\n\nfunction missingSession(): OperationExecutionOutcome<never> {\n return operationFailure(\"SESSION_NOT_FOUND\", \"The selected profile does not have an active session.\");\n}\n\nfunction invalidDelegation(): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_ARTIFACT_INVALID\", \"The delegation artifact is invalid.\");\n}\n\nfunction expiredDelegation(): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_EXPIRED\", \"The delegation has expired.\");\n}\n\nfunction audienceMismatch(expectedSessionDid: string, artifactAudience: string): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_AUDIENCE_MISMATCH\", \"The delegation is for a different session.\", {\n expectedSessionDid,\n artifactAudience,\n });\n}\n\nfunction hostMismatch(expectedHost: string, artifactHost: string): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_HOST_MISMATCH\", \"The delegation is for a different host.\", {\n expectedHost,\n artifactHost,\n });\n}\n\nfunction invalidInput(message: string): OperationExecutionOutcome<never> {\n return operationFailure(\"INPUT_INVALID\", message);\n}\n\nfunction internalFailure(): OperationExecutionOutcome<never> {\n return operationFailure(\"INTERNAL_ERROR\", \"The authority request could not be completed.\");\n}\n\nfunction internalImportFailure(): OperationExecutionOutcome<never> {\n return operationFailure(\"INTERNAL_ERROR\", \"The delegation import could not be completed.\");\n}\n\nfunction operationFailure(\n code: Parameters<typeof operationError>[0],\n message: string,\n details?: Readonly<Record<string, unknown>>,\n): OperationExecutionOutcome<never> {\n return { status: \"error\", error: operationError(code, message, { ...(details === undefined ? {} : { details }) }) };\n}\n","import type { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport { authorizationVerdictOf, validatedCapabilityOf } from \"@tinycloud/sdk-services\";\nimport { z } from \"zod\";\n\nimport type {\n CapabilityRequirement,\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n RuntimeOperationContext,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { OperationInvocationError, operationError } from \"../errors.js\";\nimport { operationSpaceResolver } from \"../secrets.js\";\n\ntype EmptyInput = Record<never, never>;\n\ninterface AccountSpacesOutput {\n readonly spaces: readonly {\n readonly spaceId: string;\n readonly name: string;\n readonly ownerDid: string;\n readonly type: \"owned\" | \"delegated\" | \"discovered\";\n readonly permissions: readonly string[];\n readonly status: \"active\" | \"archived\";\n readonly registeredAt?: string;\n readonly updatedAt?: string;\n readonly expiresAt?: string;\n }[];\n readonly count: number;\n}\n\ninterface AccountApplicationsOutput {\n readonly applications: readonly {\n readonly appId: string;\n readonly manifests: readonly Record<string, unknown>[];\n readonly updatedAt?: string;\n readonly name?: string;\n readonly description?: string;\n readonly manifestHash?: string;\n }[];\n readonly count: number;\n}\n\ninterface KvListInput {\n readonly space: string;\n readonly prefix?: string;\n readonly limit?: number;\n}\n\ninterface KvListOutput {\n readonly space: string;\n readonly prefix: string;\n readonly keys: readonly string[];\n readonly count: number;\n readonly truncated: boolean;\n}\n\ninterface KvGetInput {\n readonly space: string;\n readonly key: string;\n readonly representation?: \"base64\" | \"text\" | \"json\";\n}\n\ninterface KvGetOutput {\n readonly space: string;\n readonly key: string;\n readonly value: unknown;\n readonly encoding: \"json\" | \"text\" | \"base64\";\n readonly metadata: {\n readonly etag?: string;\n readonly contentType?: string;\n readonly lastModified?: string;\n readonly contentLength?: number;\n };\n readonly byteLength: number;\n}\n\ntype JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };\ntype KvPutContent =\n | Readonly<{ encoding: \"utf8\"; value: string }>\n | Readonly<{ encoding: \"json\"; value: JsonValue }>\n | Readonly<{ encoding: \"base64\"; value: string }>;\ntype KvPutInput = Readonly<{\n space: string;\n key: string;\n content: KvPutContent;\n contentType?: string;\n}> & (\n | Readonly<{ mode: \"create\" | \"upsert\" }>\n | Readonly<{ mode: \"replace\"; etag: string }>\n);\ninterface KvPutOutput {\n readonly space: string;\n readonly key: string;\n readonly mode: \"create\" | \"replace\" | \"upsert\";\n readonly byteLength: number;\n readonly metadata: KvMetadata;\n}\ninterface KvHeadInput { readonly space: string; readonly key: string }\ninterface KvHeadOutput { readonly space: string; readonly key: string; readonly metadata: KvMetadata }\ninterface KvDeleteInput { readonly space: string; readonly key: string; readonly etag?: string }\ninterface KvDeleteOutput { readonly space: string; readonly key: string; readonly deleted: true; readonly etag?: string }\ninterface KvMetadata {\n readonly etag?: string;\n readonly contentType?: string;\n readonly lastModified?: string;\n readonly contentLength?: number;\n}\ntype KvOperationResult<T> =\n | Readonly<{ ok: true; data: T }>\n | Readonly<{ ok: false; error: Readonly<{ code?: string; meta?: Readonly<Record<string, unknown>> }> }>;\ninterface KvOperationHandle {\n list(options: Readonly<{ prefix?: string; limit: number }>): Promise<KvOperationResult<{\n readonly keys: readonly string[];\n readonly truncated?: boolean;\n }>>;\n get(key: string, options: Readonly<{\n binary: true;\n maxResponseBytes: number;\n }>): Promise<KvOperationResult<{ readonly data: Uint8Array; readonly headers: KvMetadata }>>;\n head(key: string): Promise<KvOperationResult<{ readonly data: void; readonly headers: KvMetadata }>>;\n put(key: string, value: Uint8Array, options: Readonly<{\n contentType: string;\n ifNoneMatch?: \"*\";\n ifMatch?: string;\n }>): Promise<KvOperationResult<{ readonly data: void; readonly headers: KvMetadata }>>;\n delete(key: string, options: Readonly<{ ifMatch?: string }>): Promise<KvOperationResult<{\n readonly data: void;\n readonly headers: KvMetadata;\n }>>;\n}\n\nconst MAX_KV_VALUE_BYTES = 1024 * 1024;\nconst DEFAULT_KV_LIST_LIMIT = 100;\nconst MAX_ACCOUNT_REGISTRY_RECORDS = 1000;\nconst MAX_ACCOUNT_REGISTRY_BYTES = 4 * 1024 * 1024;\n\nconst EmptyInputSchema: z.ZodType<EmptyInput> = z.object({}).strict();\nconst SpaceSchema = z.string().min(1).refine(\n (space) =>\n (/^[A-Za-z0-9_-]+$/.test(space) || space.startsWith(\"tinycloud:\")) &&\n !space.includes(\"*\"),\n \"Invalid TinyCloud space.\",\n);\nconst PrefixSchema = z.string().refine(\n (prefix) => prefix !== \"/\" && !prefix.includes(\"*\"),\n \"Invalid KV prefix.\",\n);\nconst KeySchema = z.string().min(1).refine(\n (key) => key !== \"/\" && !key.endsWith(\"/\") && !key.includes(\"*\"),\n \"Invalid KV key.\",\n);\nconst LimitSchema = z.number().int().min(1).max(1000);\nconst StrongEtagSchema = z.string().regex(\n /^\"blake3-[0-9a-f]{64}\"$/,\n \"A strong TinyCloud BLAKE3 ETag is required.\",\n);\nconst ContentTypeSchema = z.string().min(1).max(128).refine(\n (value) => !/[\\x00-\\x1f\\x7f]/.test(value),\n \"Invalid content type.\",\n);\nconst JsonNumberSchema = z.number().finite().refine(\n (value) => !Number.isInteger(value) || Number.isSafeInteger(value),\n \"JSON integer values must be JavaScript safe integers.\",\n);\nconst JsonValueSchema: z.ZodType<JsonValue> = z.lazy(() => z.union([\n z.null(),\n z.boolean(),\n JsonNumberSchema,\n z.string(),\n z.array(JsonValueSchema),\n z.record(JsonValueSchema),\n]));\nconst KvMetadataSchema: z.ZodType<KvMetadata> = z.object({\n etag: z.string().optional(),\n contentType: z.string().optional(),\n lastModified: z.string().optional(),\n contentLength: z.number().int().nonnegative().optional(),\n}).strict();\n\nconst AccountSpaceSchema = z.object({\n spaceId: z.string().min(1),\n name: z.string().min(1),\n ownerDid: z.string(),\n type: z.enum([\"owned\", \"delegated\", \"discovered\"]),\n permissions: z.array(z.string()),\n status: z.enum([\"active\", \"archived\"]),\n registeredAt: z.string().optional(),\n updatedAt: z.string().optional(),\n expiresAt: z.string().datetime({ offset: true }).optional(),\n}).strict();\nconst AccountSpacesOutputSchema: z.ZodType<AccountSpacesOutput> = z.object({\n spaces: z.array(AccountSpaceSchema),\n count: z.number().int().nonnegative(),\n}).strict();\n\nconst AccountApplicationSchema = z.object({\n appId: z.string().min(1),\n manifests: z.array(z.record(z.unknown())),\n updatedAt: z.string().optional(),\n name: z.string().optional(),\n description: z.string().optional(),\n manifestHash: z.string().optional(),\n}).strict();\nconst AccountApplicationsOutputSchema: z.ZodType<AccountApplicationsOutput> = z.object({\n applications: z.array(AccountApplicationSchema),\n count: z.number().int().nonnegative(),\n}).strict();\n\nconst KvListInputSchema: z.ZodType<KvListInput> = z.object({\n space: SpaceSchema,\n prefix: PrefixSchema.optional(),\n limit: LimitSchema.optional(),\n}).strict();\nconst KvListOutputSchema: z.ZodType<KvListOutput> = z.object({\n space: z.string().min(1),\n prefix: z.string(),\n keys: z.array(z.string()),\n count: z.number().int().nonnegative(),\n truncated: z.boolean(),\n}).strict();\n\nconst KvGetInputSchema: z.ZodType<KvGetInput> = z.object({\n space: SpaceSchema,\n key: KeySchema,\n representation: z.enum([\"base64\", \"text\", \"json\"]).optional(),\n}).strict();\nconst KvGetOutputSchema: z.ZodType<KvGetOutput> = z.object({\n space: z.string().min(1),\n key: z.string().min(1),\n value: z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(z.unknown()),\n z.record(z.unknown()),\n ]),\n encoding: z.enum([\"json\", \"text\", \"base64\"]),\n metadata: KvMetadataSchema,\n byteLength: z.number().int().nonnegative(),\n}).strict();\n\nconst KvPutContentSchema: z.ZodType<KvPutContent> = z.discriminatedUnion(\"encoding\", [\n z.object({ encoding: z.literal(\"utf8\"), value: z.string() }).strict(),\n z.object({ encoding: z.literal(\"json\"), value: JsonValueSchema }).strict(),\n z.object({ encoding: z.literal(\"base64\"), value: z.string() }).strict(),\n]).superRefine((content, context) => {\n const decoded = decodeKvPutContent(content);\n if (decoded === undefined) {\n context.addIssue({ code: z.ZodIssueCode.custom, message: \"Invalid canonical base64 content.\" });\n } else if (decoded.byteLength > MAX_KV_VALUE_BYTES) {\n context.addIssue({\n code: z.ZodIssueCode.too_big,\n type: \"array\",\n maximum: MAX_KV_VALUE_BYTES,\n inclusive: true,\n message: `KV content must not exceed ${MAX_KV_VALUE_BYTES} bytes.`,\n });\n }\n});\nconst KvPutCommonSchema = {\n space: SpaceSchema,\n key: KeySchema,\n content: KvPutContentSchema,\n contentType: ContentTypeSchema.optional(),\n};\nconst KvPutInputSchema: z.ZodType<KvPutInput> = z.discriminatedUnion(\"mode\", [\n z.object({ ...KvPutCommonSchema, mode: z.literal(\"create\") }).strict(),\n z.object({ ...KvPutCommonSchema, mode: z.literal(\"upsert\") }).strict(),\n z.object({ ...KvPutCommonSchema, mode: z.literal(\"replace\"), etag: StrongEtagSchema }).strict(),\n]);\nconst KvPutOutputSchema: z.ZodType<KvPutOutput> = z.object({\n space: z.string().min(1),\n key: z.string().min(1),\n mode: z.enum([\"create\", \"replace\", \"upsert\"]),\n byteLength: z.number().int().nonnegative(),\n metadata: KvMetadataSchema,\n}).strict();\nconst KvHeadInputSchema: z.ZodType<KvHeadInput> = z.object({ space: SpaceSchema, key: KeySchema }).strict();\nconst KvHeadOutputSchema: z.ZodType<KvHeadOutput> = z.object({\n space: z.string().min(1), key: z.string().min(1), metadata: KvMetadataSchema,\n}).strict();\nconst KvDeleteInputSchema: z.ZodType<KvDeleteInput> = z.object({\n space: SpaceSchema, key: KeySchema, etag: StrongEtagSchema.optional(),\n}).strict();\nconst KvDeleteOutputSchema: z.ZodType<KvDeleteOutput> = z.object({\n space: z.string().min(1), key: z.string().min(1), deleted: z.literal(true), etag: z.string().optional(),\n}).strict();\n\nconst AUTHENTICATED_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\nconst EXPLORATION_EXPOSURE: OperationExposure = {\n cli: {\n status: \"excluded\",\n reason: \"Existing account and KV Commander commands remain the CLI surface.\",\n },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\n\nconst ACCOUNT_SPACES_SENSITIVITY: OperationSensitivity = {\n input: [],\n output: [\"/spaces\"],\n};\nconst ACCOUNT_APPLICATIONS_SENSITIVITY: OperationSensitivity = {\n input: [],\n output: [\"/applications\"],\n};\nconst KV_LIST_SENSITIVITY: OperationSensitivity = {\n input: [\"/prefix\"],\n output: [\"/keys\"],\n};\nconst KV_GET_SENSITIVITY: OperationSensitivity = {\n input: [\"/key\"],\n output: [\"/value\"],\n};\nconst KV_PUT_SENSITIVITY: OperationSensitivity = { input: [\"/key\", \"/content\"], output: [] };\nconst KV_KEY_SENSITIVITY: OperationSensitivity = { input: [\"/key\"], output: [] };\n\ntype ExplorationDefinition =\n | OperationDefinition<EmptyInput, AccountSpacesOutput>\n | OperationDefinition<EmptyInput, AccountApplicationsOutput>\n | OperationDefinition<KvListInput, KvListOutput>\n | OperationDefinition<KvGetInput, KvGetOutput>\n | OperationDefinition<KvPutInput, KvPutOutput>\n | OperationDefinition<KvHeadInput, KvHeadOutput>\n | OperationDefinition<KvDeleteInput, KvDeleteOutput>;\n\nexport const explorationOperationDefinitions: readonly ExplorationDefinition[] = [\n {\n id: \"tinycloud.account.spaces.list\",\n version: 1,\n title: \"List TinyCloud account spaces\",\n description: \"List the spaces registered in the selected owner's TinyCloud account.\",\n input: EmptyInputSchema,\n output: AccountSpacesOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: ACCOUNT_SPACES_SENSITIVITY,\n authority: (context: RuntimeOperationContext) => planAccountRegistryRead(context, \"spaces/\"),\n execute: executeAccountSpacesList,\n },\n {\n id: \"tinycloud.account.applications.list\",\n version: 1,\n title: \"List TinyCloud account applications\",\n description: \"List the application manifests registered in the selected owner's TinyCloud account.\",\n input: EmptyInputSchema,\n output: AccountApplicationsOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: ACCOUNT_APPLICATIONS_SENSITIVITY,\n authority: (context: RuntimeOperationContext) => planAccountRegistryRead(context, \"applications/\"),\n execute: executeAccountApplicationsList,\n },\n {\n id: \"tinycloud.kv.list\",\n version: 1,\n title: \"List TinyCloud KV keys\",\n description: \"List keys at one exact prefix in a delegated TinyCloud space.\",\n input: KvListInputSchema,\n output: KvListOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: KV_LIST_SENSITIVITY,\n authority: planKvList,\n execute: executeKvList,\n },\n {\n id: \"tinycloud.kv.get\",\n version: 1,\n title: \"Get a TinyCloud KV value\",\n description: \"Read one exact key with a node-enforced one MiB response limit.\",\n input: KvGetInputSchema,\n output: KvGetOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: KV_GET_SENSITIVITY,\n authority: planKvGet,\n execute: executeKvGet,\n },\n {\n id: \"tinycloud.kv.head\", version: 1, title: \"Inspect TinyCloud KV metadata\",\n description: \"Read metadata for one exact key without downloading its value.\",\n input: KvHeadInputSchema, output: KvHeadOutputSchema, effects: [\"read\"], runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES, exposure: EXPLORATION_EXPOSURE, sensitivity: KV_KEY_SENSITIVITY,\n authority: (context: RuntimeOperationContext, input: KvHeadInput) =>\n planExactKv(context, input.space, input.key, \"tinycloud.kv/metadata\"),\n execute: executeKvHead,\n },\n {\n id: \"tinycloud.kv.put\", version: 1, title: \"Write a TinyCloud KV value\",\n description: \"Create, conditionally replace, or explicitly upsert one exact KV key.\",\n input: KvPutInputSchema, output: KvPutOutputSchema, effects: [\"write\"], runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES, exposure: EXPLORATION_EXPOSURE, sensitivity: KV_PUT_SENSITIVITY,\n authority: (context: RuntimeOperationContext, input: KvPutInput) =>\n planExactKv(context, input.space, input.key, \"tinycloud.kv/put\"),\n execute: executeKvPut,\n },\n {\n id: \"tinycloud.kv.delete\", version: 1, title: \"Delete a TinyCloud KV value\",\n description: \"Delete one exact KV key, optionally only when its ETag still matches.\",\n input: KvDeleteInputSchema, output: KvDeleteOutputSchema, effects: [\"destructive\"], runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES, exposure: EXPLORATION_EXPOSURE, sensitivity: KV_KEY_SENSITIVITY,\n authority: (context: RuntimeOperationContext, input: KvDeleteInput) =>\n planExactKv(context, input.space, input.key, \"tinycloud.kv/del\"),\n execute: executeKvDelete,\n },\n];\n\nasync function planAccountRegistryRead(\n context: RuntimeOperationContext,\n path: \"spaces/\" | \"applications/\",\n): Promise<readonly CapabilityRequirement[]> {\n return [{\n service: \"tinycloud.kv\",\n space: resolveSpace(context, \"account\"),\n path,\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n }];\n}\n\nasync function planKvList(\n context: RuntimeOperationContext,\n input: KvListInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveGenericKvSpace(context, input.space);\n return [{\n service: \"tinycloud.kv\",\n space,\n path: input.prefix ?? \"\",\n actions: [\"tinycloud.kv/list\"],\n }];\n}\n\nasync function planKvGet(\n context: RuntimeOperationContext,\n input: KvGetInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveGenericKvSpace(context, input.space);\n return [{\n service: \"tinycloud.kv\",\n space,\n path: input.key,\n actions: [\"tinycloud.kv/get\"],\n }];\n}\n\nasync function planExactKv(\n context: RuntimeOperationContext,\n requestedSpace: string,\n key: string,\n action: \"tinycloud.kv/metadata\" | \"tinycloud.kv/put\" | \"tinycloud.kv/del\",\n): Promise<readonly CapabilityRequirement[]> {\n return [{\n service: \"tinycloud.kv\",\n space: resolveGenericKvSpace(context, requestedSpace),\n path: key,\n actions: [action],\n }];\n}\n\nasync function executeAccountSpacesList(\n context: OperationContext,\n _input: EmptyInput,\n): Promise<OperationExecutionOutcome<AccountSpacesOutput>> {\n try {\n const entries = await readAccountRegistry(context, \"spaces/\");\n if (!entries.ok) return entries.outcome;\n const spaces = entries.records\n .map(({ key, value }) => projectAccountSpace(key, value))\n .sort((left, right) => left.name.localeCompare(right.name) || left.spaceId.localeCompare(right.spaceId));\n const output = { spaces, count: spaces.length };\n return accountRegistryOutput(output);\n } catch (error) {\n return caughtKvFailure(error, \"list account spaces\");\n }\n}\n\nasync function executeAccountApplicationsList(\n context: OperationContext,\n _input: EmptyInput,\n): Promise<OperationExecutionOutcome<AccountApplicationsOutput>> {\n try {\n const entries = await readAccountRegistry(context, \"applications/\");\n if (!entries.ok) return entries.outcome;\n const applications = entries.records\n .map(({ key, value }) => projectAccountApplication(key, value))\n .sort((left, right) => left.appId.localeCompare(right.appId));\n const output = { applications, count: applications.length };\n return accountRegistryOutput(output);\n } catch (error) {\n return caughtKvFailure(error, \"list account applications\");\n }\n}\n\nasync function executeKvList(\n context: OperationContext,\n input: KvListInput,\n): Promise<OperationExecutionOutcome<KvListOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).list({\n ...(input.prefix === undefined ? {} : { prefix: input.prefix }),\n limit: input.limit ?? DEFAULT_KV_LIST_LIMIT,\n });\n if (!result.ok) return kvFailure(result.error, \"list KV keys\");\n const keys = [...result.data.keys];\n return {\n status: \"ok\",\n output: {\n space,\n prefix: input.prefix ?? \"\",\n keys,\n count: keys.length,\n truncated: result.data.truncated ?? false,\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"list KV keys\");\n }\n}\n\nasync function executeKvGet(\n context: OperationContext,\n input: KvGetInput,\n): Promise<OperationExecutionOutcome<KvGetOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).get(input.key, {\n binary: true,\n maxResponseBytes: MAX_KV_VALUE_BYTES,\n });\n if (!result.ok) return kvFailure(result.error, \"read the KV value\");\n const bytes = result.data.data;\n if (bytes.byteLength > MAX_KV_VALUE_BYTES) {\n return kvFailure({ code: \"KV_RESPONSE_TOO_LARGE\" }, \"read the KV value\");\n }\n const encoded = encodeKvValue(bytes, input.representation ?? \"base64\");\n if (!encoded.ok) return encoded.outcome;\n return {\n status: \"ok\",\n output: {\n space,\n key: input.key,\n value: encoded.value,\n encoding: encoded.encoding,\n metadata: projectKvMetadata(result.data.headers),\n byteLength: bytes.byteLength,\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"read the KV value\");\n }\n}\n\nasync function executeKvHead(\n context: OperationContext,\n input: KvHeadInput,\n): Promise<OperationExecutionOutcome<KvHeadOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).head(input.key);\n if (!result.ok) return kvFailure(result.error, \"read KV metadata\");\n return { status: \"ok\", output: { space, key: input.key, metadata: projectKvMetadata(result.data.headers) } };\n } catch (error) {\n return caughtKvFailure(error, \"read KV metadata\");\n }\n}\n\nasync function executeKvPut(\n context: OperationContext,\n input: KvPutInput,\n): Promise<OperationExecutionOutcome<KvPutOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const decoded = decodeKvPutContent(input.content);\n if (decoded === undefined || decoded.byteLength > MAX_KV_VALUE_BYTES) {\n return { status: \"error\", error: operationError(\"INPUT_INVALID\", \"The KV content is invalid or too large.\") };\n }\n const result = await genericKv(runtime, space).put(input.key, decoded.bytes, {\n contentType: input.contentType ?? decoded.contentType,\n ...(input.mode === \"create\" ? { ifNoneMatch: \"*\" as const } : {}),\n ...(input.mode === \"replace\" ? { ifMatch: input.etag } : {}),\n });\n if (!result.ok) return kvFailure(result.error, \"write the KV value\");\n return {\n status: \"ok\",\n output: {\n space,\n key: input.key,\n mode: input.mode,\n byteLength: decoded.byteLength,\n metadata: projectKvMetadata(result.data.headers),\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"write the KV value\");\n }\n}\n\nasync function executeKvDelete(\n context: OperationContext,\n input: KvDeleteInput,\n): Promise<OperationExecutionOutcome<KvDeleteOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).delete(input.key, {\n ...(input.etag === undefined ? {} : { ifMatch: input.etag }),\n });\n if (!result.ok) return kvFailure(result.error, \"delete the KV value\");\n return {\n status: \"ok\",\n output: {\n space,\n key: input.key,\n deleted: true,\n ...(result.data.headers.etag === undefined ? {} : { etag: result.data.headers.etag }),\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"delete the KV value\");\n }\n}\n\nfunction runtimeContext(context: OperationContext): RuntimeOperationContext {\n if (context.runtime === undefined) {\n throw new TypeError(\"Authenticated operation runtime is unavailable.\");\n }\n return context as RuntimeOperationContext;\n}\n\nfunction runtimeNode(context: OperationContext): TinyCloudNode {\n return runtimeContext(context).runtime.node as TinyCloudNode;\n}\n\nfunction genericKv(context: RuntimeOperationContext, space: string): KvOperationHandle {\n return runtimeNode(context).kvForSpace(space) as unknown as KvOperationHandle;\n}\n\nfunction resolveSpace(context: RuntimeOperationContext, space: string): string {\n return operationSpaceResolver(context.runtime.node, context.summary.space)(space);\n}\n\nfunction resolveGenericKvSpace(context: RuntimeOperationContext, space: string): string {\n const resolved = resolveSpace(context, space);\n const protectedName = resolved.split(\":\").at(-1)?.toLowerCase();\n if (protectedName === \"secrets\" || protectedName === \"account\") {\n throw new OperationInvocationError(operationError(\n \"INPUT_INVALID\",\n \"Generic KV operations cannot access TinyCloud account or secrets spaces.\",\n ));\n }\n return resolved;\n}\n\nasync function readAccountRegistry(\n context: OperationContext,\n prefix: \"spaces/\" | \"applications/\",\n): Promise<\n | Readonly<{ ok: true; records: readonly Readonly<{ key: string; value: Record<string, unknown> }>[] }>\n | Readonly<{ ok: false; outcome: OperationExecutionOutcome<never> }>\n> {\n const runtime = runtimeContext(context);\n const accountSpace = resolveSpace(runtime, \"account\");\n const kv = runtimeNode(runtime).kvForSpace(accountSpace) as unknown as KvOperationHandle;\n const listed = await kv.list({ prefix, limit: MAX_ACCOUNT_REGISTRY_RECORDS });\n if (!listed.ok) return { ok: false, outcome: kvFailure(listed.error, \"list the account registry\") };\n if (listed.data.truncated === true) {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\n \"OUTPUT_INVALID\",\n `The TinyCloud account registry exceeds the ${MAX_ACCOUNT_REGISTRY_RECORDS}-record exploration limit.`,\n ),\n },\n };\n }\n\n const records: Array<Readonly<{ key: string; value: Record<string, unknown> }>> = [];\n let totalBytes = 0;\n for (const key of listed.data.keys) {\n const loaded = await kv.get(key, {\n binary: true,\n maxResponseBytes: MAX_KV_VALUE_BYTES,\n });\n if (!loaded.ok) {\n return { ok: false, outcome: kvFailure(loaded.error, \"read the account registry\") };\n }\n const bytes = loaded.data.data;\n totalBytes += bytes.byteLength;\n if (bytes.byteLength > MAX_KV_VALUE_BYTES || totalBytes > MAX_ACCOUNT_REGISTRY_BYTES) {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\n \"KV_RESPONSE_TOO_LARGE\",\n `The TinyCloud account registry exceeds the ${MAX_ACCOUNT_REGISTRY_BYTES}-byte exploration limit.`,\n ),\n },\n };\n }\n try {\n const value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n if (!isRecord(value)) throw new TypeError(\"Account registry values must be JSON objects.\");\n records.push({ key, value });\n } catch {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\"OUTPUT_INVALID\", \"The TinyCloud account registry contains an invalid record.\"),\n },\n };\n }\n }\n return { ok: true, records };\n}\n\nfunction projectAccountSpace(\n key: string,\n record: Record<string, unknown>,\n): AccountSpacesOutput[\"spaces\"][number] {\n const suffix = key.startsWith(\"spaces/\") ? key.slice(\"spaces/\".length) : key;\n const rawSpaceId = stringField(record, \"space_id\", \"spaceId\") ?? suffix;\n const rawName = stringField(record, \"name\") ?? rawSpaceId.split(\":\").at(-1) ?? rawSpaceId;\n const rawType = stringField(record, \"type\");\n const rawStatus = stringField(record, \"status\");\n const rawExpiresAt = record.expires_at ?? record.expiresAt;\n const expiresAt = rawExpiresAt instanceof Date\n ? rawExpiresAt.toISOString()\n : typeof rawExpiresAt === \"string\" && !Number.isNaN(new Date(rawExpiresAt).getTime())\n ? new Date(rawExpiresAt).toISOString()\n : undefined;\n return {\n spaceId: rawSpaceId,\n name: rawName,\n ownerDid: stringField(record, \"owner_did\", \"ownerDid\", \"owner\") ?? \"\",\n type: rawType === \"owned\" || rawType === \"delegated\" ? rawType : \"discovered\",\n permissions: Array.isArray(record.permissions)\n ? record.permissions.filter((value): value is string => typeof value === \"string\")\n : [],\n status: rawStatus === \"archived\" ? \"archived\" : \"active\",\n ...(stringField(record, \"registered_at\", \"registeredAt\") === undefined\n ? {}\n : { registeredAt: stringField(record, \"registered_at\", \"registeredAt\") }),\n ...(stringField(record, \"updated_at\", \"updatedAt\") === undefined\n ? {}\n : { updatedAt: stringField(record, \"updated_at\", \"updatedAt\") }),\n ...(expiresAt === undefined ? {} : { expiresAt }),\n };\n}\n\nfunction projectAccountApplication(\n key: string,\n record: Record<string, unknown>,\n): AccountApplicationsOutput[\"applications\"][number] {\n const manifests = Array.isArray(record.manifests)\n ? record.manifests.filter(isRecord)\n : [];\n const first = manifests[0];\n return {\n appId: stringField(record, \"app_id\", \"appId\") ??\n stringField(first, \"app_id\") ??\n (key.startsWith(\"applications/\") ? key.slice(\"applications/\".length) : key),\n manifests,\n ...(stringField(record, \"updated_at\", \"updatedAt\") === undefined\n ? {}\n : { updatedAt: stringField(record, \"updated_at\", \"updatedAt\") }),\n ...(stringField(first, \"name\") === undefined ? {} : { name: stringField(first, \"name\") }),\n ...(stringField(first, \"description\") === undefined\n ? {}\n : { description: stringField(first, \"description\") }),\n ...(stringField(record, \"manifest_hash\", \"manifestHash\") === undefined\n ? {}\n : { manifestHash: stringField(record, \"manifest_hash\", \"manifestHash\") }),\n };\n}\n\nfunction stringField(\n record: Record<string, unknown> | undefined,\n ...keys: readonly string[]\n): string | undefined {\n if (record === undefined) return undefined;\n for (const key of keys) {\n if (typeof record[key] === \"string\") return record[key];\n }\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction encodeKvValue(\n value: Uint8Array,\n representation: NonNullable<KvGetInput[\"representation\"]>,\n):\n | Readonly<{ ok: true; value: unknown; encoding: KvGetOutput[\"encoding\"] }>\n | Readonly<{ ok: false; outcome: OperationExecutionOutcome<KvGetOutput> }> {\n if (representation === \"base64\") {\n return { ok: true, value: Buffer.from(value).toString(\"base64\"), encoding: \"base64\" };\n }\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(value);\n } catch {\n return {\n ok: false,\n outcome: { status: \"error\", error: operationError(\"OUTPUT_INVALID\", \"The KV value is not valid UTF-8.\") },\n };\n }\n if (representation === \"text\") return { ok: true, value: text, encoding: \"text\" };\n try {\n const parsed = JsonValueSchema.safeParse(JSON.parse(text));\n if (!parsed.success) {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\n \"OUTPUT_INVALID\",\n \"The KV JSON contains a number that cannot be represented safely.\",\n ),\n },\n };\n }\n return { ok: true, value: parsed.data, encoding: \"json\" };\n } catch {\n return {\n ok: false,\n outcome: { status: \"error\", error: operationError(\"OUTPUT_INVALID\", \"The KV value is not valid JSON.\") },\n };\n }\n}\n\nfunction decodeKvPutContent(content: KvPutContent):\n | Readonly<{ bytes: Uint8Array; byteLength: number; contentType: string }>\n | undefined {\n let bytes: Uint8Array;\n let contentType: string;\n if (content.encoding === \"utf8\") {\n bytes = new TextEncoder().encode(content.value);\n contentType = \"text/plain;charset=UTF-8\";\n } else if (content.encoding === \"json\") {\n bytes = new TextEncoder().encode(JSON.stringify(content.value));\n contentType = \"application/json\";\n } else {\n if (!isCanonicalBase64(content.value)) return undefined;\n bytes = new Uint8Array(Buffer.from(content.value, \"base64\"));\n contentType = \"application/octet-stream\";\n }\n return { bytes, byteLength: bytes.byteLength, contentType };\n}\n\nfunction isCanonicalBase64(value: string): boolean {\n if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {\n return false;\n }\n return Buffer.from(value, \"base64\").toString(\"base64\") === value;\n}\n\nfunction projectKvMetadata(headers: {\n readonly etag?: string;\n readonly contentType?: string;\n readonly lastModified?: string;\n readonly contentLength?: number;\n}): KvMetadata {\n return {\n ...(headers.etag === undefined ? {} : { etag: headers.etag }),\n ...(headers.contentType === undefined ? {} : { contentType: headers.contentType }),\n ...(headers.lastModified === undefined ? {} : { lastModified: headers.lastModified }),\n ...(headers.contentLength === undefined ? {} : { contentLength: headers.contentLength }),\n };\n}\n\nfunction caughtKvFailure(error: unknown, action: string): OperationExecutionOutcome<never> {\n if (error instanceof OperationInvocationError) return { status: \"error\", error: error.operationError };\n return authorizationFailure(error, action) ?? nodeFailure(action);\n}\n\nexport function authorizationFailure(error: unknown, action: string): OperationExecutionOutcome<never> | undefined {\n const verdict = authorizationVerdictOf(error);\n if (verdict === \"unauthenticated\") {\n if (validatedCapabilityOf(error) !== undefined) {\n return { status: \"error\", error: operationError(\"PERMISSION_DENIED\", `Permission is denied to ${action}.`) };\n }\n return { status: \"error\", error: operationError(\"AUTH_REQUIRED\", `Authentication is required to ${action}.`) };\n }\n if (verdict === \"forbidden\") {\n return { status: \"error\", error: operationError(\"PERMISSION_DENIED\", `Permission is denied to ${action}.`) };\n }\n return undefined;\n}\n\nfunction accountRegistryOutput<T>(output: T): OperationExecutionOutcome<T> {\n if (Buffer.byteLength(JSON.stringify(output), \"utf8\") > MAX_ACCOUNT_REGISTRY_BYTES) {\n return {\n status: \"error\",\n error: operationError(\n \"KV_RESPONSE_TOO_LARGE\",\n `The TinyCloud account registry exceeds the ${MAX_ACCOUNT_REGISTRY_BYTES}-byte exploration limit.`,\n ),\n };\n }\n return { status: \"ok\", output };\n}\n\nfunction kvFailure(\n error: Readonly<{ code?: string; meta?: Readonly<Record<string, unknown>> }>,\n action: string,\n): OperationExecutionOutcome<never> {\n const auth = authorizationFailure(error, action);\n if (auth !== undefined) return auth;\n if (error.code === \"KV_NOT_FOUND\") {\n return { status: \"error\", error: operationError(\"KV_NOT_FOUND\", \"The TinyCloud KV key was not found.\") };\n }\n if (error.code === \"KV_PRECONDITION_FAILED\") {\n return { status: \"error\", error: operationError(\"KV_PRECONDITION_FAILED\", \"The TinyCloud KV object changed or already exists.\") };\n }\n if (error.code === \"KV_CONFLICT\") {\n return {\n status: \"error\",\n error: operationError(\n \"KV_CONFLICT\",\n \"A database serialization conflict prevented the conditional KV mutation; re-read the key state, which may still be absent, before deciding whether to retry.\",\n { retryable: true },\n ),\n };\n }\n if (error.code === \"KV_RESPONSE_TOO_LARGE\") {\n return { status: \"error\", error: operationError(\"KV_RESPONSE_TOO_LARGE\", `The TinyCloud KV value exceeds ${MAX_KV_VALUE_BYTES} bytes.`) };\n }\n return nodeFailure(action);\n}\n\nfunction nodeFailure(action: string): OperationExecutionOutcome<never> {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n `The TinyCloud node could not ${action}.`,\n { retryable: true },\n ),\n };\n}\n","import { z } from \"zod\";\nimport type { SecretReadResult } from \"@tinycloud/node-sdk\";\n\nimport {\n type OperationContext,\n type CapabilityRequirement,\n type OperationDefinition,\n type OperationExecutionOutcome,\n type OperationExposure,\n type OperationSensitivity,\n type RuntimeOperationContext,\n type TinyCloudPosture,\n} from \"../contract.js\";\nimport { OperationInvocationError, operationError } from \"../errors.js\";\nimport {\n buildSecretSetupUrl,\n normalizeSecretsGetInput,\n operationSpaceResolver,\n resolveSecretReference,\n resolveSecretReferenceForOperation,\n type SecretReference,\n type SecretsGetInput,\n} from \"../secrets.js\";\n\ninterface SecretsGetOutput {\n readonly value: string;\n}\n\nconst SecretsGetInputSchema: z.ZodType<SecretsGetInput> = z.object({\n name: z.string(),\n scope: z.string().optional(),\n space: z.string().optional(),\n}).strict().superRefine((input, context) => {\n try {\n resolveSecretReference(input);\n } catch {\n context.addIssue({ code: z.ZodIssueCode.custom, message: \"Invalid secret reference.\" });\n }\n}).transform(normalizeSecretsGetInput);\n\nconst SecretsGetOutputSchema: z.ZodType<SecretsGetOutput> = z.object({\n value: z.string(),\n}).strict();\n\nconst SECRETS_GET_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\n\nconst SECRETS_GET_EXPOSURE: OperationExposure = {\n cli: { status: \"required\" },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\n\nconst SECRETS_GET_SENSITIVITY: OperationSensitivity = {\n input: [],\n output: [\"/value\"],\n};\n\nexport const secretsGetOperationDefinition: OperationDefinition<SecretsGetInput, SecretsGetOutput> = {\n id: \"tinycloud.secrets.get\",\n version: 1,\n title: \"Get a TinyCloud secret\",\n description: \"Read and decrypt one secret from the selected TinyCloud secrets space.\",\n input: SecretsGetInputSchema,\n output: SecretsGetOutputSchema,\n effects: [\"read\", \"local_write\"],\n runtime: \"authenticated\",\n postures: SECRETS_GET_POSTURES,\n exposure: SECRETS_GET_EXPOSURE,\n sensitivity: SECRETS_GET_SENSITIVITY,\n authority: planSecretGet,\n execute: executeSecretGet,\n};\n\nexport const secretsGetOperationDefinitions: readonly [typeof secretsGetOperationDefinition] = [\n secretsGetOperationDefinition,\n];\n\nasync function planSecretGet(\n context: RuntimeOperationContext,\n input: SecretsGetInput,\n): Promise<readonly CapabilityRequirement[]> {\n const reference = resolveSecretReferenceForOperation(\n input,\n context.runtime.node,\n context.summary.space,\n );\n let networkSpace = reference.space;\n if (input.space === undefined) {\n try {\n networkSpace = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n )(\"secrets\");\n } catch {\n // Definition-focused callers may omit authenticated identity metadata;\n // the runtime path supplies the owner space before production planning.\n }\n }\n const networkId = resolveEncryptionNetworkId(context.runtime.node, networkSpace);\n\n return [\n {\n service: \"tinycloud.kv\",\n space: reference.space,\n path: reference.permissionPath,\n actions: [\"tinycloud.kv/get\"],\n },\n {\n service: \"tinycloud.encryption\",\n path: networkId,\n actions: [\"tinycloud.encryption/decrypt\"],\n },\n ];\n}\n\nasync function executeSecretGet(\n context: OperationContext,\n input: SecretsGetInput,\n): Promise<OperationExecutionOutcome<SecretsGetOutput>> {\n const reference = resolveSecretReferenceForOperation(\n input,\n context.runtime?.node,\n context.summary.space,\n );\n const node = context.runtime?.node as SecretReadingNode | undefined;\n if (node === undefined || typeof node.readSecret !== \"function\") {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n \"The TinyCloud node could not read the secret.\",\n { retryable: true },\n ),\n };\n }\n\n let result: SecretReadResult;\n try {\n result = await node.readSecret({\n space: reference.space,\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n });\n } catch {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n \"The TinyCloud node could not read the secret.\",\n { retryable: true },\n ),\n };\n }\n\n return classifySecretRead(reference, result);\n}\n\nfunction classifySecretRead(\n reference: SecretReference,\n result: SecretReadResult,\n): OperationExecutionOutcome<SecretsGetOutput> {\n switch (result.status) {\n case \"ok\":\n return { status: \"ok\", output: { value: result.value } };\n case \"not_found\":\n return {\n status: \"setup_required\",\n setup: {\n kind: \"secret_manager\",\n secret: {\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n space: reference.space,\n },\n url: buildSecretSetupUrl(reference),\n message: \"Enter this secret in Secret Manager, then retry the operation.\",\n },\n requiresCallerInput: true,\n };\n case \"permission_required\":\n return {\n status: \"authority_required\",\n missing: [result.hint as unknown as CapabilityRequirement],\n request: { requestId: \"runtime-hint\" },\n approval: {\n kind: \"openkey\",\n requestId: \"runtime-hint\",\n fallback: \"tc auth grant <request-artifact>\",\n },\n };\n case \"node_unreachable\":\n return {\n status: \"error\",\n error: operationError(\n \"NODE_UNREACHABLE\",\n \"The TinyCloud node could not be reached.\",\n { retryable: true },\n ),\n };\n case \"read_failed\":\n case \"corrupt_envelope\":\n return {\n status: \"error\",\n error: operationError(\n \"SECRET_READ_FAILED\",\n \"The secret ciphertext could not be read.\",\n ),\n };\n case \"decrypt_failed\":\n case \"invalid_payload\":\n return {\n status: \"error\",\n error: operationError(\n \"SECRET_DECRYPT_FAILED\",\n \"The secret could not be decrypted.\",\n ),\n };\n }\n\n return {\n status: \"error\",\n error: operationError(\"SECRET_READ_FAILED\", \"The secret read failed.\"),\n };\n}\n\nfunction resolveEncryptionNetworkId(node: unknown, space: string): string {\n const candidate = node as {\n getEncryptionNetworkIdForSpace?: (spaceId: string) => unknown;\n getDefaultEncryptionNetworkId?: () => unknown;\n };\n\n let scoped: unknown;\n try {\n scoped = candidate.getEncryptionNetworkIdForSpace?.(space);\n } catch {\n // A scoped resolver is optional and may fail for a non-primary space.\n }\n if (typeof scoped === \"string\" && scoped.length > 0) return scoped;\n\n let fallback: unknown;\n try {\n fallback = candidate.getDefaultEncryptionNetworkId?.();\n } catch {\n // Both local sources must fail before the operation reports unresolved.\n }\n if (typeof fallback === \"string\" && fallback.length > 0) return fallback;\n\n throw new OperationInvocationError(\n operationError(\n \"ENCRYPTION_NETWORK_UNRESOLVED\",\n \"The encryption network for the target secrets space could not be resolved.\",\n ),\n );\n}\n\ninterface SecretReadingNode {\n readSecret(input: {\n space: string;\n name: string;\n scope?: string;\n }): Promise<SecretReadResult>;\n getEncryptionNetworkIdForSpace?: (spaceId: string) => unknown;\n getDefaultEncryptionNetworkId?: () => unknown;\n}\n","import type { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport nodeSqlParser from \"node-sql-parser\";\nimport { z } from \"zod\";\n\nimport type {\n CapabilityRequirement,\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n RuntimeOperationContext,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { OperationInvocationError, operationError } from \"../errors.js\";\nimport { operationSpaceResolver } from \"../secrets.js\";\nimport { authorizationFailure } from \"./exploration.js\";\n\nconst DEFAULT_MAX_ROWS = 100;\nconst MAX_MAX_ROWS = 1_000;\nconst DEFAULT_MAX_BYTES = 1024 * 1024;\nconst MAX_MAX_BYTES = 4 * 1024 * 1024;\nconst SCHEMA_MAX_ROWS = 500;\nconst SCHEMA_MAX_BYTES = 1024 * 1024;\nconst MAX_PARAMETERS = 100;\nconst MAX_SQL_LENGTH = 64 * 1024;\nconst SQL_WRITE_AUTHORITY_NOTICE =\n \"Approving tinycloud.sql/write grants full read/write/schema mutation authority over this exact database; the MCP tool itself accepts only one parameterized INSERT, UPDATE, or DELETE.\";\n\nconst SCHEMA_QUERY = `SELECT type, name, tbl_name, sql\nFROM sqlite_schema\nWHERE type IN ('table', 'view', 'index', 'trigger')\n AND name NOT LIKE 'sqlite_%'\nORDER BY type, name`;\n\ntype SqlPrimitive = null | number | string;\ninterface SqlBlob {\n readonly type: \"blob\";\n readonly base64: string;\n readonly byteLength: number;\n}\ntype SqlOutputValue = SqlPrimitive | SqlBlob;\ntype SqlInputValue = SqlPrimitive | Readonly<{ type: \"blob\"; base64: string }>;\n\ninterface SqlTargetInput {\n readonly space: string;\n readonly database: string;\n}\n\ninterface SqlQueryInput extends SqlTargetInput {\n readonly sql: string;\n readonly params?: readonly SqlInputValue[];\n readonly maxRows?: number;\n readonly maxBytes?: number;\n}\n\ninterface SqlExecuteInput extends SqlTargetInput {\n readonly sql: string;\n readonly params: readonly SqlInputValue[];\n readonly acknowledgeDatabaseWideAuthority: true;\n}\n\ninterface SqlLimitsOutput {\n readonly maxRows: number;\n readonly maxBytes: number;\n readonly enforcement: \"node-requested-client-verified\";\n}\n\ninterface SqlSchemaInspectOutput {\n readonly space: string;\n readonly database: string;\n readonly objects: readonly {\n readonly type: \"table\" | \"view\" | \"index\" | \"trigger\";\n readonly name: string;\n readonly tableName: string;\n readonly sql?: string;\n }[];\n readonly count: number;\n readonly limits: SqlLimitsOutput;\n}\n\ninterface SqlQueryOutput {\n readonly space: string;\n readonly database: string;\n readonly columns: readonly string[];\n readonly rows: readonly (readonly SqlOutputValue[])[];\n readonly rowCount: number;\n readonly limits: SqlLimitsOutput;\n}\n\ninterface SqlExecuteOutput {\n readonly space: string;\n readonly database: string;\n readonly statementType: \"insert\" | \"update\" | \"delete\";\n readonly changes: number;\n readonly lastInsertRowId: number | null;\n readonly authorityNotice: typeof SQL_WRITE_AUTHORITY_NOTICE;\n}\n\nconst sqlParser = new nodeSqlParser.Parser();\n\nconst SpaceSchema = z.string().min(1).refine(\n (space) =>\n (/^[A-Za-z0-9_-]+$/.test(space) || space.startsWith(\"tinycloud:\")) &&\n !space.includes(\"*\"),\n \"Invalid TinyCloud space.\",\n);\nconst DatabaseSchema = z.string().min(1).max(256).refine(\n (database) =>\n database !== \"/\" &&\n !database.endsWith(\"/\") &&\n !database.includes(\"*\") &&\n !/[\\u0000-\\u001f\\u007f]/.test(database),\n \"Invalid SQLite database name.\",\n);\nconst SafeNumberSchema = z.number().finite().refine(\n (value) => !Number.isInteger(value) || Number.isSafeInteger(value),\n \"SQLite integer parameters must be JavaScript safe integers.\",\n);\nconst Base64Schema = z.string().max(Math.ceil(MAX_MAX_BYTES / 3) * 4).refine(\n isCanonicalBase64,\n \"Invalid base64 BLOB value.\",\n);\nconst SqlInputValueSchema: z.ZodType<SqlInputValue> = z.union([\n z.null(),\n SafeNumberSchema,\n z.string().max(MAX_MAX_BYTES),\n z.object({ type: z.literal(\"blob\"), base64: Base64Schema }).strict(),\n]);\nconst SqlParamsSchema = z.array(SqlInputValueSchema).max(MAX_PARAMETERS).superRefine(\n (params, context) => {\n const totalBytes = params.reduce<number>(\n (total, value) => total + sqlInputValueBytes(value),\n 0,\n );\n if (totalBytes > MAX_MAX_BYTES) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"SQLite query parameters exceed the 4 MiB input limit.\",\n });\n }\n },\n);\nconst RequiredSqlParamsSchema = z.array(SqlInputValueSchema).min(1).max(MAX_PARAMETERS).superRefine(\n (params, context) => {\n const totalBytes = params.reduce<number>(\n (total, value) => total + sqlInputValueBytes(value),\n 0,\n );\n if (totalBytes > MAX_MAX_BYTES) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"SQLite query parameters exceed the 4 MiB input limit.\",\n });\n }\n },\n);\nconst SqlOutputValueSchema: z.ZodType<SqlOutputValue> = z.union([\n z.null(),\n SafeNumberSchema,\n z.string(),\n z.object({\n type: z.literal(\"blob\"),\n base64: z.string(),\n byteLength: z.number().int().nonnegative(),\n }).strict(),\n]);\nconst SqlTargetInputSchema: z.ZodType<SqlTargetInput> = z.object({\n space: SpaceSchema,\n database: DatabaseSchema,\n}).strict();\nconst SqlQueryInputSchema: z.ZodType<SqlQueryInput> = z.object({\n space: SpaceSchema,\n database: DatabaseSchema,\n sql: z.string().min(1).max(MAX_SQL_LENGTH).superRefine((sql, context) => {\n if (!isSingleReadQuery(sql)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"SQL must parse as exactly one SQLite SELECT statement.\",\n });\n }\n }),\n params: SqlParamsSchema.optional(),\n maxRows: z.number().int().positive().max(MAX_MAX_ROWS).optional(),\n maxBytes: z.number().int().positive().max(MAX_MAX_BYTES).optional(),\n}).strict();\nconst SqlExecuteInputSchema: z.ZodType<SqlExecuteInput> = z.object({\n space: SpaceSchema,\n database: DatabaseSchema,\n sql: z.string().min(1).max(MAX_SQL_LENGTH),\n params: RequiredSqlParamsSchema,\n acknowledgeDatabaseWideAuthority: z.literal(true).describe(SQL_WRITE_AUTHORITY_NOTICE),\n}).strict().superRefine((input, context) => {\n if (parseSingleDmlStatement(input.sql, input.params.length) === undefined) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"sql\"],\n message: \"SQL must parse as exactly one parameterized INSERT, UPDATE, or DELETE with one value per positional placeholder.\",\n });\n }\n});\n\nconst SqlLimitsOutputSchema: z.ZodType<SqlLimitsOutput> = z.object({\n maxRows: z.number().int().positive(),\n maxBytes: z.number().int().positive(),\n enforcement: z.literal(\"node-requested-client-verified\"),\n}).strict();\nconst SqlSchemaInspectOutputSchema: z.ZodType<SqlSchemaInspectOutput> = z.object({\n space: z.string().min(1),\n database: z.string().min(1),\n objects: z.array(z.object({\n type: z.enum([\"table\", \"view\", \"index\", \"trigger\"]),\n name: z.string().min(1),\n tableName: z.string().min(1),\n sql: z.string().optional(),\n }).strict()),\n count: z.number().int().nonnegative(),\n limits: SqlLimitsOutputSchema,\n}).strict();\nconst SqlQueryOutputSchema: z.ZodType<SqlQueryOutput> = z.object({\n space: z.string().min(1),\n database: z.string().min(1),\n columns: z.array(z.string()),\n rows: z.array(z.array(SqlOutputValueSchema)),\n rowCount: z.number().int().nonnegative(),\n limits: SqlLimitsOutputSchema,\n}).strict();\nconst SqlExecuteOutputSchema: z.ZodType<SqlExecuteOutput> = z.object({\n space: z.string().min(1),\n database: z.string().min(1),\n statementType: z.enum([\"insert\", \"update\", \"delete\"]),\n changes: z.number().int().nonnegative(),\n lastInsertRowId: z.number().int().nullable(),\n authorityNotice: z.literal(SQL_WRITE_AUTHORITY_NOTICE),\n}).strict();\n\nconst AUTHENTICATED_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\nconst SQL_EXPOSURE: OperationExposure = {\n cli: {\n status: \"excluded\",\n reason: \"Existing SQL Commander commands remain the CLI surface.\",\n },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\nconst SQL_SCHEMA_SENSITIVITY: OperationSensitivity = {\n input: [\"/database\"],\n output: [\"/objects\"],\n};\nconst SQL_QUERY_SENSITIVITY: OperationSensitivity = {\n input: [\"/database\", \"/sql\", \"/params\"],\n output: [\"/columns\", \"/rows\"],\n};\nconst SQL_EXECUTE_SENSITIVITY: OperationSensitivity = {\n input: [\"/database\", \"/sql\", \"/params\"],\n output: [\"/lastInsertRowId\"],\n};\n\ntype SqlDefinition =\n | OperationDefinition<SqlTargetInput, SqlSchemaInspectOutput>\n | OperationDefinition<SqlQueryInput, SqlQueryOutput>\n | OperationDefinition<SqlExecuteInput, SqlExecuteOutput>;\n\nexport const sqlOperationDefinitions: readonly SqlDefinition[] = [\n {\n id: \"tinycloud.sql.schema.inspect\",\n version: 1,\n title: \"Inspect a TinyCloud SQLite schema\",\n description: \"List user tables, views, indexes, and triggers in one exact TinyCloud SQLite database using a fixed read-only query.\",\n input: SqlTargetInputSchema,\n output: SqlSchemaInspectOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: SQL_EXPOSURE,\n sensitivity: SQL_SCHEMA_SENSITIVITY,\n authority: planSqlRead,\n execute: executeSqlSchemaInspect,\n },\n {\n id: \"tinycloud.sql.query\",\n version: 1,\n title: \"Query a TinyCloud SQLite database\",\n description: \"Run exactly one parser-approved SELECT against one exact TinyCloud SQLite database. Result limits are requested from the node and verified locally without silent truncation.\",\n input: SqlQueryInputSchema,\n output: SqlQueryOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: SQL_EXPOSURE,\n sensitivity: SQL_QUERY_SENSITIVITY,\n invalidInputErrorCode: \"SQL_QUERY_INVALID\",\n authority: planSqlRead,\n execute: executeSqlQuery,\n },\n {\n id: \"tinycloud.sql.execute\",\n version: 1,\n title: \"Execute a TinyCloud SQLite DML statement\",\n description: `Run exactly one parameterized INSERT, UPDATE, or DELETE against one exact TinyCloud SQLite database. ${SQL_WRITE_AUTHORITY_NOTICE}`,\n input: SqlExecuteInputSchema,\n output: SqlExecuteOutputSchema,\n effects: [\"write\", \"destructive\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: SQL_EXPOSURE,\n sensitivity: SQL_EXECUTE_SENSITIVITY,\n invalidInputErrorCode: \"SQL_QUERY_INVALID\",\n authority: planSqlWrite,\n execute: executeSqlDml,\n },\n];\n\nasync function planSqlRead(\n context: RuntimeOperationContext,\n input: SqlTargetInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveSqlSpace(context, input.space);\n return [{\n service: \"tinycloud.sql\",\n space,\n path: input.database,\n actions: [\"tinycloud.sql/read\"],\n }];\n}\n\nasync function planSqlWrite(\n context: RuntimeOperationContext,\n input: SqlExecuteInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveSqlSpace(context, input.space);\n return [{\n service: \"tinycloud.sql\",\n space,\n path: input.database,\n actions: [\"tinycloud.sql/write\"],\n description: SQL_WRITE_AUTHORITY_NOTICE,\n }];\n}\n\nasync function executeSqlSchemaInspect(\n context: OperationContext,\n input: SqlTargetInput,\n): Promise<OperationExecutionOutcome<SqlSchemaInspectOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveSqlSpace(runtime, input.space);\n const result = await runtimeNode(runtime)\n .sqlForSpace(space)\n .db(input.database)\n .query(SCHEMA_QUERY, [], { maxRows: SCHEMA_MAX_ROWS, maxBytes: SCHEMA_MAX_BYTES });\n if (!result.ok) return sqlServiceFailure(result.error, \"inspect the SQLite schema\");\n\n const normalized = normalizeQueryResult(result.data, SCHEMA_MAX_ROWS, SCHEMA_MAX_BYTES);\n const objects = normalized.rows.map((row) => schemaObject(row));\n return {\n status: \"ok\",\n output: {\n space,\n database: input.database,\n objects,\n count: objects.length,\n limits: limitsOutput(SCHEMA_MAX_ROWS, SCHEMA_MAX_BYTES),\n },\n };\n } catch (error) {\n return sqlFailure(error, \"inspect the SQLite schema\");\n }\n}\n\nasync function executeSqlQuery(\n context: OperationContext,\n input: SqlQueryInput,\n): Promise<OperationExecutionOutcome<SqlQueryOutput>> {\n try {\n if (!isSingleReadQuery(input.sql)) {\n return {\n status: \"error\",\n error: operationError(\n \"SQL_QUERY_INVALID\",\n \"SQL must parse as exactly one SQLite SELECT statement.\",\n ),\n };\n }\n\n const runtime = runtimeContext(context);\n const space = resolveSqlSpace(runtime, input.space);\n const maxRows = input.maxRows ?? DEFAULT_MAX_ROWS;\n const maxBytes = input.maxBytes ?? DEFAULT_MAX_BYTES;\n const params = (input.params ?? []).map(decodeSqlInputValue);\n const result = await runtimeNode(runtime)\n .sqlForSpace(space)\n .db(input.database)\n .query(input.sql, params, { maxRows, maxBytes });\n if (!result.ok) return sqlServiceFailure(result.error, \"run the SQLite query\");\n\n const normalized = normalizeQueryResult(result.data, maxRows, maxBytes);\n return {\n status: \"ok\",\n output: {\n space,\n database: input.database,\n columns: normalized.columns,\n rows: normalized.rows,\n rowCount: normalized.rows.length,\n limits: limitsOutput(maxRows, maxBytes),\n },\n };\n } catch (error) {\n return sqlFailure(error, \"run the SQLite query\");\n }\n}\n\nasync function executeSqlDml(\n context: OperationContext,\n input: SqlExecuteInput,\n): Promise<OperationExecutionOutcome<SqlExecuteOutput>> {\n try {\n const statementType = parseSingleDmlStatement(input.sql, input.params.length);\n if (statementType === undefined) {\n return {\n status: \"error\",\n error: operationError(\n \"SQL_QUERY_INVALID\",\n \"SQL must parse as exactly one parameterized INSERT, UPDATE, or DELETE with one value per positional placeholder.\",\n ),\n };\n }\n\n const runtime = runtimeContext(context);\n const space = resolveSqlSpace(runtime, input.space);\n const result = await runtimeNode(runtime)\n .sqlForSpace(space)\n .db(input.database)\n .execute(input.sql, input.params.map(decodeSqlInputValue));\n if (!result.ok) return authorizationFailure(result.error, \"execute the SQLite statement\") ?? sqlMutationFailure();\n const normalized = normalizeExecuteResult(result.data);\n return {\n status: \"ok\",\n output: {\n space,\n database: input.database,\n statementType,\n ...normalized,\n authorityNotice: SQL_WRITE_AUTHORITY_NOTICE,\n },\n };\n } catch (error) {\n if (error instanceof OperationInvocationError) return { status: \"error\", error: error.operationError };\n return authorizationFailure(error, \"execute the SQLite statement\") ?? sqlMutationFailure();\n }\n}\n\nfunction isSingleReadQuery(sql: string): boolean {\n const ast = parseSingleStatement(sql);\n return ast !== undefined && ast.type === \"select\";\n}\n\nfunction parseSingleDmlStatement(\n sql: string,\n parameterCount: number,\n): \"insert\" | \"update\" | \"delete\" | undefined {\n const ast = parseSingleStatement(sql);\n if (\n ast === undefined ||\n (ast.type !== \"insert\" && ast.type !== \"update\" && ast.type !== \"delete\") ||\n ast.with !== undefined && ast.with !== null\n ) {\n return undefined;\n }\n const placeholders = countPositionalParameters(ast);\n return placeholders > 0 && placeholders === parameterCount ? ast.type : undefined;\n}\n\nfunction parseSingleStatement(sql: string): Record<string, unknown> | undefined {\n try {\n const ast = sqlParser.astify(sql, { database: \"sqlite\" }) as unknown;\n return !Array.isArray(ast) && isRecord(ast) ? ast : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction countPositionalParameters(value: unknown): number {\n if (Array.isArray(value)) {\n return value.reduce((count, entry) => count + countPositionalParameters(entry), 0);\n }\n if (!isRecord(value)) return 0;\n const current = value.type === \"origin\" && value.value === \"?\" ? 1 : 0;\n return Object.values(value).reduce<number>(\n (count, entry) => count + countPositionalParameters(entry),\n current,\n );\n}\n\nfunction decodeSqlInputValue(value: SqlInputValue): null | number | string | Uint8Array {\n if (isRecord(value) && value.type === \"blob\") {\n return new Uint8Array(Buffer.from(value.base64 as string, \"base64\"));\n }\n return value as null | number | string;\n}\n\nfunction normalizeQueryResult(\n value: unknown,\n maxRows: number,\n maxBytes: number,\n): Readonly<{ columns: readonly string[]; rows: readonly (readonly SqlOutputValue[])[] }> {\n if (!isRecord(value) || !Array.isArray(value.columns) || !Array.isArray(value.rows)) {\n throw unsafeSqlValue(\"The node returned an invalid SQLite query result.\");\n }\n const columns = value.columns.map((column) => {\n if (typeof column !== \"string\") {\n throw unsafeSqlValue(\"The node returned an invalid SQLite column name.\");\n }\n return column;\n });\n const rows = value.rows.map((row) => {\n if (!Array.isArray(row) || row.length !== columns.length) {\n throw unsafeSqlValue(\"The node returned an invalid SQLite row.\");\n }\n return row.map(normalizeSqlOutputValue);\n });\n\n const serializedBytes = Buffer.byteLength(JSON.stringify({ columns, rows }), \"utf8\");\n if (rows.length > maxRows || serializedBytes > maxBytes) {\n throw new OperationInvocationError(operationError(\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"The SQLite query result exceeded the requested result limits.\",\n {\n details: {\n maxRows,\n maxBytes,\n returnedRows: rows.length,\n returnedBytes: serializedBytes,\n },\n },\n ));\n }\n return { columns, rows };\n}\n\nfunction normalizeSqlOutputValue(value: unknown): SqlOutputValue {\n if (value === null || typeof value === \"string\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {\n throw unsafeSqlValue(\"The node returned an integer that cannot be represented safely in JavaScript.\");\n }\n return value;\n }\n if (value instanceof Uint8Array) return encodeBlob(value);\n if (Array.isArray(value) && value.every(isByte)) {\n return encodeBlob(Uint8Array.from(value));\n }\n if (isRecord(value) && value.type === \"Buffer\" && Array.isArray(value.data) && value.data.every(isByte)) {\n return encodeBlob(Uint8Array.from(value.data));\n }\n throw unsafeSqlValue(\"The node returned an unsupported SQLite value.\");\n}\n\nfunction normalizeExecuteResult(\n value: unknown,\n): Readonly<{ changes: number; lastInsertRowId: number | null }> {\n if (\n !isRecord(value) ||\n !Number.isSafeInteger(value.changes) ||\n (value.changes as number) < 0 ||\n (\n value.lastInsertRowId !== null &&\n !Number.isSafeInteger(value.lastInsertRowId)\n )\n ) {\n throw unsafeSqlValue(\"The node returned SQLite mutation metadata that cannot be represented safely in JavaScript.\");\n }\n return {\n changes: value.changes as number,\n lastInsertRowId: value.lastInsertRowId as number | null,\n };\n}\n\nfunction schemaObject(row: readonly SqlOutputValue[]): SqlSchemaInspectOutput[\"objects\"][number] {\n const [type, name, tableName, sql] = row;\n if (\n (type !== \"table\" && type !== \"view\" && type !== \"index\" && type !== \"trigger\") ||\n typeof name !== \"string\" ||\n typeof tableName !== \"string\" ||\n (sql !== null && typeof sql !== \"string\")\n ) {\n throw unsafeSqlValue(\"The node returned an invalid SQLite schema record.\");\n }\n return {\n type,\n name,\n tableName,\n ...(sql === null ? {} : { sql }),\n };\n}\n\nfunction limitsOutput(maxRows: number, maxBytes: number): SqlLimitsOutput {\n return { maxRows, maxBytes, enforcement: \"node-requested-client-verified\" };\n}\n\nfunction runtimeContext(context: OperationContext): RuntimeOperationContext {\n if (context.runtime === undefined) {\n throw new TypeError(\"Authenticated operation runtime is unavailable.\");\n }\n return context as RuntimeOperationContext;\n}\n\nfunction runtimeNode(context: RuntimeOperationContext): TinyCloudNode {\n return context.runtime.node as TinyCloudNode;\n}\n\nfunction resolveSqlSpace(context: RuntimeOperationContext, space: string): string {\n const resolved = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n )(space);\n const name = resolved.split(\":\").at(-1)?.toLowerCase();\n if (name === \"secrets\" || name === \"account\") {\n throw new OperationInvocationError(operationError(\n \"INPUT_INVALID\",\n \"Generic SQL operations cannot access protected TinyCloud account or secrets spaces.\",\n ));\n }\n return resolved;\n}\n\nfunction encodeBlob(value: Uint8Array): SqlBlob {\n return {\n type: \"blob\",\n base64: Buffer.from(value).toString(\"base64\"),\n byteLength: value.byteLength,\n };\n}\n\nfunction unsafeSqlValue(message: string): OperationInvocationError {\n return new OperationInvocationError(operationError(\"SQL_VALUE_UNSAFE\", message));\n}\n\nfunction sqlFailure(\n error: unknown,\n action: string,\n): OperationExecutionOutcome<never> {\n if (error instanceof OperationInvocationError) {\n return { status: \"error\", error: error.operationError };\n }\n return authorizationFailure(error, action) ?? nodeFailure(action);\n}\n\nfunction nodeFailure(action: string): OperationExecutionOutcome<never> {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n `The TinyCloud node could not ${action}.`,\n { retryable: true },\n ),\n };\n}\n\nfunction sqlServiceFailure(\n error: unknown,\n action: string,\n): OperationExecutionOutcome<never> {\n const auth = authorizationFailure(error, action);\n if (auth !== undefined) return auth;\n if (isRecord(error) && error.code === \"SQL_RESPONSE_TOO_LARGE\") {\n return {\n status: \"error\",\n error: operationError(\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"The SQLite query result exceeded the requested result limits.\",\n ),\n };\n }\n return nodeFailure(action);\n}\n\nfunction sqlMutationFailure(): OperationExecutionOutcome<never> {\n return {\n status: \"error\",\n error: operationError(\n \"SQL_EXECUTION_FAILED\",\n \"The SQLite statement outcome is unknown; inspect database state before considering another write.\",\n { retryable: false },\n ),\n };\n}\n\nfunction isCanonicalBase64(value: string): boolean {\n if (value === \"\") return true;\n if (value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return false;\n return Buffer.from(value, \"base64\").toString(\"base64\") === value;\n}\n\nfunction sqlInputValueBytes(value: SqlInputValue): number {\n if (typeof value === \"string\") return Buffer.byteLength(value, \"utf8\");\n if (isRecord(value) && value.type === \"blob\") {\n return Buffer.from(value.base64 as string, \"base64\").byteLength;\n }\n return 8;\n}\n\nfunction isByte(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 255;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { join } from \"node:path\";\n\n// Keep the value import namespace-shaped so modules that import this one stay\n// compatible with lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\nimport type {\n PermissionEntry,\n PortableDelegation,\n RuntimeDelegationActivator,\n ValidatedRuntimeDelegation,\n} from \"@tinycloud/node-sdk\";\n\nimport { DelegationRequestBindingSchema } from \"./artifacts.js\";\nimport { delegationWithinRequest, type OperationSpaceResolver } from \"./authority.js\";\nimport {\n profilePath,\n readAdditionalDelegations,\n readJson,\n readSession,\n updateProfileStore,\n withProfileLock,\n writeJsonAtomic,\n} from \"./state.js\";\n\nexport { operationSpaceResolver } from \"./secrets.js\";\n\n/**\n * Request bindings for delegations stored in `additional-delegations.json`.\n *\n * A compact-UCAN or signed-login (SIWE) record replays only when its\n * `authorityRequest` binding is valid and the capabilities its signed bytes\n * grant fit inside the binding's `requested`. Validated activation checks that\n * before anything is activated. Three writers produce bindings:\n *\n * - `tinycloud.auth.import`: the stored request the delegation was checked\n * against (`requestId` is that request's).\n * - `tc auth import` of an artifact with no request: exactly the delegation's\n * own signed capabilities (`unbound-import:<cid>`).\n * - The one-time migration of records stored before bindings existed: exactly\n * each record's own signed capabilities (`migrated:<cid>`).\n *\n * Records the CLI stores from its own signed-login grants carry no\n * `siweProof`, cannot be verified here, and keep their legacy CLI replay.\n *\n * The binding is local profile data. It stops records written by any other\n * path from granting authority. It does not stop someone who can write the\n * profile directory, who already holds the session key and the signed bytes.\n */\n\nexport type BindingSource = \"migration\" | \"unbound-import\";\n\nconst REQUEST_ID_PREFIX: Record<BindingSource, string> = {\n migration: \"migrated\",\n \"unbound-import\": \"unbound-import\",\n};\n\n/** The audit note written beside a binding synthesized from a record's own signed capabilities. */\nexport const BINDING_NOTES: Record<BindingSource, string> = {\n migration:\n \"Stored without a request binding before bindings were required. Bound at migration to exactly \" +\n \"its own signed capabilities, so replay refuses any delegation in this record that exceeds them.\",\n \"unbound-import\":\n \"Imported by `tc auth import` without a stored request. Bound to exactly its own signed \" +\n \"capabilities, so replay refuses any delegation in this record that exceeds them.\",\n};\n\n/** Short so a busy profile only defers migration to a later runtime. */\nconst MIGRATION_LOCK_TIMEOUT_MS = 250;\n\n/** The per-profile marker: present once that profile's unbound records were migrated. */\nexport function bindingMigrationPath(profile: string): string {\n return join(profilePath(profile), \"delegation-binding-migration.json\");\n}\n\n/**\n * How replay treats a stored record:\n *\n * - `compact` and `signed-login` records go through validated activation and\n * the binding rule.\n * - `other` records keep the CLI's legacy replay: an unbound record whose\n * bytes are not compact and that has no `siweProof`, which is how the CLI\n * stores its own signed-login grants. The operations runtime never installs\n * them.\n * - `refused` records install nothing anywhere.\n *\n * A record is `refused` unless its `delegationHeader` has exactly one own\n * key, `Authorization`, with a string value: header names are matched\n * case-insensitively on the wire, and other value types are stringified, so\n * any other shape could reach the node as authorization bytes this rule never\n * read. Bytes containing a `.` are never `other`: a CACAO has none, and\n * validated activation refuses anything compact-shaped that it cannot parse.\n * A record with an `authorityRequest` (valid or not) is never `other`: the\n * legacy path cannot hold it to a binding, so dropping a `siweProof` cannot\n * route a bound signed-login delegation around its binding.\n */\nexport function storedDelegationKind(\n entry: unknown,\n): \"compact\" | \"signed-login\" | \"other\" | \"refused\" {\n // A stored element that is not an object is not a record at all.\n if (!isRecord(entry)) return \"refused\";\n const delegation = entry.delegation;\n if (!isRecord(delegation)) return \"refused\";\n const header = delegation.delegationHeader;\n if (\n !isRecord(header) ||\n Object.keys(header).length !== 1 ||\n !Object.prototype.hasOwnProperty.call(header, \"Authorization\") ||\n typeof header.Authorization !== \"string\"\n ) {\n return \"refused\";\n }\n if (\"siweProof\" in delegation) return \"signed-login\";\n if (header.Authorization.includes(\".\")) return \"compact\";\n return \"authorityRequest\" in entry ? \"refused\" : \"other\";\n}\n\n/**\n * What replay holds a stored record to: its binding's `requested`, `\"signed\"`\n * for an unbound compact record before the profile has migrated (it installs\n * with its own signed authority, as before bindings existed), or `undefined`\n * when the record installs nothing.\n */\nexport function replayLimit(\n entry: unknown,\n migrated: boolean,\n): readonly PermissionEntry[] | \"signed\" | undefined {\n const kind = storedDelegationKind(entry);\n if (!isRecord(entry) || (kind !== \"compact\" && kind !== \"signed-login\")) return undefined;\n const binding = DelegationRequestBindingSchema.safeParse(entry.authorityRequest);\n if (binding.success) return binding.data.requested;\n return !migrated && kind === \"compact\" && !(\"authorityRequest\" in entry) ? \"signed\" : undefined;\n}\n\n/**\n * Binds a record to exactly the capabilities its signed bytes grant, with an\n * audit note naming where the binding came from.\n */\nfunction bindToSignedCapabilities<T extends { readonly delegation: { readonly cid: string } }>(\n record: T,\n signed: readonly PermissionEntry[],\n source: BindingSource,\n recordedAt = new Date().toISOString(),\n): T & Record<\"authorityRequest\" | \"authorityRequestAudit\", unknown> {\n return {\n ...record,\n authorityRequest: DelegationRequestBindingSchema.parse({\n requestId: `${REQUEST_ID_PREFIX[source]}:${record.delegation.cid}`,\n requested: structuredClone(signed),\n }),\n authorityRequestAudit: { source, recordedAt, note: BINDING_NOTES[source] },\n };\n}\n\n/**\n * Validates and activates a compact delegation that `tc auth import` received\n * without a stored request, through the same validated activation replay uses,\n * and returns its record bound to exactly the capabilities its signed bytes\n * grant. Throws when validation or activation fails.\n */\nexport async function activateUnboundCompactImport(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<{ delegation: PortableDelegation; permissions: PermissionEntry[] } & Record<string, unknown>> {\n const activated = await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, { host });\n return bindToSignedCapabilities(\n // The record keeps the delegation as imported; replay validates it again.\n { delegation, permissions: [...activated.effectivePermissions] },\n activated.effectivePermissions,\n \"unbound-import\",\n );\n}\n\n/**\n * The stored records after adding records written without a stored request\n * (by `tc auth import` or a CLI grant). A stored record for the same CID that\n * carries an `authorityRequest` is kept as it is, so this route never drops,\n * replaces or weakens a binding; otherwise each record replaces every row for\n * its CID, at the first one's position, or is appended. Callers write the\n * result under the profile lock they already use for this store.\n */\nexport function mergeDelegationsWithoutRequest(\n stored: readonly unknown[],\n incoming: readonly ({ readonly delegation: { readonly cid: string } } & Record<string, unknown>)[],\n): unknown[] {\n let records = [...stored];\n for (const record of incoming) {\n const cid = record.delegation.cid;\n if (records.some((entry) => storedCid(entry) === cid && isRecord(entry) && \"authorityRequest\" in entry)) continue;\n const position = records.findIndex((entry) => storedCid(entry) === cid);\n const others = records.filter((entry) => storedCid(entry) !== cid);\n records = position === -1\n ? [...records, record]\n : [...others.slice(0, position), record, ...others.slice(position)];\n }\n return records;\n}\n\n/**\n * Runs before replay reads the profile's records, so those records and the\n * migration marker agree. Returns whether the profile has migrated.\n *\n * Migration runs under the profile lock, and only while the profile's\n * persisted session is still the one `node` restored: a session rotated since\n * the restore leaves migration to a runtime of the new session. Each compact\n * record with no `authorityRequest` is handled on its own: if validated\n * activation can read its signed capabilities (CID, expiry, audience and\n * declared resources checked, nothing activated) and they form a valid\n * binding, the record is bound to exactly those capabilities; otherwise it\n * stays unbound, is listed in the marker's `unbound`, and installs nothing\n * after migration. A compact record whose capabilities cannot be read could\n * not activate for this session either. `migrate` must be false unless `node`\n * holds the profile's own restored session.\n *\n * Migration is best-effort and restartable. The bound records are written\n * first and the marker last; a busy lock or any failure before the marker\n * leaves the profile unmigrated, so this runtime replays under the\n * pre-migration rule and the next one migrates again. Records already bound\n * by an interrupted run keep their bindings.\n */\nexport async function prepareStoredDelegationReplay(\n profile: string,\n node: RuntimeDelegationActivator,\n options: { readonly host: string; readonly migrate: boolean },\n): Promise<boolean> {\n if (await bindingMigrationRecorded(profile)) return true;\n // A persisted session without a `verificationMethod`, or one this node did\n // not restore, never migrates here; skip the lock rather than take it for\n // nothing on every command.\n if (!options.migrate || !await holdsPersistedSession(profile, node)) return false;\n try {\n return await withProfileLock(profile, async () => {\n if (await bindingMigrationRecorded(profile)) return true;\n // Checked again under the lock: a session rotated since the restore\n // leaves migration to a runtime of the new session.\n if (!await holdsPersistedSession(profile, node)) return false;\n const recordedAt = new Date().toISOString();\n const bound = new Map<string, Record<string, unknown>>();\n const unbound: string[] = [];\n for (const entry of await readAdditionalDelegations<unknown>(profile)) {\n // Elements that are not objects are skipped: they install nothing.\n if (!isRecord(entry) || \"authorityRequest\" in entry || storedDelegationKind(entry) !== \"compact\") continue;\n const migrated = await migratedRecord(node, entry, options.host, recordedAt);\n if (migrated === undefined) unbound.push(String(storedCid(entry)));\n else bound.set(recordKey(entry)!, migrated);\n }\n if (bound.size > 0) {\n await updateProfileStore<unknown, void>(profile, \"additional-delegations\", (records) => ({\n records: records.map((entry) => {\n const key = !isRecord(entry) || \"authorityRequest\" in entry ? undefined : recordKey(entry);\n return (key === undefined ? undefined : bound.get(key)) ?? entry;\n }),\n result: undefined,\n }));\n }\n await writeJsonAtomic(bindingMigrationPath(profile), {\n formatVersion: 1,\n migratedAt: recordedAt,\n bound: [...bound.values()].map(storedCid),\n unbound,\n });\n return true;\n }, { timeoutMs: MIGRATION_LOCK_TIMEOUT_MS });\n } catch {\n return false;\n }\n}\n\n/** Whether the profile's persisted session is the one `node` restored. */\nasync function holdsPersistedSession(profile: string, node: RuntimeDelegationActivator): Promise<boolean> {\n try {\n const persisted = await readSession<Record<string, unknown>>(profile);\n return typeof persisted?.verificationMethod === \"string\" &&\n typeof node.sessionDid === \"string\" &&\n persisted.verificationMethod.split(\"#\", 1)[0] === node.sessionDid.split(\"#\", 1)[0];\n } catch {\n return false;\n }\n}\n\n/** One record's migration: bound to its own signed capabilities, or `undefined` if it cannot be. */\nasync function migratedRecord(\n node: RuntimeDelegationActivator,\n entry: Record<string, unknown>,\n host: string,\n recordedAt: string,\n): Promise<Record<string, unknown> | undefined> {\n const delegation = normalizeStoredDelegation(entry);\n if (delegation === undefined) return undefined;\n const signed = await signedCapabilities(node, delegation, host);\n if (signed === undefined) return undefined;\n try {\n // The stored delegation is kept exactly as it was; only the binding is added.\n return bindToSignedCapabilities({ ...entry, delegation: { ...entry.delegation as object, cid: delegation.cid } }, signed, \"migration\", recordedAt);\n } catch {\n // Signed capabilities a request binding cannot hold (an empty action, say).\n return undefined;\n }\n}\n\n/**\n * Replays one stored record under the binding rule. A record with a valid\n * binding installs only if its signed capabilities fit inside it. Before the\n * profile has migrated, an unbound compact record installs with its signed\n * authority as it always did; after, it installs nothing. A signed-login\n * record installs only with a binding. Returns the installed delegation, or\n * `undefined` when the record installs nothing. Never throws: stored data is\n * untrusted transport material.\n */\nexport async function replayStoredDelegation(\n node: RuntimeDelegationActivator,\n entry: unknown,\n options: {\n readonly host: string;\n readonly migrated: boolean;\n readonly resolveSpace: OperationSpaceResolver;\n },\n): Promise<ValidatedRuntimeDelegation | undefined> {\n const delegation = normalizeStoredDelegation(entry);\n if (delegation === undefined || delegation.expiry.getTime() <= Date.now()) return undefined;\n const limit = replayLimit(entry, options.migrated);\n if (limit === undefined) return undefined;\n const authorize = limit === \"signed\"\n ? () => true\n : (effective: readonly PermissionEntry[]) => delegationWithinRequest(limit, effective, options.resolveSpace);\n try {\n return await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, { host: options.host, authorize });\n } catch {\n // An invalid, stale, wrong-session, or rejected record grants nothing and\n // must not reveal its contents through a safe operation channel.\n return undefined;\n }\n}\n\n/** An unreadable marker counts as migrated: a damaged marker never reopens migration. */\nexport async function bindingMigrationRecorded(profile: string): Promise<boolean> {\n try {\n return await readJson<unknown>(bindingMigrationPath(profile)) !== null;\n } catch {\n return true;\n }\n}\n\n/**\n * The capabilities a stored delegation's signed bytes grant, read through\n * validated activation, which `authorize` stops before anything is activated.\n */\nasync function signedCapabilities(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<readonly PermissionEntry[] | undefined> {\n let signed: readonly PermissionEntry[] | undefined;\n try {\n await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, {\n // The transport host is not signed authority; check it at replay instead.\n host: delegation.host ?? host,\n authorize: (effective) => {\n signed = effective;\n return false;\n },\n });\n } catch {\n // Refused by `authorize` once the capabilities were read, or failed a check before it.\n }\n return signed;\n}\n\nfunction normalizeStoredDelegation(entry: unknown): PortableDelegation | undefined {\n if (!isRecord(entry)) return undefined;\n const raw = entry.delegation;\n if (!isRecord(raw) || !isRecord(raw.delegationHeader)) return undefined;\n const expiry = raw.expiry instanceof Date\n ? raw.expiry\n : typeof raw.expiry === \"string\" ? new Date(raw.expiry) : undefined;\n if (\n expiry === undefined || Number.isNaN(expiry.getTime()) ||\n typeof raw.cid !== \"string\" ||\n typeof raw.spaceId !== \"string\" ||\n typeof raw.path !== \"string\" ||\n !Array.isArray(raw.actions) || !raw.actions.every((action) => typeof action === \"string\") ||\n typeof raw.delegateDID !== \"string\" ||\n typeof raw.ownerAddress !== \"string\" ||\n typeof raw.chainId !== \"number\" ||\n typeof raw.delegationHeader.Authorization !== \"string\"\n ) {\n return undefined;\n }\n return { ...raw, expiry } as PortableDelegation;\n}\n\nfunction storedCid(entry: unknown): string | undefined {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid === \"string\" ? cid : undefined;\n}\n\n/** A record's CID and exact authorization bytes. */\nfunction recordKey(entry: Record<string, unknown>): string | undefined {\n const delegation = entry.delegation;\n if (!isRecord(delegation) || !isRecord(delegation.delegationHeader)) return undefined;\n return JSON.stringify([delegation.cid, delegation.delegationHeader.Authorization]);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { z } from \"zod\";\n\nimport type {\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { bindingMigrationRecorded, replayLimit, storedDelegationKind } from \"../delegation-binding.js\";\nimport { operationError } from \"../errors.js\";\nimport {\n additionalDelegationsPath,\n readJson,\n readProfile,\n readSession,\n readStoreMetadata,\n} from \"../state.js\";\n\ntype StatusInput = Record<never, never>;\n\ninterface StatusOutput {\n readonly profile: string;\n readonly host: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType?: \"human\" | \"agent\";\n readonly principalDid?: string;\n readonly sessionDid?: string;\n readonly ownerDid?: string;\n readonly space?: string;\n readonly session: {\n readonly present: boolean;\n readonly expired: boolean | null;\n readonly expiresAt: string | null;\n };\n readonly liveAdditionalDelegationCount: number;\n}\n\nconst StatusInputSchema: z.ZodType<StatusInput> = z.object({}).strict();\n\nconst StatusOutputSchema: z.ZodType<StatusOutput> = z.object({\n profile: z.string().min(1),\n host: z.string().min(1),\n posture: z.enum([\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n \"unauthenticated\",\n ]),\n operatorType: z.enum([\"human\", \"agent\"]).optional(),\n principalDid: z.string().min(1).optional(),\n sessionDid: z.string().min(1).optional(),\n ownerDid: z.string().min(1).optional(),\n space: z.string().min(1).optional(),\n session: z.object({\n present: z.boolean(),\n expired: z.boolean().nullable(),\n expiresAt: z.string().datetime({ offset: true }).nullable(),\n }).strict(),\n liveAdditionalDelegationCount: z.number().int().nonnegative().describe(\n \"Stored, unexpired delegations the replay rule accepts: compact-UCAN or signed-login records with a request \" +\n \"binding, and unbound compact-UCAN records before the profile's one-time binding migration. Each is still \" +\n \"validated, and checked against its binding, when a runtime installs it.\",\n ),\n}).strict();\n\nconst STATUS_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n \"unauthenticated\",\n];\n\nconst STATUS_EXPOSURE: OperationExposure = {\n cli: { status: \"required\" },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\n\nconst STATUS_SENSITIVITY: OperationSensitivity = { input: [], output: [] };\n\n/**\n * Internal I2 definition material. The registry integration owner imports this\n * collection; package entrypoints intentionally do not expose these handlers.\n */\nexport const statusOperationDefinitions: readonly OperationDefinition<StatusInput, StatusOutput>[] = [\n createStatusDefinition({\n id: \"tinycloud.status.get\",\n title: \"TinyCloud status\",\n description: \"Inspect the selected TinyCloud profile's safe local status.\",\n }),\n createStatusDefinition({\n id: \"tinycloud.auth.status\",\n title: \"TinyCloud authentication status\",\n description: \"Inspect the selected TinyCloud profile's safe authentication status.\",\n }),\n];\n\nfunction createStatusDefinition(params: Readonly<{\n id: \"tinycloud.status.get\" | \"tinycloud.auth.status\";\n title: string;\n description: string;\n}>): OperationDefinition<StatusInput, StatusOutput> {\n return {\n id: params.id,\n version: 1,\n title: params.title,\n description: params.description,\n input: StatusInputSchema,\n output: StatusOutputSchema,\n effects: [\"read\"],\n runtime: \"inspection\",\n postures: STATUS_POSTURES,\n exposure: STATUS_EXPOSURE,\n sensitivity: STATUS_SENSITIVITY,\n authority: async () => [],\n execute: inspectPinnedProfileStatus,\n };\n}\n\nasync function inspectPinnedProfileStatus(\n context: OperationContext,\n _input: StatusInput,\n): Promise<OperationExecutionOutcome<StatusOutput>> {\n const profile = context.summary.profile;\n if (!(await pinnedProfileExists(profile))) return profileNotFound(profile);\n\n try {\n const [session, liveAdditionalDelegationCount] = await Promise.all([\n readSession<Record<string, unknown>>(profile),\n countLiveAdditionalDelegations(profile),\n ]);\n const sessionSummary = summarizeSession(session);\n\n return {\n status: \"ok\",\n output: {\n profile,\n host: context.summary.host,\n posture: context.summary.posture,\n ...(context.summary.operatorType === undefined\n ? {}\n : { operatorType: context.summary.operatorType }),\n ...(context.summary.principalDid === undefined\n ? {}\n : { principalDid: context.summary.principalDid }),\n ...(context.summary.sessionDid === undefined\n ? {}\n : { sessionDid: context.summary.sessionDid }),\n ...(context.summary.ownerDid === undefined\n ? {}\n : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { space: context.summary.space }),\n session: sessionSummary,\n liveAdditionalDelegationCount,\n },\n };\n } catch {\n // Store contents may contain keys, session material, or delegation bytes.\n // A state-inspection failure must not relay any part of that material.\n return {\n status: \"error\",\n error: operationError(\n \"INTERNAL_ERROR\",\n \"The profile state could not be inspected.\",\n ),\n };\n }\n}\n\nasync function pinnedProfileExists(profile: string): Promise<boolean> {\n try {\n const storedProfile = await readProfile<Record<string, unknown>>(profile);\n return isRecord(storedProfile);\n } catch {\n return false;\n }\n}\n\nasync function countLiveAdditionalDelegations(profile: string): Promise<number> {\n await readStoreMetadata(profile, \"additional-delegations\");\n const rawDelegations = await readJson<unknown>(additionalDelegationsPath(profile));\n if (rawDelegations === null) return 0;\n if (!Array.isArray(rawDelegations)) throw new TypeError(\"Invalid additional delegation store.\");\n\n const now = Date.now();\n const migrated = await bindingMigrationRecorded(profile);\n let count = 0;\n for (const entry of rawDelegations) {\n // Elements replay refuses outright (not objects, no delegation, malformed\n // headers) never install, so they are not inspected either.\n if (storedDelegationKind(entry) === \"refused\") continue;\n const expiry = storedDelegationExpiry(entry);\n // Records replay refuses outright (unbound after migration, malformed,\n // or the CLI's own signed-login grants) are not runtime authority.\n if (expiry.getTime() > now && replayLimit(entry, migrated) !== undefined) count += 1;\n }\n return count;\n}\n\nfunction summarizeSession(session: Record<string, unknown> | null): StatusOutput[\"session\"] {\n if (session === null) return { present: false, expired: null, expiresAt: null };\n if (!isRecord(session)) throw new TypeError(\"Invalid session store.\");\n\n const expiry = extractSessionExpiry(session);\n if (expiry === null) return { present: true, expired: null, expiresAt: null };\n\n return {\n present: true,\n expired: expiry.getTime() <= Date.now(),\n expiresAt: expiry.toISOString(),\n };\n}\n\nfunction storedDelegationExpiry(entry: unknown): Date {\n if (!isRecord(entry) || !isRecord(entry.delegation) || !(\"expiry\" in entry.delegation)) {\n throw new TypeError(\"Invalid stored delegation.\");\n }\n return parseExpiry(entry.delegation.expiry);\n}\n\nfunction extractSessionExpiry(session: Record<string, unknown>): Date | null {\n for (const field of [\"expiresAt\", \"expiry\", \"expirationTime\"] as const) {\n if (!(field in session) || session[field] === undefined || session[field] === null) continue;\n return parseExpiry(session[field]);\n }\n\n if (!(\"siwe\" in session) || session.siwe === undefined || session.siwe === null) return null;\n if (typeof session.siwe !== \"string\") throw new TypeError(\"Invalid session expiry.\");\n const match = session.siwe.match(/^Expiration Time:\\s*(.+)$/im);\n return match === null ? null : parseExpiry(match[1].trim());\n}\n\nfunction parseExpiry(value: unknown): Date {\n const date = value instanceof Date\n ? value\n : typeof value === \"number\" && Number.isFinite(value)\n ? new Date(value > 0 && value < 1_000_000_000_000 ? value * 1_000 : value)\n : typeof value === \"string\" && value.trim() !== \"\"\n ? new Date(value)\n : null;\n if (date === null || Number.isNaN(date.getTime())) throw new TypeError(\"Invalid expiry.\");\n return date;\n}\n\nfunction profileNotFound(profile: string): OperationExecutionOutcome<never> {\n return {\n status: \"error\",\n error: operationError(\n \"PROFILE_NOT_FOUND\",\n `Profile \"${profile}\" is not available.`,\n ),\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { OperationDefinition, OperationId } from \"./contract.js\";\nimport { authOperationDefinitions } from \"./operations/auth.js\";\nimport { explorationOperationDefinitions } from \"./operations/exploration.js\";\nimport { secretsGetOperationDefinitions } from \"./operations/secrets-get.js\";\nimport { sqlOperationDefinitions } from \"./operations/sql.js\";\nimport { statusOperationDefinitions } from \"./operations/status.js\";\n\nexport type OperationLookup =\n | Readonly<{ status: \"found\"; definition: OperationDefinition<any, any> }>\n | Readonly<{ status: \"operation_not_found\" }>\n | Readonly<{\n status: \"operation_version_unsupported\";\n supportedVersions: readonly number[];\n }>;\n\n/**\n * The closed v1 catalog is assembled from internal definitions. There is no\n * exported registration hook for projections or a handler bypass API.\n */\nlet operationDefinitions: readonly OperationDefinition<any, any>[] | undefined;\n\nfunction registeredOperationDefinitions(): readonly OperationDefinition<any, any>[] {\n // Auth handlers consult lookupOperation while executing. Lazy assembly keeps\n // that internal dependency out of the module-initialization cycle.\n operationDefinitions ??= [\n ...statusOperationDefinitions,\n ...authOperationDefinitions,\n ...explorationOperationDefinitions,\n ...sqlOperationDefinitions,\n ...secretsGetOperationDefinitions,\n ];\n return operationDefinitions;\n}\n\n/** Internal generator input; package exports prevent projection access. */\nexport function operationDefinitionsForCatalog(): readonly OperationDefinition<any, any>[] {\n return registeredOperationDefinitions();\n}\n\nexport function lookupOperation(\n operationId: OperationId,\n operationVersion: number,\n): OperationLookup {\n const matchingId = registeredOperationDefinitions().filter(\n (definition) => definition.id === operationId,\n );\n if (matchingId.length === 0) {\n return { status: \"operation_not_found\" };\n }\n\n const definition = matchingId.find(\n (candidate) => candidate.version === operationVersion,\n );\n if (definition === undefined) {\n return {\n status: \"operation_version_unsupported\",\n supportedVersions: matchingId.map((candidate) => candidate.version),\n };\n }\n\n return { status: \"found\", definition };\n}\n","import {\n DEFAULT_PROFILE,\n readJson,\n readProfile,\n tinycloudConfigPath,\n} from \"./state.js\";\nimport type {\n InvocationTarget,\n OperationContextSummary,\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\n\nconst DEFAULT_HOST = \"https://tee.node.tinycloud.xyz\";\n\nexport type SafeInvocationContext = OperationContextSummary & {\n operatorType: OperationOperatorType;\n};\n\nexport type InvocationContextResolution =\n | { ok: true; context: SafeInvocationContext }\n | {\n ok: false;\n error: {\n code: \"PROFILE_NOT_FOUND\";\n message: string;\n retryable: false;\n };\n };\n\ninterface GlobalConfig {\n defaultProfile?: unknown;\n}\n\n/** Validated profile material retained only inside runtime resolution. */\nexport type StoredProfile = {\n name: string;\n host: string;\n chainId: number;\n spaceName: string;\n did: string;\n createdAt: string;\n sessionDid?: unknown;\n ownerDid?: unknown;\n spaceId?: unknown;\n posture?: unknown;\n operatorType?: unknown;\n authMethod?: unknown;\n defaultSpace?: unknown;\n privateKey?: unknown;\n address?: unknown;\n openkeyHost?: unknown;\n};\n\n/** Profile snapshot plus its derived safe invocation context. */\nexport type InvocationProfileResolution =\n | { ok: true; profile: StoredProfile; context: SafeInvocationContext }\n | Extract<InvocationContextResolution, { ok: false }>;\n\n/**\n * Resolves one selected profile to safe identity data. Resolution is deliberately\n * one-way: after selecting a name, any missing, malformed, or unreadable\n * profile is PROFILE_NOT_FOUND rather than a reason to choose another profile.\n */\nexport async function resolveInvocationContext(\n target: InvocationTarget = {},\n): Promise<InvocationContextResolution> {\n const resolved = await resolveInvocationProfile(target);\n return resolved.ok ? { ok: true, context: resolved.context } : resolved;\n}\n\n/** Resolves the selected profile and its safe context from one profile read. */\nexport async function resolveInvocationProfile(\n target: InvocationTarget = {},\n): Promise<InvocationProfileResolution> {\n const profile = await resolveProfileName(target);\n let storedProfile: StoredProfile | null;\n try {\n storedProfile = await readProfile<StoredProfile>(profile);\n } catch {\n return profileNotFound(profile);\n }\n\n if (!isStoredProfile(storedProfile)) {\n return profileNotFound(profile);\n }\n // An explicit CLI key is a complete identity override. Do not let stale\n // persisted auth posture reject that live local-owner authentication path.\n if (target.privateKey === undefined && !isCoherentProfile(storedProfile)) {\n return profileNotFound(profile);\n }\n\n const host = firstString(target.host, process.env.TC_HOST, storedProfile.host, DEFAULT_HOST);\n const posture = resolvePosture(storedProfile);\n\n return {\n ok: true,\n profile: storedProfile,\n context: {\n profile,\n host,\n posture,\n operatorType: isOperatorType(storedProfile.operatorType) ? storedProfile.operatorType : \"human\",\n principalDid: maybeDid(storedProfile.did),\n sessionDid: maybeDid(storedProfile.sessionDid),\n ownerDid: maybeDid(storedProfile.ownerDid),\n space: typeof storedProfile.spaceId === \"string\" ? storedProfile.spaceId : undefined,\n },\n };\n}\n\n/**\n * Selects the profile name once for a long-lived projection process. The\n * selected name is safe identity data; profile material is read only by the\n * invocation runtime after the projection pins this value.\n */\nexport async function resolveInvocationProfileName(\n explicitProfile?: string,\n): Promise<string> {\n return resolveProfileName(\n explicitProfile === undefined ? {} : { profile: explicitProfile },\n );\n}\n\nasync function resolveProfileName(target: InvocationTarget): Promise<string> {\n if (typeof target.profile === \"string\") return target.profile;\n if (typeof process.env.TC_PROFILE === \"string\") return process.env.TC_PROFILE;\n\n try {\n const config = await readJson<GlobalConfig>(tinycloudConfigPath());\n if (typeof config?.defaultProfile === \"string\") return config.defaultProfile;\n } catch {\n // Config only chooses the initial name. A missing or malformed config falls\n // back to the documented default, never to another existing profile.\n }\n return DEFAULT_PROFILE;\n}\n\n/** Derives the effective posture without consulting any later profile read. */\nexport function resolvePosture(profile: Pick<StoredProfile, \"posture\" | \"authMethod\">): TinyCloudPosture {\n if (isPosture(profile.posture)) return profile.posture;\n if (profile.authMethod === \"local\") return \"local-owner-key\";\n return \"owner-openkey\";\n}\n\nfunction profileNotFound(profile: string): Extract<InvocationContextResolution, { ok: false }> {\n return {\n ok: false,\n error: {\n code: \"PROFILE_NOT_FOUND\",\n message: `Profile \"${profile}\" is not available.`,\n retryable: false,\n },\n };\n}\n\nfunction firstString(...values: unknown[]): string {\n for (const value of values) {\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return DEFAULT_HOST;\n}\n\nfunction maybeDid(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n const fragment = value.indexOf(\"#\");\n return fragment === -1 ? value : value.slice(0, fragment);\n}\n\nfunction isPosture(value: unknown): value is TinyCloudPosture {\n return value === \"owner-openkey\" ||\n value === \"delegate-session\" ||\n value === \"local-owner-key\" ||\n value === \"unauthenticated\";\n}\n\nfunction isOperatorType(value: unknown): value is OperationOperatorType {\n return value === \"human\" || value === \"agent\";\n}\n\n/**\n * The CLI's original persisted profile format required these six fields.\n * Posture and operator fields arrived later, so they remain optional while\n * any present typed field must still have its documented shape.\n */\nfunction isStoredProfile(value: unknown): value is StoredProfile {\n return isRecord(value) &&\n isNonEmptyString(value.name) &&\n isNonEmptyString(value.host) &&\n typeof value.chainId === \"number\" &&\n Number.isFinite(value.chainId) &&\n isNonEmptyString(value.spaceName) &&\n isNonEmptyString(value.did) &&\n isNonEmptyString(value.createdAt) &&\n isOptionalNonEmptyString(value.sessionDid) &&\n isOptionalNonEmptyString(value.ownerDid) &&\n isOptionalNonEmptyString(value.spaceId) &&\n isOptionalPosture(value.posture) &&\n isOptionalOperatorType(value.operatorType) &&\n isOptionalAuthMethod(value.authMethod) &&\n isOptionalNonEmptyString(value.defaultSpace) &&\n isOptionalNonEmptyString(value.privateKey) &&\n isOptionalNonEmptyString(value.address) &&\n isOptionalNonEmptyString(value.openkeyHost);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isOptionalNonEmptyString(value: unknown): boolean {\n return value === undefined || isNonEmptyString(value);\n}\n\nfunction isOptionalPosture(value: unknown): boolean {\n return value === undefined || isPosture(value);\n}\n\nfunction isOptionalOperatorType(value: unknown): boolean {\n return value === undefined || isOperatorType(value);\n}\n\nfunction isOptionalAuthMethod(value: unknown): boolean {\n return value === undefined || value === \"openkey\" || value === \"local\";\n}\n\n/**\n * Local-key authentication is owner authentication. A persisted delegate or\n * OpenKey posture must never be allowed to select that path later in runtime\n * construction, so reject the inconsistent profile before policy inspection.\n */\nfunction isCoherentProfile(profile: StoredProfile): boolean {\n if (profile.authMethod === \"local\") {\n return profile.posture === undefined || profile.posture === \"local-owner-key\";\n }\n if (profile.posture === \"local-owner-key\") {\n return profile.authMethod === \"local\";\n }\n return true;\n}\n","import type {\n PermissionEntry,\n RuntimeDelegationActivator,\n TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\n\nimport type {\n InvocationTarget,\n OperationContext,\n OperationRuntime,\n OperationRuntimeRequirement,\n RuntimeOperationContext,\n} from \"./contract.js\";\nimport { canonicalizeCapabilities } from \"./authority.js\";\nimport { operationError, type OperationError } from \"./errors.js\";\nimport { resolveInvocationProfile, resolvePosture } from \"./profile.js\";\nimport { operationSpaceResolver } from \"./secrets.js\";\nimport {\n profilePath,\n readAdditionalDelegations,\n readJson,\n readProfile,\n readSession,\n} from \"./state.js\";\nimport { prepareStoredDelegationReplay, replayStoredDelegation } from \"./delegation-binding.js\";\n\nexport type InvocationRuntimeResolution =\n | Readonly<{ ok: true; context: OperationContext }>\n | Readonly<{\n ok: false;\n context: RuntimeOperationContext[\"summary\"];\n error: OperationError;\n }>;\n\ninterface StoredSession extends Record<string, unknown> {\n readonly delegationHeader?: unknown;\n readonly delegationCid?: unknown;\n readonly spaceId?: unknown;\n readonly jwk?: unknown;\n readonly verificationMethod?: unknown;\n readonly address?: unknown;\n readonly chainId?: unknown;\n readonly siwe?: unknown;\n readonly signature?: unknown;\n readonly tinycloudHosts?: unknown;\n}\n\n/**\n * Creates one authenticated runtime for an invocation. The selected profile\n * name is resolved once and every subsequent read is explicitly scoped to that\n * name; no failure path can choose a different profile.\n */\ntype AuthenticatedRuntimeResolution =\n | Readonly<{ ok: true; context: RuntimeOperationContext }>\n | Exclude<InvocationRuntimeResolution, Readonly<{ ok: true; context: OperationContext }>>;\n\nexport function createInvocationRuntime(\n target: InvocationTarget,\n): Promise<AuthenticatedRuntimeResolution>;\nexport function createInvocationRuntime(\n target: InvocationTarget,\n requirement: \"authenticated\",\n): Promise<AuthenticatedRuntimeResolution>;\nexport function createInvocationRuntime(\n target: InvocationTarget,\n requirement: \"inspection\",\n): Promise<InvocationRuntimeResolution>;\nexport function createInvocationRuntime(\n target: InvocationTarget,\n requirement: OperationRuntimeRequirement,\n): Promise<InvocationRuntimeResolution>;\nexport async function createInvocationRuntime(\n target: InvocationTarget,\n requirement: OperationRuntimeRequirement = \"authenticated\",\n): Promise<InvocationRuntimeResolution> {\n const resolved = await resolveInvocationProfile(target);\n if (!resolved.ok) {\n return {\n ok: false,\n context: unresolvedSummary(target),\n error: resolved.error,\n };\n }\n\n const summary = resolved.context;\n if (requirement === \"inspection\") {\n return { ok: true, context: { summary } };\n }\n\n const profileName = summary.profile;\n try {\n // Keep the value import namespace-shaped so projection modules remain\n // compatible with lightweight node-sdk test doubles.\n const {\n TinyCloudNode: TinyCloudNodeConstructor,\n } = nodeSdk;\n const explicitPrivateKeyOverride = typeof target.privateKey === \"string\";\n const [session, key] = explicitPrivateKeyOverride\n ? [null, null]\n : await Promise.all([\n readSession<StoredSession>(profileName),\n readJson<Record<string, unknown>>(`${profilePath(profileName)}/key.json`),\n ]);\n const profile = resolved.profile;\n\n // The inspection summary and authenticated material are intentionally\n // separate reads. Fail closed if the profile changed posture between\n // them; otherwise local-owner-key could be authenticated under a stale\n // delegate-session summary and bypass the caller's posture policy.\n const actualPosture = resolvePosture(profile);\n if (!explicitPrivateKeyOverride && actualPosture !== summary.posture) {\n return failed(\n { ...summary, posture: actualPosture },\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The selected profile changed posture during runtime resolution.\",\n ),\n );\n }\n\n const privateKey = typeof target.privateKey === \"string\"\n ? target.privateKey\n : typeof profile.privateKey === \"string\"\n ? profile.privateKey\n : undefined;\n const selectedPosture = explicitPrivateKeyOverride || profile.authMethod === \"local\"\n ? \"local-owner-key\"\n : summary.posture;\n if (selectedPosture !== summary.posture && !explicitPrivateKeyOverride) {\n return failed(\n { ...summary, posture: selectedPosture },\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The selected profile authentication material does not match its posture.\",\n ),\n );\n }\n const node = new TinyCloudNodeConstructor({\n host: summary.host,\n ...(privateKey === undefined ? {} : { privateKey }),\n });\n\n const activeSession = session === null ? undefined : normalizeSession(session, key);\n if (explicitPrivateKeyOverride) {\n // An explicit key is a complete, non-persisted identity. Do not inherit\n // an OpenKey session (or require one) from the selected profile.\n await node.signIn();\n } else if (activeSession === undefined) {\n if (profile.authMethod === \"local\" && privateKey !== undefined) {\n await node.signIn();\n } else {\n return failed(summary, operationError(\n \"SESSION_NOT_FOUND\",\n \"The selected profile does not have an active session.\",\n ));\n }\n } else {\n await node.restoreSession(activeSession);\n }\n\n // The restored node is the authority for the active session identity. In\n // particular, do not report the persisted verification method if SDK\n // restoration failed to install its key as the live session key.\n const activeSessionDid = normalizeDid(node.sessionDid);\n const livePrincipalDid = normalizeDid(node.did);\n const authenticatedSpace = explicitPrivateKeyOverride\n ? spaceForAuthenticatedPrincipal(livePrincipalDid)\n : undefined;\n // This API derives from the restored, verified base session rather than\n // from an SDK private field or a second parse of signed authority here.\n const livePermissions: PermissionEntry[] = [...node.getVerifiedSessionCapabilities()];\n const resolveSpace = operationSpaceResolver(node, authenticatedSpace ?? summary.space);\n const seenCids = new Set<string>();\n // An explicit key is another identity: it neither replays nor migrates\n // this profile's records.\n if (!explicitPrivateKeyOverride) {\n const activator = node as unknown as RuntimeDelegationActivator;\n // Migration runs before the records are read, so the records replayed\n // here and the migration marker agree.\n const migrated = await prepareStoredDelegationReplay(profileName, activator, {\n host: summary.host,\n // Only the profile's own restored session; a local sign-in without\n // one uses a fresh session key the stored records do not address.\n migrate: activeSession !== undefined,\n });\n // Elements are untrusted and may not even be objects; the shared rule\n // classifies each before reading any field.\n for (const entry of await readAdditionalDelegations<unknown>(profileName)) {\n const activated = await replayStoredDelegation(activator, entry, {\n host: summary.host,\n migrated,\n resolveSpace,\n });\n if (activated !== undefined && !seenCids.has(activated.cid)) {\n seenCids.add(activated.cid);\n livePermissions.push(...activated.effectivePermissions);\n }\n }\n }\n\n const runtime: OperationRuntime = {\n node,\n granted: canonicalizeCapabilities(livePermissions),\n };\n return {\n ok: true,\n context: {\n summary: {\n ...summary,\n posture: selectedPosture,\n ...(livePrincipalDid === undefined ? {} : { principalDid: livePrincipalDid }),\n ...(explicitPrivateKeyOverride && livePrincipalDid !== undefined\n ? { ownerDid: livePrincipalDid }\n : {}),\n ...(authenticatedSpace === undefined ? {} : { space: authenticatedSpace }),\n ...(activeSessionDid === undefined ? {} : { sessionDid: activeSessionDid }),\n },\n runtime,\n },\n };\n } catch {\n return failed(summary, operationError(\n \"NODE_ERROR\",\n \"The selected profile runtime could not be initialized.\",\n { retryable: true },\n ));\n }\n}\n\nfunction spaceForAuthenticatedPrincipal(principal: string | undefined): string | undefined {\n if (principal === undefined) return undefined;\n try {\n const pkh = nodeSdk.parsePkhDid(principal);\n return pkh === null ? undefined : nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, \"secrets\");\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeSession(\n session: StoredSession,\n key: Record<string, unknown> | null,\n): Parameters<TinyCloudNode[\"restoreSession\"]>[0] | undefined {\n const header = session.delegationHeader;\n const jwk = hasPrivateParameter(session.jwk) ? session.jwk : key;\n if (\n !isRecord(header) ||\n typeof header.Authorization !== \"string\" ||\n typeof session.delegationCid !== \"string\" ||\n typeof session.spaceId !== \"string\" ||\n !hasPrivateParameter(jwk) ||\n typeof session.verificationMethod !== \"string\"\n ) {\n return undefined;\n }\n\n return {\n delegationHeader: { Authorization: header.Authorization },\n delegationCid: session.delegationCid,\n spaceId: session.spaceId,\n jwk,\n verificationMethod: session.verificationMethod,\n ...(typeof session.address === \"string\" ? { address: session.address } : {}),\n ...(typeof session.chainId === \"number\" ? { chainId: session.chainId } : {}),\n ...(typeof session.siwe === \"string\" ? { siwe: session.siwe } : {}),\n ...(typeof session.signature === \"string\" ? { signature: session.signature } : {}),\n ...(Array.isArray(session.tinycloudHosts) && session.tinycloudHosts.every((host) => typeof host === \"string\")\n ? { tinycloudHosts: session.tinycloudHosts }\n : {}),\n };\n}\n\nfunction hasPrivateParameter(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && typeof value.d === \"string\" && value.d.length > 0;\n}\n\nfunction normalizeDid(value: string | undefined): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n return value.split(\"#\", 1)[0];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction failed(\n context: RuntimeOperationContext[\"summary\"],\n error: OperationError,\n): InvocationRuntimeResolution {\n return { ok: false, context, error };\n}\n\nfunction unresolvedSummary(target: InvocationTarget): RuntimeOperationContext[\"summary\"] {\n return {\n profile: target.profile ?? \"unresolved\",\n host: target.host ?? \"unresolved\",\n posture: \"unauthenticated\",\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { isAbsolute } from \"node:path\";\n\nimport {\n makePkhSpaceId,\n parsePkhDid,\n parseSpaceUri,\n type PermissionEntry,\n} from \"@tinycloud/node-sdk\";\nimport { jcsCanonicalize } from \"@tinycloud/sdk-core/policy\";\nimport type { ZodError } from \"zod\";\n\nimport {\n type ApprovalAction,\n type CapabilityRequirement,\n type InvocationTarget,\n type OperationContextSummary,\n type OperationDefinition,\n type OperationRef,\n type OperationResult,\n type OperationRuntimeRequirement,\n type RuntimeOperationContext,\n} from \"./contract.js\";\nimport {\n internalOperationError,\n operationError,\n sanitizeOperationError,\n sanitizeThrownOperationError,\n} from \"./errors.js\";\nimport {\n canonicalizeOperationCapabilities,\n evaluateOperationAuthority,\n isExactCapabilityMemberSubset,\n validateExactCapabilities,\n} from \"./authority.js\";\nimport {\n createOrReusePermissionRequest,\n buildPermissionRequestArtifact,\n type PermissionRequestArtifact,\n} from \"./artifacts.js\";\nimport { redactOperationError } from \"./redaction.js\";\nimport { safeOriginHost } from \"./safe-values.js\";\nimport { withTinyCloudStateRoot } from \"./state.js\";\nimport type { InvocationRuntimeResolution } from \"./runtime.js\";\nimport {\n operationSpaceResolver,\n resolveSecretReferenceForOperation,\n} from \"./secrets.js\";\n\n/** The sole projection-facing execution API. */\nexport async function invokeOperation(\n operationId: string,\n operationVersion: number,\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n const target = normalizeInvocationTarget(invocationTarget);\n if (target === undefined) {\n return errorResult(\n { operationId, operationVersion },\n unresolvedContextSummary(),\n operationError(\"INPUT_INVALID\", \"The invocation target is invalid.\"),\n );\n }\n return withTinyCloudStateRoot(target.stateRoot, async () => {\n const prepared = await prepareInvocation(\n operationId,\n operationVersion,\n target,\n unknownInput,\n );\n if (isPreparedError(prepared)) return prepared.result;\n return executePreparedInvocation(prepared);\n });\n}\n\n/**\n * CLI-only local-owner acquisition path. The runtime is deliberately created\n * and retained inside operations so a grant is installed on the exact session\n * that performs the one retry. The explicit key remains a non-persisted target\n * value and no runtime object crosses the operations boundary.\n */\nexport async function invokeOperationWithLocalAuthorityRetry(\n operationId: string,\n operationVersion: number,\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n const target = normalizeInvocationTarget(invocationTarget);\n if (target === undefined) {\n return errorResult(\n { operationId, operationVersion },\n unresolvedContextSummary(),\n operationError(\"INPUT_INVALID\", \"The invocation target is invalid.\"),\n );\n }\n if (typeof target.privateKey !== \"string\" || target.privateKey.length === 0) {\n return errorResult(\n { operationId, operationVersion },\n unresolvedContextSummary(target),\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"Local authority retry requires an explicit private key.\",\n ),\n );\n }\n\n return withTinyCloudStateRoot(target.stateRoot, () =>\n invokeLocalAuthorityRetry(\n operationId,\n operationVersion,\n target,\n unknownInput,\n )\n );\n}\n\nasync function invokeLocalAuthorityRetry(\n operationId: string,\n operationVersion: number,\n target: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n const prepared = await prepareInvocation(\n operationId,\n operationVersion,\n target,\n unknownInput,\n );\n if (isPreparedError(prepared)) return prepared.result;\n\n if (\n prepared.operation.operationId !== \"tinycloud.secrets.get\" ||\n prepared.operation.operationVersion !== 1\n ) {\n return errorResult(\n prepared.operation,\n prepared.runtimeResolution.context.summary,\n operationError(\n \"OPERATION_NOT_FOUND\",\n \"The local CLI authority helper supports only tinycloud.secrets.get@1.\",\n ),\n );\n }\n\n const runtimeContext = prepared.runtimeResolution.context;\n if (runtimeContext.runtime === undefined) return internalOperationErrorResult(prepared);\n const operationContext = runtimeContext as RuntimeOperationContext;\n let planned: CapabilityRequirement[] | undefined;\n try {\n planned = exactCapabilities(await prepared.definition.authority(\n operationContext,\n prepared.parsedInput.data,\n ));\n } catch {\n return errorResult(\n prepared.operation,\n operationContext.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The local CLI authority plan is invalid.\",\n ),\n );\n }\n const planStatus = planned === undefined\n ? \"invalid\"\n : isExactLocalSecretsGetPlan(prepared, planned, operationContext);\n if (planStatus === \"ineligible\") {\n return errorResult(\n prepared.operation,\n operationContext.summary,\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The explicit private key cannot authorize the requested owner space.\",\n ),\n );\n }\n if (planStatus !== \"valid\") {\n return errorResult(\n prepared.operation,\n operationContext.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The local CLI authority plan is invalid.\",\n ),\n );\n }\n\n const first = await executePreparedInvocation(prepared, { deferAuthorityRequest: true });\n if (first.status !== \"authority_required\") {\n return first;\n }\n if (\n operationContext.summary.posture !== \"local-owner-key\" ||\n !requirementsBelongToAuthenticatedOwner(\n first.missing as unknown as PermissionEntry[],\n operationContext.summary.space,\n )\n ) {\n return localAuthorityFailure(prepared);\n }\n\n try {\n const grantRuntimePermissions = (operationContext.runtime.node as {\n grantRuntimePermissions?: (\n permissions: PermissionEntry[],\n ) => Promise<unknown>;\n }).grantRuntimePermissions;\n if (typeof grantRuntimePermissions !== \"function\") {\n return localAuthorityFailure(prepared);\n }\n await grantRuntimePermissions.call(\n operationContext.runtime.node,\n first.missing as unknown as PermissionEntry[],\n );\n\n const resolveSpace = operationSpaceResolver(\n operationContext.runtime.node,\n operationContext.summary.space,\n );\n const refreshedGranted = refreshLiveRuntimeAuthority(\n operationContext.runtime.node,\n first.missing as unknown as PermissionEntry[],\n planned as unknown as PermissionEntry[],\n resolveSpace,\n );\n if (refreshedGranted === undefined) {\n return localAuthorityFailure(prepared);\n }\n const retryContext: RuntimeOperationContext = {\n ...operationContext,\n runtime: {\n ...operationContext.runtime,\n granted: refreshedGranted,\n },\n };\n const retry = await executePreparedInvocation({\n ...prepared,\n runtimeResolution: { ok: true, context: retryContext },\n }, { deferAuthorityRequest: true });\n return retry.status === \"authority_required\"\n ? localAuthorityFailure(prepared)\n : retry;\n } catch {\n return localAuthorityFailure(prepared);\n }\n}\n\ntype PreparedInvocation = Readonly<{\n operation: OperationRef;\n definition: OperationDefinition<any, any>;\n parsedInput: { data: any };\n runtimeResolution: Extract<InvocationRuntimeResolution, { ok: true }>;\n}> | Readonly<{\n status: \"error\";\n result: OperationResult<never>;\n}>;\n\nfunction isPreparedError(\n prepared: PreparedInvocation,\n): prepared is Extract<PreparedInvocation, { status: \"error\" }> {\n return \"status\" in prepared;\n}\n\nasync function prepareInvocation(\n operationId: string,\n operationVersion: number,\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<PreparedInvocation> {\n const operation: OperationRef = { operationId, operationVersion };\n const target = normalizeInvocationTarget(invocationTarget);\n if (target === undefined) {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(),\n operationError(\"INPUT_INVALID\", \"The invocation target is invalid.\"),\n ) };\n }\n // Load internal registry material only when invoking. This keeps the packed\n // root entrypoint free of auth/runtime SDK initialization until a call is\n // made, while preserving registry resolution before input or profile access.\n const { lookupOperation } = await import(\"./registry.js\");\n const lookup = lookupOperation(operationId, operationVersion);\n\n // Registry resolution is deliberately complete before any input parsing or\n // profile access. An unrecognized operation must not cause an invocation to\n // consult profile state.\n if (lookup.status === \"operation_not_found\") {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(target),\n operationError(\n \"OPERATION_NOT_FOUND\",\n \"The requested operation is not registered.\",\n ),\n ) };\n }\n if (lookup.status === \"operation_version_unsupported\") {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(target),\n operationError(\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"The requested operation version is not supported.\",\n { details: { supportedVersions: lookup.supportedVersions } },\n ),\n ) };\n }\n\n const definition = lookup.definition;\n const parsedInput = definition.input.safeParse(unknownInput);\n if (!parsedInput.success) {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(target),\n operationError(\n definition.invalidInputErrorCode ?? \"INPUT_INVALID\",\n \"The operation input is invalid.\",\n {\n details: zodIssueDetails(parsedInput.error),\n },\n ),\n ) };\n }\n\n // Only a registered operation with valid input may inspect the pinned\n // profile. Inspection is deliberately node-free, so owner opt-in and status\n // availability are decided before any authentication or external effect.\n const inspectionResolution = await resolveRuntime(target, \"inspection\");\n if (!inspectionResolution.ok) {\n return { status: \"error\", result: errorResult(\n operation,\n inspectionResolution.context,\n inspectionResolution.error,\n ) };\n }\n\n if (\n target.privateKey === undefined &&\n !definition.postures.includes(inspectionResolution.context.summary.posture)\n ) {\n return { status: \"error\", result: errorResult(\n operation,\n inspectionResolution.context.summary,\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The active profile posture cannot execute this operation.\",\n ),\n ) };\n }\n if (\n target.privateKey === undefined &&\n definition.runtime === \"authenticated\" &&\n isOwnerPosture(inspectionResolution.context.summary.posture) &&\n target.allowOwnerProfile !== true\n ) {\n return { status: \"error\", result: errorResult(\n operation,\n inspectionResolution.context.summary,\n operationError(\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"Owner-profile execution requires explicit opt-in.\",\n ),\n ) };\n }\n\n const runtimeResolution =\n definition.runtime === \"inspection\"\n ? inspectionResolution\n : await resolveRuntime(target, \"authenticated\");\n if (!runtimeResolution.ok) {\n return { status: \"error\", result: errorResult(\n operation,\n runtimeResolution.context,\n runtimeResolution.error,\n ) };\n }\n if (definition.runtime === \"authenticated\") {\n const actualPosture = runtimeResolution.context.summary.posture;\n if (!definition.postures.includes(actualPosture)) {\n return { status: \"error\", result: errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The authenticated profile posture cannot execute this operation.\",\n ),\n ) };\n }\n if (isOwnerPosture(actualPosture) && target.allowOwnerProfile !== true) {\n return { status: \"error\", result: errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"Owner-profile execution requires explicit opt-in.\",\n ),\n ) };\n }\n }\n return {\n operation,\n definition,\n parsedInput,\n runtimeResolution,\n };\n}\n\nasync function executePreparedInvocation(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n options: Readonly<{ deferAuthorityRequest?: boolean }> = {},\n): Promise<OperationResult<unknown>> {\n const { operation, definition, parsedInput, runtimeResolution } = prepared;\n const runtimeContext =\n runtimeResolution.context.runtime === undefined\n ? undefined\n : (runtimeResolution.context as RuntimeOperationContext);\n const resolveSpace = runtimeContext === undefined\n ? undefined\n : operationSpaceResolver(\n runtimeContext.runtime.node,\n runtimeContext.summary.space,\n );\n\n try {\n const planned = await definition.authority(\n (runtimeContext ?? runtimeResolution.context) as RuntimeOperationContext,\n parsedInput.data,\n );\n const required = exactCapabilities(planned);\n if (required === undefined) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The operation returned an invalid permission requirement.\",\n ),\n );\n }\n\n const evaluation = evaluateOperationAuthority(\n (runtimeContext?.runtime.granted ?? []) as unknown as PermissionEntry[],\n required as unknown as PermissionEntry[],\n resolveSpace,\n );\n if (!evaluation.satisfied) {\n if (runtimeContext === undefined) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n if (options.deferAuthorityRequest) {\n try {\n const request = buildPermissionRequestArtifact({\n profile: runtimeContext.summary.profile,\n host: runtimeContext.summary.host,\n sessionDid: runtimeContext.summary.sessionDid!,\n posture: runtimeContext.summary.posture,\n operatorType: runtimeContext.summary.operatorType ?? \"human\",\n ...(runtimeContext.summary.ownerDid === undefined\n ? {}\n : { ownerDid: runtimeContext.summary.ownerDid }),\n ...(runtimeContext.summary.space === undefined\n ? {}\n : { spaceId: runtimeContext.summary.space }),\n missing: evaluation.missing as unknown as PermissionEntry[],\n });\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n request,\n evaluation.missing,\n runtimeContext.runtime.node,\n );\n } catch {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n }\n const authority = await persistAuthorityRequest(\n runtimeContext,\n evaluation.missing,\n );\n if (authority.status === \"error\") {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n authority.error,\n );\n }\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n authority.request,\n authority.missing,\n runtimeContext.runtime.node,\n );\n }\n\n const outcome = await definition.execute(\n runtimeResolution.context,\n parsedInput.data,\n );\n\n switch (outcome.status) {\n case \"ok\": {\n const parsedOutput = definition.output.safeParse(outcome.output);\n if (!parsedOutput.success) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"OUTPUT_INVALID\",\n \"The operation returned an invalid result.\",\n ),\n );\n }\n return {\n status: \"ok\",\n operation,\n context: runtimeResolution.context.summary,\n output: parsedOutput.data,\n };\n }\n case \"authority_required\": {\n const hinted = exactCapabilities(outcome.missing);\n if (\n hinted === undefined ||\n !isExactCapabilityMemberSubset(\n hinted as unknown as PermissionEntry[],\n required as unknown as PermissionEntry[],\n resolveSpace,\n )\n ) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The node returned an invalid permission hint.\",\n ),\n );\n }\n if (runtimeContext === undefined) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n if (options.deferAuthorityRequest) {\n try {\n const request = buildPermissionRequestArtifact({\n profile: runtimeContext.summary.profile,\n host: runtimeContext.summary.host,\n sessionDid: runtimeContext.summary.sessionDid!,\n posture: runtimeContext.summary.posture,\n operatorType: runtimeContext.summary.operatorType ?? \"human\",\n ...(runtimeContext.summary.ownerDid === undefined\n ? {}\n : { ownerDid: runtimeContext.summary.ownerDid }),\n ...(runtimeContext.summary.space === undefined\n ? {}\n : { spaceId: runtimeContext.summary.space }),\n missing: hinted as unknown as PermissionEntry[],\n });\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n request,\n hinted,\n runtimeContext.runtime.node,\n outcome.requiresCallerInput ?? false,\n );\n } catch {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n }\n const authority = await persistAuthorityRequest(\n runtimeContext,\n hinted,\n true,\n );\n if (authority.status === \"error\") {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n authority.error,\n );\n }\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n authority.request,\n authority.missing,\n runtimeContext.runtime.node,\n outcome.requiresCallerInput ?? false,\n );\n }\n case \"setup_required\":\n return {\n status: \"setup_required\",\n operation,\n context: runtimeResolution.context.summary,\n setup: outcome.setup,\n retry: retryDescriptor(\n operation,\n parsedInput.data,\n outcome.requiresCallerInput ?? false,\n ),\n };\n case \"error\":\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n redactOperationError(\n definition,\n sanitizeOperationError(outcome.error),\n ),\n );\n default:\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n } catch (error) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n redactOperationError(definition, sanitizeThrownOperationError(error)),\n );\n }\n}\n\nfunction normalizeInvocationTarget(\n target: unknown,\n): InvocationTarget | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n\n try {\n const candidate = target as InvocationTarget;\n const profile = candidate.profile;\n const host = candidate.host;\n const stateRoot = candidate.stateRoot;\n const allowOwnerProfile = candidate.allowOwnerProfile;\n const privateKey = candidate.privateKey;\n\n if (\n (profile !== undefined && typeof profile !== \"string\") ||\n (host !== undefined && typeof host !== \"string\") ||\n (stateRoot !== undefined &&\n (typeof stateRoot !== \"string\" || !isAbsolute(stateRoot))) ||\n (allowOwnerProfile !== undefined &&\n typeof allowOwnerProfile !== \"boolean\") ||\n (privateKey !== undefined && typeof privateKey !== \"string\")\n ) {\n return undefined;\n }\n\n return {\n ...(profile === undefined ? {} : { profile }),\n ...(host === undefined ? {} : { host }),\n ...(stateRoot === undefined ? {} : { stateRoot }),\n ...(allowOwnerProfile === true ? { allowOwnerProfile: true } : {}),\n ...(privateKey === undefined ? {} : { privateKey }),\n };\n } catch {\n return undefined;\n }\n}\n\nasync function resolveRuntime(\n target: InvocationTarget,\n requirement: OperationRuntimeRequirement,\n): Promise<InvocationRuntimeResolution> {\n try {\n // Keep the root package loadable for projections that only inspect its\n // public invocation export. The SDK runtime is needed only once a valid\n // operation reaches runtime construction.\n const { createInvocationRuntime } = await import(\"./runtime.js\");\n return await createInvocationRuntime(target, requirement);\n } catch (error) {\n return {\n ok: false,\n context: unresolvedContextSummary(target),\n error: sanitizeThrownOperationError(error),\n };\n }\n}\n\nfunction unresolvedContextSummary(\n target: InvocationTarget = {},\n): OperationContextSummary {\n return {\n profile: typeof target.profile === \"string\" ? target.profile : \"unresolved\",\n host: safeOriginHost(target.host) ?? \"unresolved\",\n posture: \"unauthenticated\",\n };\n}\n\nfunction errorResult(\n operation: OperationRef,\n context: OperationContextSummary,\n error: ReturnType<typeof sanitizeOperationError>,\n): OperationResult<never> {\n return { status: \"error\", operation, context, error };\n}\n\nfunction retryDescriptor(\n operation: OperationRef,\n input: unknown,\n requiresCallerInput: boolean,\n): Readonly<{\n operationId: string;\n operationVersion: number;\n inputDigest: string;\n requiresCallerInput: boolean;\n}> {\n return {\n operationId: operation.operationId,\n operationVersion: operation.operationVersion,\n inputDigest: createHash(\"sha256\")\n .update(jcsCanonicalize(input), \"utf8\")\n .digest(\"hex\"),\n requiresCallerInput,\n };\n}\n\ntype PersistedAuthority =\n | Readonly<{\n status: \"ok\";\n request: PermissionRequestArtifact;\n missing: readonly CapabilityRequirement[];\n }>\n | Readonly<{\n status: \"error\";\n error: ReturnType<typeof sanitizeOperationError>;\n }>;\n\nasync function persistAuthorityRequest(\n context: RuntimeOperationContext,\n missing: readonly CapabilityRequirement[],\n force = false,\n): Promise<PersistedAuthority> {\n const sessionDid = context.summary.sessionDid;\n if (sessionDid === undefined) {\n return {\n status: \"error\",\n error: operationError(\n \"SESSION_NOT_FOUND\",\n \"The selected profile does not have an active session.\",\n ),\n };\n }\n try {\n const resolveSpace = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n );\n const canonicalMissing = canonicalizeOperationCapabilities(missing as unknown as PermissionEntry[], resolveSpace);\n const canonicalGranted = canonicalizeOperationCapabilities(context.runtime.granted as unknown as PermissionEntry[], resolveSpace);\n const resolution = await createOrReusePermissionRequest({\n profile: context.summary.profile,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n host: context.summary.host,\n sessionDid,\n ...(context.summary.ownerDid === undefined\n ? {}\n : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined\n ? {}\n : { spaceId: context.summary.space }),\n missing: canonicalMissing as unknown as PermissionEntry[],\n granted: (force\n ? []\n : canonicalGranted) as unknown as PermissionEntry[],\n resolveSpace,\n });\n if (resolution.status !== \"created\") {\n return {\n status: \"error\",\n error: operationError(\n \"INTERNAL_ERROR\",\n \"The authority request could not be created.\",\n ),\n };\n }\n return {\n status: \"ok\",\n request: resolution.request,\n missing: canonicalMissing as CapabilityRequirement[],\n };\n } catch {\n return {\n status: \"error\",\n error: operationError(\n \"INTERNAL_ERROR\",\n \"The authority request could not be created.\",\n ),\n };\n }\n}\n\nfunction authorityRequiredResult(\n operation: OperationRef,\n context: OperationContextSummary,\n input: unknown,\n request: PermissionRequestArtifact,\n missing: readonly CapabilityRequirement[],\n node: unknown,\n requiresCallerInput = false,\n): OperationResult<never> {\n return {\n status: \"authority_required\",\n operation,\n context,\n missing,\n request,\n approval: approvalAction(request, node),\n retry: retryDescriptor(operation, input, requiresCallerInput),\n };\n}\n\nfunction approvalAction(\n request: PermissionRequestArtifact,\n node: unknown,\n): ApprovalAction {\n const maybeNode = node as {\n getOpenKeyApprovalUrl?: (artifact: PermissionRequestArtifact) => unknown;\n };\n let url: string | undefined;\n try {\n const candidate = maybeNode.getOpenKeyApprovalUrl?.(request);\n if (typeof candidate === \"string\" && candidate.length > 0) url = candidate;\n } catch {\n // The stored request remains the source of truth when a runtime does not\n // expose a canonical OpenKey URL.\n }\n return {\n kind: \"openkey\",\n requestId: request.requestId,\n ...(url === undefined ? {} : { url }),\n fallback: \"tc auth grant <request-artifact>\",\n };\n}\n\nfunction exactCapabilities(\n value: unknown,\n): CapabilityRequirement[] | undefined {\n return validateExactCapabilities(value) as\n | CapabilityRequirement[]\n | undefined;\n}\n\nfunction requirementsBelongToAuthenticatedOwner(\n requirements: readonly PermissionEntry[],\n authenticatedSpace: string | undefined,\n): boolean {\n const authenticatedOwner = canonicalPkhOwner(authenticatedSpace);\n if (authenticatedOwner === undefined) return false;\n return requirements.every((requirement) => {\n if (requirement.service === \"tinycloud.encryption\") {\n return requirement.space === undefined;\n }\n const requirementOwner = canonicalPkhOwner(requirement.space);\n return requirement.service === \"tinycloud.kv\" && requirementOwner === authenticatedOwner;\n });\n}\n\nfunction canonicalPkhOwner(space: string | undefined): string | undefined {\n if (typeof space !== \"string\") return undefined;\n const parsedSpace = parseSpaceUri(space);\n if (parsedSpace === null) return undefined;\n try {\n const pkh = parsePkhDid(parsedSpace.owner);\n return pkh === null\n ? undefined\n : parseSpaceUri(makePkhSpaceId(pkh.address, pkh.chainId, parsedSpace.name))?.owner;\n } catch {\n return undefined;\n }\n}\n\nfunction isExactLocalSecretsGetPlan(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n planned: readonly CapabilityRequirement[],\n context: RuntimeOperationContext,\n): \"valid\" | \"ineligible\" | \"invalid\" {\n if (\n prepared.definition.id !== \"tinycloud.secrets.get\" ||\n prepared.definition.version !== 1 ||\n JSON.stringify(prepared.definition.effects) !== JSON.stringify([\"read\", \"local_write\"])\n ) return \"invalid\";\n\n const resolveSpace = operationSpaceResolver(context.runtime.node, context.summary.space);\n let reference;\n try {\n reference = resolveSecretReferenceForOperation(\n prepared.parsedInput.data,\n context.runtime.node,\n context.summary.space,\n );\n } catch {\n return \"invalid\";\n }\n const canonicalPlan = canonicalizeOperationCapabilities(\n planned as unknown as PermissionEntry[],\n resolveSpace,\n );\n if (canonicalPlan.length !== 2) return \"invalid\";\n const kv = canonicalPlan.find((permission) => permission.service === \"tinycloud.kv\");\n const decrypt = canonicalPlan.find((permission) => permission.service === \"tinycloud.encryption\");\n if (kv === undefined || decrypt === undefined) return \"invalid\";\n const requestedOwner = canonicalPkhOwner(kv.space);\n const authenticatedOwner = canonicalPkhOwner(context.summary.space);\n if (requestedOwner === undefined || authenticatedOwner === undefined || requestedOwner !== authenticatedOwner) {\n return \"ineligible\";\n }\n if (JSON.stringify(kv) !== JSON.stringify({\n service: \"tinycloud.kv\",\n space: resolveSpace(reference.space),\n path: reference.permissionPath,\n actions: [\"tinycloud.kv/get\"],\n })) return \"invalid\";\n if (\n JSON.stringify(decrypt) !== JSON.stringify({\n service: \"tinycloud.encryption\",\n path: decrypt.path,\n actions: [\"tinycloud.encryption/decrypt\"],\n }) ||\n typeof decrypt.path !== \"string\" ||\n !decrypt.path.startsWith(\"urn:tinycloud:encryption:\")\n ) return \"invalid\";\n return \"valid\";\n}\n\nfunction refreshLiveRuntimeAuthority(\n node: unknown,\n requested: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace: (space: string) => string,\n): readonly CapabilityRequirement[] | undefined {\n const candidate = node as {\n hasRuntimePermissions?: (permissions: PermissionEntry[]) => unknown;\n getVerifiedSessionCapabilities?: () => unknown;\n getEffectiveRuntimePermissionEntries?: () => unknown;\n };\n if (typeof candidate.hasRuntimePermissions !== \"function\") return undefined;\n if (candidate.hasRuntimePermissions([...requested]) !== true) return undefined;\n if (typeof candidate.getVerifiedSessionCapabilities !== \"function\" ||\n typeof candidate.getEffectiveRuntimePermissionEntries !== \"function\") return undefined;\n\n const base = candidate.getVerifiedSessionCapabilities();\n const activated = candidate.getEffectiveRuntimePermissionEntries();\n if (!Array.isArray(base) || !Array.isArray(activated)) return undefined;\n const exactActivated = validateExactCapabilities(activated);\n if (exactActivated === undefined) return undefined;\n const selectedActivated = exactActivated.filter((permission) =>\n isExactCapabilityMemberSubset([permission], planned, resolveSpace),\n );\n if (!isExactCapabilityMemberSubset(requested, selectedActivated, resolveSpace)) return undefined;\n const combined = canonicalizeOperationCapabilities(\n [...base, ...selectedActivated],\n resolveSpace,\n );\n return evaluateOperationAuthority(combined, planned as unknown as PermissionEntry[], resolveSpace).satisfied\n ? combined\n : undefined;\n}\n\nfunction localAuthorityFailure(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n): OperationResult<never> {\n return errorResult(\n prepared.operation,\n prepared.runtimeResolution.context.summary,\n operationError(\n \"NODE_ERROR\",\n \"The local owner could not acquire the requested secret permissions.\",\n { retryable: true },\n ),\n );\n}\n\nfunction internalOperationErrorResult(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n): OperationResult<never> {\n return errorResult(\n prepared.operation,\n prepared.runtimeResolution.context.summary,\n internalOperationError(),\n );\n}\n\nfunction isOwnerPosture(posture: OperationContextSummary[\"posture\"]): boolean {\n return posture === \"owner-openkey\" || posture === \"local-owner-key\";\n}\n\nfunction zodIssueDetails(error: ZodError): Readonly<Record<string, unknown>> {\n return {\n // The canonical error channel carries only schema-owned issue codes.\n // Messages and paths can contain arbitrary input keys and values.\n issues: error.issues.map((issue) => ({ code: issue.code })),\n };\n}\n","export type SignedObjectErrorCode =\n | \"schema-invalid\"\n | \"canonicalization-mismatch\"\n | \"digest-mismatch\"\n | \"id-mismatch\"\n | \"signing-key-binding\"\n | \"signature-material-invalid\"\n | \"signature-suite-unsupported\"\n | \"signature-invalid\";\n\nexport class SignedObjectProfileError extends Error {\n public readonly code: SignedObjectErrorCode;\n\n constructor(code: SignedObjectErrorCode, message: string) {\n super(message);\n this.name = \"SignedObjectProfileError\";\n this.code = code;\n }\n}\n\nexport class SignedObjectSchemaError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"schema-invalid\", message);\n this.name = \"SignedObjectSchemaError\";\n }\n}\n\nexport class SignedObjectCanonicalizationError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"canonicalization-mismatch\", message);\n this.name = \"SignedObjectCanonicalizationError\";\n }\n}\n\nexport class SignedObjectDigestError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"digest-mismatch\", message);\n this.name = \"SignedObjectDigestError\";\n }\n}\n\nexport class SignedObjectIdError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"id-mismatch\", message);\n this.name = \"SignedObjectIdError\";\n }\n}\n\nexport class SigningKeyBindingError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signing-key-binding\", message);\n this.name = \"SigningKeyBindingError\";\n }\n}\n\nexport class SignatureMaterialError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signature-material-invalid\", message);\n this.name = \"SignatureMaterialError\";\n }\n}\n\nexport class UnsupportedSignatureSuiteError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signature-suite-unsupported\", message);\n this.name = \"UnsupportedSignatureSuiteError\";\n }\n}\n\nexport class SignatureVerificationError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signature-invalid\", message);\n this.name = \"SignatureVerificationError\";\n }\n}\n\nexport function toSignedObjectError(error: unknown): SignedObjectProfileError {\n if (error instanceof SignedObjectProfileError) {\n return error;\n }\n return new SignedObjectProfileError(\n \"schema-invalid\",\n error instanceof Error ? error.message : String(error),\n );\n}\n","import { SignedObjectCanonicalizationError } from \"./errors\";\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { readonly [key: string]: JsonValue };\n\ntype MutableJsonObject = { [key: string]: JsonValue };\nconst objectHasOwn: (object: object, propertyKey: PropertyKey) => boolean =\n (Object as ObjectConstructor & {\n hasOwn?: (object: object, propertyKey: PropertyKey) => boolean;\n }).hasOwn ??\n (Object.prototype.hasOwnProperty.call.bind(\n Object.prototype.hasOwnProperty,\n ) as (object: object, propertyKey: PropertyKey) => boolean);\n\n/**\n * RFC 8785 JSON Canonicalization Scheme encoder for the signed-object profile.\n *\n * This local encoder is intentionally stricter than JSON.stringify:\n * it rejects non-plain JSON inputs, sparse arrays, undefined/functions/symbols,\n * non-finite numbers, BigInt, dangerous prototype keys, and lone surrogates.\n * Object keys are sorted lexicographically by their raw UTF-16 code units,\n * as required by RFC 8785 section 3.2.3, before serialization.\n */\nexport function jcsCanonicalize(input: unknown): string {\n return serialize(normalizeJson(input, \"$\"));\n}\n\nexport function normalizeJson(input: unknown, path = \"$\"): JsonValue {\n if (input === null) {\n return null;\n }\n\n switch (typeof input) {\n case \"boolean\":\n return input;\n case \"number\":\n if (!Number.isFinite(input)) {\n throw new SignedObjectCanonicalizationError(\n `${path} must be a finite JSON number`,\n );\n }\n return input;\n case \"string\":\n assertUnicodeScalarString(input, path);\n return input;\n case \"object\":\n return normalizeJsonObjectOrArray(input, path);\n case \"bigint\":\n case \"function\":\n case \"symbol\":\n case \"undefined\":\n default:\n throw new SignedObjectCanonicalizationError(\n `${path} is not a JSON value`,\n );\n }\n}\n\nexport function serialize(value: JsonValue): string {\n if (value === null) {\n return \"null\";\n }\n\n switch (typeof value) {\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"number\": {\n const encoded = JSON.stringify(value);\n if (encoded === undefined) {\n throw new SignedObjectCanonicalizationError(\n \"number could not be serialized as JSON\",\n );\n }\n return encoded;\n }\n case \"string\":\n return JSON.stringify(value);\n case \"object\":\n if (Array.isArray(value)) {\n return `[${value.map((item) => serialize(item)).join(\",\")}]`;\n }\n return serializeObject(value);\n default:\n throw new SignedObjectCanonicalizationError(\n `unsupported JSON value type ${typeof value}`,\n );\n }\n}\n\nfunction normalizeJsonObjectOrArray(input: object, path: string): JsonValue {\n assertNoSymbolKeys(input, path);\n\n if (Array.isArray(input)) {\n for (const key of Object.getOwnPropertyNames(input)) {\n if (key === \"length\") {\n continue;\n }\n if (!isArrayIndexKey(key, input.length)) {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} is not allowed on a JSON array`,\n );\n }\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor?.enumerable !== true) {\n throw new SignedObjectCanonicalizationError(\n `${path}[${key}] must be an enumerable JSON array item`,\n );\n }\n if (!(\"value\" in descriptor)) {\n throw new SignedObjectCanonicalizationError(\n `${path}[${key}] must be a JSON data property`,\n );\n }\n }\n const output: JsonValue[] = [];\n for (let index = 0; index < input.length; index++) {\n if (!objectHasOwn(input, index)) {\n throw new SignedObjectCanonicalizationError(\n `${path}[${index}] must not be a sparse array hole`,\n );\n }\n output.push(normalizeJson(input[index], `${path}[${index}]`));\n }\n return output;\n }\n\n const proto = Object.getPrototypeOf(input);\n if (proto !== Object.prototype && proto !== null) {\n throw new SignedObjectCanonicalizationError(\n `${path} must be a plain JSON object`,\n );\n }\n\n const output = Object.create(null) as MutableJsonObject;\n for (const key of Object.getOwnPropertyNames(input)) {\n assertUnicodeScalarString(key, `${path} key`);\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} is not allowed`,\n );\n }\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor?.enumerable !== true) {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} must be an enumerable JSON object property`,\n );\n }\n if (!(\"value\" in descriptor)) {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} must be a JSON data property`,\n );\n }\n const value = descriptor.value;\n output[key] = normalizeJson(value, `${path}.${key}`);\n }\n return output;\n}\n\nfunction assertNoSymbolKeys(input: object, path: string): void {\n if (Object.getOwnPropertySymbols(input).length > 0) {\n throw new SignedObjectCanonicalizationError(\n `${path} must not have symbol properties`,\n );\n }\n}\n\nfunction isArrayIndexKey(key: string, length: number): boolean {\n if (!/^(0|[1-9]\\d*)$/.test(key)) {\n return false;\n }\n const index = Number(key);\n return Number.isSafeInteger(index) && index >= 0 && index < length;\n}\n\nfunction serializeObject(value: { readonly [key: string]: JsonValue }): string {\n const keys = Object.keys(value).sort(compareUtf16CodeUnits);\n const parts = keys.map((key) => `${JSON.stringify(key)}:${serialize(value[key])}`);\n return `{${parts.join(\",\")}}`;\n}\n\nfunction compareUtf16CodeUnits(a: string, b: string): number {\n const max = Math.min(a.length, b.length);\n for (let index = 0; index < max; index++) {\n const leftCodeUnit = a.charCodeAt(index);\n const rightCodeUnit = b.charCodeAt(index);\n if (leftCodeUnit !== rightCodeUnit) {\n return leftCodeUnit - rightCodeUnit;\n }\n }\n return a.length - b.length;\n}\n\nfunction assertUnicodeScalarString(value: string, path: string): void {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (Number.isNaN(next) || next < 0xdc00 || next > 0xdfff) {\n throw new SignedObjectCanonicalizationError(\n `${path} contains a lone high surrogate`,\n );\n }\n index++;\n continue;\n }\n if (code >= 0xdc00 && code <= 0xdfff) {\n throw new SignedObjectCanonicalizationError(\n `${path} contains a lone low surrogate`,\n );\n }\n }\n}\n","/**\n * Values allowed to cross the operation error and context channels.\n *\n * These are intentionally strict. A mismatch detail is useful only when it\n * identifies the same kind of value the runtime actually compares; treating\n * every string as safe would turn the detail field into an exfiltration path.\n */\nexport function safeOriginHost(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return undefined;\n }\n\n if (\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n parsed.username !== \"\" ||\n parsed.password !== \"\" ||\n parsed.search !== \"\" ||\n parsed.hash !== \"\" ||\n (parsed.pathname !== \"\" && parsed.pathname !== \"/\") ||\n parsed.origin === \"null\"\n ) {\n return undefined;\n }\n\n const originWithOptionalSlash = `${parsed.origin}/`;\n if (value !== parsed.origin && value !== originWithOptionalSlash) {\n return undefined;\n }\n return parsed.origin;\n}\n\nexport function safeSessionDid(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n\n const [principal, fragment, ...extra] = value.split(\"#\");\n if (\n extra.length > 0 ||\n (fragment !== undefined && !/^[A-Za-z0-9._:-]+$/.test(fragment))\n ) {\n return undefined;\n }\n\n if (isEd25519DidKey(principal) || isEip155PkhDid(principal)) {\n return principal;\n }\n return undefined;\n}\n\nfunction isEd25519DidKey(value: string): boolean {\n if (!value.startsWith(\"did:key:z\")) return false;\n const bytes = decodeBase58(value.slice(\"did:key:z\".length));\n return (\n bytes !== undefined &&\n bytes.length === 34 &&\n bytes[0] === 0xed &&\n bytes[1] === 0x01\n );\n}\n\nfunction isEip155PkhDid(value: string): boolean {\n return /^did:pkh:eip155:[1-9][0-9]*:0x[0-9a-fA-F]{40}$/.test(value);\n}\n\nfunction decodeBase58(value: string): Uint8Array | undefined {\n if (value.length === 0) return undefined;\n const alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n const digits = [0];\n for (const character of value) {\n const index = alphabet.indexOf(character);\n if (index < 0) return undefined;\n let carry = index;\n for (let i = 0; i < digits.length; i += 1) {\n carry += digits[i]! * 58;\n digits[i] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n digits.push(carry & 0xff);\n carry >>= 8;\n }\n }\n for (const character of value) {\n if (character !== \"1\") break;\n digits.push(0);\n }\n return Uint8Array.from(digits.reverse());\n}\n","import type {\n OperationContextSummary,\n OperationDefinition,\n OperationRef,\n} from \"./contract.js\";\nimport type { OperationError, OperationErrorCode } from \"./errors.js\";\nimport { safeOriginHost, safeSessionDid } from \"./safe-values.js\";\n\nexport const REDACTED_VALUE = \"[REDACTED]\";\n\nexport interface SafeOperationDiagnostic {\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly input?: unknown;\n readonly output?: unknown;\n readonly error?: OperationError;\n}\n\n/**\n * Return a detached redacted value. A missing pointer is intentionally a no-op\n * so an operation can evolve an optional shape without leaking another field.\n */\nexport function redactOperationValue(\n definition: Pick<OperationDefinition<unknown, unknown>, \"sensitivity\">,\n value: unknown,\n): unknown {\n const clone = cloneValue(value);\n const pointers = [\n ...definition.sensitivity.input,\n ...definition.sensitivity.output,\n ];\n\n let redacted: unknown = clone;\n for (const pointer of pointers) {\n redacted = redactPointer(redacted, pointer);\n }\n return redacted;\n}\n\n/**\n * Diagnostic payloads are a supported non-result channel. They accept raw\n * operation values only through this helper, never an invocation target.\n */\nexport function createSafeOperationDiagnostic(\n definition: Pick<OperationDefinition<unknown, unknown>, \"sensitivity\">,\n diagnostic: Readonly<{\n operation: OperationRef;\n context: OperationContextSummary;\n input?: unknown;\n output?: unknown;\n error?: OperationError;\n }>,\n): SafeOperationDiagnostic {\n return {\n operation: {\n operationId: diagnostic.operation.operationId,\n operationVersion: diagnostic.operation.operationVersion,\n },\n context: {\n profile: diagnostic.context.profile,\n host: diagnostic.context.host,\n posture: diagnostic.context.posture,\n ...(diagnostic.context.operatorType === undefined\n ? {}\n : { operatorType: diagnostic.context.operatorType }),\n ...(diagnostic.context.principalDid === undefined\n ? {}\n : { principalDid: diagnostic.context.principalDid }),\n ...(diagnostic.context.sessionDid === undefined\n ? {}\n : { sessionDid: diagnostic.context.sessionDid }),\n ...(diagnostic.context.ownerDid === undefined\n ? {}\n : { ownerDid: diagnostic.context.ownerDid }),\n ...(diagnostic.context.space === undefined\n ? {}\n : { space: diagnostic.context.space }),\n },\n ...(diagnostic.input === undefined\n ? {}\n : { input: redactOperationValue(definition, diagnostic.input) }),\n ...(diagnostic.output === undefined\n ? {}\n : { output: redactOperationValue(definition, diagnostic.output) }),\n ...(diagnostic.error === undefined\n ? {}\n : { error: redactOperationError(definition, diagnostic.error) }),\n };\n}\n\nexport function redactOperationError(\n _definition: Pick<OperationDefinition<unknown, unknown>, \"sensitivity\">,\n error: OperationError,\n): OperationError {\n const details =\n error.details === undefined\n ? undefined\n : redactSafeErrorDetails(error.code, error.details);\n\n return {\n code: error.code,\n message: error.message,\n retryable: error.retryable,\n ...(details === undefined\n ? {}\n : {\n details: isRecord(details) ? details : { redacted: details },\n }),\n };\n}\n\n/**\n * Error details are a separate, code-owned channel. Only fields with an\n * explicit stable policy can cross the canonical result or diagnostic\n * boundary; arbitrary handler details are dropped rather than redacted by\n * input pointers, which could accidentally preserve a transport secret.\n */\nconst SAFE_ERROR_DETAIL_POLICIES: Readonly<\n Partial<\n Record<\n OperationErrorCode,\n Readonly<Record<string, (value: unknown) => unknown | undefined>>\n >\n >\n> = {\n INPUT_INVALID: {\n issues: (value) =>\n Array.isArray(value) ? safeIssueCodes(value) : undefined,\n },\n OPERATION_VERSION_UNSUPPORTED: {\n supportedVersions: (value) =>\n Array.isArray(value) && value.every((item) => Number.isInteger(item))\n ? value\n : undefined,\n },\n DELEGATION_AUDIENCE_MISMATCH: {\n expectedSessionDid: safeSessionDid,\n artifactAudience: safeSessionDid,\n },\n DELEGATION_HOST_MISMATCH: {\n expectedHost: safeOriginHost,\n artifactHost: safeOriginHost,\n },\n};\n\nfunction redactSafeErrorDetails(\n code: OperationErrorCode,\n details: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> | undefined {\n const policy = SAFE_ERROR_DETAIL_POLICIES[code];\n if (policy === undefined) return undefined;\n\n const safeDetails: Record<string, unknown> = {};\n for (const [key, sanitize] of Object.entries(policy)) {\n if (!hasOwn(details, key)) continue;\n const value = sanitize(details[key]);\n if (value !== undefined) safeDetails[key] = value;\n }\n return Object.keys(safeDetails).length === 0 ? undefined : safeDetails;\n}\n\nfunction safeIssueCodes(\n value: readonly unknown[],\n): readonly Readonly<{ code: string }>[] | undefined {\n const codes = value.map((issue) => {\n if (!isRecord(issue) || typeof issue.code !== \"string\") return undefined;\n return SAFE_ISSUE_CODES.has(issue.code) ? { code: issue.code } : undefined;\n });\n return codes.every(\n (issue): issue is Readonly<{ code: string }> => issue !== undefined,\n )\n ? codes\n : undefined;\n}\n\nconst SAFE_ISSUE_CODES = new Set([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\n\nfunction redactPointer(value: unknown, pointer: string): unknown {\n if (pointer === \"\") {\n return REDACTED_VALUE;\n }\n if (!pointer.startsWith(\"/\")) {\n return value;\n }\n\n const tokens = pointer.slice(1).split(\"/\").map(unescapePointerToken);\n const parent = getPointerParent(value, tokens);\n if (parent === undefined) {\n return value;\n }\n\n const key = tokens[tokens.length - 1];\n if (key === undefined || !hasOwn(parent, key)) {\n return value;\n }\n\n Reflect.set(parent, key, REDACTED_VALUE);\n return value;\n}\n\nfunction getPointerParent(\n value: unknown,\n tokens: readonly string[],\n): Record<string, unknown> | unknown[] | undefined {\n if (tokens.length === 0) {\n return undefined;\n }\n\n let cursor = value;\n for (const token of tokens.slice(0, -1)) {\n if (!isRecordOrArray(cursor) || !hasOwn(cursor, token)) {\n return undefined;\n }\n cursor = Reflect.get(cursor, token);\n }\n return isRecordOrArray(cursor) ? cursor : undefined;\n}\n\nfunction unescapePointerToken(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction cloneValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => cloneValue(entry));\n }\n\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n Object.defineProperty(clone, key, {\n configurable: true,\n enumerable: true,\n value: cloneValue((value as Record<string, unknown>)[key]),\n writable: true,\n });\n }\n return clone;\n}\n\nfunction isRecordOrArray(\n value: unknown,\n): value is Record<string, unknown> | unknown[] {\n return value !== null && typeof value === \"object\";\n}\n\nfunction hasOwn(value: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(value, key);\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import type { InvocationTarget, OperationResult } from \"./contract.js\";\nimport { invokeOperationWithLocalAuthorityRetry } from \"./invoke.js\";\n\n/**\n * The only published CLI acquisition helper. Its fixed operation identity is\n * deliberate: adding a future registry operation cannot expand this seam.\n */\nexport function invokeSecretsGetWithLocalAuthorityRetry(\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n return invokeOperationWithLocalAuthorityRetry(\n \"tinycloud.secrets.get\",\n 1,\n invocationTarget,\n unknownInput,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CO,SAAS,eACd,MACA,SACA,UAGK,CAAC,GACU;AAChB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,WAAW,QAAQ,aAAa;AAAA,IAChC,GAAI,QAAQ,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;AAAA,EACtE;AACF;AAgBO,SAAS,qBAAqB,OAA6C;AAChF,SAAO,OAAO,UAAU,YAAY,sBAAsB,SAAS,KAA2B;AAChG;AAEO,SAAS,yBAAyC;AACvD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,6BAA6B,OAAgC;AAC3E,MAAI,iBAAiB,0BAA0B;AAC7C,WAAO,uBAAuB,MAAM,cAAc;AAAA,EACpD;AAEA,SAAO,uBAAuB;AAChC;AAEO,SAAS,uBAAuB,OAAgC;AACrE,MACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,qBAAsB,MAA6B,IAAI,KACxD,OAAQ,MAAgC,YAAY,YACpD,OAAQ,MAAkC,cAAc,WACxD;AACA,WAAO,uBAAuB;AAAA,EAChC;AAEA,QAAM,YAAY;AAClB,SAAO,eAAe,UAAU,MAAM,UAAU,SAAS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,kBACA,cACmC;AACnC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["operationError","ms","resolveSpace","_a","ownership","resolve","randomUUID","resolveSpace","SECRET_NAME_RE","nodeSdk","z","resolveSpace","z","isRecord","EmptyInputSchema","z","z","runtimeContext","runtimeNode","isRecord","nodeFailure","isCanonicalBase64","SpaceSchema","AUTHENTICATED_POSTURES","join","nodeSdk","isRecord","z","isRecord","definition","profileNotFound","isRecord","nodeSdk","resolveSpace","principal","isRecord","isAbsolute","makePkhSpaceId","parsePkhDid","parseSpaceUri","output","principal","runtimeContext","exactCapabilities","resolveSpace","lookupOperation","isAbsolute","createInvocationRuntime","parseSpaceUri","parsePkhDid","makePkhSpaceId"]}
1
+ {"version":3,"sources":["../src/errors.ts","../../../node_modules/ms/index.js","../../sdk-core/src/manifest.ts","../../sdk-core/src/capabilities.ts","../src/authority.ts","../src/state.ts","../src/artifacts.ts","../src/secrets.ts","../src/operations/auth.ts","../src/operations/exploration.ts","../src/operations/secrets-get.ts","../src/operations/sql.ts","../src/contract.ts","../src/delegation-binding.ts","../src/operations/status.ts","../src/registry.ts","../src/profile.ts","../src/runtime.ts","../src/invoke.ts","../../sdk-core/src/policy/errors.ts","../../sdk-core/src/policy/jcs.ts","../src/safe-values.ts","../src/redaction.ts","../src/cli-runtime.ts"],"sourcesContent":["export const OPERATION_ERROR_CODES = [\n \"INPUT_INVALID\",\n \"OPERATION_NOT_FOUND\",\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"PROFILE_NOT_FOUND\",\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"AUTH_REQUIRED\",\n \"PERMISSION_DENIED\",\n \"SESSION_NOT_FOUND\",\n \"PERMISSION_HINT_INVALID\",\n \"DELEGATION_ARTIFACT_INVALID\",\n \"DELEGATION_EXPIRED\",\n \"DELEGATION_AUDIENCE_MISMATCH\",\n \"DELEGATION_HOST_MISMATCH\",\n \"DELEGATION_REJECTED\",\n \"ENCRYPTION_NETWORK_UNRESOLVED\",\n \"NODE_UNREACHABLE\",\n \"NODE_ERROR\",\n \"STORAGE_QUOTA_EXCEEDED\",\n \"KV_NOT_FOUND\",\n \"KV_PRECONDITION_FAILED\",\n \"KV_CONFLICT\",\n \"KV_RESPONSE_TOO_LARGE\",\n \"SQL_QUERY_INVALID\",\n \"SQL_EXECUTION_FAILED\",\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"SQL_VALUE_UNSAFE\",\n \"SECRET_READ_FAILED\",\n \"SECRET_DECRYPT_FAILED\",\n \"OUTPUT_INVALID\",\n \"INTERNAL_ERROR\",\n] as const;\n\nexport type OperationErrorCode = (typeof OPERATION_ERROR_CODES)[number];\n\nexport interface OperationError {\n readonly code: OperationErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport function operationError(\n code: OperationErrorCode,\n message: string,\n options: Readonly<{\n retryable?: boolean;\n details?: Readonly<Record<string, unknown>>;\n }> = {},\n): OperationError {\n return {\n code,\n message,\n retryable: options.retryable ?? false,\n ...(options.details === undefined ? {} : { details: options.details }),\n };\n}\n\nconst MANAGE_STORAGE = \"Do not retry: the owner must free up space or upgrade at https://account.tinycloud.xyz/billing.\";\n\n/**\n * A write the node refused because the owner's TinyCloud storage is full\n * (SDK `STORAGE_QUOTA_EXCEEDED`, HTTP 402) or too small for this write\n * (`STORAGE_LIMIT_REACHED`, HTTP 413). Nothing was written, so the outcome is\n * known, and it stays refused until the owner acts, so it is never retryable.\n * The SDK's account totals travel as details; per-space numbers never do.\n */\nexport function storageFullOperationError(error: unknown): OperationError | undefined {\n if (typeof error !== \"object\" || error === null) return undefined;\n const { code, meta } = error as { code?: unknown; meta?: unknown };\n if (code !== \"STORAGE_QUOTA_EXCEEDED\" && code !== \"STORAGE_LIMIT_REACHED\") return undefined;\n const account = typeof meta === \"object\" && meta !== null ? (meta as { account?: unknown }).account : undefined;\n return operationError(\n \"STORAGE_QUOTA_EXCEEDED\",\n code === \"STORAGE_LIMIT_REACHED\"\n ? `This write is larger than the TinyCloud storage left, so nothing was written. Reading still works. ${MANAGE_STORAGE}`\n : `TinyCloud storage is full, so nothing was written. Reading still works. ${MANAGE_STORAGE}`,\n { retryable: false, ...(account === undefined ? {} : { details: { account } }) },\n );\n}\n\n/**\n * Internal operations and profile resolution use this for expected failures.\n * Generic exceptions are never exposed at the projection boundary.\n */\nexport class OperationInvocationError extends Error {\n public readonly operationError: OperationError;\n\n constructor(operationError: OperationError) {\n super(operationError.message);\n this.name = \"OperationInvocationError\";\n this.operationError = operationError;\n }\n}\n\nexport function isOperationErrorCode(value: unknown): value is OperationErrorCode {\n return typeof value === \"string\" && OPERATION_ERROR_CODES.includes(value as OperationErrorCode);\n}\n\nexport function internalOperationError(): OperationError {\n return operationError(\n \"INTERNAL_ERROR\",\n \"The operation could not be completed.\",\n );\n}\n\nexport function sanitizeThrownOperationError(error: unknown): OperationError {\n if (error instanceof OperationInvocationError) {\n return sanitizeOperationError(error.operationError);\n }\n\n return internalOperationError();\n}\n\nexport function sanitizeOperationError(error: unknown): OperationError {\n if (\n typeof error !== \"object\" ||\n error === null ||\n !isOperationErrorCode((error as { code?: unknown }).code) ||\n typeof (error as { message?: unknown }).message !== \"string\" ||\n typeof (error as { retryable?: unknown }).retryable !== \"boolean\"\n ) {\n return internalOperationError();\n }\n\n const candidate = error as OperationError;\n return operationError(candidate.code, candidate.message, {\n retryable: candidate.retryable,\n ...(candidate.details === undefined ? {} : { details: candidate.details }),\n });\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/**\n * TinyCloud App Manifest\n *\n * A declarative description of an app's identity and the capabilities it\n * needs. The manifest drives the SIWE recap at sign-in time, enabling a\n * single wallet prompt that covers the app's own permissions plus any\n * pre-declared delegations.\n *\n * The SDK does NOT fetch external manifests. Apps compose their own manifest\n * (optionally including backend or agent addenda) before handing it to the\n * SDK.\n *\n * Canonical spec: `.claude/specs/manifest.md`.\n *\n * @packageDocumentation\n */\n\nimport ms from \"ms\";\nimport { ACCOUNT_MANIFEST_PERMISSIONS } from \"@tinycloud/bootstrap\";\nimport { resolveSecretPath, SECRET_NAME_RE } from \"@tinycloud/sdk-services\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A single permission entry inside a manifest. This is the shape apps write\n * in their `manifest.json` and the shape we compare against when performing\n * the capability-subset derivability check in the delegation flow.\n *\n * `service` uses the long form (e.g. `\"tinycloud.kv\"`, `\"tinycloud.sql\"`).\n * `\"tinycloud.vault\"` is an SDK-only shorthand that expands to the KV\n * resources the vault service uses; it is never encoded as a recap service.\n */\nexport interface PermissionEntry {\n /** Service namespace, e.g. \"tinycloud.kv\", \"tinycloud.sql\", \"tinycloud.duckdb\", \"tinycloud.capabilities\". */\n service: string;\n /** Space name or full space URI. Defaults to \"applications\" inside manifests. */\n space?: string;\n /**\n * Service-specific path.\n * - tinycloud.kv: hierarchical prefix. \"/\" = all, \"foo/\" = prefix match, \"foo\" = exact key\n * - tinycloud.sql: database name/file (e.g. \"data.sqlite\") or \"/\" for all\n * - tinycloud.duckdb: database name/file\n * - tinycloud.capabilities: capability key URI or \"/\" for all\n */\n path: string;\n /**\n * Short action names (e.g. \"get\", \"put\", \"read\", \"schema\"). The SDK expands\n * these to full URNs (e.g. `tinycloud.kv/get`) during resolution.\n * Already-expanded URNs are passed through unchanged.\n */\n actions: string[];\n /** Exact ReCap caveat branches when this authority came from a signed ReCap. */\n caveats?: Record<string, unknown>[];\n /** When true, the manifest prefix is NOT prepended to `path`. Default false. */\n skipPrefix?: boolean;\n /** Per-entry expiry override, ms-format. */\n expiry?: string;\n /** User/agent-facing context for why this permission is requested. */\n description?: string;\n}\n\nexport type ManifestSecretActions =\n | true\n | string\n | string[]\n | {\n /** Actual vault secret name. Defaults to the manifest object key. */\n name?: string;\n /** Optional scoped secret namespace. Omit for global secrets. */\n scope?: string;\n actions?: string | string[];\n expiry?: string;\n description?: string;\n };\n\n/**\n * The valid values for `Manifest.defaults`.\n *\n * - `false` → no auto-included permissions\n * - `true` → standard tier (KV + SQL read/write + capabilities:read)\n * - `\"admin\"` → standard + SQL schema\n * - `\"all\"` → everything the SDK supports (including DuckDB)\n *\n * Unknown string values silently fall back to `true`. Values are normalized\n * (lowercase + trim) before matching.\n */\nexport type ManifestDefaults = boolean | \"admin\" | \"all\";\n\n/**\n * Agent-readable app knowledge bundle pointer.\n *\n * - `true` means the default root: `knowledge/index.md`\n * - string values must point at a markdown root under `knowledge/`\n */\nexport type ManifestKnowledge = true | string;\n\n/** Default root used when `manifest.knowledge === true`. */\nexport const DEFAULT_KNOWLEDGE_ROOT = \"knowledge/index.md\";\n\n/**\n * The raw manifest shape an app declares. See `.claude/specs/manifest.md`.\n */\nexport interface Manifest {\n /** Schema version. Optional, defaults to 1. */\n manifest_version?: 1;\n /** Application identifier / namespace prefix. Required. */\n app_id: string;\n /** Display name. Required. */\n name: string;\n /** Description of what the app or delegate does. Optional. */\n description?: string;\n /** DID of this manifest's delegate target. Optional. Required only for delegation materialization. */\n did?: string;\n /** URL to app icon. Optional. */\n icon?: string;\n /** App version string. Optional. */\n appVersion?: string;\n /** Default expiry for permissions. ms-format (\"30d\", \"2h\", \"1y\"). Default \"30d\". */\n expiry?: string;\n /** Space name or full space URI. Optional, defaults to \"applications\". */\n space?: string;\n /**\n * Path prefix auto-prepended to permission paths. Optional, defaults to\n * `app_id`. Set to `\"\"` to disable entirely. Individual permissions can opt\n * out with `skipPrefix: true`.\n */\n prefix?: string;\n /**\n * Default permission set to auto-include. Optional, defaults to `true`.\n * See {@link ManifestDefaults}.\n */\n defaults?: ManifestDefaults | string;\n /** Whether to include the public-space companion delegation. Default `true`. */\n includePublicSpace?: boolean;\n /** Agent-readable knowledge bundle root. `true` means `knowledge/index.md`. */\n knowledge?: ManifestKnowledge;\n /**\n * Additional permissions beyond the defaults. Use for cross-space access,\n * DuckDB (opt-in), or `skipPrefix: true` entries.\n */\n permissions?: PermissionEntry[];\n /**\n * Secret name shorthand. Entries resolve to encrypted vault KV resources in\n * the `secrets` space.\n */\n secrets?: Record<string, ManifestSecretActions>;\n}\n\n/**\n * A resolved permission entry with fully-expanded paths and action URNs.\n * This is the shape the delegation flow compares against parsed recap\n * capabilities, and the shape the session-key delegation path actually uses.\n */\nexport interface ResourceCapability {\n /** Long-form service, e.g. \"tinycloud.kv\". */\n service: string;\n /** Space name or URI. Short names are resolved to full SpaceIds at sign-in time. */\n space: string;\n /** Path with the manifest prefix applied (or skipped per `skipPrefix`). */\n path: string;\n /** Full-URN actions, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: string[];\n /** Per-entry expiry override in milliseconds. */\n expiryMs?: number;\n /** User/agent-facing context copied from the source permission entry. */\n description?: string;\n}\n\n/**\n * A resolved delegation entry with fully-expanded permissions.\n */\nexport interface ResolvedDelegate {\n /** DID of the delegate. */\n did: string;\n /** Informational display name. Optional. */\n name?: string;\n /** Expiry in milliseconds (per-delegation > manifest default > 30 days). */\n expiryMs: number;\n /** Fully resolved permissions. */\n permissions: ResourceCapability[];\n}\n\n/**\n * The output of {@link resolveManifest}: a fully-expanded capability set\n * ready to drive the SIWE recap.\n */\nexport interface ResolvedCapabilities {\n /** Application identifier copied from manifest.app_id. */\n app_id: string;\n /** Delegate DID copied from manifest.did, when present. */\n did?: string;\n /** Effective default space for this manifest. */\n space: string;\n /** All session-key resources with paths fully resolved (prefix applied). */\n resources: ResourceCapability[];\n /** Default expiry for the session, in milliseconds. */\n expiryMs: number;\n /** Whether to include the public-space companion. */\n includePublicSpace: boolean;\n /** Delegate targets derived from manifests that declare `did`. */\n additionalDelegates: ResolvedDelegate[];\n}\n\nexport interface ManifestRegistryRecord {\n /** KV key inside the account space. */\n key: string;\n /** App id this record describes. */\n app_id: string;\n /** Latest manifest payloads composed for this app id. */\n manifests: Manifest[];\n}\n\nexport interface ComposeManifestOptions {\n /** Include implicit account-space registry permissions. Default true. */\n includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface ComposedManifestRequest {\n /** Validated manifests that were composed. */\n manifests: Manifest[];\n /** Full permission union requested from the user in one SIWE. */\n resources: ResourceCapability[];\n /** Delegations that can be materialized after sign-in. */\n delegationTargets: ResolvedDelegate[];\n /** Account-space registry records to write after successful sign-in. */\n registryRecords: ManifestRegistryRecord[];\n /** Effective session expiry, using the longest composed manifest expiry. */\n expiryMs: number;\n /** Whether to include the public-space companion behavior. */\n includePublicSpace: boolean;\n}\n\n/**\n * Thrown when the manifest fails validation (missing id/name, bad expiry,\n * empty actions on a permission, etc).\n */\nexport class ManifestValidationError extends Error {\n constructor(message: string) {\n super(`Manifest validation failed: ${message}`);\n this.name = \"ManifestValidationError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default expiry when neither the manifest, delegation, nor permission\n * specifies one. APP tier — see `expiry.ts`. Spec: 30 days.\n *\n * Kept as an ms-format string because the manifest schema stores expiry\n * as a string and the parser is shared between this default and\n * caller-provided values; converting `EXPIRY.APP_MS` back to a string\n * here would duplicate that same `30d` literal in another form.\n */\nexport const DEFAULT_EXPIRY = \"30d\";\n\n/**\n * Default `defaults` value when the manifest omits it. Spec: standard tier.\n */\nexport const DEFAULT_DEFAULTS: ManifestDefaults = true;\n\n/** Default manifest schema version. */\nexport const DEFAULT_MANIFEST_VERSION = 1;\n\n/** Default space for manifest-declared app data. */\nexport const DEFAULT_MANIFEST_SPACE = \"applications\";\n\n/** Account-space name used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_SPACE = \"account\";\n\n/** Account-space KV prefix used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_PATH = \"applications/\";\n\nexport const SECRETS_SPACE = \"secrets\";\n\n/** SDK-only permission service for encrypted vault resources. */\nexport const VAULT_PERMISSION_SERVICE = \"tinycloud.vault\";\n\ntype VaultKVBase = \"vault\";\n\ninterface VaultActionExpansion {\n bases: readonly VaultKVBase[];\n action: string;\n}\n\n/**\n * Known services and their short-form (recap URI) names. The TinyCloud\n * node encodes the recap resource URI with the short service name, while\n * action URNs and manifest entries use the long `tinycloud.<short>` form.\n * This table is the canonical bridge between the two.\n */\nexport const SERVICE_SHORT_TO_LONG: Readonly<Record<string, string>> =\n Object.freeze({\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n capabilities: \"tinycloud.capabilities\",\n hooks: \"tinycloud.hooks\",\n encryption: \"tinycloud.encryption\",\n delegation: \"tinycloud.delegation\",\n });\n\n/**\n * Manifest service identifier for TinyCloud encryption network grants.\n *\n * Encryption permissions live on a network id URN\n * (`urn:tinycloud:encryption:<ownerDid>:<network>`), not on a space.\n * The `path` field is the literal networkId; `actions` are\n * `[\"decrypt\"]` (expanded to `[\"tinycloud.encryption/decrypt\"]`).\n *\n * Apps should omit `space` for encryption permissions. The SDK may emit\n * an internal `\"encryption\"` compatibility label after expansion so the\n * older `PermissionEntry`/`ResourceCapability` shape can still carry the\n * raw network URN through subset checks.\n */\nexport const ENCRYPTION_PERMISSION_SERVICE = \"tinycloud.encryption\";\n\n/** Synthetic space label used by encryption manifest entries. */\nexport const ENCRYPTION_MANIFEST_SPACE = \"encryption\";\n\n/**\n * Inverse of {@link SERVICE_SHORT_TO_LONG}.\n */\nexport const SERVICE_LONG_TO_SHORT: Readonly<Record<string, string>> =\n Object.freeze(\n Object.fromEntries(\n Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s]),\n ),\n );\n\n/**\n * Default permission entries for the `true` / standard tier.\n *\n * `tinycloud.capabilities/read` is added separately for every requested\n * space, without the app path prefix. That keeps capability introspection\n * space-scoped instead of app-data scoped.\n */\nconst DEFAULT_STANDARD_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n/**\n * Default permission entries for the `\"admin\"` tier: standard + sql/schema.\n */\nconst DEFAULT_ADMIN_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n];\n\n/**\n * Default permission entries for the `\"all\"` tier: admin + DuckDB.\n *\n * DuckDB is opt-in and only appears in this tier or in explicit manifest\n * `permissions` entries.\n */\nconst DEFAULT_ALL_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n {\n service: \"tinycloud.duckdb\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ms-format duration string (e.g. \"30d\", \"2h\", \"1y\") into\n * milliseconds.\n *\n * @throws {ManifestValidationError} on empty string, non-string input, or\n * any input `ms()` cannot parse.\n */\nexport function parseExpiry(duration: string): number {\n if (typeof duration !== \"string\" || duration.length === 0) {\n throw new ManifestValidationError(\n `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`,\n );\n }\n // `ms` returns `undefined` for unparseable input and can return a number\n // or a string depending on the call signature; cast explicitly.\n const parsed = (ms as unknown as (v: string) => number | undefined)(duration);\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new ManifestValidationError(\n `invalid expiry duration: ${JSON.stringify(duration)}`,\n );\n }\n return parsed;\n}\n\n/**\n * Expand a list of action short names (or already-expanded URNs) into full\n * ability URNs of the form `<service>/<action>`.\n *\n * Examples:\n * `expandActionShortNames(\"tinycloud.kv\", [\"get\", \"put\"])`\n * → `[\"tinycloud.kv/get\", \"tinycloud.kv/put\"]`\n * `expandActionShortNames(\"tinycloud.kv\", [\"tinycloud.kv/get\"])`\n * → `[\"tinycloud.kv/get\"]` (passed through unchanged)\n */\nexport function expandActionShortNames(\n service: string,\n actions: readonly string[],\n): string[] {\n return actions.map((a) => {\n if (a.includes(\"/\")) {\n // Already a full URN — pass through.\n return a;\n }\n return `${service}/${a}`;\n });\n}\n\n/**\n * Expand SDK virtual permission services into concrete recap-capable services.\n *\n * Today this handles `\"tinycloud.vault\"`, which is backed by inline\n * network-encrypted KV records:\n * - read/get: `vault/<path>` with `tinycloud.kv/get`\n * - write/put: `vault/<path>` with `tinycloud.kv/put`\n * - delete/del: `vault/<path>` with `tinycloud.kv/del`\n * - list: `vault/<path>` with `tinycloud.kv/list`\n * - head: `vault/<path>` with `tinycloud.kv/get`\n * - metadata: `vault/<path>` with `tinycloud.kv/metadata`\n */\nexport function expandPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {\n return expandEncryptionPermissionEntry(entry);\n }\n if (entry.service !== VAULT_PERMISSION_SERVICE) {\n return [\n {\n ...entry,\n actions: expandActionShortNames(entry.service, entry.actions),\n },\n ];\n }\n\n return expandVaultPermissionEntry(entry);\n}\n\n/**\n * Expand a `tinycloud.encryption` manifest entry.\n *\n * - `path` MUST be a networkId URN (`urn:tinycloud:encryption:...`).\n * The manifest prefix is always skipped — network ids are top-level\n * owner-scoped resources, not space-scoped paths.\n * - `actions` must be `decrypt`, `network.create`, or `network.revoke`\n * (or their already-expanded `tinycloud.encryption/*` forms).\n *\n * The returned entry uses an internal `space = \"encryption\"` compatibility\n * label so old manifest grouping code does not collapse it into the app's\n * data space, and `skipPrefix` is forced to `true` so the prefix application\n * step is a no-op.\n */\nfunction expandEncryptionPermissionEntry(\n entry: PermissionEntry,\n): PermissionEntry[] {\n if (\n typeof entry.path !== \"string\" ||\n !entry.path.startsWith(\"urn:tinycloud:encryption:\")\n ) {\n throw new ManifestValidationError(\n `tinycloud.encryption entries require path to be a networkId URN ` +\n `(got ${JSON.stringify(entry.path)})`,\n );\n }\n const normalizedActions: string[] = [];\n for (const action of entry.actions) {\n if (action === \"decrypt\" || action === \"tinycloud.encryption/decrypt\") {\n normalizedActions.push(\"tinycloud.encryption/decrypt\");\n continue;\n }\n if (\n action === \"network.create\" ||\n action === \"tinycloud.encryption/network.create\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.create\");\n continue;\n }\n if (\n action === \"network.revoke\" ||\n action === \"tinycloud.encryption/network.revoke\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.revoke\");\n continue;\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n // Dedupe while preserving order\n const dedupedActions: string[] = [];\n const seen = new Set<string>();\n for (const a of normalizedActions) {\n if (!seen.has(a)) {\n dedupedActions.push(a);\n seen.add(a);\n }\n }\n // Encryption resources are network-scoped, not space-scoped. We\n // always emit the synthetic \"encryption\" space label so manifest\n // grouping can deal with it uniformly without collapsing the\n // networkId URN into an app data space.\n return [\n {\n service: ENCRYPTION_PERMISSION_SERVICE,\n space: ENCRYPTION_MANIFEST_SPACE,\n path: entry.path,\n actions: dedupedActions,\n skipPrefix: true,\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n },\n ];\n}\n\n/**\n * Expand a list of permission entries using {@link expandPermissionEntry}.\n */\nexport function expandPermissionEntries(\n entries: readonly PermissionEntry[],\n): PermissionEntry[] {\n return entries.flatMap(expandPermissionEntry);\n}\n\n/**\n * Apply the manifest prefix to a permission path per the spec rules.\n *\n * - `skipPrefix: true` → path is returned as-is\n * - `prefix === \"\"` → path is returned as-is\n * - path starts with \"/\" → `prefix + path` (e.g. \"com.listen.app\" + \"/\" → \"com.listen.app/\")\n * - otherwise → `prefix + \"/\" + path` (e.g. \"com.listen.app\" + \"data.sqlite\" → \"com.listen.app/data.sqlite\")\n */\nexport function applyPrefix(\n prefix: string,\n path: string,\n skipPrefix: boolean,\n): string {\n if (skipPrefix) {\n return path;\n }\n if (prefix === \"\") {\n return path;\n }\n if (path.startsWith(\"/\")) {\n return `${prefix}${path}`;\n }\n return `${prefix}/${path}`;\n}\n\n/**\n * Fetch and parse a manifest from a URL (browser) or file path (node).\n * The runtime decides the fetch strategy via `globalThis.fetch`; this is\n * platform-agnostic. Callers that want custom loading should JSON.parse a\n * Manifest themselves and skip this helper.\n *\n * @throws if the fetch fails, the JSON is invalid, or the manifest fails\n * validation.\n */\nexport async function loadManifest(url: string): Promise<Manifest> {\n const fetchFn: typeof fetch | undefined = (\n globalThis as { fetch?: typeof fetch }\n ).fetch;\n if (typeof fetchFn !== \"function\") {\n throw new ManifestValidationError(\n \"loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch\",\n );\n }\n const res = await fetchFn(url);\n if (!res.ok) {\n throw new ManifestValidationError(\n `failed to fetch manifest from ${url}: HTTP ${res.status}`,\n );\n }\n const json = (await res.json()) as unknown;\n return validateManifest(json);\n}\n\n/**\n * Validate a manifest-shaped object and return it strongly-typed.\n * Throws {@link ManifestValidationError} on any hard failure.\n */\nexport function validateManifest(input: unknown): Manifest {\n if (input === null || typeof input !== \"object\") {\n throw new ManifestValidationError(\"manifest must be an object\");\n }\n const m = input as Manifest;\n if (\n m.manifest_version !== undefined &&\n m.manifest_version !== DEFAULT_MANIFEST_VERSION\n ) {\n throw new ManifestValidationError(\n `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`,\n );\n }\n if (typeof m.app_id !== \"string\" || m.app_id.length === 0) {\n throw new ManifestValidationError(\n \"manifest.app_id is required and must be a non-empty string\",\n );\n }\n if (typeof m.name !== \"string\" || m.name.length === 0) {\n throw new ManifestValidationError(\n \"manifest.name is required and must be a non-empty string\",\n );\n }\n if (\n m.did !== undefined &&\n (typeof m.did !== \"string\" || m.did.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.did must be a non-empty DID string\",\n );\n }\n if (\n m.space !== undefined &&\n (typeof m.space !== \"string\" || m.space.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.space must be a non-empty string\",\n );\n }\n if (m.expiry !== undefined) {\n // Will throw with a clear error if invalid.\n parseExpiry(m.expiry);\n }\n if (m.knowledge !== undefined) {\n resolveManifestKnowledgeRoot(m.knowledge);\n }\n if (m.permissions !== undefined) {\n if (!Array.isArray(m.permissions)) {\n throw new ManifestValidationError(\n \"manifest.permissions must be an array\",\n );\n }\n m.permissions.forEach((p, i) =>\n validatePermissionEntry(p, `permissions[${i}]`),\n );\n }\n if (m.secrets !== undefined) {\n validateManifestSecrets(m.secrets);\n }\n return m;\n}\n\n/**\n * Resolve a manifest knowledge pointer to its root markdown file.\n *\n * This is metadata only; app knowledge does not create capabilities.\n */\nexport function resolveManifestKnowledgeRoot(\n knowledge: Manifest[\"knowledge\"] | undefined,\n): string | undefined {\n if (knowledge === undefined) {\n return undefined;\n }\n if (knowledge === true) {\n return DEFAULT_KNOWLEDGE_ROOT;\n }\n if (typeof knowledge !== \"string\" || knowledge.length === 0) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n if (!/^knowledge\\/.+\\.md$/.test(knowledge)) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n return knowledge;\n}\n\nfunction validateManifestSecrets(secrets: unknown): void {\n if (secrets === null || typeof secrets !== \"object\" || Array.isArray(secrets)) {\n throw new ManifestValidationError(\"manifest.secrets must be an object\");\n }\n\n for (const [name, spec] of Object.entries(secrets)) {\n if (!SECRET_NAME_RE.test(name)) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`,\n );\n }\n try {\n resolveSecretPath(\n secretNameFromSpec(name, spec as ManifestSecretActions),\n { scope: secretScopeFromSpec(spec as ManifestSecretActions) },\n );\n } catch (error) {\n throw new ManifestValidationError(\n `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const actions = secretActionsFromSpec(name, spec as ManifestSecretActions);\n if (actions.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty`,\n );\n }\n for (const action of actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty strings`,\n );\n }\n }\n if (\n spec !== null &&\n typeof spec === \"object\" &&\n !Array.isArray(spec) &&\n (spec as { expiry?: unknown }).expiry !== undefined\n ) {\n parseExpiry((spec as { expiry: string }).expiry);\n }\n }\n}\n\nfunction validatePermissionEntry(p: unknown, path: string): void {\n if (p === null || typeof p !== \"object\") {\n throw new ManifestValidationError(`${path} must be an object`);\n }\n const entry = p as PermissionEntry;\n if (typeof entry.service !== \"string\" || entry.service.length === 0) {\n throw new ManifestValidationError(`${path}.service is required`);\n }\n if (\n entry.space !== undefined &&\n (typeof entry.space !== \"string\" || entry.space.length === 0)\n ) {\n throw new ManifestValidationError(\n `${path}.space must be a non-empty string`,\n );\n }\n if (typeof entry.path !== \"string\") {\n throw new ManifestValidationError(\n `${path}.path is required (use \"\" or \"/\" for root)`,\n );\n }\n if (!Array.isArray(entry.actions) || entry.actions.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must be a non-empty array`,\n );\n }\n for (const action of entry.actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must contain non-empty strings`,\n );\n }\n if (entry.service === VAULT_PERMISSION_SERVICE) {\n vaultActionExpansion(action);\n }\n }\n if (entry.caveats !== undefined &&\n (!Array.isArray(entry.caveats) || entry.caveats.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n ))\n ) {\n throw new ManifestValidationError(`${path}.caveats must be an array of objects`);\n }\n if (entry.expiry !== undefined) {\n parseExpiry(entry.expiry);\n }\n}\n\n/**\n * Normalize a `defaults` value: lowercase + trim, then match against known\n * tiers. Unknown string values silently fall back to `true` (standard).\n * Boolean values pass through.\n */\nexport function normalizeDefaults(\n value: Manifest[\"defaults\"] | undefined,\n): ManifestDefaults {\n if (value === undefined) {\n return DEFAULT_DEFAULTS;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value !== \"string\") {\n // Spec says unknown values silently fall back to `true`.\n return true;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"admin\" || normalized === \"all\") {\n return normalized;\n }\n // Anything else, including \"true\"/\"false\"/\"standard\"/garbage, falls back\n // to the standard tier per spec.\n return true;\n}\n\n/**\n * Return the default permission entries for the given tier. Entries are\n * deep-cloned so callers can mutate them without affecting the constants.\n */\nfunction defaultEntriesForTier(tier: ManifestDefaults): PermissionEntry[] {\n if (tier === false) {\n return [];\n }\n const source =\n tier === \"admin\"\n ? DEFAULT_ADMIN_ENTRIES\n : tier === \"all\"\n ? DEFAULT_ALL_ENTRIES\n : DEFAULT_STANDARD_ENTRIES;\n return source.map((e) => ({\n service: e.service,\n space: e.space,\n path: e.path,\n actions: [...e.actions],\n ...(e.skipPrefix !== undefined ? { skipPrefix: e.skipPrefix } : {}),\n }));\n}\n\n/**\n * Resolve a raw manifest into a {@link ResolvedCapabilities} object: expand\n * shortform actions, apply the prefix, merge defaults, and compute effective\n * expiries. Pure function — does no I/O.\n *\n * Resolution semantics (spec):\n * - `prefix` defaults to `app_id`; set to `\"\"` to disable prefix application entirely.\n * - `space` defaults to `applications`; per-permission `space` overrides it.\n * - `defaults` defaults to `true` (standard tier); unknown string values fall back to `true`.\n * - Per-entry expiry overrides per-delegation overrides manifest > `DEFAULT_EXPIRY`.\n * - Default entries use `skipPrefix: false` so they inherit the manifest prefix.\n */\nexport function resolveManifest(input: Manifest): ResolvedCapabilities {\n const manifest = validateManifest(input);\n\n const prefix =\n manifest.prefix !== undefined ? manifest.prefix : manifest.app_id;\n const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;\n const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);\n const includePublicSpace = manifest.includePublicSpace ?? true;\n const tier = normalizeDefaults(manifest.defaults);\n\n const defaultEntries = defaultEntriesForTier(tier);\n const explicitEntries = manifest.permissions ?? [];\n const secretEntries = secretEntriesForManifest(manifest.secrets);\n\n // Merge order: defaults first, then explicit entries, so explicit entries\n // for the same (service, space, path) tuple override defaults.\n const allEntries: PermissionEntry[] = [\n ...defaultEntries,\n ...explicitEntries,\n ...secretEntries,\n ];\n\n const resources: ResourceCapability[] = withCapabilitiesReadForSpaces(\n allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space)),\n );\n\n const additionalDelegates: ResolvedDelegate[] =\n manifest.did === undefined\n ? []\n : [\n {\n did: manifest.did,\n name: manifest.name,\n expiryMs,\n permissions: resources.map(cloneResourceCapability),\n },\n ];\n\n return {\n app_id: manifest.app_id,\n ...(manifest.did !== undefined ? { did: manifest.did } : {}),\n space,\n resources,\n expiryMs,\n includePublicSpace,\n additionalDelegates,\n };\n}\n\nfunction normalizeSecretActions(actions: readonly string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const add = (action: string) => {\n if (!seen.has(action)) {\n out.push(action);\n seen.add(action);\n }\n };\n\n for (const action of actions) {\n if (action === \"read\") {\n add(\"get\");\n continue;\n }\n if (action === \"write\") {\n add(\"put\");\n continue;\n }\n if (action === \"delete\") {\n add(\"del\");\n continue;\n }\n if (\n action === \"get\" ||\n action === \"put\" ||\n action === \"del\" ||\n action === \"list\" ||\n action === \"metadata\"\n ) {\n add(action);\n continue;\n }\n if (\n action === \"tinycloud.kv/get\" ||\n action === \"tinycloud.kv/put\" ||\n action === \"tinycloud.kv/del\" ||\n action === \"tinycloud.kv/list\" ||\n action === \"tinycloud.kv/metadata\"\n ) {\n add(action);\n continue;\n }\n throw new ManifestValidationError(\n `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`,\n );\n }\n\n return out;\n}\n\nfunction secretNameFromSpec(\n fallbackName: string,\n spec: ManifestSecretActions,\n): string {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.name ?? fallbackName;\n }\n return fallbackName;\n}\n\nfunction secretScopeFromSpec(\n spec: ManifestSecretActions,\n): string | undefined {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.scope;\n }\n return undefined;\n}\n\nfunction secretActionsFromSpec(\n name: string,\n spec: ManifestSecretActions,\n): string[] {\n if (spec === true) {\n return [\"read\"];\n }\n if (typeof spec === \"string\") {\n return [spec];\n }\n if (Array.isArray(spec)) {\n return spec;\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must be true, a string action, an actions array, or an object`,\n );\n }\n if (spec.actions === undefined) {\n return [\"read\"];\n }\n if (typeof spec.actions === \"string\") {\n return [spec.actions];\n }\n if (Array.isArray(spec.actions)) {\n return spec.actions;\n }\n throw new ManifestValidationError(\n `manifest.secrets.${name}.actions must be a string or array`,\n );\n}\n\nfunction secretEntriesForManifest(\n secrets: Manifest[\"secrets\"] | undefined,\n): PermissionEntry[] {\n if (secrets === undefined) {\n return [];\n }\n\n const entries: PermissionEntry[] = [];\n for (const [name, spec] of Object.entries(secrets)) {\n const actions = secretActionsFromSpec(name, spec);\n const secretPath = resolveSecretPath(\n secretNameFromSpec(name, spec),\n { scope: secretScopeFromSpec(spec) },\n );\n const extra: { expiry?: string; description?: string } =\n spec !== true && typeof spec === \"object\" && !Array.isArray(spec)\n ? spec\n : {};\n entries.push({\n service: VAULT_PERMISSION_SERVICE,\n space: SECRETS_SPACE,\n path: secretPath.vaultKey,\n actions: normalizeSecretActions(actions),\n skipPrefix: true,\n ...(extra.expiry !== undefined ? { expiry: extra.expiry } : {}),\n ...(extra.description !== undefined\n ? { description: extra.description }\n : {}),\n });\n }\n return entries;\n}\n\n/**\n * Expand a single permission entry into a {@link ResourceCapability}:\n * apply the prefix to the path and expand short actions into full URNs.\n */\nfunction resolveEntry(\n entry: PermissionEntry,\n prefix: string,\n _inheritedExpiryMs: number,\n inheritedSpace: string,\n): ResourceCapability[] {\n // Encryption permissions reference a networkId URN as their resource\n // — the manifest prefix is meaningless against a top-level\n // owner-scoped resource and would corrupt the URN. Always skip.\n const skipPrefixForEntry =\n entry.skipPrefix === true ||\n entry.service === ENCRYPTION_PERMISSION_SERVICE;\n const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);\n const entryExpiryMs =\n entry.expiry !== undefined ? parseExpiry(entry.expiry) : undefined;\n return expandPermissionEntry({\n ...entry,\n space: entry.space ?? inheritedSpace,\n path: resolvedPath,\n skipPrefix: true,\n }).map((expanded) => ({\n service: expanded.service,\n space: expanded.space ?? inheritedSpace,\n path: expanded.path,\n actions: expanded.actions,\n // Only populate `expiryMs` when the entry had its own expiry override.\n // When absent, callers use the parent (delegation or manifest) expiry\n // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.\n ...(entryExpiryMs !== undefined ? { expiryMs: entryExpiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n }));\n}\n\nfunction expandVaultPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n const byBase = new Map<VaultKVBase, string[]>();\n\n for (const action of entry.actions) {\n const expansion = vaultActionExpansion(action);\n for (const base of expansion.bases) {\n const actions = byBase.get(base) ?? [];\n if (!actions.includes(expansion.action)) {\n actions.push(expansion.action);\n }\n byBase.set(base, actions);\n }\n }\n\n return [...byBase.entries()].map(([base, actions]) => ({\n ...entry,\n service: \"tinycloud.kv\",\n path: vaultKVPath(base, entry.path),\n actions,\n skipPrefix: true,\n }));\n}\n\nfunction vaultActionExpansion(action: string): VaultActionExpansion {\n const normalized = normalizeVaultAction(action);\n if (normalized === \"read\" || normalized === \"get\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"write\" || normalized === \"put\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/put\" };\n }\n if (normalized === \"delete\" || normalized === \"del\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/del\" };\n }\n if (normalized === \"list\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/list\" };\n }\n if (normalized === \"head\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"metadata\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/metadata\" };\n }\n\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`,\n );\n}\n\nfunction normalizeVaultAction(action: string): string {\n if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {\n return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);\n }\n if (action.startsWith(\"tinycloud.kv/\")) {\n return action.slice(\"tinycloud.kv/\".length);\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`,\n );\n }\n return action;\n}\n\nfunction vaultKVPath(base: VaultKVBase, path: string): string {\n const normalized = path.startsWith(\"/\") ? path.slice(1) : path;\n return `${base}/${normalized}`;\n}\n\nfunction cloneResourceCapability(\n entry: ResourceCapability,\n): ResourceCapability {\n return {\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.expiryMs !== undefined ? { expiryMs: entry.expiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction clonePermissionEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction dedupeResources(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n const byKey = new Map<string, ResourceCapability>();\n\n for (const resource of resources) {\n const key = `${resource.service}\\u0000${resource.space}\\u0000${resource.path}\\u0000${resource.expiryMs ?? \"\"}`;\n const existing = byKey.get(key);\n if (existing === undefined) {\n byKey.set(key, cloneResourceCapability(resource));\n continue;\n }\n\n const seen = new Set(existing.actions);\n for (const action of resource.actions) {\n if (!seen.has(action)) {\n existing.actions.push(action);\n seen.add(action);\n }\n }\n if (\n existing.description === undefined &&\n resource.description !== undefined\n ) {\n existing.description = resource.description;\n }\n }\n\n return [...byKey.values()];\n}\n\nfunction capabilitiesReadPermission(space: string): ResourceCapability {\n return {\n service: \"tinycloud.capabilities\",\n space,\n path: \"\",\n actions: [\"tinycloud.capabilities/read\"],\n };\n}\n\nfunction withCapabilitiesReadForSpaces(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n if (resources.length === 0) {\n return [];\n }\n\n const spaces = new Set(\n resources\n .filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE)\n .map((resource) => resource.space),\n );\n return dedupeResources([\n ...resources,\n ...[...spaces].map(capabilitiesReadPermission),\n ]);\n}\n\n/**\n * Compose one or more manifests into the single capability request that should\n * be signed. Fetching manifests is intentionally out of band; callers pass the\n * already-loaded manifest objects.\n */\nexport function composeManifestRequest(\n inputs: readonly Manifest[],\n options: ComposeManifestOptions = {},\n): ComposedManifestRequest {\n if (!Array.isArray(inputs) || inputs.length === 0) {\n throw new ManifestValidationError(\n \"composeManifestRequest requires at least one manifest\",\n );\n }\n\n const includeAccountRegistryPermissions =\n options.includeAccountRegistryPermissions ?? true;\n const manifests = inputs.map(validateManifest);\n const resolved = manifests.map(resolveManifest);\n const resources = resolved.flatMap((entry) => entry.resources);\n const delegationTargets = resolved.flatMap((entry) =>\n entry.additionalDelegates.map((delegate) => ({\n ...delegate,\n permissions: dedupeResources(delegate.permissions),\n })),\n );\n\n if (includeAccountRegistryPermissions) {\n resources.push(\n ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n );\n }\n const resourcesWithImplicitCapabilities =\n withCapabilitiesReadForSpaces(resources);\n\n const manifestsByAppId = new Map<string, Manifest[]>();\n for (const manifest of manifests) {\n const current = manifestsByAppId.get(manifest.app_id);\n if (current === undefined) {\n manifestsByAppId.set(manifest.app_id, [manifest]);\n } else {\n current.push(manifest);\n }\n }\n\n const registryRecords: ManifestRegistryRecord[] =\n includeAccountRegistryPermissions\n ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({\n key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,\n app_id,\n manifests: appManifests.map((manifest) => ({\n ...manifest,\n permissions: manifest.permissions?.map(clonePermissionEntry),\n })),\n }))\n : [];\n\n return {\n manifests,\n resources: resourcesWithImplicitCapabilities,\n delegationTargets,\n registryRecords,\n expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),\n includePublicSpace: resolved.some((entry) => entry.includePublicSpace),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abilities map construction (bridge to WASM prepareSession / createDelegation)\n// ---------------------------------------------------------------------------\n\n/**\n * The shape `prepareSession` and the multi-resource `createDelegation` WASM\n * export both accept:\n *\n * ```\n * { [shortService]: { [path]: [fullUrnAction, ...] } }\n * ```\n *\n * - `shortService` is the recap-level service segment (`\"kv\"`, `\"sql\"`,\n * `\"duckdb\"`, `\"capabilities\"`, `\"hooks\"`) — not the manifest long form.\n * - `path` is the fully-resolved path (prefix already applied). An empty\n * string means \"no path segment\" on the resource URI.\n * - Action strings are full URNs like `\"tinycloud.kv/get\"`.\n *\n * This is a single source of truth for both the session's own recap (at\n * sign-in) and the delegations it can derive (post sign-in). We re-use it\n * for both so one manifest drives both sides.\n */\nexport type AbilitiesMap = Record<string, Record<string, string[]>>;\n\n/**\n * Per-space abilities map accepted by the newer WASM session config:\n *\n * ```\n * { [spaceIdOrName]: { [shortService]: { [path]: [fullUrnAction, ...] } } }\n * ```\n */\nexport type SpaceAbilitiesMap = Record<string, AbilitiesMap>;\n\n/**\n * Convert a list of {@link ResourceCapability} entries (manifest\n * long-form service, full-URN actions) into the {@link AbilitiesMap}\n * shape the WASM layer expects.\n *\n * When multiple entries target the same `(service, path)` pair, their\n * action lists are merged and deduped. Entries whose service has no\n * short-form mapping in {@link SERVICE_LONG_TO_SHORT} are rejected with\n * a {@link ManifestValidationError} — the SDK does not silently drop\n * unknown services because the recap encoding would lose them.\n *\n * Paths are kept verbatim: this function does NOT collapse\n * `\"com.listen.app/\"` and `\"com.listen.app\"` or reinterpret empty /\n * slash strings. Callers that care about path canonicalization should\n * normalize before calling.\n */\nexport function resourceCapabilitiesToAbilitiesMap(\n resources: readonly ResourceCapability[],\n): AbilitiesMap {\n const out: AbilitiesMap = {};\n for (const r of resources) {\n const shortService = SERVICE_LONG_TO_SHORT[r.service];\n if (shortService === undefined) {\n throw new ManifestValidationError(\n `unknown service '${r.service}' — no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(\", \")}`,\n );\n }\n if (out[shortService] === undefined) {\n out[shortService] = {};\n }\n const pathsMap = out[shortService];\n const existing = pathsMap[r.path];\n if (existing === undefined) {\n // Copy so downstream mutation can't leak back into the input.\n pathsMap[r.path] = [...r.actions];\n } else {\n // Merge + dedupe while preserving first-seen order.\n const seen = new Set(existing);\n for (const action of r.actions) {\n if (!seen.has(action)) {\n existing.push(action);\n seen.add(action);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Group resolved capabilities by `space`, then convert each group into a WASM\n * abilities map. Short space names are left as-is here; platform layers that\n * know the wallet address and chain id turn them into full SpaceIds.\n */\nexport function resourceCapabilitiesToSpaceAbilitiesMap(\n resources: readonly ResourceCapability[],\n): SpaceAbilitiesMap {\n const grouped = new Map<string, ResourceCapability[]>();\n for (const resource of resources) {\n const entries = grouped.get(resource.space);\n if (entries === undefined) {\n grouped.set(resource.space, [resource]);\n } else {\n entries.push(resource);\n }\n }\n\n const out: SpaceAbilitiesMap = {};\n for (const [space, entries] of grouped.entries()) {\n out[space] = resourceCapabilitiesToAbilitiesMap(entries);\n }\n return out;\n}\n\n/**\n * Build the {@link AbilitiesMap} that a session should be signed with,\n * given a {@link ResolvedCapabilities} (i.e. the output of\n * {@link resolveManifest}).\n *\n * The resulting map is the **union** of:\n * 1. the app's own resources (`resolved.resources`), and\n * 2. every permission declared in every `additionalDelegates[*]` entry.\n *\n * The union is what makes the manifest's delegations ergonomic: at\n * sign-in, the session key acquires recap coverage for both the app's\n * runtime needs and every downstream delegation target. Post sign-in,\n * `delegateTo(backendDID, backendPermissions)` can then issue the\n * sub-delegation via the session key (no wallet prompt) because the\n * caps are already part of the granted set.\n *\n * Duplicate `(service, path, action)` triples across resources and\n * delegations are merged and deduped — the session SIWE doesn't need\n * them repeated.\n */\nexport function manifestAbilitiesUnion(\n resolved: ResolvedCapabilities,\n): AbilitiesMap {\n const all: ResourceCapability[] = [...resolved.resources];\n for (const delegate of resolved.additionalDelegates) {\n for (const perm of delegate.permissions) {\n all.push(perm);\n }\n }\n return resourceCapabilitiesToAbilitiesMap(all);\n}\n","/**\n * Capability subset checking and recap parsing.\n *\n * This module powers the capability-chain delegation flow. The key decision\n * a `delegateTo` call has to make is: \"are the requested capabilities a\n * subset of what the current session already grants?\"\n *\n * - If yes → issue the delegation via the session-key UCAN path (no wallet prompt).\n * - If no → raise {@link PermissionNotInManifestError} so the caller can\n * trigger an escalation flow via `requestPermissions`.\n *\n * Canonical spec: `.claude/specs/capability-chain.md`.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_MANIFEST_SPACE,\n type PermissionEntry,\n SERVICE_SHORT_TO_LONG,\n expandActionShortNames,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a `delegateTo` call requests capabilities that the current\n * session does not already grant. The caller can catch this and trigger\n * `requestPermissions(missing)` to show an escalation modal.\n */\nexport class PermissionNotInManifestError extends Error {\n public readonly missing: PermissionEntry[];\n public readonly granted: PermissionEntry[];\n\n constructor(missing: PermissionEntry[], granted: PermissionEntry[]) {\n super(\n `Requested capabilities exceed current session. Missing ${missing.length} entries.`\n );\n this.name = \"PermissionNotInManifestError\";\n this.missing = missing;\n this.granted = granted;\n }\n}\n\n/**\n * Thrown when the current session has expired (or will expire within the\n * safety margin). The caller should trigger a fresh sign-in.\n */\nexport class SessionExpiredError extends Error {\n public readonly expiredAt: Date;\n\n constructor(expiredAt: Date) {\n super(`Session expired at ${expiredAt.toISOString()}`);\n this.name = \"SessionExpiredError\";\n this.expiredAt = expiredAt;\n }\n}\n\n/**\n * Thrown when the installed WASM delegation boundary cannot encode every\n * constrained ReCap branch in a requested child delegation.\n */\nexport class CaveatedDelegationUnsupportedError extends Error {\n /** Stable machine-readable error code for fail-closed caveated delegation. */\n code = \"CAVEATED_DELEGATION_UNSUPPORTED\" as const;\n /** Requested entries whose constrained ReCap branches cannot be preserved. */\n entries: PermissionEntry[];\n\n constructor(entries: PermissionEntry[]) {\n super(\n \"Cannot create a caveated delegation because this WASM delegation boundary cannot preserve every ReCap caveat branch exactly.\"\n );\n this.name = \"CaveatedDelegationUnsupportedError\";\n this.entries = entries.map(cloneEntry);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space normalization\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a space identifier to its short-name form.\n *\n * Recap resource URIs in a signed SIWE encode the space as a full URI of the\n * form `tinycloud:pkh:eip155:{chainId}:{address}:{name}` (e.g.\n * `tinycloud:pkh:eip155:1:0xd559...:default`). Manifest permissions and\n * backend-advertised permissions use the short `{name}` form (e.g.\n * `\"default\"`).\n *\n * Strict string comparison between these two forms would always fail, so we\n * normalize both sides to the short name before comparing. The trailing\n * segment after the last `:` in a `tinycloud:` URI is the space name.\n *\n * Short names (`\"default\"`, `\"work-space\"`) are returned unchanged.\n * Any non-`tinycloud:` string is returned unchanged. A malformed URI with a\n * trailing colon is returned unchanged (so the check degrades to a strict\n * mismatch rather than collapsing to an empty string).\n *\n * @internal\n */\nexport function normalizeSpace(space: string): string {\n if (!space.startsWith(\"tinycloud:\")) {\n return space;\n }\n const lastColon = space.lastIndexOf(\":\");\n if (lastColon === -1 || lastColon === space.length - 1) {\n return space;\n }\n return space.slice(lastColon + 1);\n}\n\n// ---------------------------------------------------------------------------\n// Subset check\n// ---------------------------------------------------------------------------\n\nexport interface SubsetCheckResult {\n /** True when every requested entry is covered by a granted entry. */\n subset: boolean;\n /** Entries the granted set does not cover (empty when `subset` is true). */\n missing: PermissionEntry[];\n}\n\n/**\n * Check whether `requested` is a strict subset of `granted`.\n *\n * Matching rules for each `requested[i]`:\n * - `service` matches exactly.\n * - `space` matches exactly.\n * - Path containment:\n * - If `granted.path` ends with `/`, it covers any `requested.path` that\n * starts with `granted.path`.\n * - Otherwise, the paths must match exactly.\n * - Action containment: every requested URN must be matched exactly or by a\n * service-scoped wildcard such as `tinycloud.kv/*`.\n *\n * Grant entries with the same service, space, path coverage, and caveats are\n * considered together. This matters because ReCap parsers may return one\n * entry per action even when the original manifest grouped those actions.\n * Any `requested` entry whose actions are not collectively covered is added\n * to `missing` and the overall result is non-subset.\n *\n * Both sides are expected to be in the canonical long-form shape (service\n * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}\n * or `expandActionShortNames` to normalize inputs first.\n */\nexport function isCapabilitySubset(\n requested: readonly PermissionEntry[],\n granted: readonly PermissionEntry[]\n): SubsetCheckResult {\n const missing: PermissionEntry[] = [];\n\n for (const req of requested) {\n const matchingScope = granted.filter((entry) =>\n canonicalizeEntryScopeMatches(req, entry)\n );\n const requestedActions = expandActionShortNames(\n req.service,\n req.actions\n );\n const grantedActions = matchingScope.flatMap((entry) =>\n expandActionShortNames(entry.service, entry.actions)\n );\n const covered = requestedActions.every((requestedAction) =>\n grantedActions.some((grantedAction) =>\n actionContains(grantedAction, requestedAction)\n )\n );\n if (!covered) {\n missing.push(cloneEntry(req));\n }\n }\n\n return { subset: missing.length === 0, missing };\n}\n\n/**\n * Returns true when `granted` fully covers `requested` — same service, same\n * space, path containment per spec, and action set containment.\n */\nfunction canonicalizeEntryScopeMatches(\n requested: PermissionEntry,\n granted: PermissionEntry\n): boolean {\n if (requested.service !== granted.service) {\n return false;\n }\n // Normalize both sides so callers passing short names (`\"default\"`) match\n // recap-parsed full URIs (`\"tinycloud:pkh:eip155:1:0xd559...:default\"`) and\n // vice versa. Idempotent for short names.\n if (\n normalizeSpace(requested.space ?? DEFAULT_MANIFEST_SPACE) !==\n normalizeSpace(granted.space ?? DEFAULT_MANIFEST_SPACE)\n ) {\n return false;\n }\n if (!pathContains(granted.path, requested.path)) {\n return false;\n }\n // There is no safe general partial ordering for arbitrary ReCap caveat\n // objects. A caveated authority therefore only covers the same caveat set;\n // treating it as uncaveated would authorize a broader child delegation.\n if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {\n return false;\n }\n return true;\n}\n\n/**\n * Compare ReCap caveat branch sets without losing signed branch structure.\n *\n * ReCap represents an unconstrained ability as `[{}]`, while SDK callers can\n * represent that same authority as `undefined` or `[]`. Those three forms are\n * equivalent. Every other branch, including an unconstrained branch mixed\n * with a constrained one, remains part of the canonical comparison.\n */\nexport function recapCaveatsEqual(\n left: readonly Record<string, unknown>[] | undefined,\n right: readonly Record<string, unknown>[] | undefined,\n): boolean {\n return canonicalizeRecapCaveats(left) === canonicalizeRecapCaveats(right);\n}\n\n/**\n * Canonicalize a ReCap caveat branch set for exact equality checks.\n *\n * Object keys and branch order do not affect equality. A lone unconstrained\n * branch is normalized to the SDK's empty-caveat representation, but an\n * unconstrained branch in a mixed set is deliberately retained.\n */\nexport function canonicalizeRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): string {\n const canonicalize = (value: unknown): string => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return JSON.stringify(value);\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(\",\")}]`;\n if (typeof value === \"object\") {\n const object = value as Record<string, unknown>;\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n return `{${Object.keys(object).sort().map((key) =>\n `${JSON.stringify(key)}:${canonicalize(object[key])}`,\n ).join(\",\")}}`;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n const branches = (caveats ?? []).map(canonicalize).sort();\n if (branches.length === 0 || (branches.length === 1 && branches[0] === \"{}\")) {\n return \"[]\";\n }\n return `[${branches.join(\",\")}]`;\n}\n\n// Literal strings, not `KV.SYNC`/`KV.RETAIN`: those are derived from the\n// vendored registry at runtime, so an older bootstrap would turn them into\n// `undefined` and silently disable this guard.\nconst EXPLICIT_ONLY_ACTIONS: Readonly<Record<string, true>> = {\n \"tinycloud.kv/sync\": true,\n \"tinycloud.kv/retain\": true,\n};\n\n/**\n * Whether `action` is one no wildcard covers: `*` and `tinycloud.kv/*` do not\n * grant it, so a grant must name it (TC-732). `tinycloud.kv/sync` discloses a\n * prefix's change feed and `tinycloud.kv/retain` is an owner-approved\n * retention attestation; the node refuses both unless granted by name.\n */\nexport function isExplicitOnlyAction(action: string): boolean {\n return Object.prototype.hasOwnProperty.call(EXPLICIT_ONLY_ACTIONS, action);\n}\n\n/** Return whether a granted action pattern covers one requested action. */\nexport function actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === requestedAction) return true;\n if (isExplicitOnlyAction(requestedAction)) return false;\n if (grantedAction === \"*\") return true;\n if (!grantedAction.endsWith(\"/*\")) return false;\n const service = grantedAction.slice(0, -2);\n return requestedAction === service || requestedAction.startsWith(`${service}/`);\n}\n\n/**\n * Path containment per spec:\n * - `granted.path` ends with `/` → prefix match (requested starts with granted)\n * - otherwise → exact string match\n *\n * The empty string is treated as \"no path constraint\" and matches anything.\n * The single-character `\"/\"` also matches anything (it is a trailing-slash\n * prefix of zero-length).\n */\nfunction pathContains(grantedPath: string, requestedPath: string): boolean {\n if (grantedPath === \"\" || grantedPath === \"/\") {\n return true;\n }\n if (grantedPath.endsWith(\"/\")) {\n return requestedPath.startsWith(grantedPath);\n }\n return requestedPath === grantedPath;\n}\n\nfunction cloneEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Recap parsing (WASM wrapper)\n// ---------------------------------------------------------------------------\n\n/**\n * The raw shape returned from the WASM `parseRecapFromSiwe` export. The\n * Rust layer encodes the service in the short form (e.g. `\"kv\"`) because\n * that is what the SIWE recap resource URI actually contains. We normalize\n * to the manifest long form (`\"tinycloud.kv\"`) in {@link parseRecapCapabilities}.\n *\n * @internal\n */\nexport interface WasmRecapEntry {\n service: string;\n space: string;\n path: string;\n actions: string[];\n /** Exact ReCap caveats shared by every action in this entry. */\n caveats?: Record<string, unknown>[];\n}\n\n/**\n * Signature of the WASM `parseRecapFromSiwe` export. Accepts the signed\n * SIWE message string and returns an array of raw recap entries. Throws if\n * the SIWE is malformed or the recap statement has been tampered.\n *\n * Exposed as an interface so the SDK can inject the web or node binding\n * without `capabilities.ts` needing to know which.\n */\nexport type ParseRecapFromSiwe = (siweString: string) => WasmRecapEntry[];\n\n/**\n * Parse a signed SIWE message into an array of {@link PermissionEntry}\n * objects in the canonical long-form manifest shape.\n *\n * This is a thin wrapper around the WASM `parseRecapFromSiwe` export that:\n * 1. Normalizes short-form services (`\"kv\"`) to long-form (`\"tinycloud.kv\"`).\n * 2. Returns entries in a deterministic order (sorted by space, then service,\n * then path) so downstream equality checks are stable.\n *\n * Returns an empty array when the SIWE has no recap resource (plain auth\n * SIWE); this matches the WASM function's behavior and the spec.\n *\n * @param parseWasm The WASM `parseRecapFromSiwe` binding.\n * @param siwe The signed SIWE message string (exactly what `session.siwe` stores).\n */\nexport function parseRecapCapabilities(\n parseWasm: ParseRecapFromSiwe,\n siwe: string\n): PermissionEntry[] {\n const raw = parseWasm(siwe);\n if (!Array.isArray(raw)) {\n throw new Error(\n \"parseRecapFromSiwe returned a non-array value; wasm binding may be out of sync\"\n );\n }\n const normalized: PermissionEntry[] = raw.map((entry) => {\n const longService =\n SERVICE_SHORT_TO_LONG[entry.service] ??\n // Unknown short names pass through. If the recap already contained a\n // long-form service (e.g. a future tinycloud-node version emits long\n // form directly), don't double-prefix.\n (entry.service.startsWith(\"tinycloud.\")\n ? entry.service\n : `tinycloud.${entry.service}`);\n return {\n service: longService,\n // The Rust layer emits the space as a full `tinycloud:pkh:...:name`\n // URI (the recap target URI). Normalize to the short name so the\n // returned entries match the shape manifests use.\n space: normalizeSpace(entry.space),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats === undefined\n ? {}\n : { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }),\n };\n });\n\n // Sort for determinism (callers do equality checks on arrays of entries\n // in tests; deterministic ordering keeps those stable).\n normalized.sort((a, b) => {\n const aSpace = a.space ?? DEFAULT_MANIFEST_SPACE;\n const bSpace = b.space ?? DEFAULT_MANIFEST_SPACE;\n if (aSpace !== bSpace) return aSpace < bSpace ? -1 : 1;\n if (a.service !== b.service) return a.service < b.service ? -1 : 1;\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return 0;\n });\n\n return normalized;\n}\n","import {\n canonicalizeRecapCaveats,\n isCapabilitySubset,\n type PermissionEntry,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * A capability in the canonical form persisted in a v1 request artifact.\n *\n * The SDK remains the semantic authority for containment. This module only\n * establishes deterministic exact identity for persistence and display.\n */\nexport type CanonicalPermissionEntry = Readonly<PermissionEntry>;\n\nexport interface AuthorityEvaluation {\n readonly satisfied: boolean;\n readonly missing: readonly CanonicalPermissionEntry[];\n}\n\n/**\n * Operation-owned space resolution. The SDK's general capability evaluator\n * intentionally preserves its historical short/full-space compatibility; the\n * operation kernel supplies this narrower resolver when a space identifies a\n * remote owner's resource.\n */\nexport type OperationSpaceResolver = (space: string) => string;\n\nconst EXACT_PERMISSION_KEYS = new Set([\n \"service\",\n \"space\",\n \"path\",\n \"actions\",\n \"skipPrefix\",\n \"expiry\",\n \"description\",\n]);\n\n/**\n * Validate requirements that can be represented without semantic broadening in\n * a v1 artifact. Caveated authority is intentionally rejected: the v1 request\n * schema and grant path cannot preserve those signed branches end-to-end.\n */\nexport function validateExactCapabilities(value: unknown): PermissionEntry[] | undefined {\n if (!Array.isArray(value)) return undefined;\n\n const permissions: PermissionEntry[] = [];\n for (const candidate of value) {\n if (!isExactPermission(candidate)) return undefined;\n permissions.push(candidate);\n }\n return canonicalizeCapabilities(permissions);\n}\n\n/**\n * Evaluates required authority with the SDK's public subset primitive.\n *\n * In particular, this intentionally does not implement matching rules or\n * manufacture wildcards. A wildcard can cover a requirement only when it was\n * already present in the supplied granted authority and the SDK says so.\n */\nexport function evaluateAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeCapabilities(granted);\n const canonicalRequired = canonicalizeCapabilities(required);\n const result = isCapabilitySubset(canonicalRequired, canonicalGranted);\n\n return {\n satisfied: result.subset,\n missing: canonicalizeCapabilities(result.missing),\n };\n}\n\n/**\n * Evaluate operation capabilities without allowing two owners' same-named\n * spaces to compare equal. Path and action containment still come from the\n * SDK primitive; only the operation space identity is made owner-exact.\n */\nexport function evaluateOperationAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeOperationCapabilities(granted, resolveSpace);\n const canonicalRequired = canonicalizeOperationCapabilities(required, resolveSpace);\n const missing: CanonicalPermissionEntry[] = [];\n\n for (const requested of canonicalRequired) {\n const covered = canonicalGranted.some((candidate) =>\n candidate.service === requested.service &&\n operationSpacesEqual(candidate.space, requested.space) &&\n isCapabilitySubset([requested], [candidate]).subset,\n );\n if (!covered) missing.push(requested);\n }\n\n return {\n satisfied: missing.length === 0,\n missing: canonicalizeCapabilities(missing),\n };\n}\n\n/**\n * Whether a delegation's signed capabilities stay inside the stored request\n * it answers. `tinycloud.auth.import` and runtime replay share this check, so\n * a delegation import accepts is never one replay discards.\n */\nexport function delegationWithinRequest(\n requested: readonly PermissionEntry[],\n effective: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n return requested.length > 0 &&\n evaluateOperationAuthority(requested, canonicalizeCapabilities(effective), resolveSpace).satisfied;\n}\n\n/**\n * Validate a runtime hint as an exact member of the registered plan. Runtime\n * nodes may report the one phase that failed, but they may not introduce a\n * broader, differently-owned, caveated, or otherwise new capability.\n */\nexport function isExactCapabilityMemberSubset(\n hinted: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n const canonicalHinted = canonicalizeOperationCapabilities(hinted, resolveSpace);\n const canonicalPlanned = canonicalizeOperationCapabilities(planned, resolveSpace);\n return canonicalHinted.length > 0 && canonicalHinted.every((hint) => canonicalPlanned.some((plan) =>\n JSON.stringify(hint) === JSON.stringify(plan),\n ));\n}\n\n/** Canonical identity used by operation preflight, hints, and artifacts. */\nexport function canonicalizeOperationCapabilities(\n permissions: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): CanonicalPermissionEntry[] {\n return canonicalizeCapabilities(permissions.map((permission) => {\n const canonicalPath = canonicalizeOperationPath(permission);\n if (permission.space === undefined || resolveSpace === undefined) {\n return canonicalPath;\n }\n try {\n return { ...canonicalPath, space: resolveSpace(permission.space) };\n } catch {\n // An unresolvable identity remains a non-matching literal. It must never\n // be widened to a wildcard or to another authenticated owner.\n return canonicalPath;\n }\n }));\n}\n\nfunction canonicalizeOperationPath(permission: PermissionEntry): PermissionEntry {\n if (permission.service !== \"tinycloud.encryption\") return permission;\n const match = permission.path.match(\n /^(urn:tinycloud:encryption:did:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.*)$/,\n );\n if (!match) return permission;\n return { ...permission, path: `${match[1]}${match[2]!.toLowerCase()}${match[3]}` };\n}\n\nfunction operationSpacesEqual(\n granted: string | undefined,\n requested: string | undefined,\n): boolean {\n return granted === requested;\n}\n\n/** Returns a stable exact identity for one capability without containment. */\nexport function permissionIdentity(permission: PermissionEntry): string {\n return JSON.stringify(canonicalizeCapability(permission));\n}\n\n/**\n * Sorts actions and entries and removes only exactly-identical capabilities.\n * It does not coalesce paths, services, spaces, or actions into a broader\n * capability.\n */\nexport function canonicalizeCapabilities(\n permissions: readonly PermissionEntry[],\n): CanonicalPermissionEntry[] {\n const byIdentity = new Map<string, CanonicalPermissionEntry>();\n for (const permission of permissions) {\n const canonical = canonicalizeCapability(permission);\n byIdentity.set(permissionIdentityFromCanonical(canonical), canonical);\n }\n\n return [...byIdentity.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, permission]) => permission);\n}\n\nfunction canonicalizeCapability(permission: PermissionEntry): CanonicalPermissionEntry {\n const actions = [...new Set(permission.actions)].sort((left, right) => left.localeCompare(right));\n return {\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined\n ? {}\n : { caveats: canonicalizeCaveats(permission.caveats) }),\n };\n}\n\nfunction permissionIdentityFromCanonical(permission: CanonicalPermissionEntry): string {\n return JSON.stringify({\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions: permission.actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n });\n}\n\nfunction isExactPermission(value: unknown): value is PermissionEntry {\n if (\n !isExactRecord(value) ||\n Object.getOwnPropertyNames(value).some((key) => !EXACT_PERMISSION_KEYS.has(key)) ||\n Object.getOwnPropertySymbols(value).length > 0\n ) {\n return false;\n }\n if (\n !isExactText(value.service) ||\n !isExactPath(value.path, value.actions) ||\n (value.space !== undefined && !isExactText(value.space)) ||\n !Array.isArray(value.actions) ||\n value.actions.length === 0 ||\n !value.actions.every(isExactText) ||\n new Set(value.actions).size !== value.actions.length ||\n value.skipPrefix === true ||\n (value.skipPrefix !== undefined && value.skipPrefix !== false) ||\n (value.expiry !== undefined && !isExactText(value.expiry)) ||\n (value.description !== undefined && !isExactText(value.description))\n ) {\n return false;\n }\n return !(\"caveats\" in value);\n}\n\nfunction isExactRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isExactText(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && !value.includes(\"*\");\n}\n\nfunction isExactPath(value: unknown, actions: unknown): value is string {\n if (typeof value !== \"string\" || value === \"/\" || value.includes(\"*\")) return false;\n if (value === \"\" || value.endsWith(\"/\")) {\n return Array.isArray(actions) && actions.includes(\"tinycloud.kv/list\");\n }\n return true;\n}\n\nfunction canonicalizeCaveats(\n caveats: readonly Record<string, unknown>[],\n): Record<string, unknown>[] {\n return [...caveats]\n .map((caveat) => ({\n identity: canonicalizeRecapCaveats([caveat]),\n value: JSON.parse(JSON.stringify(caveat)) as Record<string, unknown>,\n }))\n .sort((left, right) => left.identity.localeCompare(right.identity))\n .map(({ value }) => value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n readdir,\n rename,\n rmdir,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\nconst DEFAULT_PROFILE = \"default\";\nconst DEFAULT_LOCK_TIMEOUT_MS = 2_000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\nconst DEFAULT_STALE_LOCK_MS = 30_000;\nconst TEST_LOCK_CONTENTION_SIGNAL_PATH = \"TC_TEST_PROFILE_LOCK_CONTENTION_SIGNAL_PATH\";\n// Profile state holds keys, sessions and delegations: owner-only access.\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIR_MODE = 0o700;\nconst TEST_LOCK_RECOVERY_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RECOVERY_BARRIER_DIR\";\nconst TEST_LOCK_OWNERLESS_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_OWNERLESS_BARRIER_DIR\";\nconst TEST_LOCK_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_RELEASE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RELEASE_BARRIER_DIR\";\nconst TEST_LOCK_CLAIM_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIM_BARRIER_DIR\";\nconst TEST_LOCK_CLAIMED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIMED_BARRIER_DIR\";\nconst TEST_LOCK_VERIFIED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_VERIFIED_BARRIER_DIR\";\nconst TEST_LOCK_MOVED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_MOVED_BARRIER_DIR\";\nconst TEST_LOCK_TURN_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_TURN_SETTLE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_SETTLE_BARRIER_DIR\";\nconst TEST_LOCK_TURN_COLLECT_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_COLLECT_BARRIER_DIR\";\n/** One acquisition of a profile lock; `active` is cleared before release. */\ninterface HeldProfileLock {\n readonly lockPath: string;\n /** The number of the turn this acquisition holds (see acquireTurn). */\n readonly turnSlot: number;\n /** A deletion of the profile ran while this acquisition waited for the lock. */\n readonly deletedWhileWaiting: boolean;\n active: boolean;\n}\n/**\n * Async context shared by every copy of this module in the process. Each\n * bundled operations entry point (`state`, `delegation-binding`, the root)\n * carries its own copy, so module-level context would make lock reentrancy and\n * the invocation state root stop at an entry-point boundary.\n * Each key is independently versioned for the shape and meaning of the\n * value it stores. Held-lock entries gained `turnSlot` and\n * `deletedWhileWaiting` in TC-633, so `.v2` must not read TC-602's `.v1`\n * entries. The invocation root remains a string path with unchanged\n * semantics and stays `.v1`. Relinquished turn tokens use a separate\n * versioned process-wide key: only an explicitly given-up turn of this PID\n * may be settled across separately bundled entry points.\n */\nfunction processWideContext<T>(key: string): AsyncLocalStorage<T> {\n const registry = globalThis as unknown as Record<symbol, AsyncLocalStorage<T> | undefined>;\n return registry[Symbol.for(key)] ??= new AsyncLocalStorage<T>();\n}\nconst invocationStateRoot = processWideContext<string>(\"tinycloud.operations.invocationStateRoot.v1\");\n/** Profile lock acquisitions held by the current async call chain (see withProfileLock). */\nconst heldProfileLocks = processWideContext<readonly HeldProfileLock[]>(\"tinycloud.operations.heldProfileLocks.v2\");\n\nexport type ProfileStoreName =\n | \"session\"\n | \"additional-delegations\"\n | \"auth-requests\";\n\nexport interface StoreMetadata {\n formatVersion: number;\n}\n\nexport interface ProfileStoreContents<T> {\n formatVersion: number;\n records: T[];\n}\n\nexport interface ProfileLockOptions {\n timeoutMs?: number;\n retryMs?: number;\n staleAfterMs?: number;\n /**\n * Lock only a profile that exists (its `profile.json` is present), and\n * never create its directory: a missing or deleted profile is refused with\n * ProfileDeletedError, before and after waiting for the lock. For writers\n * of state that lives inside an existing profile (replicas).\n */\n requireProfile?: boolean;\n}\n\nexport class ProfileLockTimeoutError extends Error {\n readonly code = \"PROFILE_LOCK_TIMEOUT\";\n\n /** `detail` names the cause when it is not simply another process holding the lock. */\n constructor(profile: string, timeoutMs: number, detail?: string) {\n super(`Timed out waiting for the profile lock for \"${profile}\" after ${timeoutMs}ms.${detail ? ` ${detail}` : \"\"}`);\n this.name = \"ProfileLockTimeoutError\";\n }\n}\n\n/**\n * A store write that waited for the profile lock while a deletion of that\n * profile held it, and found no profile settings once it got the lock. The\n * write is refused rather than recreating a profile with only a session or\n * store in it.\n */\nexport class ProfileDeletedError extends Error {\n readonly code = \"PROFILE_NOT_FOUND\";\n\n constructor(profile: string) {\n super(`Profile \"${profile}\" was deleted while this change waited for its lock, so the change was not written.`);\n this.name = \"ProfileDeletedError\";\n }\n}\n\n/**\n * The CLI's delegated-secret path treats TC_HOME as a home directory, rather\n * than a direct TinyCloud directory. Keep the shared store on that convention.\n */\nexport function tinycloudHomePath(): string {\n const home = invocationStateRoot.getStore() ??\n process.env.TC_HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n homedir();\n return join(home, \".tinycloud\");\n}\n\n/** Run one operation against an isolated TinyCloud home directory. */\nexport function withTinyCloudStateRoot<T>(\n stateRoot: string | undefined,\n action: () => Promise<T>,\n): Promise<T> {\n if (stateRoot === undefined) return action();\n if (!isAbsolute(stateRoot) || stateRoot.includes(\"\\0\")) {\n throw new TypeError(\"The TinyCloud state root must be an absolute path.\");\n }\n return invocationStateRoot.run(resolve(stateRoot), action);\n}\n\nexport function tinycloudConfigPath(): string {\n return join(tinycloudHomePath(), \"config.json\");\n}\n\nexport function profilesPath(): string {\n return join(tinycloudHomePath(), \"profiles\");\n}\n\nexport function profilePath(profile: string): string {\n return join(profilesPath(), validateProfileName(profile));\n}\n\nexport function profileConfigPath(profile: string): string {\n return join(profilePath(profile), \"profile.json\");\n}\n\nexport function sessionPath(profile: string): string {\n return profileStorePath(profile, \"session\");\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n return profileStorePath(profile, \"additional-delegations\");\n}\n\nexport function authRequestsPath(profile: string): string {\n return profileStorePath(profile, \"auth-requests\");\n}\n\nexport function profileStorePath(profile: string, store: ProfileStoreName): string {\n return join(profilePath(profile), `${store}.json`);\n}\n\n/** The format record is deliberately separate from each legacy JSON payload. */\nexport function profileStoreMetadataPath(profile: string, store: ProfileStoreName): string {\n return `${profileStorePath(profile, store)}.metadata.json`;\n}\n\nexport function profileLockPath(profile: string): string {\n return join(profilePath(profile), \".lock\");\n}\n\nexport function profileLockMetadataPath(profile: string): string {\n return join(profileLockPath(profile), \"owner.json\");\n}\n\n/**\n * The turn lock of a profile (see acquireTurn). It lives outside the profile\n * directory, so neither a profile deletion nor an older release's cleanup\n * removes it.\n */\nexport function profileTurnLockPath(profile: string): string {\n return join(tinycloudHomePath(), \"profile-locks\", validateProfileName(profile));\n}\n\n/**\n * Reads JSON without hiding malformed or inaccessible files. A missing file is\n * the only condition represented as null.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(filePath, \"utf8\")) as T;\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return null;\n throw error;\n }\n}\n\n/**\n * Writes the same pretty-printed, trailing-newline JSON shape used by the CLI,\n * but publishes it with an atomic rename from the same directory.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n await replaceJson(filePath, value, false);\n}\n\n/**\n * writeJsonAtomic; `durable` also flushes the data to disk before the rename,\n * so a crash or power loss leaves the old record or the new one, never a\n * truncated one (for lock records, whose damage would stop every writer).\n */\nasync function replaceJson(filePath: string, value: unknown, durable: boolean): Promise<void> {\n const directory = dirname(filePath);\n const temporaryPath = join(\n directory,\n `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,\n );\n const contents = `${JSON.stringify(value, null, 2)}\\n`;\n\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n try {\n if (durable) await writeFileDurably(temporaryPath, contents);\n else await writeFile(temporaryPath, contents, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE });\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Creates a file (exclusively) and, when it has contents, flushes them to disk. */\nasync function writeFileDurably(path: string, contents: string): Promise<void> {\n const handle = await open(path, \"wx\", PRIVATE_FILE_MODE);\n try {\n if (contents) {\n await handle.writeFile(contents, \"utf8\");\n await handle.datasync();\n }\n } finally {\n await handle.close();\n }\n}\n\nexport async function readProfile<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n return readJson<T>(profileConfigPath(profile));\n}\n\nexport async function readSession<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n await readStoreMetadata(profile, \"session\");\n return readJson<T>(sessionPath(profile));\n}\n\nexport async function readAdditionalDelegations<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"additional-delegations\")).records;\n}\n\nexport async function readAuthRequests<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"auth-requests\")).records;\n}\n\nexport async function readStoreMetadata(\n profile: string,\n store: ProfileStoreName,\n): Promise<StoreMetadata> {\n const metadata = await readJson<StoreMetadata>(profileStoreMetadataPath(profile, store));\n if (metadata === null) return { formatVersion: 1 };\n if (\n typeof metadata !== \"object\" ||\n metadata.formatVersion !== 1\n ) {\n throw new TypeError(`Unsupported store format for \"${store}\".`);\n }\n return metadata;\n}\n\nexport async function readProfileStore<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n): Promise<ProfileStoreContents<T>> {\n const [metadata, raw] = await Promise.all([\n readStoreMetadata(profile, store),\n readJson<unknown>(profileStorePath(profile, store)),\n ]);\n return {\n formatVersion: metadata.formatVersion,\n records: Array.isArray(raw) ? raw as T[] : [],\n };\n}\n\n/**\n * Runs a small critical section under the one lock shared by all profile\n * stores (see acquireProfileLock). Lock release verifies its ownership token\n * before removing the exact metadata instance it acquired.\n *\n * Reentrant within one async call chain: a critical section that already\n * holds a profile's lock (for example a login's compare-and-commit) can call\n * store writers that take the same lock without deadlocking. Ownership is\n * keyed by the resolved lock path (so switching state roots inside a lock\n * still takes the other root's lock) and lasts exactly as long as the\n * acquisition: it is revoked before release, so work deferred past the\n * critical section waits for the lock like any other caller.\n */\nexport async function withProfileLock<T>(\n profile: string,\n action: () => Promise<T>,\n options: ProfileLockOptions = {},\n): Promise<T> {\n const normalizedProfile = validateProfileName(profile);\n const lockPath = profileLockPath(normalizedProfile);\n const held = (heldProfileLocks.getStore() ?? []).filter((ownership) => ownership.active);\n if (held.some((ownership) => ownership.lockPath === lockPath)) return action();\n const acquired = await acquireProfileLock(normalizedProfile, options);\n const ownership: HeldProfileLock = {\n lockPath,\n turnSlot: acquired.turnSlot,\n deletedWhileWaiting: acquired.deletedWhileWaiting,\n active: true,\n };\n try {\n return await heldProfileLocks.run([...held, ownership], action);\n } finally {\n ownership.active = false;\n await acquired.release();\n // Taking the lock recreated the deleted profile's directory; remove it\n // again unless something was written into it (rmdir needs it empty).\n if (acquired.deletedWhileWaiting) await rmdir(profilePath(normalizedProfile)).catch(() => undefined);\n }\n}\n\n/**\n * Records, inside a profile deletion's critical section and after its files\n * are gone, that the profile was deleted, with the number of the deleting\n * turn. A store write whose wait overlapped that turn (it arrived before the\n * deletion released the lock, whether before or after this record) then\n * refuses (ProfileDeletedError) instead of recreating a profile with only a\n * session or store in it. The caller must hold the profile's lock.\n */\nexport async function recordProfileDeletion(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership) throw new Error(`Recording the deletion of profile \"${profile}\" requires holding its lock.`);\n await replaceJson(join(profileTurnLockPath(profile), \"deleted.json\"), { slot: ownership.turnSlot }, true);\n}\n\n/**\n * Refuses a write that would recreate a profile deleted while this critical\n * section waited for the lock (ProfileDeletedError). Every writer of profile\n * state other than the profile settings themselves calls this inside its\n * critical section, before writing. The caller must hold the profile's lock.\n */\nexport async function refuseWriteToDeletedProfile(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership?.deletedWhileWaiting) return;\n // Recreated meanwhile (or by this critical section): writing is fine.\n if (await exists(profileConfigPath(profile))) return;\n throw new ProfileDeletedError(profile);\n}\n\n/**\n * Appends a record or replaces the existing record with the supplied explicit\n * key. The extractor is supplied by the owning store so state.ts never needs\n * to know permission-request or delegation record shapes.\n */\nexport async function upsertProfileRecord<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n key: string,\n record: T,\n getKey: (candidate: T) => string | undefined,\n options: ProfileLockOptions = {},\n): Promise<T[]> {\n if (!key) throw new TypeError(\"A non-empty record key is required.\");\n\n return withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n const current = (await readProfileStore<T>(profile, store)).records;\n const next = current.filter((candidate) => getKey(candidate) !== key);\n next.push(record);\n await writeJsonAtomic(profileStorePath(profile, store), next);\n await writeFormatOneMetadata(profile, store);\n return next;\n }, options);\n}\n\n/**\n * Performs a typed read-modify-write of a legacy array store under the one\n * per-profile lock. The payload stays an array and the sibling metadata stays\n * format 1, so existing CLI readers keep their byte/layout contract.\n */\nexport async function updateProfileStore<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n options: ProfileLockOptions = {},\n): Promise<Result> {\n return withProfileLock(\n profile,\n () => updateProfileStoreWhileLocked(profile, store, update),\n options,\n );\n}\n\n/** The caller must already own this profile's lock. */\nasync function updateProfileStoreWhileLocked<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n): Promise<Result> {\n await refuseWriteToDeletedProfile(profile);\n const current = await readProfileStore<T>(profile, store);\n const next = await update(current.records);\n await writeJsonAtomic(profileStorePath(profile, store), next.records);\n await writeFormatOneMetadata(profile, store);\n return next.result;\n}\n\nexport async function writeSession<T extends object>(\n profile: string,\n session: T,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n await readStoreMetadata(profile, \"session\");\n await writeJsonAtomic(sessionPath(profile), session);\n await writeFormatOneMetadata(profile, \"session\");\n }, options);\n}\n\nexport async function removeSession(\n profile: string,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await readStoreMetadata(profile, \"session\");\n await rm(sessionPath(profile), { force: true });\n }, options);\n}\n\nasync function writeFormatOneMetadata(profile: string, store: ProfileStoreName): Promise<void> {\n await writeJsonAtomic(profileStoreMetadataPath(profile, store), { formatVersion: 1 });\n}\n\ninterface AcquiredProfileLock {\n readonly deletedWhileWaiting: boolean;\n readonly turnSlot: number;\n release(): Promise<void>;\n}\n\ninterface LockDeadline {\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly retryMs: number;\n}\n\n/**\n * Takes a profile's lock in two layers:\n *\n * 1. The turn lock (acquireTurn), used by this release and later ones. It\n * decides nothing from elapsed time, so a process paused anywhere, for\n * any length of time, cannot let a second holder in.\n * 2. Holding a turn, the `.lock` directory every older release uses\n * (publishProfileLock), so they keep excluding this release and it them.\n * Only one process of this release at a time acquires, recovers or\n * releases `.lock`.\n *\n * Also reports whether a profile deletion (recordProfileDeletion) ran while\n * this acquisition waited.\n */\nasync function acquireProfileLock(\n profile: string,\n options: ProfileLockOptions,\n): Promise<AcquiredProfileLock> {\n const deadline: LockDeadline = {\n startedAt: Date.now(),\n timeoutMs: options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS,\n retryMs: options.retryMs ?? DEFAULT_LOCK_RETRY_MS,\n };\n const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_LOCK_MS;\n const lockPath = profileLockPath(profile);\n const turnDirectory = profileTurnLockPath(profile);\n\n const directory = profilePath(profile);\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) throw new ProfileDeletedError(profile);\n if (!options.requireProfile) await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n await mkdir(dirname(turnDirectory), { recursive: true, mode: PRIVATE_DIR_MODE });\n // Every store write takes this lock: tighten the tree older releases\n // created 0775 before writing sessions or delegations into it.\n for (const path of [tinycloudHomePath(), profilesPath(), directory]) {\n await chmod(path, PRIVATE_DIR_MODE).catch((error: unknown) => {\n // A profile deletion can remove the profile directory right after the\n // mkdir above; the lock attempt below recreates it 0700.\n if (path !== directory || !isErrno(error, \"ENOENT\")) throw error;\n });\n }\n\n const { turn, firstWaitedTurn } = await acquireTurn(profile, turnDirectory, deadline);\n try {\n // Holding the turn, no deletion runs: a profile present now stays until release.\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) {\n // A deletion that finished while this waited could not remove the\n // directory if a lock was held then; remove it if empty.\n await rmdir(directory).catch(() => undefined);\n throw new ProfileDeletedError(profile);\n }\n // An unreadable deletion record is ignored rather than failing every\n // acquisition; it is written durably, so only damage makes it so.\n const deletion = await readJson<{ slot?: unknown }>(join(turnDirectory, \"deleted.json\")).catch(() => null);\n const deletedWhileWaiting = typeof deletion?.slot === \"number\" && deletion.slot >= firstWaitedTurn;\n while (true) {\n const token = randomUUID();\n if (await publishProfileLock(profile, lockPath, token, options.requireProfile === true)) {\n return {\n deletedWhileWaiting,\n turnSlot: turn.slot,\n release: async () => {\n try {\n await releaseProfileLock(profile, lockPath, token);\n } finally {\n await releaseTurn(profile, turn);\n }\n },\n };\n }\n await signalTestLockContention(profile);\n if (await recoverStaleLock(profile, lockPath, staleAfterMs)) continue;\n await waitOrTimeOut(profile, deadline);\n }\n } catch (error) {\n await releaseTurn(profile, turn);\n throw error;\n }\n}\n\n/** Throws once the acquisition's time is up; `detail` explains a damaged turn lock. */\nfunction checkDeadline(profile: string, deadline: LockDeadline, detail?: string): void {\n if (Date.now() - deadline.startedAt >= deadline.timeoutMs) {\n throw new ProfileLockTimeoutError(profile, deadline.timeoutMs, detail);\n }\n}\n\n/** Sleeps one retry interval, or throws once the acquisition's time is up. */\nasync function waitOrTimeOut(profile: string, deadline: LockDeadline, detail?: string): Promise<void> {\n checkDeadline(profile, deadline, detail);\n await sleep(Math.min(deadline.retryMs, deadline.timeoutMs - (Date.now() - deadline.startedAt)));\n}\n\n/** One granted turn of the turn lock. */\ninterface Turn {\n readonly directory: string;\n readonly slot: number;\n readonly token: string;\n}\n\n/** A turn as recorded on disk. */\ninterface TurnState {\n readonly slot: number;\n readonly token: string;\n readonly pid: number;\n /** The token of the turn before it that its creator observed; null for turn 0. */\n readonly after: string | null;\n readonly held: boolean;\n readonly done: boolean;\n}\n\n/** Turn directory names: decimal turn numbers. */\nconst TURN = /^(?:0|[1-9][0-9]*)$/;\n\n/**\n * Tokens of turns this process published and then gave up (a marker write or\n * a read failed after publication): the positive evidence that lets this\n * process settle a turn of its own PID. A live process's turn that is not in\n * here is never settled by it, so a module instance that cannot see another\n * instance's set (another bundled copy of this package) waits rather than\n * settling a turn that copy still holds.\n *\n * One set per process, not per module instance: the package's entry points\n * (state, index, artifacts, cli-runtime; ESM and CJS) each bundle their own\n * copy of this module, and one process may load several. The key is\n * versioned so that a release changing what the set holds uses a new one.\n */\nconst relinquishedTurns: Set<string> =\n (globalThis as unknown as Record<symbol, Set<string> | undefined>)[Symbol.for(\"tinycloud.operations.relinquishedProfileTurns.v1\")] ??=\n new Set<string>();\n\n/** Marker writes are retried this many times, after these delays (ms), before giving up. */\nconst MARKER_RETRY_DELAYS_MS = [10, 50, 250];\n/** A given-up turn is settled in the background every second for up to five minutes. */\nconst SETTLE_RETRY_MS = 1_000;\nconst SETTLE_RETRIES = 300;\n\n/**\n * The turn lock: mutual exclusion among processes of this release that does\n * not depend on how long any of them is paused. It uses only `mkdir`,\n * `rename`, exclusive file creation, and a check that a holder's PID is gone\n * (as `.lock` recovery always has), so it needs no hard links.\n *\n * Turns are numbered directories in profileTurnLockPath(profile). Turn n has\n * `owner.json` ({ pid, createdAt, token, after }), where `after` is the token\n * of the turn n-1 its creator observed, and gains `<token>.held` when granted\n * and `<token>.done` when over. Markers name the turn's own token, so one\n * written late into a recreated directory of the same number means nothing.\n *\n * - A turn is published by renaming a fully written staging directory to\n * `n`, which fails while `n` exists (rename never replaces a non-empty\n * directory, and turn directories are never empty). The turn directory\n * itself is published the same way, with a granted, finished turn 0.\n * - A process takes turn n only after reading turn n-1 granted and done.\n * Once `n` is published it checks that turn n-1 is still the one it read\n * (same token, granted, done) and only then writes `held`; otherwise the\n * turn is void: it writes `done` alone and starts over.\n * - Turns are removed by renaming them aside: a void turn at any time, a\n * granted one only once no older turn is left and turn n+1 is granted and\n * done. The latest turn is never removed.\n *\n * Why at most one granted turn is ever not done: a removed number can be\n * published again, but turn n-1 is always removed before turn n, so a\n * process whose stale read led it to republish n finds n-1 gone or holding\n * another token, and its turn is void. A process that finds n-1 as it read\n * it published `n` for the first time, so it is the only process granted n,\n * and n-1 was done before. A turn is marked done only by its holder, or by\n * another process once the holder's PID is gone (or by its own process,\n * once it has explicitly given that turn up); a paused holder is alive.\n * A turn is voided only on definite evidence (the turn it follows is gone or\n * holds another token), never because a read failed. Nothing above is\n * decided from elapsed time.\n *\n * Returns the turn and the number of the first turn this acquisition waited\n * on: the latest turn when it first looked if that was not done yet, else\n * the next one.\n */\nasync function acquireTurn(\n profile: string,\n directory: string,\n deadline: LockDeadline,\n): Promise<{ turn: Turn; firstWaitedTurn: number }> {\n let firstWaitedTurn: number | undefined;\n // Why the turn lock looks damaged, as of the last look, for the timeout message.\n let problem: string | undefined;\n const damaged = (what: string) =>\n `The turn lock ${directory} ${what}, so no process can take it. ` +\n `If no tc or MCP process is using profile \"${profile}\", remove that directory.`;\n for (let first = true; ; first = false) {\n if (!first) checkDeadline(profile, deadline, problem);\n problem = undefined;\n const latest = await readLatestTurn(directory);\n if (latest === \"missing\") {\n await createTurnDirectory(directory);\n continue;\n }\n if (latest === \"empty\") {\n // Usually a listing that straddled a turn's publication and an older\n // turn's removal (readdir is not a snapshot); damaged if it persists.\n problem = damaged(\"has no turns\");\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n if (latest === null) continue;\n if (typeof latest === \"number\") {\n problem = damaged(`has an unreadable turn ${latest}`);\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n firstWaitedTurn ??= latest.done ? latest.slot + 1 : latest.slot;\n if (latest.held && latest.done) {\n const turn = await takeTurn(profile, directory, latest);\n if (turn !== null) return { turn, firstWaitedTurn };\n await waitOrTimeOut(profile, deadline);\n } else if (latest.done) {\n problem = damaged(`ends with turn ${latest.slot}, which was never granted`);\n await waitOrTimeOut(profile, deadline, problem);\n } else if (latest.pid === process.pid ? relinquishedTurns.has(latest.token) : !isProcessAlive(latest.pid)) {\n await waitForTestBarrier(TEST_LOCK_TURN_SETTLE_BARRIER_DIR, profile);\n await settleAbandonedTurn(directory, latest);\n relinquishedTurns.delete(latest.token);\n } else {\n await signalTestLockContention(profile);\n await waitOrTimeOut(profile, deadline);\n }\n }\n}\n\n/**\n * The highest-numbered turn: its state, its number if it is damaged, null if\n * it went away while being read.\n */\nasync function readLatestTurn(directory: string): Promise<TurnState | number | \"missing\" | \"empty\" | null> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return \"missing\";\n throw error;\n }\n const slots = names.filter((name) => TURN.test(name)).map(Number);\n if (slots.length === 0) return \"empty\";\n const slot = Math.max(...slots);\n const turn = await readTurn(directory, slot);\n return turn === \"damaged\" ? slot : turn;\n}\n\n/**\n * Turn `slot` as recorded now; null if it is gone; \"damaged\" if its owner\n * record is missing or unreadable (turns are renamed into place and aside\n * whole, with their owner record written durably). Any other read error is\n * thrown: it says nothing about the turn. `done` is read before `held`,\n * which every writer creates first, so a turn read as done is never misread\n * as void.\n */\nasync function readTurn(directory: string, slot: number): Promise<TurnState | \"damaged\" | null> {\n const path = join(directory, String(slot));\n let text: string;\n try {\n text = await readFile(join(path, \"owner.json\"), \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\") && !isErrno(error, \"ENOTDIR\")) throw error;\n return await exists(path) ? \"damaged\" : null;\n }\n let owner: { pid?: unknown; token?: unknown; after?: unknown } | null;\n try {\n owner = JSON.parse(text) as typeof owner;\n } catch {\n return \"damaged\";\n }\n if (owner === null || typeof owner !== \"object\" || typeof owner.token !== \"string\" || typeof owner.pid !== \"number\") {\n return \"damaged\";\n }\n const done = await exists(join(path, `${owner.token}.done`));\n const held = await exists(join(path, `${owner.token}.held`));\n return {\n slot,\n token: owner.token,\n pid: owner.pid,\n after: typeof owner.after === \"string\" ? owner.after : null,\n held,\n done,\n };\n}\n\n/**\n * Whether turn `slot` is still the granted, finished turn with `token`. False\n * only on definite evidence: it is gone, or holds another token. Throws if it\n * cannot be read, or is damaged, so the caller leaves its own turn undecided.\n */\nasync function isFinishedTurn(directory: string, slot: number, token: string): Promise<boolean> {\n const turn = await readTurn(directory, slot);\n if (turn === \"damaged\") throw new Error(`Turn ${slot} of the turn lock ${directory} is unreadable.`);\n return turn !== null && turn.token === token && turn.held && turn.done;\n}\n\n/**\n * Publishes the turn after `latest` and claims it. Null if another process\n * published that number first, or the turn is void. If a step after\n * publication fails, the turn is handed to settleOwnTurn and the error thrown.\n */\nasync function takeTurn(profile: string, directory: string, latest: TurnState): Promise<Turn | null> {\n const token = randomUUID();\n const slot = latest.slot + 1;\n const path = join(directory, String(slot));\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: latest.token };\n let published = false;\n try {\n published = await publishDirectory(\n join(directory, `.stage-${process.pid}-${token}`),\n path,\n { \"owner.json\": `${JSON.stringify(owner, null, 2)}\\n` },\n () => waitForTestBarrier(TEST_LOCK_TURN_PUBLISH_BARRIER_DIR, profile),\n );\n if (published && await isFinishedTurn(directory, latest.slot, latest.token) && await markTurn(path, token, \"held\")) {\n return { directory, slot, token };\n }\n if (published) await markTurn(path, token, \"done\");\n return null;\n } catch (error) {\n if (published) settleOwnTurn(directory, slot, token);\n throw error;\n }\n}\n\n/**\n * Finishes the turn of a process that is gone (or one this process gave up).\n * A turn its creator never got to grant is granted first if the turn before\n * it is still the one its creator read (the check the creator would have\n * made; that turn cannot have been removed, since that needs this turn\n * done), and left void only if it definitely is not.\n */\nasync function settleAbandonedTurn(directory: string, abandoned: TurnState): Promise<void> {\n const path = join(directory, String(abandoned.slot));\n if (!abandoned.held && abandoned.after !== null &&\n await isFinishedTurn(directory, abandoned.slot - 1, abandoned.after)) {\n await markTurn(path, abandoned.token, \"held\");\n }\n await markTurn(path, abandoned.token, \"done\");\n}\n\n/**\n * Settles a turn this process published but could not grant or finish (a\n * marker write or a read failed). Other processes wait on this live PID, so\n * it is retried in the background until it succeeds or the turn is settled\n * otherwise (by this process's next acquisition, or by another process once\n * this one has exited). The timer does not keep the process alive.\n */\nfunction settleOwnTurn(directory: string, slot: number, token: string, retries = SETTLE_RETRIES): void {\n relinquishedTurns.add(token);\n void (async () => {\n try {\n const turn = await readTurn(directory, slot);\n if (turn !== null && turn !== \"damaged\" && turn.token === token && !turn.done) await settleAbandonedTurn(directory, turn);\n relinquishedTurns.delete(token);\n } catch {\n // Still relinquished: this process's next acquisition settles it too.\n if (retries > 0) setTimeout(() => settleOwnTurn(directory, slot, token, retries - 1), SETTLE_RETRY_MS).unref();\n }\n })();\n}\n\n/**\n * Creates `<token>.<kind>` in a turn directory; false if the directory is\n * gone. Other failures (a full disk, a permission error) are retried a few\n * times, then thrown.\n */\nasync function markTurn(path: string, token: string, kind: \"held\" | \"done\"): Promise<boolean> {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(join(path, `${token}.${kind}`), \"\", { mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return true;\n if (isErrno(error, \"ENOENT\")) return false;\n if (attempt >= MARKER_RETRY_DELAYS_MS.length) throw error;\n await sleep(MARKER_RETRY_DELAYS_MS[attempt]!);\n }\n }\n}\n\n/** Creates the turn directory with a granted, finished turn 0, unless another process did. */\nasync function createTurnDirectory(directory: string): Promise<void> {\n const token = randomUUID();\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: null };\n await publishDirectory(join(dirname(directory), `.stage-${basename(directory)}-${process.pid}-${token}`), directory, {\n \"0/owner.json\": `${JSON.stringify(owner, null, 2)}\\n`,\n [`0/${token}.held`]: \"\",\n [`0/${token}.done`]: \"\",\n });\n}\n\n/**\n * Writes `files` (durably, when not empty) into a new staging directory and\n * renames it to `target`. False if `target` already exists (or the turn\n * directory is gone); the caller starts over. Nothing else removes a live\n * process's staging directory (see collectTurns), so `target` never appears\n * incomplete.\n */\nasync function publishDirectory(\n stage: string,\n target: string,\n files: Readonly<Record<string, string>>,\n beforeRename?: () => Promise<void>,\n): Promise<boolean> {\n try {\n for (const [name, contents] of Object.entries(files)) {\n await mkdir(dirname(join(stage, name)), { recursive: true, mode: PRIVATE_DIR_MODE });\n await writeFileDurably(join(stage, name), contents);\n }\n await beforeRename?.();\n await rename(stage, target);\n return true;\n } catch (error) {\n // ENOTEMPTY/EEXIST: `target` exists, though it may be gone again by now.\n // Windows reports an existing target directory as EPERM.\n if ([\"ENOTEMPTY\", \"EEXIST\", \"ENOENT\"].some((code) => isErrno(error, code)) || await exists(target)) return false;\n throw error;\n } finally {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Finishes this process's turn. If `done` cannot be written even after\n * retries, the critical section is still over and its writes stand: the turn\n * is handed to settleOwnTurn rather than failing the caller.\n */\nasync function releaseTurn(profile: string, turn: Turn): Promise<void> {\n try {\n await markTurn(join(turn.directory, String(turn.slot)), turn.token, \"done\");\n } catch {\n settleOwnTurn(turn.directory, turn.slot, turn.token);\n return;\n }\n await collectTurns(profile, turn).catch(() => undefined);\n}\n\n/**\n * Leftovers in a turn directory whose writer is gone: trash (a removed turn\n * renamed aside, garbage from then on), and staging directories and\n * deletion-record temporaries named after their writer's PID.\n */\nfunction isAbandonedTurnEntry(name: string): boolean {\n if (name.startsWith(\".trash-\")) return true;\n const writer = /^\\.(?:stage|deleted\\.json)[-.]([0-9]+)[-.]/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/** A turn directory's staging directory left beside it by a process that is gone. */\nfunction isAbandonedTurnDirectoryStage(name: string): boolean {\n const writer = /^\\.stage-.+-([0-9]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/**\n * Removes the turns before `turn`, which just finished: void turns, and\n * granted ones oldest first, each once no older turn is left and the next is\n * granted and done (see acquireTurn). A turn is renamed aside before it is\n * deleted, so its number is never an empty directory. A turn that is damaged\n * or cannot be read is left alone, and a read error stops the collection.\n * Leftovers of crashed processes go too, judged by PID, never by age:\n * removing a paused process's staging directory could publish an incomplete\n * turn.\n */\nasync function collectTurns(profile: string, turn: Turn): Promise<void> {\n for (const [directory, abandoned] of [\n [turn.directory, isAbandonedTurnEntry],\n [dirname(turn.directory), isAbandonedTurnDirectoryStage],\n ] as const) {\n for (const name of (await readdir(directory)).filter(abandoned)) {\n await rm(join(directory, name), { recursive: true, force: true }).catch(() => undefined);\n }\n }\n const older = (await readdir(turn.directory)).filter((name) => TURN.test(name)).map(Number)\n .filter((slot) => slot < turn.slot)\n .sort((left, right) => left - right);\n for (const slot of older) {\n const candidate = await readTurn(turn.directory, slot);\n if (candidate === null || candidate === \"damaged\" || !candidate.done) continue;\n if (candidate.held) {\n if (await exists(join(turn.directory, String(slot - 1)))) continue;\n const next = await readTurn(turn.directory, slot + 1);\n if (next === null || next === \"damaged\" || !next.held || !next.done) continue;\n }\n await waitForTestBarrier(TEST_LOCK_TURN_COLLECT_BARRIER_DIR, profile);\n const trash = join(turn.directory, `.trash-${randomUUID()}`);\n if (await rename(join(turn.directory, String(slot)), trash).then(() => true, () => false)) {\n await rm(trash, { recursive: true, force: true }).catch(() => undefined);\n }\n }\n}\n\n/**\n * One attempt to take `.lock`, made while holding a turn. Nothing here\n * replaces an existing path:\n *\n * 1. `mkdir(.lock)` (never recursive) is exclusive, and is the primitive\n * older releases use too, so they exclude each other.\n * 2. Ownership is published by `link`ing a fully written owner file (staged\n * beside `.lock`, on the same filesystem) to `.lock/owner.json`. `link`\n * fails with EEXIST if an owner exists, and with ENOENT if the directory\n * was removed meanwhile (an aged ownerless-lock reclaim by an older\n * release). Only a successful link holds the lock; on either failure\n * nothing is released, since nothing was acquired, and the caller retries.\n * On a filesystem without hard links (FAT/exFAT, some SMB mounts) the\n * owner file is created in place with an exclusive create instead, with\n * the same EEXIST/ENOENT outcomes. A reader may then briefly see it\n * incomplete; every release treats an owner file it cannot parse as a\n * held lock, and this release removes one only once it has aged (see\n * isAbandonedOwner).\n *\n * A profile deletion removes the profile directory once it has released its\n * lock, so `mkdir(.lock)` can see ENOENT; the directory is recreated (0700)\n * and the caller retries within its deadline, as for a first write to a new\n * profile.\n *\n * Only one owner.json can exist at the lock path, and it is removed only by\n * its holder's release or by recovery of an abandoned holder, so at most one\n * process holds the lock. Returns false when the lock is not acquired.\n */\nasync function publishProfileLock(profile: string, lockPath: string, token: string, requireProfile: boolean): Promise<boolean> {\n try {\n await mkdir(lockPath, { mode: PRIVATE_DIR_MODE });\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return false;\n if (!isErrno(error, \"ENOENT\")) throw error;\n // With requireProfile only an older release's deletion (which takes no turn) gets here.\n if (requireProfile) throw new ProfileDeletedError(profile);\n await mkdir(profilePath(profile), { recursive: true, mode: PRIVATE_DIR_MODE });\n return false;\n }\n await waitForTestBarrier(TEST_LOCK_PUBLISH_BARRIER_DIR, profile);\n const ownerPath = join(lockPath, \"owner.json\");\n const staged = join(dirname(lockPath), `.lock-owner-${token}.tmp`);\n const owner = `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString(), token }, null, 2)}\\n`;\n try {\n await writeFile(staged, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n try {\n await link(staged, ownerPath);\n } catch (error) {\n if (!lacksHardLinks(error)) throw error;\n await writeFile(ownerPath, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n }\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\") || isErrno(error, \"ENOENT\")) return false;\n // Do not leave an ownerless lock behind for others to wait out. rmdir\n // removes only an empty directory; anyone who created it after ours went\n // away sees ENOENT on link and retries.\n await rmdir(lockPath).catch(() => undefined);\n throw error;\n } finally {\n await rm(staged, { force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Errors `link` reports on a filesystem without hard links: EPERM (Linux\n * FAT/exFAT), ENOTSUP/EOPNOTSUPP (macOS FAT/exFAT, SMB), ENOSYS, EISDIR\n * (libuv's code for Windows' ERROR_INVALID_FUNCTION on FAT32), and EMLINK\n * (too many links), for which the same fallback is just as correct.\n */\nconst NO_HARD_LINK_ERRORS = new Set([\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\", \"EISDIR\", \"EMLINK\"]);\n\nfunction lacksHardLinks(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n NO_HARD_LINK_ERRORS.has(String((error as { code?: unknown }).code));\n}\n\n/**\n * Releases the lock if `.lock/owner.json` is still this acquisition's. No\n * one else can put an owner record there while it exists (owners are only\n * published into a directory their own `mkdir` created, and recovery\n * removes only an abandoned holder's record), so the record read is the one\n * unlinked.\n */\nasync function releaseProfileLock(profile: string, lockPath: string, token: string): Promise<void> {\n const ownerPath = join(lockPath, \"owner.json\");\n const owner = await readJson<{ token?: unknown }>(ownerPath).catch(() => null);\n if (owner?.token !== token) return;\n await rm(ownerPath, { force: true });\n // `.lock` is empty from here until the rmdir; a contender that removes it\n // and creates its own meanwhile is not harmed: rmdir fails on its owner\n // file, or the contender's link sees ENOENT and retries. If a recoverer's\n // claim file is still inside, rmdir fails and that recoverer removes the\n // directory when it drops its claim.\n await waitForTestBarrier(TEST_LOCK_RELEASE_BARRIER_DIR, profile);\n await rmdir(lockPath).catch(() => undefined);\n}\n\n/**\n * Gives process-level contention tests an event-driven witness that a second\n * writer has reached an already-held lock. This deliberately has no effect\n * outside an explicit test environment, and only creates a new signal file\n * beneath TC_HOME; it never changes lock acquisition or release semantics.\n */\nasync function signalTestLockContention(profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n\n const configuredPath = process.env[TEST_LOCK_CONTENTION_SIGNAL_PATH];\n const configuredHome = process.env.TC_HOME;\n if (!configuredPath || !configuredHome) return;\n\n const home = resolve(configuredHome);\n const signalPath = resolve(configuredPath);\n const pathFromHome = relative(home, signalPath);\n if (\n pathFromHome === \"\" ||\n pathFromHome === \"..\" ||\n pathFromHome.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) ||\n pathFromHome.startsWith(\"../\") ||\n pathFromHome.startsWith(\"..\\\\\")\n ) {\n return;\n }\n\n await writeFile(signalPath, `${profile}\\n`, { encoding: \"utf8\", flag: \"wx\" })\n .catch(() => undefined);\n}\n\n/**\n * Reclaims a `.lock` with no owner record, while holding a turn. A\n * `.recover-*` claim may contain a live legacy owner's record moved by a\n * no-hard-links recoverer just before it crashed. Restore that record first;\n * only orphaned claims holding dead or malformed records can be removed.\n * Otherwise the directory must be older than the stale threshold: one left\n * by a crash, or by an older release, whose `.stale-*` / `.release-*` claim\n * files are removed too. owner.json is never unlinked, and the directory\n * itself is only `rmdir`ed, which succeeds only while it is empty.\n *\n * Holding a turn, no other process of this release reclaims concurrently.\n * That closes the race in which two reclaimers' age checks let the later one\n * remove a directory a 1.0.0-beta.16-or-older release had just created,\n * which holds the lock from its `mkdir`. That race remains only if a\n * 1.0.0-beta.17 … 1.0.1-beta.4 release reclaims at the same moment, or the\n * older process stays paused between its `mkdir` and its owner write for\n * longer than the stale threshold; recoveryFenced bounds how stale this\n * process's age check can be.\n */\nasync function recoverOwnerlessLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n let aged: boolean;\n try {\n const { mtimeMs } = await stat(lockPath);\n aged = Date.now() - mtimeMs >= staleAfterMs;\n } catch {\n return false;\n }\n const checkedAt = performance.now();\n await waitForTestBarrier(TEST_LOCK_OWNERLESS_BARRIER_DIR, profile);\n try {\n const entries = await readdir(lockPath);\n if (entries.includes(\"owner.json\")) return false;\n const onlyOrphanedClaims = entries.length > 0 && entries.every((entry) => RECOVERY_CLAIM.test(entry));\n if (!onlyOrphanedClaims && (!aged || recoveryFenced(checkedAt, staleAfterMs))) return false;\n for (const name of entries.filter((entry) => RECOVERY_CLAIM.test(entry))) {\n const claimPath = join(lockPath, name);\n if (await hasLiveRecoveryOwner(claimPath)) {\n // The claim keeps the directory in place. Only the original mkdir\n // owner could publish owner.json here; never overwrite that record.\n if (!await exists(join(lockPath, \"owner.json\"))) await rename(claimPath, join(lockPath, \"owner.json\"));\n return false;\n }\n await rm(claimPath, { force: true });\n }\n for (const name of entries.filter((entry) => ABANDONED_CLAIM.test(entry))) {\n await rm(join(lockPath, name), { force: true });\n }\n await rmdir(lockPath);\n } catch {\n return false;\n }\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/** A no-hard-links claim may contain a live owner's record moved before a crash. */\nasync function hasLiveRecoveryOwner(claimPath: string): Promise<boolean> {\n let contents: string;\n try {\n contents = await readFile(claimPath, \"utf8\");\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return false;\n throw error; // An I/O failure is not evidence that the holder is gone.\n }\n let owner: unknown;\n try {\n owner = JSON.parse(contents);\n } catch {\n return false;\n }\n const pid = typeof owner === \"object\" && owner !== null && \"pid\" in owner ? owner.pid : null;\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && isProcessAlive(pid);\n}\n\n/**\n * Whether an ownerless-reclaim decision made at `since` (a monotonic\n * timestamp) is too old to act on. The age check is only good for a while:\n * past half the stale threshold the reclaim starts over.\n */\nfunction recoveryFenced(since: number, staleAfterMs: number): boolean {\n return performance.now() - since >= staleAfterMs / 2;\n}\n\n/** Claim files of older releases' stale recovery and (up to 1.0.0-beta.16) release. */\nconst ABANDONED_CLAIM = /^\\.(?:release|stale)-[0-9a-f-]+\\.json$/;\n/**\n * Claim files of this release's stale recovery. Releases up to 1.0.1-beta.4\n * never remove them, which is what makes this recovery safe against them; a\n * recoverer that crashes leaves one that only a release with the turn lock\n * clears (see REFERENCE.md, \"Profile lock\").\n */\nconst RECOVERY_CLAIM = /^\\.recover-[0-9a-f-]+\\.json$/;\n/** Owner files staged by publishProfileLock beside `.lock`. */\nconst STAGED_OWNER = /^\\.lock-owner-[0-9a-f-]+\\.tmp$/;\n/**\n * Removes owner files a crashed acquirer staged beside `.lock`. A live\n * acquirer's staged file exists only for its write and link, so only files\n * older than the stale threshold are removed. Runs after a recovery, never\n * on the uncontended path.\n */\nasync function removeAgedOwnerFiles(lockPath: string, staleAfterMs: number): Promise<void> {\n const directory = dirname(lockPath);\n const names = await readdir(directory).catch(() => []);\n for (const name of names.filter((entry) => STAGED_OWNER.test(entry))) {\n const path = join(directory, name);\n const aged = await stat(path).then(({ mtimeMs }) => Date.now() - mtimeMs >= staleAfterMs, () => false);\n if (aged) await rm(path, { force: true }).catch(() => undefined);\n }\n}\n\n\n/**\n * Removes an abandoned owner record (see isAbandonedOwner) and its `.lock`,\n * while holding a turn, so no other process of this release recovers,\n * reclaims or acquires `.lock` meanwhile.\n *\n * The record is claimed first: hard-linked to `.recover-<uuid>.json`, and the\n * claim compared with the exact bytes read. A record that replaced the\n * observed one is left in place. While the claim is inside `.lock`, the\n * directory cannot be removed and recreated: older releases never remove a\n * `.recover-*` claim (they clean up only their own claim names), and other\n * processes of this release are kept out by the turn lock. So no other owner\n * record can appear in it, and the unlink of owner.json can only remove the\n * claimed, dead record. A live record is never unlinked or moved. `.lock`\n * itself is removed only after this process's claim is unlinked from it,\n * which proves it is still the dead holder's directory; if the claim cannot\n * be made, `.lock` is left alone (it may be a directory a 1.0.0-beta.16-or-\n * older writer just created, which it holds from that `mkdir`). No step\n * depends on how long this process takes.\n *\n * Without hard links (where 1.0.0-beta.17 … 1.0.1-beta.4 cannot run at all),\n * the record is renamed into the claim instead, and put back if it is not\n * the observed one: one a 1.0.0-beta.16-or-older process published after\n * recovering the same lock at the same moment. The claim keeps `.lock` held\n * meanwhile, so no second writer gets in, but if that holder releases\n * between the two renames, the put-back restores a released record, and\n * `.lock` stays held until that PID is gone and the record is 30 s old.\n */\nasync function recoverStaleLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n const ownerPath = join(lockPath, \"owner.json\");\n const observed = await readFile(ownerPath, \"utf8\").catch(() => null);\n if (observed === null) return recoverOwnerlessLock(profile, lockPath, staleAfterMs);\n if (!await isAbandonedOwner(observed, ownerPath, staleAfterMs)) return false;\n\n await waitForTestBarrier(TEST_LOCK_RECOVERY_BARRIER_DIR, profile);\n const claimPath = join(lockPath, `.recover-${randomUUID()}.json`);\n let moved = false;\n try {\n await link(ownerPath, claimPath);\n } catch (error) {\n // Gone or replaced already (another release recovered it): leave `.lock`.\n if (!lacksHardLinks(error)) return false;\n try {\n await rename(ownerPath, claimPath);\n moved = true;\n } catch {\n return false;\n }\n }\n if (moved) await waitForTestBarrier(TEST_LOCK_MOVED_BARRIER_DIR, profile);\n const sameInstance = await readFile(claimPath, \"utf8\").then((claimed) => claimed === observed, () => false);\n await waitForTestBarrier(TEST_LOCK_VERIFIED_BARRIER_DIR, profile);\n if (!sameInstance) {\n if (moved) {\n // No other owner.json can have appeared meanwhile: only a process\n // whose mkdir created this `.lock` publishes one, and it already has.\n await rename(claimPath, ownerPath).catch(() => undefined);\n } else {\n await unlink(claimPath).catch(() => undefined);\n }\n return false;\n }\n if (!moved) await rm(ownerPath, { force: true });\n await waitForTestBarrier(TEST_LOCK_CLAIM_BARRIER_DIR, profile);\n await waitForTestBarrier(TEST_LOCK_CLAIMED_BARRIER_DIR, profile);\n // Drop any claim a crashed recoverer of this release left, then this one.\n for (const name of (await readdir(lockPath).catch(() => [])).filter((entry) => RECOVERY_CLAIM.test(entry))) {\n if (join(lockPath, name) !== claimPath) await rm(join(lockPath, name), { force: true });\n }\n // Empty now, and still the dead holder's directory if this claim was in\n // it: remove it rather than leave an ownerless lock to age out.\n if (await unlink(claimPath).then(() => true, () => false)) await rmdir(lockPath).catch(() => undefined);\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/**\n * Whether an owner record (its exact bytes, read from `ownerPath`) is\n * abandoned: a holder's whose PID is gone, older than the stale threshold;\n * or, if it is not a complete record, a file older than that threshold.\n * Every release publishes complete records (by link or rename) except this\n * one's no-hard-link fallback, which writes in place while holding a turn;\n * so an incomplete record seen while holding a turn was left by a crash.\n */\nasync function isAbandonedOwner(observed: string, ownerPath: string, staleAfterMs: number): Promise<boolean> {\n let owner: unknown;\n try {\n owner = JSON.parse(observed);\n } catch {\n owner = null;\n }\n if (typeof owner === \"object\" && owner !== null && \"pid\" in owner) {\n return isStaleOwner(owner as { pid?: unknown; createdAt?: unknown }, staleAfterMs);\n }\n const modifiedAt = await stat(ownerPath).then(({ mtimeMs }) => mtimeMs, () => Number.NaN);\n return Date.now() - modifiedAt >= staleAfterMs;\n}\n\n/** Test-only rendezvous (NODE_ENV=test and the named barrier directory set). */\nasync function waitForTestBarrier(environmentName: string, profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n const barrierDirectory = process.env[environmentName];\n if (!barrierDirectory) return;\n await mkdir(barrierDirectory, { recursive: true });\n const readyPath = join(barrierDirectory, `ready-${process.pid}-${profile}`);\n await writeFile(readyPath, \"ready\\n\", { encoding: \"utf8\", flag: \"wx\" }).catch(() => undefined);\n const releasePath = join(barrierDirectory, \"release\");\n while (true) {\n try {\n await readFile(releasePath, \"utf8\");\n return;\n } catch {\n await sleep(1);\n }\n }\n}\n\nfunction isStaleOwner(\n owner: { pid?: unknown; createdAt?: unknown } | null,\n staleAfterMs: number,\n): boolean {\n const now = Date.now();\n const createdAt = typeof owner?.createdAt === \"string\"\n ? Date.parse(owner.createdAt)\n : Number.NaN;\n\n // Reclaim only a fully published lock whose owner PID is confirmed dead.\n // A lock without an owner record is handled by recoverOwnerlessLock: a\n // process holds the lock only once its owner.json is linked in.\n if (!Number.isFinite(createdAt) || now - createdAt < staleAfterMs) return false;\n if (typeof owner?.pid !== \"number\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n return false;\n }\n return !isProcessAlive(owner.pid);\n}\n\n/** Whether `path` exists. Only ENOENT/ENOTDIR mean it does not; other errors are thrown. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, \"ENOENT\") || isErrno(error, \"ENOTDIR\")) return false;\n throw error;\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return !isErrno(error, \"ESRCH\");\n }\n}\n\nfunction validateProfileName(profile: string): string {\n if (\n !profile ||\n profile === \".\" ||\n profile === \"..\" ||\n profile.includes(\"/\") ||\n profile.includes(\"\\\\\") ||\n profile.includes(\"\\0\")\n ) {\n throw new TypeError(\"Profile names must be non-empty path segments.\");\n }\n return profile;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n (error as { code?: unknown }).code === code;\n}\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nexport { DEFAULT_PROFILE };\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/sdk-core\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n evaluateOperationAuthority,\n evaluateAuthority,\n} from \"./authority.js\";\nimport type { OperationSpaceResolver } from \"./authority.js\";\nimport type {\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\nimport { readAuthRequests, updateProfileStore } from \"./state.js\";\n\nexport { evaluateAuthority } from \"./authority.js\";\n\nconst THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1_000;\n\n/** The shared wire schema for SDK PermissionEntry values, including signed ReCap caveats. */\nexport const PermissionEntrySchema = z.object({\n service: z.string().min(1),\n space: z.string().min(1).optional(),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n caveats: z.array(z.record(z.unknown())).optional(),\n skipPrefix: z.boolean().optional(),\n expiry: z.string().min(1).optional(),\n description: z.string().optional(),\n}).strict();\n\nconst CommandSchema = z.object({\n argv: z.array(z.string()).min(1),\n cwd: z.string().min(1),\n}).strict();\n\nconst LegacyPermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string(),\n sessionDid: z.string().min(1),\n requested: z.array(PermissionEntrySchema),\n requestedExpiry: z.union([z.string(), z.number().finite()]).optional(),\n}).strict();\n\nconst PortableDelegationSchema: z.ZodType<Record<string, unknown>> = z.lazy(() => z.object({\n cid: z.string().min(1),\n spaceId: z.string().min(1),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n delegateDID: z.string().min(1),\n ownerAddress: z.string().min(1),\n chainId: z.number().int().positive(),\n expiry: z.union([z.string().datetime({ offset: true }), z.date()]),\n delegationHeader: z.object({ Authorization: z.string().min(1) }).strict(),\n host: z.string().min(1).optional(),\n disableSubDelegation: z.boolean().optional(),\n publicDelegation: PortableDelegationSchema.optional(),\n resources: z.array(PermissionEntrySchema).optional(),\n}).passthrough());\n\n/** Canonical wire-format v1 request retained for CLI and OpenKey compatibility. */\nexport const PermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string().min(1), z.number().finite()]).optional(),\n requested: z.array(PermissionEntrySchema),\n command: CommandSchema.optional(),\n}).strict();\n\n/** Canonical structured v1 delegation import accepted by the auth operation. */\nexport const DelegationImportArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.delegation\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n delegationCid: z.string().min(1).optional(),\n delegation: PortableDelegationSchema,\n // This field is presentation metadata only. A later import operation obtains\n // effective permissions from validated, installed delegation authority.\n permissions: z.array(PermissionEntrySchema).optional(),\n expiry: z.string().datetime({ offset: true }).optional(),\n prompted: z.boolean().optional(),\n}).strict();\n\n/**\n * The stored request an imported delegation was checked against, persisted\n * with the delegation. Its fields are exactly the request artifact's, so\n * replay accepts every binding import can write.\n */\nexport const DelegationRequestBindingSchema = PermissionRequestArtifactSchema\n .pick({ requestId: true, requested: true })\n .strict();\nexport type DelegationRequestBinding = z.infer<typeof DelegationRequestBindingSchema>;\n\nexport type PermissionRequestArtifact = z.infer<typeof PermissionRequestArtifactSchema>;\nexport type DelegationImportArtifact = z.infer<typeof DelegationImportArtifactSchema>;\n/** The minimal public node-sdk request shape accepted by the legacy reader. */\nexport type LegacyPermissionRequestArtifact = z.infer<typeof LegacyPermissionRequestArtifactSchema>;\nexport type ArtifactClock = () => Date;\nexport type RequestIdSource = () => string;\n\n/** Invocation-owned values used to safely complete a legacy request record. */\nexport interface LegacyRequestContext {\n readonly profile: string;\n readonly host: string;\n readonly sessionDid: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly now?: Date;\n}\n\nexport interface PermissionRequestIdentityInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly host: string;\n readonly missing: readonly PermissionEntry[];\n}\n\nexport interface BuildPermissionRequestArtifactInput extends PermissionRequestIdentityInput {\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly requestedExpiry?: string | number;\n readonly command?: { readonly argv: readonly string[]; readonly cwd: string };\n readonly now?: ArtifactClock;\n readonly createRequestId?: RequestIdSource;\n}\n\nexport interface CreateOrReusePermissionRequestInput extends BuildPermissionRequestArtifactInput {\n readonly granted: readonly PermissionEntry[];\n /** Owner-aware identity resolver used by registered operation callers. */\n readonly resolveSpace?: OperationSpaceResolver;\n readonly replace?: boolean;\n}\n\nexport type PermissionRequestResolution =\n | Readonly<{ status: \"satisfied\"; reused: false }>\n | Readonly<{ status: \"created\"; reused: boolean; request: PermissionRequestArtifact }>;\n\n/** Parses a request artifact without accepting a newer wire format as v1. */\nexport function validatePermissionRequestArtifact(value: unknown): PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.parse(value);\n}\n\n/** Parses a structured active-session import artifact without accepting a newer wire format as v1. */\nexport function validateDelegationImportArtifact(value: unknown): DelegationImportArtifact {\n return DelegationImportArtifactSchema.parse(value);\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.safeParse(value).success;\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n return DelegationImportArtifactSchema.safeParse(value).success;\n}\n\nfunction normalizeLegacyPermissionRequest(\n value: LegacyPermissionRequestArtifact,\n context: LegacyRequestContext,\n): PermissionRequestArtifact {\n if (principal(value.sessionDid) !== principal(context.sessionDid)) {\n throw new TypeError(\"Stored authority request belongs to a different session.\");\n }\n const createdAt = context.now ?? new Date();\n if (Number.isNaN(createdAt.getTime())) {\n throw new TypeError(\"The legacy authority request has no usable creation time.\");\n }\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: value.requestId,\n createdAt: createdAt.toISOString(),\n profile: context.profile,\n posture: context.posture,\n operatorType: context.operatorType,\n host: context.host,\n sessionDid: context.sessionDid,\n ...(context.ownerDid === undefined ? {} : { ownerDid: context.ownerDid }),\n ...(context.spaceId === undefined ? {} : { spaceId: context.spaceId }),\n ...(value.requestedExpiry === undefined ? {} : { requestedExpiry: value.requestedExpiry }),\n requested: canonicalizeCapabilities(value.requested),\n } as PermissionRequestArtifact;\n}\n\nfunction principal(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\n/**\n * Stable exact identity used only for request reuse. It binds a request to its\n * selected profile, active session DID, host, and canonical missing subset.\n */\nexport function createPermissionRequestIdentity(input: PermissionRequestIdentityInput): string {\n return JSON.stringify({\n profile: input.profile,\n sessionDid: input.sessionDid,\n host: input.host,\n missing: canonicalizeCapabilities(input.missing),\n });\n}\n\n/** Builds an on-disk-compatible v1 record. Omitted values stay omitted. */\nexport function buildPermissionRequestArtifact(\n input: BuildPermissionRequestArtifactInput,\n): PermissionRequestArtifact {\n const now = input.now ?? (() => new Date());\n const createdAt = now();\n if (Number.isNaN(createdAt.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n const requested = canonicalizeCapabilities(input.missing);\n if (requested.length === 0) throw new TypeError(\"Permission requests require at least one missing capability.\");\n\n return validatePermissionRequestArtifact({\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: input.createRequestId?.() ?? defaultRequestId(createdAt),\n createdAt: createdAt.toISOString(),\n profile: input.profile,\n posture: input.posture,\n operatorType: input.operatorType,\n host: input.host,\n sessionDid: input.sessionDid,\n ...(input.ownerDid !== undefined ? { ownerDid: input.ownerDid } : {}),\n ...(input.spaceId !== undefined ? { spaceId: input.spaceId } : {}),\n ...(input.requestedExpiry !== undefined ? { requestedExpiry: input.requestedExpiry } : {}),\n requested,\n ...(input.command !== undefined\n ? { command: { argv: [...input.command.argv], cwd: input.command.cwd } }\n : {}),\n });\n}\n\n/** Reads only valid canonical v1 records and refuses malformed stored artifacts. */\nexport async function listPermissionRequests(\n profile: string,\n context?: LegacyRequestContext,\n): Promise<PermissionRequestArtifact[]> {\n const records: PermissionRequestArtifact[] = [];\n for (const value of await readAuthRequests<unknown>(profile)) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (context !== undefined && principal(canonical.data.sessionDid) !== principal(context.sessionDid)) {\n continue;\n }\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (context === undefined) {\n throw new TypeError(\"Legacy authority requests require the selected invocation context.\");\n }\n if (principal(legacy.data.sessionDid) !== principal(context.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, context));\n }\n return records;\n}\n\nexport async function findPermissionRequest(\n profile: string,\n requestId: string,\n identity: Pick<PermissionRequestIdentityInput, \"sessionDid\" | \"host\"> &\n Partial<Omit<LegacyRequestContext, \"profile\" | \"host\" | \"sessionDid\">>,\n): Promise<PermissionRequestArtifact | null> {\n const records = await listPermissionRequests(profile, {\n profile,\n host: identity.host,\n sessionDid: identity.sessionDid,\n posture: identity.posture ?? \"delegate-session\",\n operatorType: identity.operatorType ?? \"human\",\n ...(identity.ownerDid === undefined ? {} : { ownerDid: identity.ownerDid }),\n ...(identity.spaceId === undefined ? {} : { spaceId: identity.spaceId }),\n });\n return records.find((record) =>\n record.requestId === requestId &&\n record.sessionDid === identity.sessionDid &&\n record.host === identity.host,\n ) ?? null;\n}\n\n/**\n * Atomically returns the newest identical unresolved request, or writes a new\n * v1 record. Retention, stale-session pruning, covered-record pruning, and\n * partial-grant supersession all happen in the same existing profile lock.\n */\nexport async function createOrReusePermissionRequest(\n input: CreateOrReusePermissionRequestInput,\n): Promise<PermissionRequestResolution> {\n // Registered operations already computed this exact missing set during\n // canonical preflight. Do not recompute it with the legacy global matcher:\n // that matcher intentionally treats same-named short/full spaces as equal.\n const missing = input.resolveSpace === undefined\n ? evaluateAuthority(input.granted, input.missing).missing\n : canonicalizeCapabilities(input.missing);\n const now = input.now ?? (() => new Date());\n const observedNow = now();\n if (Number.isNaN(observedNow.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n\n return updateProfileStore<unknown, PermissionRequestResolution>(\n input.profile,\n \"auth-requests\",\n (rawRecords) => {\n const records: PermissionRequestArtifact[] = [];\n for (const value of rawRecords) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (principal(canonical.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (principal(legacy.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, {\n profile: input.profile,\n host: input.host,\n sessionDid: input.sessionDid,\n posture: input.posture,\n operatorType: input.operatorType,\n ...(input.ownerDid === undefined ? {} : { ownerDid: input.ownerDid }),\n ...(input.spaceId === undefined ? {} : { spaceId: input.spaceId }),\n now: observedNow,\n }));\n }\n const retained = prunePermissionRequests(records, {\n profile: input.profile,\n sessionDid: input.sessionDid,\n granted: input.granted,\n resolveSpace: input.resolveSpace,\n now: observedNow,\n });\n\n if (missing.length === 0) {\n return { records: retained, result: { status: \"satisfied\", reused: false } };\n }\n\n const identity = createPermissionRequestIdentity({ ...input, missing });\n const withoutSuperseded = retained.filter((record) => !isSupersededBy(record, input, missing));\n const equivalent = newestEquivalentRequest(withoutSuperseded, identity);\n if (equivalent !== undefined && input.replace !== true) {\n return { records: withoutSuperseded, result: { status: \"created\", reused: true, request: equivalent } };\n }\n\n const next = withoutSuperseded.filter((record) =>\n input.replace !== true || permissionRequestArtifactIdentity(record) !== identity,\n );\n const request = buildPermissionRequestArtifact({ ...input, missing, now: () => observedNow });\n return {\n records: [...next, request],\n result: { status: \"created\", reused: false, request },\n };\n },\n );\n}\n\nexport interface PrunePermissionRequestsInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly granted: readonly PermissionEntry[];\n readonly resolveSpace?: OperationSpaceResolver;\n readonly now: Date;\n}\n\n/** Pure retention policy used by the locked persistence operation. */\nexport function prunePermissionRequests(\n records: readonly PermissionRequestArtifact[],\n input: PrunePermissionRequestsInput,\n): PermissionRequestArtifact[] {\n const cutoff = input.now.getTime() - THIRTY_DAYS_MS;\n return records.filter((record) => {\n const createdAt = Date.parse(record.createdAt);\n if (!Number.isFinite(createdAt) || createdAt < cutoff) return false;\n if (record.profile === input.profile && principal(record.sessionDid) !== principal(input.sessionDid)) return false;\n // Empty request arrays are historical CLI records. They carry no\n // authority, but remain readable and are retained byte-for-byte by the\n // shared format-1 writer for compatibility.\n if (record.requested.length === 0) return true;\n return !evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).satisfied;\n });\n}\n\nfunction newestEquivalentRequest(\n records: readonly PermissionRequestArtifact[],\n identity: string,\n): PermissionRequestArtifact | undefined {\n let newest: PermissionRequestArtifact | undefined;\n for (const record of records) {\n if (permissionRequestArtifactIdentity(record) !== identity) continue;\n if (newest === undefined || record.createdAt >= newest.createdAt) newest = record;\n }\n return newest;\n}\n\nfunction isSupersededBy(\n record: PermissionRequestArtifact,\n input: CreateOrReusePermissionRequestInput,\n missing: readonly PermissionEntry[],\n): boolean {\n if (\n record.profile !== input.profile ||\n record.sessionDid !== input.sessionDid ||\n record.host !== input.host\n ) {\n return false;\n }\n const remaining = evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).missing;\n return remaining.length > 0 &&\n permissionRequestArtifactIdentity(record) !==\n createPermissionRequestIdentity({ ...input, missing }) &&\n createPermissionRequestIdentity({ ...input, missing: remaining }) ===\n createPermissionRequestIdentity({ ...input, missing });\n}\n\nfunction permissionRequestArtifactIdentity(record: PermissionRequestArtifact): string {\n return createPermissionRequestIdentity({\n profile: record.profile,\n sessionDid: record.sessionDid,\n host: record.host,\n missing: record.requested,\n });\n}\n\nfunction evaluateArtifactAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n) {\n return resolveSpace === undefined\n ? evaluateAuthority(granted, required)\n : evaluateOperationAuthority(granted, required, resolveSpace);\n}\n\nfunction defaultRequestId(now: Date): string {\n return `req_${now.getTime().toString(36)}_${randomUUID().replace(/-/g, \"\")}`;\n}\n","// Namespace-shaped so modules that bundle this one stay compatible with\n// lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\n\nimport { OperationInvocationError, operationError } from \"./errors.js\";\n\nconst DEFAULT_SECRETS_SPACE = \"secrets\";\nconst SECRET_MANAGER_BASE_URL = \"https://secrets.tinycloud.xyz\";\nconst SECRET_NAME_RE = /^[A-Z][A-Z0-9_]*$/;\nconst RESERVED_SECRET_SCOPES = new Set([\"default\", \"global\"]);\n\nexport interface SecretsGetInput {\n readonly name: string;\n readonly scope?: string;\n readonly space?: string;\n}\n\nexport interface SecretReference {\n readonly name: string;\n readonly scope?: string;\n readonly space: string;\n readonly vaultKey: string;\n readonly permissionPath: string;\n}\n\nexport function normalizeSecretsGetInput(\n input: SecretsGetInput,\n): SecretsGetInput {\n const reference = resolveSecretReference(input);\n return {\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n // Omission is meaningful: the CLI's default is the literal `secrets`\n // space, while an explicitly supplied short name is resolved later against\n // the authenticated identity.\n ...(input.space === undefined ? {} : { space: reference.space }),\n };\n}\n\n/** Resolves the one canonical backing key/path used by planning and setup. */\nexport function resolveSecretReference(\n input: SecretsGetInput,\n): SecretReference {\n const name = input.name.trim();\n if (!SECRET_NAME_RE.test(name)) {\n throw invalidSecretInput();\n }\n\n const scope = canonicalizeSecretScope(input.scope);\n const space = normalizeSecretsSpace(input.space);\n const vaultKey = scope === undefined\n ? `secrets/${name}`\n : `secrets/scoped/${scope}/${name}`;\n\n return {\n name,\n ...(scope === undefined ? {} : { scope }),\n space,\n vaultKey,\n permissionPath: `vault/${vaultKey}`,\n };\n}\n\n/**\n * Resolve the operation's space against the authenticated identity. The\n * public short-name contract remains `secrets`, while an authenticated\n * operation uses its owner-exact URI for the actual read boundary.\n */\nexport function resolveSecretReferenceForOperation(\n input: SecretsGetInput,\n node: unknown,\n ownerSpace?: string,\n): SecretReference {\n const reference = resolveSecretReference(input);\n if (input.space === undefined && ownerSpace === undefined) return reference;\n return {\n ...reference,\n space: resolveOperationSpace(reference.space, node, ownerSpace),\n };\n}\n\n/** Creates the one owner-aware resolver shared by operation matching paths. */\nexport function operationSpaceResolver(\n node: unknown,\n ownerSpace?: string,\n): (space: string) => string {\n return (space) => resolveOperationSpace(space, node, ownerSpace);\n}\n\nfunction resolveOperationSpace(space: string, node: unknown, ownerSpace?: string): string {\n if (space.startsWith(\"tinycloud:\")) return canonicalizeSpaceUri(space);\n\n const ownerSpaceId = ownerSpace === undefined ? undefined : ownedSpaceForName(ownerSpace, space);\n if (ownerSpaceId !== undefined) return canonicalizeSpaceUri(ownerSpaceId);\n\n const candidate = node as {\n resolveOwnedSpace?: (spaceName: string) => unknown;\n spaceId?: unknown;\n address?: unknown;\n did?: unknown;\n };\n try {\n const resolved = candidate.resolveOwnedSpace?.(space);\n if (typeof resolved === \"string\" && resolved.length > 0) {\n return canonicalizeSpaceUri(resolved);\n }\n } catch {\n // Continue to the identity-derived resolver below.\n }\n\n // A restored delegate session carries the owner's primary space even though\n // node.did is the delegate/session principal. This is the same owner\n // identity used by the CLI space resolver.\n if (typeof candidate.spaceId === \"string\") {\n const resolved = ownedSpaceForName(candidate.spaceId, space);\n if (resolved !== undefined) return canonicalizeSpaceUri(resolved);\n }\n\n const did = typeof candidate.did === \"string\" ? candidate.did : undefined;\n const pkh = did === undefined ? null : nodeSdk.parsePkhDid(did);\n if (pkh === null) {\n throw invalidSecretInput();\n }\n return nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, space);\n}\n\nfunction ownedSpaceForName(ownerSpace: string, name: string): string | undefined {\n const parsed = nodeSdk.parseSpaceUri(ownerSpace);\n if (parsed === null) return undefined;\n try {\n const pkh = nodeSdk.parsePkhDid(parsed.owner);\n return pkh === null ? undefined : nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, name);\n } catch {\n return undefined;\n }\n}\n\nfunction canonicalizeSpaceUri(space: string): string {\n const parts = space.split(\":\");\n const name = parts.at(-1);\n if (parts.length < 3 || name === undefined || name === \"\") {\n throw invalidSecretInput();\n }\n // EIP-155 address casing is interchangeable only in the repository's\n // anchored PKH space form. Other TinyCloud space/DID syntaxes are opaque\n // method-specific identifiers and must remain byte-for-byte unchanged.\n const pkh = space.match(\n /^tinycloud:pkh:eip155:(\\d+):(0x[0-9a-fA-F]{40}):([^:]+)$/,\n );\n if (pkh !== null) {\n return `tinycloud:pkh:eip155:${pkh[1]}:${nodeSdk.canonicalizeAddress(pkh[2]!).toLowerCase()}:${pkh[3]}`;\n }\n return space;\n}\n\n/**\n * Builds a setup action URL without ever accepting a secret value. It opens\n * Secret Manager's app with the secret's name (and scope) filled in.\n */\nexport function buildSecretSetupUrl(reference: SecretReference): string {\n const parameters = [\n [\"secret\", reference.name],\n ...(reference.scope === undefined ? [] : [[\"scope\", reference.scope] as const]),\n [\"space\", reference.space],\n ] as const;\n const query = parameters\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return `${SECRET_MANAGER_BASE_URL}/app?${query}`;\n}\n\nfunction canonicalizeSecretScope(scope: string | undefined): string | undefined {\n if (scope === undefined || scope === \"\") return undefined;\n\n const trimmed = scope.trim();\n if (trimmed === \"\") throw invalidSecretInput();\n\n const canonical = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n if (canonical === \"\" || RESERVED_SECRET_SCOPES.has(canonical)) {\n throw invalidSecretInput();\n }\n return canonical;\n}\n\nfunction normalizeSecretsSpace(space: string | undefined): string {\n if (space === undefined || space === \"\") return DEFAULT_SECRETS_SPACE;\n\n if (space.startsWith(\"tinycloud:\")) {\n const parts = space.split(\":\");\n if (parts.length < 3 || parts.at(-1) === undefined || parts.at(-1) === \"\") {\n throw invalidSecretInput();\n }\n return `tinycloud:${parts.slice(1, -1).join(\":\")}:${parts.at(-1)}`;\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(space)) throw invalidSecretInput();\n return space;\n}\n\nfunction invalidSecretInput(): OperationInvocationError {\n return new OperationInvocationError(\n operationError(\"INPUT_INVALID\", \"The secret reference is invalid.\"),\n );\n}\n","import * as nodeSdk from \"@tinycloud/node-sdk\";\nimport type {\n PermissionEntry,\n PortableDelegation,\n RuntimeDelegationActivator,\n} from \"@tinycloud/node-sdk\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n canonicalizeOperationCapabilities,\n delegationWithinRequest,\n evaluateAuthority,\n validateExactCapabilities,\n} from \"../authority.js\";\nimport {\n createOrReusePermissionRequest,\n DelegationImportArtifactSchema,\n findPermissionRequest,\n listPermissionRequests,\n PermissionEntrySchema,\n type DelegationImportArtifact,\n type DelegationRequestBinding,\n type PermissionRequestArtifact,\n} from \"../artifacts.js\";\nimport type {\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n RuntimeOperationContext,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { operationError } from \"../errors.js\";\nimport { lookupOperation } from \"../registry.js\";\nimport {\n readSession,\n readProfile,\n updateProfileStore,\n} from \"../state.js\";\nimport { operationSpaceResolver } from \"../secrets.js\";\n\ntype CapabilitiesInput = Record<never, never>;\ntype CapabilitiesOutput = { readonly capabilities: readonly PermissionEntry[] };\ntype AuthRequestInput =\n | Readonly<{ requestId: string }>\n | Readonly<{\n operationId: string;\n operationVersion: number;\n input?: unknown;\n }>;\ntype AuthRequestOutput = Readonly<{\n missing: readonly PermissionEntry[];\n request?: PermissionRequestArtifact;\n}>;\ntype AuthImportOutput = Readonly<{\n cid: string;\n effectivePermissions: readonly PermissionEntry[];\n expiry: string;\n audience: string;\n host: string;\n activated: true;\n alreadyPresent: boolean;\n}>;\n\nconst EmptyInputSchema: z.ZodType<CapabilitiesInput> = z.object({}).strict();\nconst CapabilitiesOutputSchema: z.ZodType<CapabilitiesOutput> = z.object({\n capabilities: z.array(PermissionEntrySchema),\n}).strict();\nconst AuthRequestInputSchema: z.ZodType<AuthRequestInput> = z.union([\n z.object({ requestId: z.string().min(1) }).strict(),\n z.object({\n operationId: z.string().min(1),\n operationVersion: z.number().int().positive(),\n input: z.unknown(),\n }).strict().superRefine((value, issue) => {\n if (!Object.prototype.hasOwnProperty.call(value, \"input\")) {\n issue.addIssue({ code: z.ZodIssueCode.custom, message: \"Operation input is required.\" });\n }\n }),\n]);\nconst PermissionRequestOutputSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string(), z.number()]).optional(),\n requested: z.array(PermissionEntrySchema).min(1),\n command: z.object({ argv: z.array(z.string()).min(1), cwd: z.string().min(1) }).strict().optional(),\n}).strict();\nconst AuthRequestOutputSchema: z.ZodType<AuthRequestOutput> = z.object({\n missing: z.array(PermissionEntrySchema),\n request: PermissionRequestOutputSchema.optional(),\n}).strict();\nconst AuthImportOutputSchema: z.ZodType<AuthImportOutput> = z.object({\n cid: z.string().min(1),\n effectivePermissions: z.array(PermissionEntrySchema),\n expiry: z.string().datetime({ offset: true }),\n audience: z.string().min(1),\n host: z.string().min(1),\n activated: z.literal(true),\n alreadyPresent: z.boolean(),\n}).strict();\n\nconst AUTH_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\nconst AUTH_EXPOSURE: OperationExposure = {\n cli: { status: \"required\" },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\nconst AUTH_CAPABILITIES_SENSITIVITY: OperationSensitivity = { input: [], output: [] };\nconst AUTH_REQUEST_SENSITIVITY: OperationSensitivity = { input: [\"/input\"], output: [] };\nconst AUTH_IMPORT_SENSITIVITY: OperationSensitivity = { input: [\"\"], output: [] };\n\n/**\n * Internal I2 auth definitions. Registry integration intentionally owns their\n * registration and root exports remain limited to invokeOperation.\n */\ntype AuthOperationDefinition =\n | OperationDefinition<CapabilitiesInput, CapabilitiesOutput>\n | OperationDefinition<AuthRequestInput, AuthRequestOutput>\n | OperationDefinition<DelegationImportArtifact, AuthImportOutput>;\n\nexport const authOperationDefinitions: readonly AuthOperationDefinition[] = [\n {\n id: \"tinycloud.auth.capabilities\",\n version: 1,\n title: \"TinyCloud active capabilities\",\n description: \"Inspect validated active runtime capabilities for the selected profile.\",\n input: EmptyInputSchema,\n output: CapabilitiesOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTH_POSTURES,\n exposure: AUTH_EXPOSURE,\n sensitivity: AUTH_CAPABILITIES_SENSITIVITY,\n authority: async () => [],\n execute: async (context: OperationContext): Promise<OperationExecutionOutcome<CapabilitiesOutput>> => ({\n status: \"ok\",\n output: {\n capabilities: canonicalizeCapabilities(\n (context.runtime?.granted ?? []) as unknown as PermissionEntry[],\n ),\n },\n }),\n },\n {\n id: \"tinycloud.auth.request\",\n version: 1,\n title: \"Request TinyCloud capabilities\",\n description: \"Create or recover an exact stored request from a canonical operation planner.\",\n input: AuthRequestInputSchema,\n output: AuthRequestOutputSchema,\n effects: [\"local_write\"],\n runtime: \"authenticated\",\n postures: AUTH_POSTURES,\n exposure: AUTH_EXPOSURE,\n sensitivity: AUTH_REQUEST_SENSITIVITY,\n authority: async () => [],\n execute: (context: OperationContext, input: AuthRequestInput) => requestExactAuthority(\n context as RuntimeOperationContext,\n input,\n ),\n },\n {\n id: \"tinycloud.auth.import\",\n version: 1,\n title: \"Import TinyCloud delegation\",\n description: \"Validate, activate, and persist one request-bound runtime delegation.\",\n input: DelegationImportArtifactSchema,\n output: AuthImportOutputSchema,\n effects: [\"local_write\"],\n runtime: \"authenticated\",\n postures: AUTH_POSTURES,\n exposure: AUTH_EXPOSURE,\n sensitivity: AUTH_IMPORT_SENSITIVITY,\n invalidInputErrorCode: \"DELEGATION_ARTIFACT_INVALID\",\n authority: async () => [],\n execute: (context: OperationContext, input: DelegationImportArtifact) => importRequestBoundDelegation(\n context as RuntimeOperationContext,\n input,\n ),\n },\n];\n\nasync function requestExactAuthority(\n context: RuntimeOperationContext,\n input: AuthRequestInput,\n): Promise<OperationExecutionOutcome<AuthRequestOutput>> {\n const sessionDid = context.summary.sessionDid;\n if (sessionDid === undefined) return missingSession();\n\n if (\"requestId\" in input) {\n try {\n const request = await findPermissionRequest(context.summary.profile, input.requestId, {\n sessionDid,\n host: context.summary.host,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n });\n if (request === null) {\n return invalidInput(\"The requested authority request is not available for this session.\");\n }\n if (request.profile !== context.summary.profile) {\n return invalidInput(\"The requested authority request is not available for this profile.\");\n }\n const required = exactCapabilities(request.requested);\n if (required === undefined) {\n return operationFailure(\n \"PERMISSION_HINT_INVALID\",\n \"The stored authority request has invalid capabilities.\",\n );\n }\n const evaluation = evaluateAuthority(\n context.runtime.granted as unknown as PermissionEntry[],\n required,\n );\n if (evaluation.satisfied) {\n return { status: \"ok\", output: { missing: [] } };\n }\n const narrowed = await createOrReusePermissionRequest({\n profile: context.summary.profile,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n host: context.summary.host,\n sessionDid,\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n missing: evaluation.missing,\n granted: context.runtime.granted as unknown as PermissionEntry[],\n });\n if (narrowed.status === \"satisfied\") return { status: \"ok\", output: { missing: [] } };\n return { status: \"ok\", output: { missing: evaluation.missing, request: narrowed.request } };\n } catch {\n return internalFailure();\n }\n }\n\n const target = lookupOperation(input.operationId, input.operationVersion);\n if (target.status === \"operation_not_found\") {\n return operationFailure(\"OPERATION_NOT_FOUND\", \"The requested operation is not registered.\");\n }\n if (target.status === \"operation_version_unsupported\") {\n return operationFailure(\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"The requested operation version is not supported.\",\n );\n }\n if (target.definition.id === \"tinycloud.auth.request\") {\n return invalidInput(\"Authority requests cannot plan themselves.\");\n }\n if (!target.definition.postures.includes(context.summary.posture)) {\n return operationFailure(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The active profile posture cannot execute this operation.\",\n );\n }\n\n const parsed = target.definition.input.safeParse(input.input);\n if (!parsed.success) return invalidInput(\"The operation input is invalid.\");\n\n try {\n const planned = await target.definition.authority(context, parsed.data);\n const required = exactCapabilities(planned);\n if (required === undefined) {\n return operationFailure(\n \"PERMISSION_HINT_INVALID\",\n \"The operation returned an invalid permission requirement.\",\n );\n }\n const evaluation = evaluateAuthority(\n context.runtime.granted as unknown as PermissionEntry[],\n required,\n );\n if (evaluation.satisfied) {\n // Do not call the artifact store: even a retention-only write is not an\n // allowed side effect for an already-authorized request.\n return { status: \"ok\", output: { missing: [] } };\n }\n const request = await createOrReusePermissionRequest({\n profile: context.summary.profile,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n host: context.summary.host,\n sessionDid,\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n missing: evaluation.missing,\n granted: context.runtime.granted as unknown as PermissionEntry[],\n });\n if (request.status === \"satisfied\") return { status: \"ok\", output: { missing: [] } };\n return {\n status: \"ok\",\n output: { missing: evaluation.missing, request: request.request },\n };\n } catch {\n return internalFailure();\n }\n}\n\nasync function importRequestBoundDelegation(\n context: RuntimeOperationContext,\n input: DelegationImportArtifact,\n): Promise<OperationExecutionOutcome<AuthImportOutput>> {\n try {\n const rawDelegation = input.delegation as unknown as Record<string, unknown>;\n if (typeof rawDelegation.delegateDID !== \"string\") return invalidDelegation();\n if (context.summary.sessionDid !== undefined && !samePrincipal(\n rawDelegation.delegateDID,\n context.summary.sessionDid,\n )) {\n return audienceMismatch(context.summary.sessionDid, rawDelegation.delegateDID);\n }\n const initial = await importState(context, input.requestId);\n if (!initial.ok) return initial.result;\n const { request, sessionDid, host } = initial;\n const explicitHost = rawDelegation.host;\n if (explicitHost !== undefined && typeof explicitHost !== \"string\") {\n return invalidDelegation();\n }\n if (typeof explicitHost === \"string\" && normalizeHost(explicitHost) !== normalizeHost(host)) {\n return hostMismatch(host, explicitHost);\n }\n const expiry = normalizeExpiry(rawDelegation.expiry);\n if (expiry === undefined) return invalidDelegation();\n if (expiry.getTime() <= Date.now()) return expiredDelegation();\n if (input.delegationCid !== undefined && input.delegationCid !== rawDelegation.cid) {\n return invalidDelegation();\n }\n if (typeof rawDelegation.delegateDID !== \"string\" || !samePrincipal(rawDelegation.delegateDID, sessionDid)) {\n return audienceMismatch(sessionDid, String(rawDelegation.delegateDID ?? \"unknown\"));\n }\n\n const delegation = {\n ...rawDelegation,\n expiry,\n host: explicitHost ?? host,\n } as PortableDelegation;\n let activated: Awaited<ReturnType<typeof nodeSdk.activateValidatedRuntimeDelegation>>;\n try {\n activated = await nodeSdk.activateValidatedRuntimeDelegation(\n context.runtime.node as RuntimeDelegationActivator,\n delegation,\n { host },\n );\n } catch {\n return operationFailure(\n \"DELEGATION_REJECTED\",\n \"The delegation was rejected by the TinyCloud runtime.\",\n );\n }\n\n const effectivePermissions = canonicalizeCapabilities(activated.effectivePermissions);\n const resolveSpace = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n );\n if (!delegationWithinRequest(request.requested, effectivePermissions, resolveSpace)) {\n return operationFailure(\n \"DELEGATION_REJECTED\",\n \"The delegation exceeds the stored authority request.\",\n );\n }\n\n try {\n return await updateProfileStore<Record<string, unknown>, OperationExecutionOutcome<AuthImportOutput>>(\n context.summary.profile,\n \"additional-delegations\",\n async (records) => {\n const state = await importState(context, input.requestId);\n if (!state.ok) return { records, result: state.result };\n if (state.sessionDid !== sessionDid || normalizeHost(state.host) !== normalizeHost(host)) {\n return {\n records,\n result: audienceMismatch(state.sessionDid, sessionDid),\n };\n }\n if (state.request.profile !== context.summary.profile ||\n !samePrincipal(state.request.sessionDid, sessionDid) ||\n normalizeHost(state.request.host) !== normalizeHost(host) ||\n JSON.stringify(canonicalizeOperationCapabilities(state.request.requested, resolveSpace)) !==\n JSON.stringify(canonicalizeOperationCapabilities(request.requested, resolveSpace))) {\n return {\n records,\n result: operationFailure(\n \"DELEGATION_ARTIFACT_INVALID\",\n \"The delegation does not reference a current stored request.\",\n ),\n };\n }\n // Replay re-checks the delegation against this binding; the stored\n // request itself may later be pruned.\n const record = {\n delegation: activated.delegation,\n permissions: activated.effectivePermissions,\n authorityRequest: {\n requestId: request.requestId,\n requested: request.requested,\n } satisfies DelegationRequestBinding,\n };\n // A validated import replaces every stored row for its CID with this\n // record, whatever binding those rows carried (none, a synthesized\n // one, or one replay cannot use), keeping the first row's position.\n const position = records.findIndex((entry) => delegationCid(entry) === activated.cid);\n const alreadyPresent = position !== -1;\n const others = records.filter((entry) => delegationCid(entry) !== activated.cid);\n return {\n records: alreadyPresent\n ? [...others.slice(0, position), record, ...others.slice(position)]\n : [...records, record],\n result: {\n status: \"ok\",\n output: {\n cid: activated.cid,\n effectivePermissions,\n expiry: activated.expiry.toISOString(),\n audience: activated.audience,\n host: activated.host,\n activated: true,\n alreadyPresent,\n },\n },\n };\n },\n );\n } catch {\n return internalImportFailure();\n }\n } catch {\n return internalImportFailure();\n }\n}\n\nasync function importState(\n context: RuntimeOperationContext,\n requestId: string,\n): Promise<\n | { ok: true; request: PermissionRequestArtifact; sessionDid: string; host: string }\n | { ok: false; result: OperationExecutionOutcome<never> }\n> {\n const sessionDid = await currentSessionDid(context.summary.profile);\n if (sessionDid === undefined) return { ok: false, result: missingSession() };\n if (context.summary.sessionDid === undefined || !samePrincipal(context.summary.sessionDid, sessionDid)) {\n return { ok: false, result: audienceMismatch(sessionDid, context.summary.sessionDid ?? \"unknown\") };\n }\n const current = await readProfile<Record<string, unknown>>(context.summary.profile);\n const host = typeof current?.host === \"string\" ? current.host : context.summary.host;\n if (normalizeHost(host) !== normalizeHost(context.summary.host)) {\n return { ok: false, result: hostMismatch(context.summary.host, host) };\n }\n let requests: PermissionRequestArtifact[];\n try {\n requests = await listPermissionRequests(context.summary.profile, {\n profile: context.summary.profile,\n host: context.summary.host,\n sessionDid,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n ...(context.summary.ownerDid === undefined ? {} : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { spaceId: context.summary.space }),\n });\n } catch {\n return {\n ok: false,\n result: operationFailure(\n \"DELEGATION_ARTIFACT_INVALID\",\n \"The stored authority request is malformed.\",\n ),\n };\n }\n const request = requests.find((candidate) => candidate.requestId === requestId);\n if (request === undefined || request.profile !== context.summary.profile) {\n return {\n ok: false,\n result: operationFailure(\n \"DELEGATION_ARTIFACT_INVALID\",\n \"The delegation does not reference a stored request for this profile.\",\n ),\n };\n }\n if (normalizeHost(request.host) !== normalizeHost(host)) {\n return { ok: false, result: hostMismatch(host, request.host) };\n }\n if (!samePrincipal(request.sessionDid, sessionDid)) {\n return { ok: false, result: audienceMismatch(sessionDid, request.sessionDid) };\n }\n return { ok: true, request, sessionDid, host };\n}\n\nfunction exactCapabilities(value: unknown): PermissionEntry[] | undefined {\n return validateExactCapabilities(value);\n}\n\nfunction normalizeExpiry(value: unknown): Date | undefined {\n const expiry = value instanceof Date ? value : typeof value === \"string\" ? new Date(value) : undefined;\n return expiry !== undefined && !Number.isNaN(expiry.getTime()) ? expiry : undefined;\n}\n\nfunction normalizeHost(host: string): string {\n return host.replace(/\\/+$/, \"\");\n}\n\nfunction samePrincipal(left: string, right: string): boolean {\n return left.split(\"#\", 1)[0] === right.split(\"#\", 1)[0];\n}\n\nfunction delegationCid(value: Record<string, unknown>): string | undefined {\n const delegation = value.delegation;\n if (delegation === null || typeof delegation !== \"object\") return undefined;\n const cid = (delegation as { cid?: unknown }).cid;\n return typeof cid === \"string\" ? cid : undefined;\n}\n\nasync function currentSessionDid(profile: string): Promise<string | undefined> {\n const session = await readSession<Record<string, unknown>>(profile);\n if (session === null || typeof session.verificationMethod !== \"string\") return undefined;\n return session.verificationMethod.split(\"#\", 1)[0] || undefined;\n}\n\nfunction missingSession(): OperationExecutionOutcome<never> {\n return operationFailure(\"SESSION_NOT_FOUND\", \"The selected profile does not have an active session.\");\n}\n\nfunction invalidDelegation(): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_ARTIFACT_INVALID\", \"The delegation artifact is invalid.\");\n}\n\nfunction expiredDelegation(): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_EXPIRED\", \"The delegation has expired.\");\n}\n\nfunction audienceMismatch(expectedSessionDid: string, artifactAudience: string): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_AUDIENCE_MISMATCH\", \"The delegation is for a different session.\", {\n expectedSessionDid,\n artifactAudience,\n });\n}\n\nfunction hostMismatch(expectedHost: string, artifactHost: string): OperationExecutionOutcome<never> {\n return operationFailure(\"DELEGATION_HOST_MISMATCH\", \"The delegation is for a different host.\", {\n expectedHost,\n artifactHost,\n });\n}\n\nfunction invalidInput(message: string): OperationExecutionOutcome<never> {\n return operationFailure(\"INPUT_INVALID\", message);\n}\n\nfunction internalFailure(): OperationExecutionOutcome<never> {\n return operationFailure(\"INTERNAL_ERROR\", \"The authority request could not be completed.\");\n}\n\nfunction internalImportFailure(): OperationExecutionOutcome<never> {\n return operationFailure(\"INTERNAL_ERROR\", \"The delegation import could not be completed.\");\n}\n\nfunction operationFailure(\n code: Parameters<typeof operationError>[0],\n message: string,\n details?: Readonly<Record<string, unknown>>,\n): OperationExecutionOutcome<never> {\n return { status: \"error\", error: operationError(code, message, { ...(details === undefined ? {} : { details }) }) };\n}\n","import type { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport { authorizationVerdictOf, validatedCapabilityOf } from \"@tinycloud/sdk-services\";\nimport { z } from \"zod\";\n\nimport type {\n CapabilityRequirement,\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n RuntimeOperationContext,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { OperationInvocationError, operationError, storageFullOperationError } from \"../errors.js\";\nimport { operationSpaceResolver } from \"../secrets.js\";\n\ntype EmptyInput = Record<never, never>;\n\ninterface AccountSpacesOutput {\n readonly spaces: readonly {\n readonly spaceId: string;\n readonly name: string;\n readonly ownerDid: string;\n readonly type: \"owned\" | \"delegated\" | \"discovered\";\n readonly permissions: readonly string[];\n readonly status: \"active\" | \"archived\";\n readonly registeredAt?: string;\n readonly updatedAt?: string;\n readonly expiresAt?: string;\n }[];\n readonly count: number;\n}\n\ninterface AccountApplicationsOutput {\n readonly applications: readonly {\n readonly appId: string;\n readonly manifests: readonly Record<string, unknown>[];\n readonly updatedAt?: string;\n readonly name?: string;\n readonly description?: string;\n readonly manifestHash?: string;\n }[];\n readonly count: number;\n}\n\ninterface KvListInput {\n readonly space: string;\n readonly prefix?: string;\n readonly limit?: number;\n}\n\ninterface KvListOutput {\n readonly space: string;\n readonly prefix: string;\n readonly keys: readonly string[];\n readonly count: number;\n readonly truncated: boolean;\n}\n\ninterface KvGetInput {\n readonly space: string;\n readonly key: string;\n readonly representation?: \"base64\" | \"text\" | \"json\";\n}\n\ninterface KvGetOutput {\n readonly space: string;\n readonly key: string;\n readonly value: unknown;\n readonly encoding: \"json\" | \"text\" | \"base64\";\n readonly metadata: {\n readonly etag?: string;\n readonly contentType?: string;\n readonly lastModified?: string;\n readonly contentLength?: number;\n };\n readonly byteLength: number;\n}\n\ntype JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };\ntype KvPutContent =\n | Readonly<{ encoding: \"utf8\"; value: string }>\n | Readonly<{ encoding: \"json\"; value: JsonValue }>\n | Readonly<{ encoding: \"base64\"; value: string }>;\ntype KvPutInput = Readonly<{\n space: string;\n key: string;\n content: KvPutContent;\n contentType?: string;\n}> & (\n | Readonly<{ mode: \"create\" | \"upsert\" }>\n | Readonly<{ mode: \"replace\"; etag: string }>\n);\ninterface KvPutOutput {\n readonly space: string;\n readonly key: string;\n readonly mode: \"create\" | \"replace\" | \"upsert\";\n readonly byteLength: number;\n readonly metadata: KvMetadata;\n}\ninterface KvHeadInput { readonly space: string; readonly key: string }\ninterface KvHeadOutput { readonly space: string; readonly key: string; readonly metadata: KvMetadata }\ninterface KvDeleteInput { readonly space: string; readonly key: string; readonly etag?: string }\ninterface KvDeleteOutput { readonly space: string; readonly key: string; readonly deleted: true; readonly etag?: string }\ninterface KvMetadata {\n readonly etag?: string;\n readonly contentType?: string;\n readonly lastModified?: string;\n readonly contentLength?: number;\n}\ntype KvOperationResult<T> =\n | Readonly<{ ok: true; data: T }>\n | Readonly<{ ok: false; error: Readonly<{ code?: string; meta?: Readonly<Record<string, unknown>> }> }>;\ninterface KvOperationHandle {\n list(options: Readonly<{ prefix?: string; limit: number }>): Promise<KvOperationResult<{\n readonly keys: readonly string[];\n readonly truncated?: boolean;\n }>>;\n get(key: string, options: Readonly<{\n binary: true;\n maxResponseBytes: number;\n }>): Promise<KvOperationResult<{ readonly data: Uint8Array; readonly headers: KvMetadata }>>;\n head(key: string): Promise<KvOperationResult<{ readonly data: void; readonly headers: KvMetadata }>>;\n put(key: string, value: Uint8Array, options: Readonly<{\n contentType: string;\n ifNoneMatch?: \"*\";\n ifMatch?: string;\n }>): Promise<KvOperationResult<{ readonly data: void; readonly headers: KvMetadata }>>;\n delete(key: string, options: Readonly<{ ifMatch?: string }>): Promise<KvOperationResult<{\n readonly data: void;\n readonly headers: KvMetadata;\n }>>;\n}\n\nconst MAX_KV_VALUE_BYTES = 1024 * 1024;\nconst DEFAULT_KV_LIST_LIMIT = 100;\nconst MAX_ACCOUNT_REGISTRY_RECORDS = 1000;\nconst MAX_ACCOUNT_REGISTRY_BYTES = 4 * 1024 * 1024;\n\nconst EmptyInputSchema: z.ZodType<EmptyInput> = z.object({}).strict();\nconst SpaceSchema = z.string().min(1).refine(\n (space) =>\n (/^[A-Za-z0-9_-]+$/.test(space) || space.startsWith(\"tinycloud:\")) &&\n !space.includes(\"*\"),\n \"Invalid TinyCloud space.\",\n);\nconst PrefixSchema = z.string().refine(\n (prefix) => prefix !== \"/\" && !prefix.includes(\"*\"),\n \"Invalid KV prefix.\",\n);\nconst KeySchema = z.string().min(1).refine(\n (key) => key !== \"/\" && !key.endsWith(\"/\") && !key.includes(\"*\"),\n \"Invalid KV key.\",\n);\nconst LimitSchema = z.number().int().min(1).max(1000);\nconst StrongEtagSchema = z.string().regex(\n /^\"blake3-[0-9a-f]{64}\"$/,\n \"A strong TinyCloud BLAKE3 ETag is required.\",\n);\nconst ContentTypeSchema = z.string().min(1).max(128).refine(\n (value) => !/[\\x00-\\x1f\\x7f]/.test(value),\n \"Invalid content type.\",\n);\nconst JsonNumberSchema = z.number().finite().refine(\n (value) => !Number.isInteger(value) || Number.isSafeInteger(value),\n \"JSON integer values must be JavaScript safe integers.\",\n);\nconst JsonValueSchema: z.ZodType<JsonValue> = z.lazy(() => z.union([\n z.null(),\n z.boolean(),\n JsonNumberSchema,\n z.string(),\n z.array(JsonValueSchema),\n z.record(JsonValueSchema),\n]));\nconst KvMetadataSchema: z.ZodType<KvMetadata> = z.object({\n etag: z.string().optional(),\n contentType: z.string().optional(),\n lastModified: z.string().optional(),\n contentLength: z.number().int().nonnegative().optional(),\n}).strict();\n\nconst AccountSpaceSchema = z.object({\n spaceId: z.string().min(1),\n name: z.string().min(1),\n ownerDid: z.string(),\n type: z.enum([\"owned\", \"delegated\", \"discovered\"]),\n permissions: z.array(z.string()),\n status: z.enum([\"active\", \"archived\"]),\n registeredAt: z.string().optional(),\n updatedAt: z.string().optional(),\n expiresAt: z.string().datetime({ offset: true }).optional(),\n}).strict();\nconst AccountSpacesOutputSchema: z.ZodType<AccountSpacesOutput> = z.object({\n spaces: z.array(AccountSpaceSchema),\n count: z.number().int().nonnegative(),\n}).strict();\n\nconst AccountApplicationSchema = z.object({\n appId: z.string().min(1),\n manifests: z.array(z.record(z.unknown())),\n updatedAt: z.string().optional(),\n name: z.string().optional(),\n description: z.string().optional(),\n manifestHash: z.string().optional(),\n}).strict();\nconst AccountApplicationsOutputSchema: z.ZodType<AccountApplicationsOutput> = z.object({\n applications: z.array(AccountApplicationSchema),\n count: z.number().int().nonnegative(),\n}).strict();\n\nconst KvListInputSchema: z.ZodType<KvListInput> = z.object({\n space: SpaceSchema,\n prefix: PrefixSchema.optional(),\n limit: LimitSchema.optional(),\n}).strict();\nconst KvListOutputSchema: z.ZodType<KvListOutput> = z.object({\n space: z.string().min(1),\n prefix: z.string(),\n keys: z.array(z.string()),\n count: z.number().int().nonnegative(),\n truncated: z.boolean(),\n}).strict();\n\nconst KvGetInputSchema: z.ZodType<KvGetInput> = z.object({\n space: SpaceSchema,\n key: KeySchema,\n representation: z.enum([\"base64\", \"text\", \"json\"]).optional(),\n}).strict();\nconst KvGetOutputSchema: z.ZodType<KvGetOutput> = z.object({\n space: z.string().min(1),\n key: z.string().min(1),\n value: z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(z.unknown()),\n z.record(z.unknown()),\n ]),\n encoding: z.enum([\"json\", \"text\", \"base64\"]),\n metadata: KvMetadataSchema,\n byteLength: z.number().int().nonnegative(),\n}).strict();\n\nconst KvPutContentSchema: z.ZodType<KvPutContent> = z.discriminatedUnion(\"encoding\", [\n z.object({ encoding: z.literal(\"utf8\"), value: z.string() }).strict(),\n z.object({ encoding: z.literal(\"json\"), value: JsonValueSchema }).strict(),\n z.object({ encoding: z.literal(\"base64\"), value: z.string() }).strict(),\n]).superRefine((content, context) => {\n const decoded = decodeKvPutContent(content);\n if (decoded === undefined) {\n context.addIssue({ code: z.ZodIssueCode.custom, message: \"Invalid canonical base64 content.\" });\n } else if (decoded.byteLength > MAX_KV_VALUE_BYTES) {\n context.addIssue({\n code: z.ZodIssueCode.too_big,\n type: \"array\",\n maximum: MAX_KV_VALUE_BYTES,\n inclusive: true,\n message: `KV content must not exceed ${MAX_KV_VALUE_BYTES} bytes.`,\n });\n }\n});\nconst KvPutCommonSchema = {\n space: SpaceSchema,\n key: KeySchema,\n content: KvPutContentSchema,\n contentType: ContentTypeSchema.optional(),\n};\nconst KvPutInputSchema: z.ZodType<KvPutInput> = z.discriminatedUnion(\"mode\", [\n z.object({ ...KvPutCommonSchema, mode: z.literal(\"create\") }).strict(),\n z.object({ ...KvPutCommonSchema, mode: z.literal(\"upsert\") }).strict(),\n z.object({ ...KvPutCommonSchema, mode: z.literal(\"replace\"), etag: StrongEtagSchema }).strict(),\n]);\nconst KvPutOutputSchema: z.ZodType<KvPutOutput> = z.object({\n space: z.string().min(1),\n key: z.string().min(1),\n mode: z.enum([\"create\", \"replace\", \"upsert\"]),\n byteLength: z.number().int().nonnegative(),\n metadata: KvMetadataSchema,\n}).strict();\nconst KvHeadInputSchema: z.ZodType<KvHeadInput> = z.object({ space: SpaceSchema, key: KeySchema }).strict();\nconst KvHeadOutputSchema: z.ZodType<KvHeadOutput> = z.object({\n space: z.string().min(1), key: z.string().min(1), metadata: KvMetadataSchema,\n}).strict();\nconst KvDeleteInputSchema: z.ZodType<KvDeleteInput> = z.object({\n space: SpaceSchema, key: KeySchema, etag: StrongEtagSchema.optional(),\n}).strict();\nconst KvDeleteOutputSchema: z.ZodType<KvDeleteOutput> = z.object({\n space: z.string().min(1), key: z.string().min(1), deleted: z.literal(true), etag: z.string().optional(),\n}).strict();\n\nconst AUTHENTICATED_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\nconst EXPLORATION_EXPOSURE: OperationExposure = {\n cli: {\n status: \"excluded\",\n reason: \"Existing account and KV Commander commands remain the CLI surface.\",\n },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\n\nconst ACCOUNT_SPACES_SENSITIVITY: OperationSensitivity = {\n input: [],\n output: [\"/spaces\"],\n};\nconst ACCOUNT_APPLICATIONS_SENSITIVITY: OperationSensitivity = {\n input: [],\n output: [\"/applications\"],\n};\nconst KV_LIST_SENSITIVITY: OperationSensitivity = {\n input: [\"/prefix\"],\n output: [\"/keys\"],\n};\nconst KV_GET_SENSITIVITY: OperationSensitivity = {\n input: [\"/key\"],\n output: [\"/value\"],\n};\nconst KV_PUT_SENSITIVITY: OperationSensitivity = { input: [\"/key\", \"/content\"], output: [] };\nconst KV_KEY_SENSITIVITY: OperationSensitivity = { input: [\"/key\"], output: [] };\n\ntype ExplorationDefinition =\n | OperationDefinition<EmptyInput, AccountSpacesOutput>\n | OperationDefinition<EmptyInput, AccountApplicationsOutput>\n | OperationDefinition<KvListInput, KvListOutput>\n | OperationDefinition<KvGetInput, KvGetOutput>\n | OperationDefinition<KvPutInput, KvPutOutput>\n | OperationDefinition<KvHeadInput, KvHeadOutput>\n | OperationDefinition<KvDeleteInput, KvDeleteOutput>;\n\nexport const explorationOperationDefinitions: readonly ExplorationDefinition[] = [\n {\n id: \"tinycloud.account.spaces.list\",\n version: 1,\n title: \"List TinyCloud account spaces\",\n description: \"List the spaces registered in the selected owner's TinyCloud account.\",\n input: EmptyInputSchema,\n output: AccountSpacesOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: ACCOUNT_SPACES_SENSITIVITY,\n authority: (context: RuntimeOperationContext) => planAccountRegistryRead(context, \"spaces/\"),\n execute: executeAccountSpacesList,\n },\n {\n id: \"tinycloud.account.applications.list\",\n version: 1,\n title: \"List TinyCloud account applications\",\n description: \"List the application manifests registered in the selected owner's TinyCloud account.\",\n input: EmptyInputSchema,\n output: AccountApplicationsOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: ACCOUNT_APPLICATIONS_SENSITIVITY,\n authority: (context: RuntimeOperationContext) => planAccountRegistryRead(context, \"applications/\"),\n execute: executeAccountApplicationsList,\n },\n {\n id: \"tinycloud.kv.list\",\n version: 1,\n title: \"List TinyCloud KV keys\",\n description: \"List keys at one exact prefix in a delegated TinyCloud space.\",\n input: KvListInputSchema,\n output: KvListOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: KV_LIST_SENSITIVITY,\n authority: planKvList,\n execute: executeKvList,\n },\n {\n id: \"tinycloud.kv.get\",\n version: 1,\n title: \"Get a TinyCloud KV value\",\n description: \"Read one exact key with a node-enforced one MiB response limit.\",\n input: KvGetInputSchema,\n output: KvGetOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: EXPLORATION_EXPOSURE,\n sensitivity: KV_GET_SENSITIVITY,\n authority: planKvGet,\n execute: executeKvGet,\n },\n {\n id: \"tinycloud.kv.head\", version: 1, title: \"Inspect TinyCloud KV metadata\",\n description: \"Read metadata for one exact key without downloading its value.\",\n input: KvHeadInputSchema, output: KvHeadOutputSchema, effects: [\"read\"], runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES, exposure: EXPLORATION_EXPOSURE, sensitivity: KV_KEY_SENSITIVITY,\n authority: (context: RuntimeOperationContext, input: KvHeadInput) =>\n planExactKv(context, input.space, input.key, \"tinycloud.kv/metadata\"),\n execute: executeKvHead,\n },\n {\n id: \"tinycloud.kv.put\", version: 1, title: \"Write a TinyCloud KV value\",\n description: \"Create, conditionally replace, or explicitly upsert one exact KV key.\",\n input: KvPutInputSchema, output: KvPutOutputSchema, effects: [\"write\"], runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES, exposure: EXPLORATION_EXPOSURE, sensitivity: KV_PUT_SENSITIVITY,\n authority: (context: RuntimeOperationContext, input: KvPutInput) =>\n planExactKv(context, input.space, input.key, \"tinycloud.kv/put\"),\n execute: executeKvPut,\n },\n {\n id: \"tinycloud.kv.delete\", version: 1, title: \"Delete a TinyCloud KV value\",\n description: \"Delete one exact KV key, optionally only when its ETag still matches.\",\n input: KvDeleteInputSchema, output: KvDeleteOutputSchema, effects: [\"destructive\"], runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES, exposure: EXPLORATION_EXPOSURE, sensitivity: KV_KEY_SENSITIVITY,\n authority: (context: RuntimeOperationContext, input: KvDeleteInput) =>\n planExactKv(context, input.space, input.key, \"tinycloud.kv/del\"),\n execute: executeKvDelete,\n },\n];\n\nasync function planAccountRegistryRead(\n context: RuntimeOperationContext,\n path: \"spaces/\" | \"applications/\",\n): Promise<readonly CapabilityRequirement[]> {\n return [{\n service: \"tinycloud.kv\",\n space: resolveSpace(context, \"account\"),\n path,\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/list\"],\n }];\n}\n\nasync function planKvList(\n context: RuntimeOperationContext,\n input: KvListInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveGenericKvSpace(context, input.space);\n return [{\n service: \"tinycloud.kv\",\n space,\n path: input.prefix ?? \"\",\n actions: [\"tinycloud.kv/list\"],\n }];\n}\n\nasync function planKvGet(\n context: RuntimeOperationContext,\n input: KvGetInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveGenericKvSpace(context, input.space);\n return [{\n service: \"tinycloud.kv\",\n space,\n path: input.key,\n actions: [\"tinycloud.kv/get\"],\n }];\n}\n\nasync function planExactKv(\n context: RuntimeOperationContext,\n requestedSpace: string,\n key: string,\n action: \"tinycloud.kv/metadata\" | \"tinycloud.kv/put\" | \"tinycloud.kv/del\",\n): Promise<readonly CapabilityRequirement[]> {\n return [{\n service: \"tinycloud.kv\",\n space: resolveGenericKvSpace(context, requestedSpace),\n path: key,\n actions: [action],\n }];\n}\n\nasync function executeAccountSpacesList(\n context: OperationContext,\n _input: EmptyInput,\n): Promise<OperationExecutionOutcome<AccountSpacesOutput>> {\n try {\n const entries = await readAccountRegistry(context, \"spaces/\");\n if (!entries.ok) return entries.outcome;\n const spaces = entries.records\n .map(({ key, value }) => projectAccountSpace(key, value))\n .sort((left, right) => left.name.localeCompare(right.name) || left.spaceId.localeCompare(right.spaceId));\n const output = { spaces, count: spaces.length };\n return accountRegistryOutput(output);\n } catch (error) {\n return caughtKvFailure(error, \"list account spaces\");\n }\n}\n\nasync function executeAccountApplicationsList(\n context: OperationContext,\n _input: EmptyInput,\n): Promise<OperationExecutionOutcome<AccountApplicationsOutput>> {\n try {\n const entries = await readAccountRegistry(context, \"applications/\");\n if (!entries.ok) return entries.outcome;\n const applications = entries.records\n .map(({ key, value }) => projectAccountApplication(key, value))\n .sort((left, right) => left.appId.localeCompare(right.appId));\n const output = { applications, count: applications.length };\n return accountRegistryOutput(output);\n } catch (error) {\n return caughtKvFailure(error, \"list account applications\");\n }\n}\n\nasync function executeKvList(\n context: OperationContext,\n input: KvListInput,\n): Promise<OperationExecutionOutcome<KvListOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).list({\n ...(input.prefix === undefined ? {} : { prefix: input.prefix }),\n limit: input.limit ?? DEFAULT_KV_LIST_LIMIT,\n });\n if (!result.ok) return kvFailure(result.error, \"list KV keys\");\n const keys = [...result.data.keys];\n return {\n status: \"ok\",\n output: {\n space,\n prefix: input.prefix ?? \"\",\n keys,\n count: keys.length,\n truncated: result.data.truncated ?? false,\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"list KV keys\");\n }\n}\n\nasync function executeKvGet(\n context: OperationContext,\n input: KvGetInput,\n): Promise<OperationExecutionOutcome<KvGetOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).get(input.key, {\n binary: true,\n maxResponseBytes: MAX_KV_VALUE_BYTES,\n });\n if (!result.ok) return kvFailure(result.error, \"read the KV value\");\n const bytes = result.data.data;\n if (bytes.byteLength > MAX_KV_VALUE_BYTES) {\n return kvFailure({ code: \"KV_RESPONSE_TOO_LARGE\" }, \"read the KV value\");\n }\n const encoded = encodeKvValue(bytes, input.representation ?? \"base64\");\n if (!encoded.ok) return encoded.outcome;\n return {\n status: \"ok\",\n output: {\n space,\n key: input.key,\n value: encoded.value,\n encoding: encoded.encoding,\n metadata: projectKvMetadata(result.data.headers),\n byteLength: bytes.byteLength,\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"read the KV value\");\n }\n}\n\nasync function executeKvHead(\n context: OperationContext,\n input: KvHeadInput,\n): Promise<OperationExecutionOutcome<KvHeadOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).head(input.key);\n if (!result.ok) return kvFailure(result.error, \"read KV metadata\");\n return { status: \"ok\", output: { space, key: input.key, metadata: projectKvMetadata(result.data.headers) } };\n } catch (error) {\n return caughtKvFailure(error, \"read KV metadata\");\n }\n}\n\nasync function executeKvPut(\n context: OperationContext,\n input: KvPutInput,\n): Promise<OperationExecutionOutcome<KvPutOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const decoded = decodeKvPutContent(input.content);\n if (decoded === undefined || decoded.byteLength > MAX_KV_VALUE_BYTES) {\n return { status: \"error\", error: operationError(\"INPUT_INVALID\", \"The KV content is invalid or too large.\") };\n }\n const result = await genericKv(runtime, space).put(input.key, decoded.bytes, {\n contentType: input.contentType ?? decoded.contentType,\n ...(input.mode === \"create\" ? { ifNoneMatch: \"*\" as const } : {}),\n ...(input.mode === \"replace\" ? { ifMatch: input.etag } : {}),\n });\n if (!result.ok) return kvFailure(result.error, \"write the KV value\");\n return {\n status: \"ok\",\n output: {\n space,\n key: input.key,\n mode: input.mode,\n byteLength: decoded.byteLength,\n metadata: projectKvMetadata(result.data.headers),\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"write the KV value\");\n }\n}\n\nasync function executeKvDelete(\n context: OperationContext,\n input: KvDeleteInput,\n): Promise<OperationExecutionOutcome<KvDeleteOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveGenericKvSpace(runtime, input.space);\n const result = await genericKv(runtime, space).delete(input.key, {\n ...(input.etag === undefined ? {} : { ifMatch: input.etag }),\n });\n if (!result.ok) return kvFailure(result.error, \"delete the KV value\");\n return {\n status: \"ok\",\n output: {\n space,\n key: input.key,\n deleted: true,\n ...(result.data.headers.etag === undefined ? {} : { etag: result.data.headers.etag }),\n },\n };\n } catch (error) {\n return caughtKvFailure(error, \"delete the KV value\");\n }\n}\n\nfunction runtimeContext(context: OperationContext): RuntimeOperationContext {\n if (context.runtime === undefined) {\n throw new TypeError(\"Authenticated operation runtime is unavailable.\");\n }\n return context as RuntimeOperationContext;\n}\n\nfunction runtimeNode(context: OperationContext): TinyCloudNode {\n return runtimeContext(context).runtime.node as TinyCloudNode;\n}\n\nfunction genericKv(context: RuntimeOperationContext, space: string): KvOperationHandle {\n return runtimeNode(context).kvForSpace(space) as unknown as KvOperationHandle;\n}\n\nfunction resolveSpace(context: RuntimeOperationContext, space: string): string {\n return operationSpaceResolver(context.runtime.node, context.summary.space)(space);\n}\n\nfunction resolveGenericKvSpace(context: RuntimeOperationContext, space: string): string {\n const resolved = resolveSpace(context, space);\n const protectedName = resolved.split(\":\").at(-1)?.toLowerCase();\n if (protectedName === \"secrets\" || protectedName === \"account\") {\n throw new OperationInvocationError(operationError(\n \"INPUT_INVALID\",\n \"Generic KV operations cannot access TinyCloud account or secrets spaces.\",\n ));\n }\n return resolved;\n}\n\nasync function readAccountRegistry(\n context: OperationContext,\n prefix: \"spaces/\" | \"applications/\",\n): Promise<\n | Readonly<{ ok: true; records: readonly Readonly<{ key: string; value: Record<string, unknown> }>[] }>\n | Readonly<{ ok: false; outcome: OperationExecutionOutcome<never> }>\n> {\n const runtime = runtimeContext(context);\n const accountSpace = resolveSpace(runtime, \"account\");\n const kv = runtimeNode(runtime).kvForSpace(accountSpace) as unknown as KvOperationHandle;\n const listed = await kv.list({ prefix, limit: MAX_ACCOUNT_REGISTRY_RECORDS });\n if (!listed.ok) return { ok: false, outcome: kvFailure(listed.error, \"list the account registry\") };\n if (listed.data.truncated === true) {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\n \"OUTPUT_INVALID\",\n `The TinyCloud account registry exceeds the ${MAX_ACCOUNT_REGISTRY_RECORDS}-record exploration limit.`,\n ),\n },\n };\n }\n\n const records: Array<Readonly<{ key: string; value: Record<string, unknown> }>> = [];\n let totalBytes = 0;\n for (const key of listed.data.keys) {\n const loaded = await kv.get(key, {\n binary: true,\n maxResponseBytes: MAX_KV_VALUE_BYTES,\n });\n if (!loaded.ok) {\n return { ok: false, outcome: kvFailure(loaded.error, \"read the account registry\") };\n }\n const bytes = loaded.data.data;\n totalBytes += bytes.byteLength;\n if (bytes.byteLength > MAX_KV_VALUE_BYTES || totalBytes > MAX_ACCOUNT_REGISTRY_BYTES) {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\n \"KV_RESPONSE_TOO_LARGE\",\n `The TinyCloud account registry exceeds the ${MAX_ACCOUNT_REGISTRY_BYTES}-byte exploration limit.`,\n ),\n },\n };\n }\n try {\n const value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n if (!isRecord(value)) throw new TypeError(\"Account registry values must be JSON objects.\");\n records.push({ key, value });\n } catch {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\"OUTPUT_INVALID\", \"The TinyCloud account registry contains an invalid record.\"),\n },\n };\n }\n }\n return { ok: true, records };\n}\n\nfunction projectAccountSpace(\n key: string,\n record: Record<string, unknown>,\n): AccountSpacesOutput[\"spaces\"][number] {\n const suffix = key.startsWith(\"spaces/\") ? key.slice(\"spaces/\".length) : key;\n const rawSpaceId = stringField(record, \"space_id\", \"spaceId\") ?? suffix;\n const rawName = stringField(record, \"name\") ?? rawSpaceId.split(\":\").at(-1) ?? rawSpaceId;\n const rawType = stringField(record, \"type\");\n const rawStatus = stringField(record, \"status\");\n const rawExpiresAt = record.expires_at ?? record.expiresAt;\n const expiresAt = rawExpiresAt instanceof Date\n ? rawExpiresAt.toISOString()\n : typeof rawExpiresAt === \"string\" && !Number.isNaN(new Date(rawExpiresAt).getTime())\n ? new Date(rawExpiresAt).toISOString()\n : undefined;\n return {\n spaceId: rawSpaceId,\n name: rawName,\n ownerDid: stringField(record, \"owner_did\", \"ownerDid\", \"owner\") ?? \"\",\n type: rawType === \"owned\" || rawType === \"delegated\" ? rawType : \"discovered\",\n permissions: Array.isArray(record.permissions)\n ? record.permissions.filter((value): value is string => typeof value === \"string\")\n : [],\n status: rawStatus === \"archived\" ? \"archived\" : \"active\",\n ...(stringField(record, \"registered_at\", \"registeredAt\") === undefined\n ? {}\n : { registeredAt: stringField(record, \"registered_at\", \"registeredAt\") }),\n ...(stringField(record, \"updated_at\", \"updatedAt\") === undefined\n ? {}\n : { updatedAt: stringField(record, \"updated_at\", \"updatedAt\") }),\n ...(expiresAt === undefined ? {} : { expiresAt }),\n };\n}\n\nfunction projectAccountApplication(\n key: string,\n record: Record<string, unknown>,\n): AccountApplicationsOutput[\"applications\"][number] {\n const manifests = Array.isArray(record.manifests)\n ? record.manifests.filter(isRecord)\n : [];\n const first = manifests[0];\n return {\n appId: stringField(record, \"app_id\", \"appId\") ??\n stringField(first, \"app_id\") ??\n (key.startsWith(\"applications/\") ? key.slice(\"applications/\".length) : key),\n manifests,\n ...(stringField(record, \"updated_at\", \"updatedAt\") === undefined\n ? {}\n : { updatedAt: stringField(record, \"updated_at\", \"updatedAt\") }),\n ...(stringField(first, \"name\") === undefined ? {} : { name: stringField(first, \"name\") }),\n ...(stringField(first, \"description\") === undefined\n ? {}\n : { description: stringField(first, \"description\") }),\n ...(stringField(record, \"manifest_hash\", \"manifestHash\") === undefined\n ? {}\n : { manifestHash: stringField(record, \"manifest_hash\", \"manifestHash\") }),\n };\n}\n\nfunction stringField(\n record: Record<string, unknown> | undefined,\n ...keys: readonly string[]\n): string | undefined {\n if (record === undefined) return undefined;\n for (const key of keys) {\n if (typeof record[key] === \"string\") return record[key];\n }\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction encodeKvValue(\n value: Uint8Array,\n representation: NonNullable<KvGetInput[\"representation\"]>,\n):\n | Readonly<{ ok: true; value: unknown; encoding: KvGetOutput[\"encoding\"] }>\n | Readonly<{ ok: false; outcome: OperationExecutionOutcome<KvGetOutput> }> {\n if (representation === \"base64\") {\n return { ok: true, value: Buffer.from(value).toString(\"base64\"), encoding: \"base64\" };\n }\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(value);\n } catch {\n return {\n ok: false,\n outcome: { status: \"error\", error: operationError(\"OUTPUT_INVALID\", \"The KV value is not valid UTF-8.\") },\n };\n }\n if (representation === \"text\") return { ok: true, value: text, encoding: \"text\" };\n try {\n const parsed = JsonValueSchema.safeParse(JSON.parse(text));\n if (!parsed.success) {\n return {\n ok: false,\n outcome: {\n status: \"error\",\n error: operationError(\n \"OUTPUT_INVALID\",\n \"The KV JSON contains a number that cannot be represented safely.\",\n ),\n },\n };\n }\n return { ok: true, value: parsed.data, encoding: \"json\" };\n } catch {\n return {\n ok: false,\n outcome: { status: \"error\", error: operationError(\"OUTPUT_INVALID\", \"The KV value is not valid JSON.\") },\n };\n }\n}\n\nfunction decodeKvPutContent(content: KvPutContent):\n | Readonly<{ bytes: Uint8Array; byteLength: number; contentType: string }>\n | undefined {\n let bytes: Uint8Array;\n let contentType: string;\n if (content.encoding === \"utf8\") {\n bytes = new TextEncoder().encode(content.value);\n contentType = \"text/plain;charset=UTF-8\";\n } else if (content.encoding === \"json\") {\n bytes = new TextEncoder().encode(JSON.stringify(content.value));\n contentType = \"application/json\";\n } else {\n if (!isCanonicalBase64(content.value)) return undefined;\n bytes = new Uint8Array(Buffer.from(content.value, \"base64\"));\n contentType = \"application/octet-stream\";\n }\n return { bytes, byteLength: bytes.byteLength, contentType };\n}\n\nfunction isCanonicalBase64(value: string): boolean {\n if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {\n return false;\n }\n return Buffer.from(value, \"base64\").toString(\"base64\") === value;\n}\n\nfunction projectKvMetadata(headers: {\n readonly etag?: string;\n readonly contentType?: string;\n readonly lastModified?: string;\n readonly contentLength?: number;\n}): KvMetadata {\n return {\n ...(headers.etag === undefined ? {} : { etag: headers.etag }),\n ...(headers.contentType === undefined ? {} : { contentType: headers.contentType }),\n ...(headers.lastModified === undefined ? {} : { lastModified: headers.lastModified }),\n ...(headers.contentLength === undefined ? {} : { contentLength: headers.contentLength }),\n };\n}\n\nfunction caughtKvFailure(error: unknown, action: string): OperationExecutionOutcome<never> {\n if (error instanceof OperationInvocationError) return { status: \"error\", error: error.operationError };\n return authorizationFailure(error, action) ?? nodeFailure(action);\n}\n\nexport function authorizationFailure(error: unknown, action: string): OperationExecutionOutcome<never> | undefined {\n const verdict = authorizationVerdictOf(error);\n if (verdict === \"unauthenticated\") {\n if (validatedCapabilityOf(error) !== undefined) {\n return { status: \"error\", error: operationError(\"PERMISSION_DENIED\", `Permission is denied to ${action}.`) };\n }\n return { status: \"error\", error: operationError(\"AUTH_REQUIRED\", `Authentication is required to ${action}.`) };\n }\n if (verdict === \"forbidden\") {\n return { status: \"error\", error: operationError(\"PERMISSION_DENIED\", `Permission is denied to ${action}.`) };\n }\n return undefined;\n}\n\nfunction accountRegistryOutput<T>(output: T): OperationExecutionOutcome<T> {\n if (Buffer.byteLength(JSON.stringify(output), \"utf8\") > MAX_ACCOUNT_REGISTRY_BYTES) {\n return {\n status: \"error\",\n error: operationError(\n \"KV_RESPONSE_TOO_LARGE\",\n `The TinyCloud account registry exceeds the ${MAX_ACCOUNT_REGISTRY_BYTES}-byte exploration limit.`,\n ),\n };\n }\n return { status: \"ok\", output };\n}\n\nfunction kvFailure(\n error: Readonly<{ code?: string; meta?: Readonly<Record<string, unknown>> }>,\n action: string,\n): OperationExecutionOutcome<never> {\n const auth = authorizationFailure(error, action);\n if (auth !== undefined) return auth;\n if (error.code === \"KV_NOT_FOUND\") {\n return { status: \"error\", error: operationError(\"KV_NOT_FOUND\", \"The TinyCloud KV key was not found.\") };\n }\n if (error.code === \"KV_PRECONDITION_FAILED\") {\n return { status: \"error\", error: operationError(\"KV_PRECONDITION_FAILED\", \"The TinyCloud KV object changed or already exists.\") };\n }\n if (error.code === \"KV_CONFLICT\") {\n return {\n status: \"error\",\n error: operationError(\n \"KV_CONFLICT\",\n \"A database serialization conflict prevented the conditional KV mutation; re-read the key state, which may still be absent, before deciding whether to retry.\",\n { retryable: true },\n ),\n };\n }\n if (error.code === \"KV_RESPONSE_TOO_LARGE\") {\n return { status: \"error\", error: operationError(\"KV_RESPONSE_TOO_LARGE\", `The TinyCloud KV value exceeds ${MAX_KV_VALUE_BYTES} bytes.`) };\n }\n const storageFull = storageFullOperationError(error);\n if (storageFull) return { status: \"error\", error: storageFull };\n return nodeFailure(action);\n}\n\nfunction nodeFailure(action: string): OperationExecutionOutcome<never> {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n `The TinyCloud node could not ${action}.`,\n { retryable: true },\n ),\n };\n}\n","import { z } from \"zod\";\nimport type { SecretReadResult } from \"@tinycloud/node-sdk\";\n\nimport {\n type OperationContext,\n type CapabilityRequirement,\n type OperationDefinition,\n type OperationExecutionOutcome,\n type OperationExposure,\n type OperationSensitivity,\n type RuntimeOperationContext,\n type TinyCloudPosture,\n} from \"../contract.js\";\nimport { OperationInvocationError, operationError } from \"../errors.js\";\nimport {\n buildSecretSetupUrl,\n normalizeSecretsGetInput,\n operationSpaceResolver,\n resolveSecretReference,\n resolveSecretReferenceForOperation,\n type SecretReference,\n type SecretsGetInput,\n} from \"../secrets.js\";\n\ninterface SecretsGetOutput {\n readonly value: string;\n}\n\nconst SecretsGetInputSchema: z.ZodType<SecretsGetInput> = z.object({\n name: z.string(),\n scope: z.string().optional(),\n space: z.string().optional(),\n}).strict().superRefine((input, context) => {\n try {\n resolveSecretReference(input);\n } catch {\n context.addIssue({ code: z.ZodIssueCode.custom, message: \"Invalid secret reference.\" });\n }\n}).transform(normalizeSecretsGetInput);\n\nconst SecretsGetOutputSchema: z.ZodType<SecretsGetOutput> = z.object({\n value: z.string(),\n}).strict();\n\nconst SECRETS_GET_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\n\nconst SECRETS_GET_EXPOSURE: OperationExposure = {\n cli: { status: \"required\" },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\n\nconst SECRETS_GET_SENSITIVITY: OperationSensitivity = {\n input: [],\n output: [\"/value\"],\n};\n\nexport const secretsGetOperationDefinition: OperationDefinition<SecretsGetInput, SecretsGetOutput> = {\n id: \"tinycloud.secrets.get\",\n version: 1,\n title: \"Get a TinyCloud secret\",\n description: \"Read and decrypt one secret from the selected TinyCloud secrets space.\",\n input: SecretsGetInputSchema,\n output: SecretsGetOutputSchema,\n effects: [\"read\", \"local_write\"],\n runtime: \"authenticated\",\n postures: SECRETS_GET_POSTURES,\n exposure: SECRETS_GET_EXPOSURE,\n sensitivity: SECRETS_GET_SENSITIVITY,\n authority: planSecretGet,\n execute: executeSecretGet,\n};\n\nexport const secretsGetOperationDefinitions: readonly [typeof secretsGetOperationDefinition] = [\n secretsGetOperationDefinition,\n];\n\nasync function planSecretGet(\n context: RuntimeOperationContext,\n input: SecretsGetInput,\n): Promise<readonly CapabilityRequirement[]> {\n const reference = resolveSecretReferenceForOperation(\n input,\n context.runtime.node,\n context.summary.space,\n );\n let networkSpace = reference.space;\n if (input.space === undefined) {\n try {\n networkSpace = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n )(\"secrets\");\n } catch {\n // Definition-focused callers may omit authenticated identity metadata;\n // the runtime path supplies the owner space before production planning.\n }\n }\n const networkId = resolveEncryptionNetworkId(context.runtime.node, networkSpace);\n\n return [\n {\n service: \"tinycloud.kv\",\n space: reference.space,\n path: reference.permissionPath,\n actions: [\"tinycloud.kv/get\"],\n },\n {\n service: \"tinycloud.encryption\",\n path: networkId,\n actions: [\"tinycloud.encryption/decrypt\"],\n },\n ];\n}\n\nasync function executeSecretGet(\n context: OperationContext,\n input: SecretsGetInput,\n): Promise<OperationExecutionOutcome<SecretsGetOutput>> {\n const reference = resolveSecretReferenceForOperation(\n input,\n context.runtime?.node,\n context.summary.space,\n );\n const node = context.runtime?.node as SecretReadingNode | undefined;\n if (node === undefined || typeof node.readSecret !== \"function\") {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n \"The TinyCloud node could not read the secret.\",\n { retryable: true },\n ),\n };\n }\n\n let result: SecretReadResult;\n try {\n result = await node.readSecret({\n space: reference.space,\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n });\n } catch {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n \"The TinyCloud node could not read the secret.\",\n { retryable: true },\n ),\n };\n }\n\n return classifySecretRead(reference, result);\n}\n\nfunction classifySecretRead(\n reference: SecretReference,\n result: SecretReadResult,\n): OperationExecutionOutcome<SecretsGetOutput> {\n switch (result.status) {\n case \"ok\":\n return { status: \"ok\", output: { value: result.value } };\n case \"not_found\":\n return {\n status: \"setup_required\",\n setup: {\n kind: \"secret_manager\",\n secret: {\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n space: reference.space,\n },\n url: buildSecretSetupUrl(reference),\n message: \"Enter this secret in Secret Manager, then retry the operation.\",\n },\n requiresCallerInput: true,\n };\n case \"permission_required\":\n return {\n status: \"authority_required\",\n missing: [result.hint as unknown as CapabilityRequirement],\n request: { requestId: \"runtime-hint\" },\n approval: {\n kind: \"openkey\",\n requestId: \"runtime-hint\",\n fallback: \"tc auth grant <request-artifact>\",\n },\n };\n case \"node_unreachable\":\n return {\n status: \"error\",\n error: operationError(\n \"NODE_UNREACHABLE\",\n \"The TinyCloud node could not be reached.\",\n { retryable: true },\n ),\n };\n case \"read_failed\":\n case \"corrupt_envelope\":\n return {\n status: \"error\",\n error: operationError(\n \"SECRET_READ_FAILED\",\n \"The secret ciphertext could not be read.\",\n ),\n };\n case \"decrypt_failed\":\n case \"invalid_payload\":\n return {\n status: \"error\",\n error: operationError(\n \"SECRET_DECRYPT_FAILED\",\n \"The secret could not be decrypted.\",\n ),\n };\n }\n\n return {\n status: \"error\",\n error: operationError(\"SECRET_READ_FAILED\", \"The secret read failed.\"),\n };\n}\n\nfunction resolveEncryptionNetworkId(node: unknown, space: string): string {\n const candidate = node as {\n getEncryptionNetworkIdForSpace?: (spaceId: string) => unknown;\n getDefaultEncryptionNetworkId?: () => unknown;\n };\n\n let scoped: unknown;\n try {\n scoped = candidate.getEncryptionNetworkIdForSpace?.(space);\n } catch {\n // A scoped resolver is optional and may fail for a non-primary space.\n }\n if (typeof scoped === \"string\" && scoped.length > 0) return scoped;\n\n let fallback: unknown;\n try {\n fallback = candidate.getDefaultEncryptionNetworkId?.();\n } catch {\n // Both local sources must fail before the operation reports unresolved.\n }\n if (typeof fallback === \"string\" && fallback.length > 0) return fallback;\n\n throw new OperationInvocationError(\n operationError(\n \"ENCRYPTION_NETWORK_UNRESOLVED\",\n \"The encryption network for the target secrets space could not be resolved.\",\n ),\n );\n}\n\ninterface SecretReadingNode {\n readSecret(input: {\n space: string;\n name: string;\n scope?: string;\n }): Promise<SecretReadResult>;\n getEncryptionNetworkIdForSpace?: (spaceId: string) => unknown;\n getDefaultEncryptionNetworkId?: () => unknown;\n}\n","import type { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport nodeSqlParser from \"node-sql-parser\";\nimport { z } from \"zod\";\n\nimport type {\n CapabilityRequirement,\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n RuntimeOperationContext,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { OperationInvocationError, operationError, storageFullOperationError } from \"../errors.js\";\nimport { operationSpaceResolver } from \"../secrets.js\";\nimport { authorizationFailure } from \"./exploration.js\";\n\nconst DEFAULT_MAX_ROWS = 100;\nconst MAX_MAX_ROWS = 1_000;\nconst DEFAULT_MAX_BYTES = 1024 * 1024;\nconst MAX_MAX_BYTES = 4 * 1024 * 1024;\nconst SCHEMA_MAX_ROWS = 500;\nconst SCHEMA_MAX_BYTES = 1024 * 1024;\nconst MAX_PARAMETERS = 100;\nconst MAX_SQL_LENGTH = 64 * 1024;\nconst SQL_WRITE_AUTHORITY_NOTICE =\n \"Approving tinycloud.sql/write grants full read/write/schema mutation authority over this exact database; the MCP tool itself accepts only one parameterized INSERT, UPDATE, or DELETE.\";\n\nconst SCHEMA_QUERY = `SELECT type, name, tbl_name, sql\nFROM sqlite_schema\nWHERE type IN ('table', 'view', 'index', 'trigger')\n AND name NOT LIKE 'sqlite_%'\nORDER BY type, name`;\n\ntype SqlPrimitive = null | number | string;\ninterface SqlBlob {\n readonly type: \"blob\";\n readonly base64: string;\n readonly byteLength: number;\n}\ntype SqlOutputValue = SqlPrimitive | SqlBlob;\ntype SqlInputValue = SqlPrimitive | Readonly<{ type: \"blob\"; base64: string }>;\n\ninterface SqlTargetInput {\n readonly space: string;\n readonly database: string;\n}\n\ninterface SqlQueryInput extends SqlTargetInput {\n readonly sql: string;\n readonly params?: readonly SqlInputValue[];\n readonly maxRows?: number;\n readonly maxBytes?: number;\n}\n\ninterface SqlExecuteInput extends SqlTargetInput {\n readonly sql: string;\n readonly params: readonly SqlInputValue[];\n readonly acknowledgeDatabaseWideAuthority: true;\n}\n\ninterface SqlLimitsOutput {\n readonly maxRows: number;\n readonly maxBytes: number;\n readonly enforcement: \"node-requested-client-verified\";\n}\n\ninterface SqlSchemaInspectOutput {\n readonly space: string;\n readonly database: string;\n readonly objects: readonly {\n readonly type: \"table\" | \"view\" | \"index\" | \"trigger\";\n readonly name: string;\n readonly tableName: string;\n readonly sql?: string;\n }[];\n readonly count: number;\n readonly limits: SqlLimitsOutput;\n}\n\ninterface SqlQueryOutput {\n readonly space: string;\n readonly database: string;\n readonly columns: readonly string[];\n readonly rows: readonly (readonly SqlOutputValue[])[];\n readonly rowCount: number;\n readonly limits: SqlLimitsOutput;\n}\n\ninterface SqlExecuteOutput {\n readonly space: string;\n readonly database: string;\n readonly statementType: \"insert\" | \"update\" | \"delete\";\n readonly changes: number;\n readonly lastInsertRowId: number | null;\n readonly authorityNotice: typeof SQL_WRITE_AUTHORITY_NOTICE;\n}\n\nconst sqlParser = new nodeSqlParser.Parser();\n\nconst SpaceSchema = z.string().min(1).refine(\n (space) =>\n (/^[A-Za-z0-9_-]+$/.test(space) || space.startsWith(\"tinycloud:\")) &&\n !space.includes(\"*\"),\n \"Invalid TinyCloud space.\",\n);\nconst DatabaseSchema = z.string().min(1).max(256).refine(\n (database) =>\n database !== \"/\" &&\n !database.endsWith(\"/\") &&\n !database.includes(\"*\") &&\n !/[\\u0000-\\u001f\\u007f]/.test(database),\n \"Invalid SQLite database name.\",\n);\nconst SafeNumberSchema = z.number().finite().refine(\n (value) => !Number.isInteger(value) || Number.isSafeInteger(value),\n \"SQLite integer parameters must be JavaScript safe integers.\",\n);\nconst Base64Schema = z.string().max(Math.ceil(MAX_MAX_BYTES / 3) * 4).refine(\n isCanonicalBase64,\n \"Invalid base64 BLOB value.\",\n);\nconst SqlInputValueSchema: z.ZodType<SqlInputValue> = z.union([\n z.null(),\n SafeNumberSchema,\n z.string().max(MAX_MAX_BYTES),\n z.object({ type: z.literal(\"blob\"), base64: Base64Schema }).strict(),\n]);\nconst SqlParamsSchema = z.array(SqlInputValueSchema).max(MAX_PARAMETERS).superRefine(\n (params, context) => {\n const totalBytes = params.reduce<number>(\n (total, value) => total + sqlInputValueBytes(value),\n 0,\n );\n if (totalBytes > MAX_MAX_BYTES) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"SQLite query parameters exceed the 4 MiB input limit.\",\n });\n }\n },\n);\nconst RequiredSqlParamsSchema = z.array(SqlInputValueSchema).min(1).max(MAX_PARAMETERS).superRefine(\n (params, context) => {\n const totalBytes = params.reduce<number>(\n (total, value) => total + sqlInputValueBytes(value),\n 0,\n );\n if (totalBytes > MAX_MAX_BYTES) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"SQLite query parameters exceed the 4 MiB input limit.\",\n });\n }\n },\n);\nconst SqlOutputValueSchema: z.ZodType<SqlOutputValue> = z.union([\n z.null(),\n SafeNumberSchema,\n z.string(),\n z.object({\n type: z.literal(\"blob\"),\n base64: z.string(),\n byteLength: z.number().int().nonnegative(),\n }).strict(),\n]);\nconst SqlTargetInputSchema: z.ZodType<SqlTargetInput> = z.object({\n space: SpaceSchema,\n database: DatabaseSchema,\n}).strict();\nconst SqlQueryInputSchema: z.ZodType<SqlQueryInput> = z.object({\n space: SpaceSchema,\n database: DatabaseSchema,\n sql: z.string().min(1).max(MAX_SQL_LENGTH).superRefine((sql, context) => {\n if (!isSingleReadQuery(sql)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"SQL must parse as exactly one SQLite SELECT statement.\",\n });\n }\n }),\n params: SqlParamsSchema.optional(),\n maxRows: z.number().int().positive().max(MAX_MAX_ROWS).optional(),\n maxBytes: z.number().int().positive().max(MAX_MAX_BYTES).optional(),\n}).strict();\nconst SqlExecuteInputSchema: z.ZodType<SqlExecuteInput> = z.object({\n space: SpaceSchema,\n database: DatabaseSchema,\n sql: z.string().min(1).max(MAX_SQL_LENGTH),\n params: RequiredSqlParamsSchema,\n acknowledgeDatabaseWideAuthority: z.literal(true).describe(SQL_WRITE_AUTHORITY_NOTICE),\n}).strict().superRefine((input, context) => {\n if (parseSingleDmlStatement(input.sql, input.params.length) === undefined) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"sql\"],\n message: \"SQL must parse as exactly one parameterized INSERT, UPDATE, or DELETE with one value per positional placeholder.\",\n });\n }\n});\n\nconst SqlLimitsOutputSchema: z.ZodType<SqlLimitsOutput> = z.object({\n maxRows: z.number().int().positive(),\n maxBytes: z.number().int().positive(),\n enforcement: z.literal(\"node-requested-client-verified\"),\n}).strict();\nconst SqlSchemaInspectOutputSchema: z.ZodType<SqlSchemaInspectOutput> = z.object({\n space: z.string().min(1),\n database: z.string().min(1),\n objects: z.array(z.object({\n type: z.enum([\"table\", \"view\", \"index\", \"trigger\"]),\n name: z.string().min(1),\n tableName: z.string().min(1),\n sql: z.string().optional(),\n }).strict()),\n count: z.number().int().nonnegative(),\n limits: SqlLimitsOutputSchema,\n}).strict();\nconst SqlQueryOutputSchema: z.ZodType<SqlQueryOutput> = z.object({\n space: z.string().min(1),\n database: z.string().min(1),\n columns: z.array(z.string()),\n rows: z.array(z.array(SqlOutputValueSchema)),\n rowCount: z.number().int().nonnegative(),\n limits: SqlLimitsOutputSchema,\n}).strict();\nconst SqlExecuteOutputSchema: z.ZodType<SqlExecuteOutput> = z.object({\n space: z.string().min(1),\n database: z.string().min(1),\n statementType: z.enum([\"insert\", \"update\", \"delete\"]),\n changes: z.number().int().nonnegative(),\n lastInsertRowId: z.number().int().nullable(),\n authorityNotice: z.literal(SQL_WRITE_AUTHORITY_NOTICE),\n}).strict();\n\nconst AUTHENTICATED_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n];\nconst SQL_EXPOSURE: OperationExposure = {\n cli: {\n status: \"excluded\",\n reason: \"Existing SQL Commander commands remain the CLI surface.\",\n },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\nconst SQL_SCHEMA_SENSITIVITY: OperationSensitivity = {\n input: [\"/database\"],\n output: [\"/objects\"],\n};\nconst SQL_QUERY_SENSITIVITY: OperationSensitivity = {\n input: [\"/database\", \"/sql\", \"/params\"],\n output: [\"/columns\", \"/rows\"],\n};\nconst SQL_EXECUTE_SENSITIVITY: OperationSensitivity = {\n input: [\"/database\", \"/sql\", \"/params\"],\n output: [\"/lastInsertRowId\"],\n};\n\ntype SqlDefinition =\n | OperationDefinition<SqlTargetInput, SqlSchemaInspectOutput>\n | OperationDefinition<SqlQueryInput, SqlQueryOutput>\n | OperationDefinition<SqlExecuteInput, SqlExecuteOutput>;\n\nexport const sqlOperationDefinitions: readonly SqlDefinition[] = [\n {\n id: \"tinycloud.sql.schema.inspect\",\n version: 1,\n title: \"Inspect a TinyCloud SQLite schema\",\n description: \"List user tables, views, indexes, and triggers in one exact TinyCloud SQLite database using a fixed read-only query.\",\n input: SqlTargetInputSchema,\n output: SqlSchemaInspectOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: SQL_EXPOSURE,\n sensitivity: SQL_SCHEMA_SENSITIVITY,\n authority: planSqlRead,\n execute: executeSqlSchemaInspect,\n },\n {\n id: \"tinycloud.sql.query\",\n version: 1,\n title: \"Query a TinyCloud SQLite database\",\n description: \"Run exactly one parser-approved SELECT against one exact TinyCloud SQLite database. Result limits are requested from the node and verified locally without silent truncation.\",\n input: SqlQueryInputSchema,\n output: SqlQueryOutputSchema,\n effects: [\"read\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: SQL_EXPOSURE,\n sensitivity: SQL_QUERY_SENSITIVITY,\n invalidInputErrorCode: \"SQL_QUERY_INVALID\",\n authority: planSqlRead,\n execute: executeSqlQuery,\n },\n {\n id: \"tinycloud.sql.execute\",\n version: 1,\n title: \"Execute a TinyCloud SQLite DML statement\",\n description: `Run exactly one parameterized INSERT, UPDATE, or DELETE against one exact TinyCloud SQLite database. ${SQL_WRITE_AUTHORITY_NOTICE}`,\n input: SqlExecuteInputSchema,\n output: SqlExecuteOutputSchema,\n effects: [\"write\", \"destructive\"],\n runtime: \"authenticated\",\n postures: AUTHENTICATED_POSTURES,\n exposure: SQL_EXPOSURE,\n sensitivity: SQL_EXECUTE_SENSITIVITY,\n invalidInputErrorCode: \"SQL_QUERY_INVALID\",\n authority: planSqlWrite,\n execute: executeSqlDml,\n },\n];\n\nasync function planSqlRead(\n context: RuntimeOperationContext,\n input: SqlTargetInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveSqlSpace(context, input.space);\n return [{\n service: \"tinycloud.sql\",\n space,\n path: input.database,\n actions: [\"tinycloud.sql/read\"],\n }];\n}\n\nasync function planSqlWrite(\n context: RuntimeOperationContext,\n input: SqlExecuteInput,\n): Promise<readonly CapabilityRequirement[]> {\n const space = resolveSqlSpace(context, input.space);\n return [{\n service: \"tinycloud.sql\",\n space,\n path: input.database,\n actions: [\"tinycloud.sql/write\"],\n description: SQL_WRITE_AUTHORITY_NOTICE,\n }];\n}\n\nasync function executeSqlSchemaInspect(\n context: OperationContext,\n input: SqlTargetInput,\n): Promise<OperationExecutionOutcome<SqlSchemaInspectOutput>> {\n try {\n const runtime = runtimeContext(context);\n const space = resolveSqlSpace(runtime, input.space);\n const result = await runtimeNode(runtime)\n .sqlForSpace(space)\n .db(input.database)\n .query(SCHEMA_QUERY, [], { maxRows: SCHEMA_MAX_ROWS, maxBytes: SCHEMA_MAX_BYTES });\n if (!result.ok) return sqlServiceFailure(result.error, \"inspect the SQLite schema\");\n\n const normalized = normalizeQueryResult(result.data, SCHEMA_MAX_ROWS, SCHEMA_MAX_BYTES);\n const objects = normalized.rows.map((row) => schemaObject(row));\n return {\n status: \"ok\",\n output: {\n space,\n database: input.database,\n objects,\n count: objects.length,\n limits: limitsOutput(SCHEMA_MAX_ROWS, SCHEMA_MAX_BYTES),\n },\n };\n } catch (error) {\n return sqlFailure(error, \"inspect the SQLite schema\");\n }\n}\n\nasync function executeSqlQuery(\n context: OperationContext,\n input: SqlQueryInput,\n): Promise<OperationExecutionOutcome<SqlQueryOutput>> {\n try {\n if (!isSingleReadQuery(input.sql)) {\n return {\n status: \"error\",\n error: operationError(\n \"SQL_QUERY_INVALID\",\n \"SQL must parse as exactly one SQLite SELECT statement.\",\n ),\n };\n }\n\n const runtime = runtimeContext(context);\n const space = resolveSqlSpace(runtime, input.space);\n const maxRows = input.maxRows ?? DEFAULT_MAX_ROWS;\n const maxBytes = input.maxBytes ?? DEFAULT_MAX_BYTES;\n const params = (input.params ?? []).map(decodeSqlInputValue);\n const result = await runtimeNode(runtime)\n .sqlForSpace(space)\n .db(input.database)\n .query(input.sql, params, { maxRows, maxBytes });\n if (!result.ok) return sqlServiceFailure(result.error, \"run the SQLite query\");\n\n const normalized = normalizeQueryResult(result.data, maxRows, maxBytes);\n return {\n status: \"ok\",\n output: {\n space,\n database: input.database,\n columns: normalized.columns,\n rows: normalized.rows,\n rowCount: normalized.rows.length,\n limits: limitsOutput(maxRows, maxBytes),\n },\n };\n } catch (error) {\n return sqlFailure(error, \"run the SQLite query\");\n }\n}\n\nasync function executeSqlDml(\n context: OperationContext,\n input: SqlExecuteInput,\n): Promise<OperationExecutionOutcome<SqlExecuteOutput>> {\n try {\n const statementType = parseSingleDmlStatement(input.sql, input.params.length);\n if (statementType === undefined) {\n return {\n status: \"error\",\n error: operationError(\n \"SQL_QUERY_INVALID\",\n \"SQL must parse as exactly one parameterized INSERT, UPDATE, or DELETE with one value per positional placeholder.\",\n ),\n };\n }\n\n const runtime = runtimeContext(context);\n const space = resolveSqlSpace(runtime, input.space);\n const result = await runtimeNode(runtime)\n .sqlForSpace(space)\n .db(input.database)\n .execute(input.sql, input.params.map(decodeSqlInputValue));\n if (!result.ok) return authorizationFailure(result.error, \"execute the SQLite statement\") ?? sqlMutationFailure(result.error);\n const normalized = normalizeExecuteResult(result.data);\n return {\n status: \"ok\",\n output: {\n space,\n database: input.database,\n statementType,\n ...normalized,\n authorityNotice: SQL_WRITE_AUTHORITY_NOTICE,\n },\n };\n } catch (error) {\n if (error instanceof OperationInvocationError) return { status: \"error\", error: error.operationError };\n return authorizationFailure(error, \"execute the SQLite statement\") ?? sqlMutationFailure(error);\n }\n}\n\nfunction isSingleReadQuery(sql: string): boolean {\n const ast = parseSingleStatement(sql);\n return ast !== undefined && ast.type === \"select\";\n}\n\nfunction parseSingleDmlStatement(\n sql: string,\n parameterCount: number,\n): \"insert\" | \"update\" | \"delete\" | undefined {\n const ast = parseSingleStatement(sql);\n if (\n ast === undefined ||\n (ast.type !== \"insert\" && ast.type !== \"update\" && ast.type !== \"delete\") ||\n ast.with !== undefined && ast.with !== null\n ) {\n return undefined;\n }\n const placeholders = countPositionalParameters(ast);\n return placeholders > 0 && placeholders === parameterCount ? ast.type : undefined;\n}\n\nfunction parseSingleStatement(sql: string): Record<string, unknown> | undefined {\n try {\n const ast = sqlParser.astify(sql, { database: \"sqlite\" }) as unknown;\n return !Array.isArray(ast) && isRecord(ast) ? ast : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction countPositionalParameters(value: unknown): number {\n if (Array.isArray(value)) {\n return value.reduce((count, entry) => count + countPositionalParameters(entry), 0);\n }\n if (!isRecord(value)) return 0;\n const current = value.type === \"origin\" && value.value === \"?\" ? 1 : 0;\n return Object.values(value).reduce<number>(\n (count, entry) => count + countPositionalParameters(entry),\n current,\n );\n}\n\nfunction decodeSqlInputValue(value: SqlInputValue): null | number | string | Uint8Array {\n if (isRecord(value) && value.type === \"blob\") {\n return new Uint8Array(Buffer.from(value.base64 as string, \"base64\"));\n }\n return value as null | number | string;\n}\n\nfunction normalizeQueryResult(\n value: unknown,\n maxRows: number,\n maxBytes: number,\n): Readonly<{ columns: readonly string[]; rows: readonly (readonly SqlOutputValue[])[] }> {\n if (!isRecord(value) || !Array.isArray(value.columns) || !Array.isArray(value.rows)) {\n throw unsafeSqlValue(\"The node returned an invalid SQLite query result.\");\n }\n const columns = value.columns.map((column) => {\n if (typeof column !== \"string\") {\n throw unsafeSqlValue(\"The node returned an invalid SQLite column name.\");\n }\n return column;\n });\n const rows = value.rows.map((row) => {\n if (!Array.isArray(row) || row.length !== columns.length) {\n throw unsafeSqlValue(\"The node returned an invalid SQLite row.\");\n }\n return row.map(normalizeSqlOutputValue);\n });\n\n const serializedBytes = Buffer.byteLength(JSON.stringify({ columns, rows }), \"utf8\");\n if (rows.length > maxRows || serializedBytes > maxBytes) {\n throw new OperationInvocationError(operationError(\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"The SQLite query result exceeded the requested result limits.\",\n {\n details: {\n maxRows,\n maxBytes,\n returnedRows: rows.length,\n returnedBytes: serializedBytes,\n },\n },\n ));\n }\n return { columns, rows };\n}\n\nfunction normalizeSqlOutputValue(value: unknown): SqlOutputValue {\n if (value === null || typeof value === \"string\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {\n throw unsafeSqlValue(\"The node returned an integer that cannot be represented safely in JavaScript.\");\n }\n return value;\n }\n if (value instanceof Uint8Array) return encodeBlob(value);\n if (Array.isArray(value) && value.every(isByte)) {\n return encodeBlob(Uint8Array.from(value));\n }\n if (isRecord(value) && value.type === \"Buffer\" && Array.isArray(value.data) && value.data.every(isByte)) {\n return encodeBlob(Uint8Array.from(value.data));\n }\n throw unsafeSqlValue(\"The node returned an unsupported SQLite value.\");\n}\n\nfunction normalizeExecuteResult(\n value: unknown,\n): Readonly<{ changes: number; lastInsertRowId: number | null }> {\n if (\n !isRecord(value) ||\n !Number.isSafeInteger(value.changes) ||\n (value.changes as number) < 0 ||\n (\n value.lastInsertRowId !== null &&\n !Number.isSafeInteger(value.lastInsertRowId)\n )\n ) {\n throw unsafeSqlValue(\"The node returned SQLite mutation metadata that cannot be represented safely in JavaScript.\");\n }\n return {\n changes: value.changes as number,\n lastInsertRowId: value.lastInsertRowId as number | null,\n };\n}\n\nfunction schemaObject(row: readonly SqlOutputValue[]): SqlSchemaInspectOutput[\"objects\"][number] {\n const [type, name, tableName, sql] = row;\n if (\n (type !== \"table\" && type !== \"view\" && type !== \"index\" && type !== \"trigger\") ||\n typeof name !== \"string\" ||\n typeof tableName !== \"string\" ||\n (sql !== null && typeof sql !== \"string\")\n ) {\n throw unsafeSqlValue(\"The node returned an invalid SQLite schema record.\");\n }\n return {\n type,\n name,\n tableName,\n ...(sql === null ? {} : { sql }),\n };\n}\n\nfunction limitsOutput(maxRows: number, maxBytes: number): SqlLimitsOutput {\n return { maxRows, maxBytes, enforcement: \"node-requested-client-verified\" };\n}\n\nfunction runtimeContext(context: OperationContext): RuntimeOperationContext {\n if (context.runtime === undefined) {\n throw new TypeError(\"Authenticated operation runtime is unavailable.\");\n }\n return context as RuntimeOperationContext;\n}\n\nfunction runtimeNode(context: RuntimeOperationContext): TinyCloudNode {\n return context.runtime.node as TinyCloudNode;\n}\n\nfunction resolveSqlSpace(context: RuntimeOperationContext, space: string): string {\n const resolved = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n )(space);\n const name = resolved.split(\":\").at(-1)?.toLowerCase();\n if (name === \"secrets\" || name === \"account\") {\n throw new OperationInvocationError(operationError(\n \"INPUT_INVALID\",\n \"Generic SQL operations cannot access protected TinyCloud account or secrets spaces.\",\n ));\n }\n return resolved;\n}\n\nfunction encodeBlob(value: Uint8Array): SqlBlob {\n return {\n type: \"blob\",\n base64: Buffer.from(value).toString(\"base64\"),\n byteLength: value.byteLength,\n };\n}\n\nfunction unsafeSqlValue(message: string): OperationInvocationError {\n return new OperationInvocationError(operationError(\"SQL_VALUE_UNSAFE\", message));\n}\n\nfunction sqlFailure(\n error: unknown,\n action: string,\n): OperationExecutionOutcome<never> {\n if (error instanceof OperationInvocationError) {\n return { status: \"error\", error: error.operationError };\n }\n return authorizationFailure(error, action) ?? nodeFailure(action);\n}\n\nfunction nodeFailure(action: string): OperationExecutionOutcome<never> {\n return {\n status: \"error\",\n error: operationError(\n \"NODE_ERROR\",\n `The TinyCloud node could not ${action}.`,\n { retryable: true },\n ),\n };\n}\n\nfunction sqlServiceFailure(\n error: unknown,\n action: string,\n): OperationExecutionOutcome<never> {\n const auth = authorizationFailure(error, action);\n if (auth !== undefined) return auth;\n if (isRecord(error) && error.code === \"SQL_RESPONSE_TOO_LARGE\") {\n return {\n status: \"error\",\n error: operationError(\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"The SQLite query result exceeded the requested result limits.\",\n ),\n };\n }\n return nodeFailure(action);\n}\n\nfunction sqlMutationFailure(error: unknown): OperationExecutionOutcome<never> {\n // A storage rejection leaves nothing written, so that outcome is known.\n const storageFull = storageFullOperationError(error);\n if (storageFull) return { status: \"error\", error: storageFull };\n return {\n status: \"error\",\n error: operationError(\n \"SQL_EXECUTION_FAILED\",\n \"The SQLite statement outcome is unknown; inspect database state before considering another write.\",\n { retryable: false },\n ),\n };\n}\n\nfunction isCanonicalBase64(value: string): boolean {\n if (value === \"\") return true;\n if (value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return false;\n return Buffer.from(value, \"base64\").toString(\"base64\") === value;\n}\n\nfunction sqlInputValueBytes(value: SqlInputValue): number {\n if (typeof value === \"string\") return Buffer.byteLength(value, \"utf8\");\n if (isRecord(value) && value.type === \"blob\") {\n return Buffer.from(value.base64 as string, \"base64\").byteLength;\n }\n return 8;\n}\n\nfunction isByte(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 255;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { z } from \"zod\";\n\nimport type { OperationError, OperationErrorCode } from \"./errors.js\";\n\n/** A stable, cross-surface operation identifier. */\nexport type OperationId = string;\n\n/** JSON Pointer syntax from RFC 6901, including the empty pointer for a root value. */\nexport type JsonPointer = \"\" | `/${string}`;\n\nexport type OperationEffect =\n | \"read\"\n | \"local_write\"\n | \"write\"\n | \"destructive\"\n | \"external\";\n\nexport type TinyCloudPosture =\n | \"owner-openkey\"\n | \"delegate-session\"\n | \"local-owner-key\"\n | \"unauthenticated\";\n\nexport type OperationOperatorType = \"human\" | \"agent\";\n\nexport type SurfaceDisposition =\n | Readonly<{ status: \"required\" }>\n | Readonly<{ status: \"excluded\"; reason: string }>;\n\n/**\n * Safe identity reported with every result. This deliberately excludes keys,\n * tokens, delegations, grants, and operation inputs or outputs.\n */\nexport interface OperationContextSummary {\n readonly profile: string;\n readonly host: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType?: OperationOperatorType;\n readonly principalDid?: string;\n readonly sessionDid?: string;\n readonly ownerDid?: string;\n readonly space?: string;\n}\n\n/**\n * The profile foundation constructs this context for every invocation. The\n * invocation target never supplies an execution context or runtime object.\n */\nexport interface OperationContext {\n readonly summary: OperationContextSummary;\n /** Present for every normal invocation; optional for focused definition tests. */\n readonly runtime?: OperationRuntime;\n}\n\n/**\n * Per-invocation authority that is constructed inside operations. It is never\n * caller supplied and it is deliberately absent from result envelopes.\n */\nexport interface OperationRuntime {\n readonly node: unknown;\n readonly granted: readonly CapabilityRequirement[];\n /** Diagnostics gathered while building the runtime, attached to the result. */\n readonly warnings?: readonly OperationWarning[];\n}\n\n/**\n * Why a stored grant was not used. A fixed vocabulary: diagnostics never\n * carry exception text, node responses, URLs or other stored transport data.\n * `unbound`: the record has no valid request binding where one is required;\n * `outside_request`: its signed authority exceeds its binding.\n */\nexport const STORED_GRANT_SKIP_REASONS = [\n \"malformed\",\n \"unbound\",\n \"outside_request\",\n \"host_mismatch\",\n \"expired\",\n \"cid_mismatch\",\n \"authority_invalid\",\n \"proof_missing\",\n \"proof_invalid\",\n \"owner_mismatch\",\n \"audience_mismatch\",\n \"resources_mismatch\",\n \"unsupported\",\n \"activation_rejected\",\n \"invalid\",\n] as const;\n\nexport type StoredGrantSkipReason = typeof STORED_GRANT_SKIP_REASONS[number];\n\n/**\n * The string form of every delegation CID TinyCloud computes: CIDv1, raw\n * codec, BLAKE3-256 multihash, base32. A published `grantCid` also has to be\n * the CID recomputed from the stored authorization bytes.\n */\nexport const DELEGATION_CID_PATTERN = \"^bafkr4i[a-z2-7]{52}$\";\n\n/**\n * A non-fatal diagnostic attached to a result. `STORED_GRANT_SKIPPED`: a\n * stored grant failed validation and gave no authority; `grantCid` is present\n * only when the stored CID is the CID of the stored authorization bytes.\n */\nexport interface OperationWarning {\n readonly code: \"STORED_GRANT_SKIPPED\";\n readonly reason: StoredGrantSkipReason;\n readonly grantCid?: string;\n}\n\n/** Context given to planners and handlers after runtime authentication. */\nexport interface RuntimeOperationContext extends OperationContext {\n readonly runtime: OperationRuntime;\n}\n\nexport type AuthorityPlanningContext = RuntimeOperationContext;\n\n/**\n * Capability details are finalized by the authority/artifacts increment. The\n * kernel intentionally preserves them as canonical operation-owned data.\n */\nexport type CapabilityRequirement = Readonly<Record<string, unknown>>;\n\nexport interface PermissionRequestArtifact {\n readonly requestId: string;\n readonly [key: string]: unknown;\n}\n\nexport interface ApprovalAction {\n readonly kind: \"openkey\";\n readonly requestId: string;\n readonly url?: string;\n readonly fallback: string;\n}\n\nexport interface SetupAction {\n readonly kind: string;\n readonly [key: string]: unknown;\n}\n\nexport interface OperationRef {\n readonly operationId: OperationId;\n readonly operationVersion: number;\n}\n\nexport interface RetryDescriptor extends OperationRef {\n readonly inputDigest: string;\n readonly safeInput?: Readonly<Record<string, unknown>>;\n readonly requiresCallerInput: boolean;\n}\n\nexport interface OperationSensitivity {\n readonly input: readonly JsonPointer[];\n readonly output: readonly JsonPointer[];\n}\n\n/**\n * An inspection operation may read safe local profile state without creating a\n * node or authenticating. Every other operation requires an authenticated\n * runtime before planning or execution.\n */\nexport type OperationRuntimeRequirement = \"authenticated\" | \"inspection\";\n\nexport interface OperationExposure {\n readonly cli: SurfaceDisposition;\n readonly mcp: SurfaceDisposition;\n readonly skill: SurfaceDisposition;\n readonly docs: SurfaceDisposition;\n}\n\nexport interface OperationOkResult<O> {\n readonly status: \"ok\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly output: O;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationAuthorityRequiredResult {\n readonly status: \"authority_required\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly missing: readonly CapabilityRequirement[];\n readonly request: PermissionRequestArtifact;\n readonly approval: ApprovalAction;\n readonly retry: RetryDescriptor;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationSetupRequiredResult {\n readonly status: \"setup_required\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly setup: SetupAction;\n readonly retry: RetryDescriptor;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationErrorResult {\n readonly status: \"error\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly error: OperationError;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport type OperationResult<O> =\n | OperationOkResult<O>\n | OperationAuthorityRequiredResult\n | OperationSetupRequiredResult\n | OperationErrorResult;\n\n/**\n * Handler outcomes intentionally omit invocation-owned operation, context, and\n * retry metadata. The kernel attaches those values after validation.\n */\nexport type OperationExecutionOutcome<O> =\n | Readonly<{ status: \"ok\"; output: O }>\n | Readonly<{\n status: \"authority_required\";\n missing: readonly CapabilityRequirement[];\n request: PermissionRequestArtifact;\n approval: ApprovalAction;\n requiresCallerInput?: boolean;\n }>\n | Readonly<{\n status: \"setup_required\";\n setup: SetupAction;\n requiresCallerInput?: boolean;\n }>\n | Readonly<{ status: \"error\"; error: OperationError }>;\n\n/**\n * Internal registry material. It is intentionally never re-exported by the\n * package root: projections can execute only by operation id and version.\n */\nexport interface OperationDefinition<I, O> {\n readonly id: OperationId;\n readonly version: 1;\n readonly title: string;\n readonly description: string;\n readonly input: z.ZodType<I>;\n readonly output: z.ZodType<O>;\n readonly effects: readonly OperationEffect[];\n readonly runtime: OperationRuntimeRequirement;\n readonly postures: readonly TinyCloudPosture[];\n readonly exposure: OperationExposure;\n readonly sensitivity: OperationSensitivity;\n /** A definition may give malformed transport artifacts a stable error code. */\n readonly invalidInputErrorCode?: OperationErrorCode;\n readonly authority: (\n context: AuthorityPlanningContext,\n input: I,\n ) => Promise<readonly CapabilityRequirement[]>;\n readonly execute: (\n context: OperationContext,\n input: I,\n ) => Promise<OperationExecutionOutcome<O>>;\n}\n\n/**\n * The only caller-controlled invocation settings. `privateKey` is a CLI-only,\n * nonpersistable override; it is deliberately excluded from result metadata,\n * retry descriptors, diagnostics, and all state written by this package.\n */\nexport interface InvocationTarget {\n readonly profile?: string;\n readonly host?: string;\n /**\n * Absolute home directory used for this invocation's TinyCloud profile\n * state. Hosted projections set this per authenticated principal so\n * concurrent tenants never share process-global TC_HOME state.\n */\n readonly stateRoot?: string;\n readonly allowOwnerProfile?: boolean;\n readonly privateKey?: string;\n}\n\n/**\n * Copy only the identity fields allowed in a public result. Keeping this\n * projection centralized prevents a profile/runtime implementation from\n * accidentally smuggling execution material into an envelope.\n */\nexport function safeOperationContextSummary(\n summary: OperationContextSummary,\n): OperationContextSummary {\n return {\n profile: summary.profile,\n host: summary.host,\n posture: summary.posture,\n ...(summary.operatorType === undefined\n ? {}\n : { operatorType: summary.operatorType }),\n ...(summary.principalDid === undefined\n ? {}\n : { principalDid: summary.principalDid }),\n ...(summary.sessionDid === undefined ? {} : { sessionDid: summary.sessionDid }),\n ...(summary.ownerDid === undefined ? {} : { ownerDid: summary.ownerDid }),\n ...(summary.space === undefined ? {} : { space: summary.space }),\n };\n}\n","import { join } from \"node:path\";\n\n// Keep the value import namespace-shaped so modules that import this one stay\n// compatible with lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\nimport type {\n PermissionEntry,\n PortableDelegation,\n RuntimeDelegationActivator,\n ValidatedRuntimeDelegation,\n} from \"@tinycloud/node-sdk\";\n\nimport { DelegationRequestBindingSchema } from \"./artifacts.js\";\nimport { delegationWithinRequest, type OperationSpaceResolver } from \"./authority.js\";\nimport { STORED_GRANT_SKIP_REASONS, type StoredGrantSkipReason } from \"./contract.js\";\nimport {\n profilePath,\n readAdditionalDelegations,\n readJson,\n readSession,\n updateProfileStore,\n withProfileLock,\n writeJsonAtomic,\n} from \"./state.js\";\n\nexport { operationSpaceResolver } from \"./secrets.js\";\n\n/**\n * Request bindings for delegations stored in `additional-delegations.json`.\n *\n * A compact-UCAN or signed-login (SIWE) record replays only when its\n * `authorityRequest` binding is valid and the capabilities its signed bytes\n * grant fit inside the binding's `requested`. Validated activation checks that\n * before anything is activated. Three writers produce bindings:\n *\n * - `tinycloud.auth.import`: the stored request the delegation was checked\n * against (`requestId` is that request's).\n * - `tc auth import` of an artifact with no request: exactly the delegation's\n * own signed capabilities (`unbound-import:<cid>`).\n * - The one-time migration of records stored before bindings existed: exactly\n * each record's own signed capabilities (`migrated:<cid>`).\n * - The CLI's own grants (`tc auth request --grant`, permission escalation),\n * once checked against the request they answer: exactly each grant's own\n * signed capabilities (`cli-grant:<cid>`). Their signed-login records carry\n * the `siweProof` replay verifies them from.\n *\n * Signed-login records the CLI stored before it kept a `siweProof` cannot be\n * verified here and keep their legacy CLI replay.\n *\n * The binding is local profile data. It stops records written by any other\n * path from granting authority. It does not stop someone who can write the\n * profile directory, who already holds the session key and the signed bytes.\n */\n\nexport type BindingSource = \"migration\" | \"unbound-import\" | \"cli-grant\";\n\nconst REQUEST_ID_PREFIX: Record<BindingSource, string> = {\n migration: \"migrated\",\n \"unbound-import\": \"unbound-import\",\n \"cli-grant\": \"cli-grant\",\n};\n\n/** The audit note written beside a binding the record's writer synthesized. */\nexport const BINDING_NOTES: Record<BindingSource, string> = {\n migration:\n \"Stored without a request binding before bindings were required. Bound at migration to exactly \" +\n \"its own signed capabilities, so replay refuses any delegation in this record that exceeds them.\",\n \"unbound-import\":\n \"Imported by `tc auth import` without a stored request. Bound to exactly its own signed \" +\n \"capabilities, so replay refuses any delegation in this record that exceeds them.\",\n \"cli-grant\":\n \"Granted to this CLI by `tc auth request --grant` or a permission escalation, and checked \" +\n \"against the request it answered. Bound to exactly its own signed capabilities, so replay \" +\n \"refuses any delegation in this record that exceeds them.\",\n};\n\n/** Short so a busy profile only defers migration to a later runtime. */\nconst MIGRATION_LOCK_TIMEOUT_MS = 250;\n\n/** The per-profile marker: present once that profile's unbound records were migrated. */\nexport function bindingMigrationPath(profile: string): string {\n return join(profilePath(profile), \"delegation-binding-migration.json\");\n}\n\n/**\n * How replay treats a stored record:\n *\n * - `compact` and `signed-login` records go through validated activation and\n * the binding rule.\n * - `other` records keep the CLI's legacy replay: an unbound record whose\n * bytes are not compact and that has no `siweProof`, which is how earlier\n * CLI releases stored their own signed-login grants. The operations runtime\n * never installs them.\n * - `refused` records install nothing anywhere.\n *\n * A record is `refused` unless its `delegationHeader` has exactly one own\n * key, `Authorization`, with a string value: header names are matched\n * case-insensitively on the wire, and other value types are stringified, so\n * any other shape could reach the node as authorization bytes this rule never\n * read. Bytes containing a `.` are never `other`: a CACAO has none, and\n * validated activation refuses anything compact-shaped that it cannot parse.\n * A record with an `authorityRequest` (valid or not) is never `other`: the\n * legacy path cannot hold it to a binding, so dropping a `siweProof` cannot\n * route a bound signed-login delegation around its binding.\n */\nexport function storedDelegationKind(\n entry: unknown,\n): \"compact\" | \"signed-login\" | \"other\" | \"refused\" {\n // A stored element that is not an object is not a record at all.\n if (!isRecord(entry)) return \"refused\";\n const delegation = entry.delegation;\n if (!isRecord(delegation)) return \"refused\";\n const header = delegation.delegationHeader;\n if (\n !isRecord(header) ||\n Object.keys(header).length !== 1 ||\n !Object.prototype.hasOwnProperty.call(header, \"Authorization\") ||\n typeof header.Authorization !== \"string\"\n ) {\n return \"refused\";\n }\n if (\"siweProof\" in delegation) return \"signed-login\";\n if (header.Authorization.includes(\".\")) return \"compact\";\n return \"authorityRequest\" in entry ? \"refused\" : \"other\";\n}\n\n/**\n * What replay holds a stored record to: its binding's `requested`, `\"signed\"`\n * for an unbound compact record before the profile has migrated (it installs\n * with its own signed authority, as before bindings existed), or `undefined`\n * when the record installs nothing.\n */\nexport function replayLimit(\n entry: unknown,\n migrated: boolean,\n): readonly PermissionEntry[] | \"signed\" | undefined {\n const kind = storedDelegationKind(entry);\n if (!isRecord(entry) || (kind !== \"compact\" && kind !== \"signed-login\")) return undefined;\n const binding = DelegationRequestBindingSchema.safeParse(entry.authorityRequest);\n if (binding.success) return binding.data.requested;\n return !migrated && kind === \"compact\" && !(\"authorityRequest\" in entry) ? \"signed\" : undefined;\n}\n\n/**\n * Binds a record to `requested`, with an audit note naming where the binding\n * came from. Throws when `requested` cannot form a valid binding.\n */\nfunction bindToRequest<T extends { readonly delegation: { readonly cid: string } }>(\n record: T,\n requested: readonly PermissionEntry[],\n source: BindingSource,\n recordedAt = new Date().toISOString(),\n): T & Record<\"authorityRequest\" | \"authorityRequestAudit\", unknown> {\n return {\n ...record,\n authorityRequest: DelegationRequestBindingSchema.parse({\n requestId: `${REQUEST_ID_PREFIX[source]}:${record.delegation.cid}`,\n requested: structuredClone(requested),\n }),\n authorityRequestAudit: { source, recordedAt, note: BINDING_NOTES[source] },\n };\n}\n\n/**\n * Binds the record of one of the CLI's own grants, already checked against\n * the request it answers, to exactly the capabilities its signed bytes grant.\n * They are read through the validated activation replay uses (nothing is\n * activated), so the binding is the authority replay will derive. Throws when\n * validated activation cannot read them for `node`'s session.\n */\nexport async function bindCliGrant<T extends { readonly delegation: PortableDelegation }>(\n node: RuntimeDelegationActivator,\n record: T,\n host: string,\n): Promise<T & Record<\"authorityRequest\" | \"authorityRequestAudit\", unknown>> {\n const signed = await signedCapabilities(node, record.delegation, host);\n if (signed === undefined) {\n throw new Error(\"The grant's signed authority could not be validated for this session.\");\n }\n return bindToRequest(record, signed, \"cli-grant\");\n}\n\n/**\n * Validates and activates a compact delegation that `tc auth import` received\n * without a stored request, through the same validated activation replay uses,\n * and returns its record bound to exactly the capabilities its signed bytes\n * grant. Throws when validation or activation fails.\n */\nexport async function activateUnboundCompactImport(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<{ delegation: PortableDelegation; permissions: PermissionEntry[] } & Record<string, unknown>> {\n const activated = await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, { host });\n return bindToRequest(\n // The record keeps the delegation as imported; replay validates it again.\n { delegation, permissions: [...activated.effectivePermissions] },\n activated.effectivePermissions,\n \"unbound-import\",\n );\n}\n\n/**\n * The stored records after adding records written without a stored request\n * (by `tc auth import` or a CLI grant). A stored record for the same CID that\n * carries an `authorityRequest` is kept as it is, so this route never drops,\n * replaces or weakens a binding; otherwise each record replaces every row for\n * its CID, at the first one's position, or is appended. Callers write the\n * result under the profile lock they already use for this store.\n */\nexport function mergeDelegationsWithoutRequest(\n stored: readonly unknown[],\n incoming: readonly ({ readonly delegation: { readonly cid: string } } & Record<string, unknown>)[],\n): unknown[] {\n let records = [...stored];\n for (const record of incoming) {\n const cid = record.delegation.cid;\n if (records.some((entry) => storedCid(entry) === cid && isRecord(entry) && \"authorityRequest\" in entry)) continue;\n const position = records.findIndex((entry) => storedCid(entry) === cid);\n const others = records.filter((entry) => storedCid(entry) !== cid);\n records = position === -1\n ? [...records, record]\n : [...others.slice(0, position), record, ...others.slice(position)];\n }\n return records;\n}\n\n/**\n * Runs before replay reads the profile's records, so those records and the\n * migration marker agree. Returns whether the profile has migrated.\n *\n * Migration runs under the profile lock, and only while the profile's\n * persisted session is still the one `node` restored: a session rotated since\n * the restore leaves migration to a runtime of the new session. Each compact\n * record with no `authorityRequest` is handled on its own: if validated\n * activation can read its signed capabilities (CID, expiry, audience and\n * declared resources checked, nothing activated) and they form a valid\n * binding, the record is bound to exactly those capabilities; otherwise it\n * stays unbound, is listed in the marker's `unbound`, and installs nothing\n * after migration. A compact record whose capabilities cannot be read could\n * not activate for this session either. `migrate` must be false unless `node`\n * holds the profile's own restored session.\n *\n * Migration is best-effort and restartable. The bound records are written\n * first and the marker last; a busy lock or any failure before the marker\n * leaves the profile unmigrated, so this runtime replays under the\n * pre-migration rule and the next one migrates again. Records already bound\n * by an interrupted run keep their bindings.\n */\nexport async function prepareStoredDelegationReplay(\n profile: string,\n node: RuntimeDelegationActivator,\n options: { readonly host: string; readonly migrate: boolean },\n): Promise<boolean> {\n if (await bindingMigrationRecorded(profile)) return true;\n // A persisted session without a `verificationMethod`, or one this node did\n // not restore, never migrates here; skip the lock rather than take it for\n // nothing on every command.\n if (!options.migrate || !await holdsPersistedSession(profile, node)) return false;\n try {\n return await withProfileLock(profile, async () => {\n if (await bindingMigrationRecorded(profile)) return true;\n // Checked again under the lock: a session rotated since the restore\n // leaves migration to a runtime of the new session.\n if (!await holdsPersistedSession(profile, node)) return false;\n const recordedAt = new Date().toISOString();\n const bound = new Map<string, Record<string, unknown>>();\n const unbound: string[] = [];\n for (const entry of await readAdditionalDelegations<unknown>(profile)) {\n // Elements that are not objects are skipped: they install nothing.\n if (!isRecord(entry) || \"authorityRequest\" in entry || storedDelegationKind(entry) !== \"compact\") continue;\n const migrated = await migratedRecord(node, entry, options.host, recordedAt);\n if (migrated === undefined) unbound.push(String(storedCid(entry)));\n else bound.set(recordKey(entry)!, migrated);\n }\n if (bound.size > 0) {\n await updateProfileStore<unknown, void>(profile, \"additional-delegations\", (records) => ({\n records: records.map((entry) => {\n const key = !isRecord(entry) || \"authorityRequest\" in entry ? undefined : recordKey(entry);\n return (key === undefined ? undefined : bound.get(key)) ?? entry;\n }),\n result: undefined,\n }));\n }\n await writeJsonAtomic(bindingMigrationPath(profile), {\n formatVersion: 1,\n migratedAt: recordedAt,\n bound: [...bound.values()].map(storedCid),\n unbound,\n });\n return true;\n }, { timeoutMs: MIGRATION_LOCK_TIMEOUT_MS });\n } catch {\n return false;\n }\n}\n\n/** Whether the profile's persisted session is the one `node` restored. */\nasync function holdsPersistedSession(profile: string, node: RuntimeDelegationActivator): Promise<boolean> {\n try {\n const persisted = await readSession<Record<string, unknown>>(profile);\n return typeof persisted?.verificationMethod === \"string\" &&\n typeof node.sessionDid === \"string\" &&\n persisted.verificationMethod.split(\"#\", 1)[0] === node.sessionDid.split(\"#\", 1)[0];\n } catch {\n return false;\n }\n}\n\n/** One record's migration: bound to its own signed capabilities, or `undefined` if it cannot be. */\nasync function migratedRecord(\n node: RuntimeDelegationActivator,\n entry: Record<string, unknown>,\n host: string,\n recordedAt: string,\n): Promise<Record<string, unknown> | undefined> {\n const delegation = normalizeStoredDelegation(entry);\n if (delegation === undefined) return undefined;\n const signed = await signedCapabilities(node, delegation, host);\n if (signed === undefined) return undefined;\n try {\n // The stored delegation is kept exactly as it was; only the binding is added.\n return bindToRequest({ ...entry, delegation: { ...entry.delegation as object, cid: delegation.cid } }, signed, \"migration\", recordedAt);\n } catch {\n // Signed capabilities a request binding cannot hold (an empty action, say).\n return undefined;\n }\n}\n\n/**\n * What replay did with one stored record. `skipped` records grant nothing and\n * carry a fixed reason code that is safe to publish; `not-replayed` records\n * are routine (expired) and give nothing to act on.\n */\nexport type StoredDelegationReplay =\n | { readonly status: \"installed\"; readonly delegation: ValidatedRuntimeDelegation }\n | { readonly status: \"skipped\"; readonly reason: StoredGrantSkipReason }\n | { readonly status: \"not-replayed\" };\n\nconst NOT_REPLAYED: StoredDelegationReplay = { status: \"not-replayed\" };\n\nfunction skipped(reason: StoredGrantSkipReason): StoredDelegationReplay {\n return { status: \"skipped\", reason };\n}\n\n/**\n * Replays one stored record under the binding rule. A record with a valid\n * binding installs only if its signed capabilities fit inside it. Before the\n * profile has migrated, an unbound compact record installs with its signed\n * authority as it always did; after, it installs nothing. A signed-login\n * record installs only with a binding. A record with neither compact bytes\n * nor a `siweProof` cannot be verified here and installs nothing. Never\n * throws, and never reports exception text: stored data is untrusted\n * transport material, and messages can quote it or a node's response.\n */\nexport async function replayStoredDelegation(\n node: RuntimeDelegationActivator,\n entry: unknown,\n options: {\n readonly host: string;\n readonly migrated: boolean;\n readonly resolveSpace: OperationSpaceResolver;\n },\n): Promise<StoredDelegationReplay> {\n const kind = storedDelegationKind(entry);\n const delegation = normalizeStoredDelegation(entry);\n if (kind === \"refused\" || delegation === undefined) return skipped(\"malformed\");\n if (delegation.expiry.getTime() <= Date.now()) return NOT_REPLAYED;\n if (kind === \"other\") return skipped(\"proof_missing\");\n const limit = replayLimit(entry, options.migrated);\n if (limit === undefined) return skipped(\"unbound\");\n let outsideRequest = false;\n const authorize = limit === \"signed\"\n ? () => true\n : (effective: readonly PermissionEntry[]) => {\n outsideRequest = !delegationWithinRequest(limit, effective, options.resolveSpace);\n return !outsideRequest;\n };\n try {\n return {\n status: \"installed\",\n delegation: await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, { host: options.host, authorize }),\n };\n } catch (error) {\n return skipped(outsideRequest ? \"outside_request\" : rejectionReason(error));\n }\n}\n\n/** The published reason node-sdk attached to a refused delegation, else `invalid`. */\nfunction rejectionReason(error: unknown): StoredGrantSkipReason {\n const reason = isRecord(error) ? error.reason : undefined;\n return typeof reason === \"string\" && (STORED_GRANT_SKIP_REASONS as readonly string[]).includes(reason)\n ? reason as StoredGrantSkipReason\n : \"invalid\";\n}\n\n/** An unreadable marker counts as migrated: a damaged marker never reopens migration. */\nexport async function bindingMigrationRecorded(profile: string): Promise<boolean> {\n try {\n return await readJson<unknown>(bindingMigrationPath(profile)) !== null;\n } catch {\n return true;\n }\n}\n\n/**\n * The capabilities a stored delegation's signed bytes grant, read through\n * validated activation, which `authorize` stops before anything is activated.\n */\nasync function signedCapabilities(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<readonly PermissionEntry[] | undefined> {\n let signed: readonly PermissionEntry[] | undefined;\n try {\n await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, {\n // The transport host is not signed authority; check it at replay instead.\n host: delegation.host ?? host,\n authorize: (effective) => {\n signed = effective;\n return false;\n },\n });\n } catch {\n // Refused by `authorize` once the capabilities were read, or failed a check before it.\n }\n return signed;\n}\n\nfunction normalizeStoredDelegation(entry: unknown): PortableDelegation | undefined {\n if (!isRecord(entry)) return undefined;\n const raw = entry.delegation;\n if (!isRecord(raw) || !isRecord(raw.delegationHeader)) return undefined;\n const expiry = raw.expiry instanceof Date\n ? raw.expiry\n : typeof raw.expiry === \"string\" ? new Date(raw.expiry) : undefined;\n if (\n expiry === undefined || Number.isNaN(expiry.getTime()) ||\n typeof raw.cid !== \"string\" ||\n typeof raw.spaceId !== \"string\" ||\n typeof raw.path !== \"string\" ||\n !Array.isArray(raw.actions) || !raw.actions.every((action) => typeof action === \"string\") ||\n typeof raw.delegateDID !== \"string\" ||\n typeof raw.ownerAddress !== \"string\" ||\n typeof raw.chainId !== \"number\" ||\n typeof raw.delegationHeader.Authorization !== \"string\"\n ) {\n return undefined;\n }\n return { ...raw, expiry } as PortableDelegation;\n}\n\nfunction storedCid(entry: unknown): string | undefined {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid === \"string\" ? cid : undefined;\n}\n\n/** A record's CID and exact authorization bytes. */\nfunction recordKey(entry: Record<string, unknown>): string | undefined {\n const delegation = entry.delegation;\n if (!isRecord(delegation) || !isRecord(delegation.delegationHeader)) return undefined;\n return JSON.stringify([delegation.cid, delegation.delegationHeader.Authorization]);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { z } from \"zod\";\n\nimport type {\n OperationContext,\n OperationDefinition,\n OperationExecutionOutcome,\n OperationExposure,\n OperationSensitivity,\n TinyCloudPosture,\n} from \"../contract.js\";\nimport { bindingMigrationRecorded, replayLimit, storedDelegationKind } from \"../delegation-binding.js\";\nimport { operationError } from \"../errors.js\";\nimport {\n additionalDelegationsPath,\n readJson,\n readProfile,\n readSession,\n readStoreMetadata,\n} from \"../state.js\";\n\ntype StatusInput = Record<never, never>;\n\ninterface StatusOutput {\n readonly profile: string;\n readonly host: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType?: \"human\" | \"agent\";\n readonly principalDid?: string;\n readonly sessionDid?: string;\n readonly ownerDid?: string;\n readonly space?: string;\n readonly session: {\n readonly present: boolean;\n readonly expired: boolean | null;\n readonly expiresAt: string | null;\n };\n readonly liveAdditionalDelegationCount: number;\n}\n\nconst StatusInputSchema: z.ZodType<StatusInput> = z.object({}).strict();\n\nconst StatusOutputSchema: z.ZodType<StatusOutput> = z.object({\n profile: z.string().min(1),\n host: z.string().min(1),\n posture: z.enum([\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n \"unauthenticated\",\n ]),\n operatorType: z.enum([\"human\", \"agent\"]).optional(),\n principalDid: z.string().min(1).optional(),\n sessionDid: z.string().min(1).optional(),\n ownerDid: z.string().min(1).optional(),\n space: z.string().min(1).optional(),\n session: z.object({\n present: z.boolean(),\n expired: z.boolean().nullable(),\n expiresAt: z.string().datetime({ offset: true }).nullable(),\n }).strict(),\n liveAdditionalDelegationCount: z.number().int().nonnegative().describe(\n \"Stored, unexpired delegations the replay rule accepts: compact-UCAN or signed-login records with a request \" +\n \"binding, and unbound compact-UCAN records before the profile's one-time binding migration. Each is still \" +\n \"validated, and checked against its binding, when a runtime installs it.\",\n ),\n}).strict();\n\nconst STATUS_POSTURES: readonly TinyCloudPosture[] = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n \"unauthenticated\",\n];\n\nconst STATUS_EXPOSURE: OperationExposure = {\n cli: { status: \"required\" },\n mcp: { status: \"required\" },\n skill: { status: \"required\" },\n docs: { status: \"required\" },\n};\n\nconst STATUS_SENSITIVITY: OperationSensitivity = { input: [], output: [] };\n\n/**\n * Internal I2 definition material. The registry integration owner imports this\n * collection; package entrypoints intentionally do not expose these handlers.\n */\nexport const statusOperationDefinitions: readonly OperationDefinition<StatusInput, StatusOutput>[] = [\n createStatusDefinition({\n id: \"tinycloud.status.get\",\n title: \"TinyCloud status\",\n description: \"Inspect the selected TinyCloud profile's safe local status.\",\n }),\n createStatusDefinition({\n id: \"tinycloud.auth.status\",\n title: \"TinyCloud authentication status\",\n description: \"Inspect the selected TinyCloud profile's safe authentication status.\",\n }),\n];\n\nfunction createStatusDefinition(params: Readonly<{\n id: \"tinycloud.status.get\" | \"tinycloud.auth.status\";\n title: string;\n description: string;\n}>): OperationDefinition<StatusInput, StatusOutput> {\n return {\n id: params.id,\n version: 1,\n title: params.title,\n description: params.description,\n input: StatusInputSchema,\n output: StatusOutputSchema,\n effects: [\"read\"],\n runtime: \"inspection\",\n postures: STATUS_POSTURES,\n exposure: STATUS_EXPOSURE,\n sensitivity: STATUS_SENSITIVITY,\n authority: async () => [],\n execute: inspectPinnedProfileStatus,\n };\n}\n\nasync function inspectPinnedProfileStatus(\n context: OperationContext,\n _input: StatusInput,\n): Promise<OperationExecutionOutcome<StatusOutput>> {\n const profile = context.summary.profile;\n if (!(await pinnedProfileExists(profile))) return profileNotFound(profile);\n\n try {\n const [session, liveAdditionalDelegationCount] = await Promise.all([\n readSession<Record<string, unknown>>(profile),\n countLiveAdditionalDelegations(profile),\n ]);\n const sessionSummary = summarizeSession(session);\n\n return {\n status: \"ok\",\n output: {\n profile,\n host: context.summary.host,\n posture: context.summary.posture,\n ...(context.summary.operatorType === undefined\n ? {}\n : { operatorType: context.summary.operatorType }),\n ...(context.summary.principalDid === undefined\n ? {}\n : { principalDid: context.summary.principalDid }),\n ...(context.summary.sessionDid === undefined\n ? {}\n : { sessionDid: context.summary.sessionDid }),\n ...(context.summary.ownerDid === undefined\n ? {}\n : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined ? {} : { space: context.summary.space }),\n session: sessionSummary,\n liveAdditionalDelegationCount,\n },\n };\n } catch {\n // Store contents may contain keys, session material, or delegation bytes.\n // A state-inspection failure must not relay any part of that material.\n return {\n status: \"error\",\n error: operationError(\n \"INTERNAL_ERROR\",\n \"The profile state could not be inspected.\",\n ),\n };\n }\n}\n\nasync function pinnedProfileExists(profile: string): Promise<boolean> {\n try {\n const storedProfile = await readProfile<Record<string, unknown>>(profile);\n return isRecord(storedProfile);\n } catch {\n return false;\n }\n}\n\nasync function countLiveAdditionalDelegations(profile: string): Promise<number> {\n await readStoreMetadata(profile, \"additional-delegations\");\n const rawDelegations = await readJson<unknown>(additionalDelegationsPath(profile));\n if (rawDelegations === null) return 0;\n if (!Array.isArray(rawDelegations)) throw new TypeError(\"Invalid additional delegation store.\");\n\n const now = Date.now();\n const migrated = await bindingMigrationRecorded(profile);\n let count = 0;\n for (const entry of rawDelegations) {\n // Elements replay refuses outright (not objects, no delegation, malformed\n // headers) never install, so they are not inspected either.\n if (storedDelegationKind(entry) === \"refused\") continue;\n const expiry = storedDelegationExpiry(entry);\n // Records replay refuses outright (unbound after migration, malformed,\n // or the CLI's own signed-login grants) are not runtime authority.\n if (expiry.getTime() > now && replayLimit(entry, migrated) !== undefined) count += 1;\n }\n return count;\n}\n\nfunction summarizeSession(session: Record<string, unknown> | null): StatusOutput[\"session\"] {\n if (session === null) return { present: false, expired: null, expiresAt: null };\n if (!isRecord(session)) throw new TypeError(\"Invalid session store.\");\n\n const expiry = extractSessionExpiry(session);\n if (expiry === null) return { present: true, expired: null, expiresAt: null };\n\n return {\n present: true,\n expired: expiry.getTime() <= Date.now(),\n expiresAt: expiry.toISOString(),\n };\n}\n\nfunction storedDelegationExpiry(entry: unknown): Date {\n if (!isRecord(entry) || !isRecord(entry.delegation) || !(\"expiry\" in entry.delegation)) {\n throw new TypeError(\"Invalid stored delegation.\");\n }\n return parseExpiry(entry.delegation.expiry);\n}\n\nfunction extractSessionExpiry(session: Record<string, unknown>): Date | null {\n for (const field of [\"expiresAt\", \"expiry\", \"expirationTime\"] as const) {\n if (!(field in session) || session[field] === undefined || session[field] === null) continue;\n return parseExpiry(session[field]);\n }\n\n if (!(\"siwe\" in session) || session.siwe === undefined || session.siwe === null) return null;\n if (typeof session.siwe !== \"string\") throw new TypeError(\"Invalid session expiry.\");\n const match = session.siwe.match(/^Expiration Time:\\s*(.+)$/im);\n return match === null ? null : parseExpiry(match[1].trim());\n}\n\nfunction parseExpiry(value: unknown): Date {\n const date = value instanceof Date\n ? value\n : typeof value === \"number\" && Number.isFinite(value)\n ? new Date(value > 0 && value < 1_000_000_000_000 ? value * 1_000 : value)\n : typeof value === \"string\" && value.trim() !== \"\"\n ? new Date(value)\n : null;\n if (date === null || Number.isNaN(date.getTime())) throw new TypeError(\"Invalid expiry.\");\n return date;\n}\n\nfunction profileNotFound(profile: string): OperationExecutionOutcome<never> {\n return {\n status: \"error\",\n error: operationError(\n \"PROFILE_NOT_FOUND\",\n `Profile \"${profile}\" is not available.`,\n ),\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { OperationDefinition, OperationId } from \"./contract.js\";\nimport { authOperationDefinitions } from \"./operations/auth.js\";\nimport { explorationOperationDefinitions } from \"./operations/exploration.js\";\nimport { secretsGetOperationDefinitions } from \"./operations/secrets-get.js\";\nimport { sqlOperationDefinitions } from \"./operations/sql.js\";\nimport { statusOperationDefinitions } from \"./operations/status.js\";\n\nexport type OperationLookup =\n | Readonly<{ status: \"found\"; definition: OperationDefinition<any, any> }>\n | Readonly<{ status: \"operation_not_found\" }>\n | Readonly<{\n status: \"operation_version_unsupported\";\n supportedVersions: readonly number[];\n }>;\n\n/**\n * The closed v1 catalog is assembled from internal definitions. There is no\n * exported registration hook for projections or a handler bypass API.\n */\nlet operationDefinitions: readonly OperationDefinition<any, any>[] | undefined;\n\nfunction registeredOperationDefinitions(): readonly OperationDefinition<any, any>[] {\n // Auth handlers consult lookupOperation while executing. Lazy assembly keeps\n // that internal dependency out of the module-initialization cycle.\n operationDefinitions ??= [\n ...statusOperationDefinitions,\n ...authOperationDefinitions,\n ...explorationOperationDefinitions,\n ...sqlOperationDefinitions,\n ...secretsGetOperationDefinitions,\n ];\n return operationDefinitions;\n}\n\n/** Internal generator input; package exports prevent projection access. */\nexport function operationDefinitionsForCatalog(): readonly OperationDefinition<any, any>[] {\n return registeredOperationDefinitions();\n}\n\nexport function lookupOperation(\n operationId: OperationId,\n operationVersion: number,\n): OperationLookup {\n const matchingId = registeredOperationDefinitions().filter(\n (definition) => definition.id === operationId,\n );\n if (matchingId.length === 0) {\n return { status: \"operation_not_found\" };\n }\n\n const definition = matchingId.find(\n (candidate) => candidate.version === operationVersion,\n );\n if (definition === undefined) {\n return {\n status: \"operation_version_unsupported\",\n supportedVersions: matchingId.map((candidate) => candidate.version),\n };\n }\n\n return { status: \"found\", definition };\n}\n","import {\n DEFAULT_PROFILE,\n readJson,\n readProfile,\n tinycloudConfigPath,\n} from \"./state.js\";\nimport type {\n InvocationTarget,\n OperationContextSummary,\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\n\nconst DEFAULT_HOST = \"https://tee.node.tinycloud.xyz\";\n\nexport type SafeInvocationContext = OperationContextSummary & {\n operatorType: OperationOperatorType;\n};\n\nexport type InvocationContextResolution =\n | { ok: true; context: SafeInvocationContext }\n | {\n ok: false;\n error: {\n code: \"PROFILE_NOT_FOUND\";\n message: string;\n retryable: false;\n };\n };\n\ninterface GlobalConfig {\n defaultProfile?: unknown;\n}\n\n/** Validated profile material retained only inside runtime resolution. */\nexport type StoredProfile = {\n name: string;\n host: string;\n chainId: number;\n spaceName: string;\n did: string;\n createdAt: string;\n sessionDid?: unknown;\n ownerDid?: unknown;\n spaceId?: unknown;\n posture?: unknown;\n operatorType?: unknown;\n authMethod?: unknown;\n defaultSpace?: unknown;\n privateKey?: unknown;\n address?: unknown;\n openkeyHost?: unknown;\n};\n\n/** Profile snapshot plus its derived safe invocation context. */\nexport type InvocationProfileResolution =\n | { ok: true; profile: StoredProfile; context: SafeInvocationContext }\n | Extract<InvocationContextResolution, { ok: false }>;\n\n/**\n * Resolves one selected profile to safe identity data. Resolution is deliberately\n * one-way: after selecting a name, any missing, malformed, or unreadable\n * profile is PROFILE_NOT_FOUND rather than a reason to choose another profile.\n */\nexport async function resolveInvocationContext(\n target: InvocationTarget = {},\n): Promise<InvocationContextResolution> {\n const resolved = await resolveInvocationProfile(target);\n return resolved.ok ? { ok: true, context: resolved.context } : resolved;\n}\n\n/** Resolves the selected profile and its safe context from one profile read. */\nexport async function resolveInvocationProfile(\n target: InvocationTarget = {},\n): Promise<InvocationProfileResolution> {\n const profile = await resolveProfileName(target);\n let storedProfile: StoredProfile | null;\n try {\n storedProfile = await readProfile<StoredProfile>(profile);\n } catch {\n return profileNotFound(profile);\n }\n\n if (!isStoredProfile(storedProfile)) {\n return profileNotFound(profile);\n }\n // An explicit CLI key is a complete identity override. Do not let stale\n // persisted auth posture reject that live local-owner authentication path.\n if (target.privateKey === undefined && !isCoherentProfile(storedProfile)) {\n return profileNotFound(profile);\n }\n\n const host = firstString(target.host, process.env.TC_HOST, storedProfile.host, DEFAULT_HOST);\n const posture = resolvePosture(storedProfile);\n\n return {\n ok: true,\n profile: storedProfile,\n context: {\n profile,\n host,\n posture,\n operatorType: isOperatorType(storedProfile.operatorType) ? storedProfile.operatorType : \"human\",\n principalDid: maybeDid(storedProfile.did),\n sessionDid: maybeDid(storedProfile.sessionDid),\n ownerDid: maybeDid(storedProfile.ownerDid),\n space: typeof storedProfile.spaceId === \"string\" ? storedProfile.spaceId : undefined,\n },\n };\n}\n\n/**\n * Selects the profile name once for a long-lived projection process. The\n * selected name is safe identity data; profile material is read only by the\n * invocation runtime after the projection pins this value.\n */\nexport async function resolveInvocationProfileName(\n explicitProfile?: string,\n): Promise<string> {\n return resolveProfileName(\n explicitProfile === undefined ? {} : { profile: explicitProfile },\n );\n}\n\nasync function resolveProfileName(target: InvocationTarget): Promise<string> {\n if (typeof target.profile === \"string\") return target.profile;\n if (typeof process.env.TC_PROFILE === \"string\") return process.env.TC_PROFILE;\n\n try {\n const config = await readJson<GlobalConfig>(tinycloudConfigPath());\n if (typeof config?.defaultProfile === \"string\") return config.defaultProfile;\n } catch {\n // Config only chooses the initial name. A missing or malformed config falls\n // back to the documented default, never to another existing profile.\n }\n return DEFAULT_PROFILE;\n}\n\n/** Derives the effective posture without consulting any later profile read. */\nexport function resolvePosture(profile: Pick<StoredProfile, \"posture\" | \"authMethod\">): TinyCloudPosture {\n if (isPosture(profile.posture)) return profile.posture;\n if (profile.authMethod === \"local\") return \"local-owner-key\";\n return \"owner-openkey\";\n}\n\nfunction profileNotFound(profile: string): Extract<InvocationContextResolution, { ok: false }> {\n return {\n ok: false,\n error: {\n code: \"PROFILE_NOT_FOUND\",\n message: `Profile \"${profile}\" is not available.`,\n retryable: false,\n },\n };\n}\n\nfunction firstString(...values: unknown[]): string {\n for (const value of values) {\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return DEFAULT_HOST;\n}\n\nfunction maybeDid(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n const fragment = value.indexOf(\"#\");\n return fragment === -1 ? value : value.slice(0, fragment);\n}\n\nfunction isPosture(value: unknown): value is TinyCloudPosture {\n return value === \"owner-openkey\" ||\n value === \"delegate-session\" ||\n value === \"local-owner-key\" ||\n value === \"unauthenticated\";\n}\n\nfunction isOperatorType(value: unknown): value is OperationOperatorType {\n return value === \"human\" || value === \"agent\";\n}\n\n/**\n * The CLI's original persisted profile format required these six fields.\n * Posture and operator fields arrived later, so they remain optional while\n * any present typed field must still have its documented shape.\n */\nfunction isStoredProfile(value: unknown): value is StoredProfile {\n return isRecord(value) &&\n isNonEmptyString(value.name) &&\n isNonEmptyString(value.host) &&\n typeof value.chainId === \"number\" &&\n Number.isFinite(value.chainId) &&\n isNonEmptyString(value.spaceName) &&\n isNonEmptyString(value.did) &&\n isNonEmptyString(value.createdAt) &&\n isOptionalNonEmptyString(value.sessionDid) &&\n isOptionalNonEmptyString(value.ownerDid) &&\n isOptionalNonEmptyString(value.spaceId) &&\n isOptionalPosture(value.posture) &&\n isOptionalOperatorType(value.operatorType) &&\n isOptionalAuthMethod(value.authMethod) &&\n isOptionalNonEmptyString(value.defaultSpace) &&\n isOptionalNonEmptyString(value.privateKey) &&\n isOptionalNonEmptyString(value.address) &&\n isOptionalNonEmptyString(value.openkeyHost);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isOptionalNonEmptyString(value: unknown): boolean {\n return value === undefined || isNonEmptyString(value);\n}\n\nfunction isOptionalPosture(value: unknown): boolean {\n return value === undefined || isPosture(value);\n}\n\nfunction isOptionalOperatorType(value: unknown): boolean {\n return value === undefined || isOperatorType(value);\n}\n\nfunction isOptionalAuthMethod(value: unknown): boolean {\n return value === undefined || value === \"openkey\" || value === \"local\";\n}\n\n/**\n * Local-key authentication is owner authentication. A persisted delegate or\n * OpenKey posture must never be allowed to select that path later in runtime\n * construction, so reject the inconsistent profile before policy inspection.\n */\nfunction isCoherentProfile(profile: StoredProfile): boolean {\n if (profile.authMethod === \"local\") {\n return profile.posture === undefined || profile.posture === \"local-owner-key\";\n }\n if (profile.posture === \"local-owner-key\") {\n return profile.authMethod === \"local\";\n }\n return true;\n}\n","import type {\n PermissionEntry,\n RuntimeDelegationActivator,\n TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\n\nimport {\n DELEGATION_CID_PATTERN,\n type InvocationTarget,\n type OperationContext,\n type OperationRuntime,\n type OperationRuntimeRequirement,\n type OperationWarning,\n type RuntimeOperationContext,\n type StoredGrantSkipReason,\n} from \"./contract.js\";\nimport { canonicalizeCapabilities } from \"./authority.js\";\nimport { operationError, type OperationError } from \"./errors.js\";\nimport { resolveInvocationProfile, resolvePosture } from \"./profile.js\";\nimport { operationSpaceResolver } from \"./secrets.js\";\nimport {\n profilePath,\n readAdditionalDelegations,\n readJson,\n readProfile,\n readSession,\n} from \"./state.js\";\nimport { prepareStoredDelegationReplay, replayStoredDelegation } from \"./delegation-binding.js\";\n\nexport type InvocationRuntimeResolution =\n | Readonly<{ ok: true; context: OperationContext }>\n | Readonly<{\n ok: false;\n context: RuntimeOperationContext[\"summary\"];\n error: OperationError;\n }>;\n\ninterface StoredSession extends Record<string, unknown> {\n readonly delegationHeader?: unknown;\n readonly delegationCid?: unknown;\n readonly spaceId?: unknown;\n readonly jwk?: unknown;\n readonly verificationMethod?: unknown;\n readonly address?: unknown;\n readonly chainId?: unknown;\n readonly siwe?: unknown;\n readonly signature?: unknown;\n readonly tinycloudHosts?: unknown;\n}\n\n/**\n * Creates one authenticated runtime for an invocation. The selected profile\n * name is resolved once and every subsequent read is explicitly scoped to that\n * name; no failure path can choose a different profile.\n */\ntype AuthenticatedRuntimeResolution =\n | Readonly<{ ok: true; context: RuntimeOperationContext }>\n | Exclude<InvocationRuntimeResolution, Readonly<{ ok: true; context: OperationContext }>>;\n\nexport function createInvocationRuntime(\n target: InvocationTarget,\n): Promise<AuthenticatedRuntimeResolution>;\nexport function createInvocationRuntime(\n target: InvocationTarget,\n requirement: \"authenticated\",\n): Promise<AuthenticatedRuntimeResolution>;\nexport function createInvocationRuntime(\n target: InvocationTarget,\n requirement: \"inspection\",\n): Promise<InvocationRuntimeResolution>;\nexport function createInvocationRuntime(\n target: InvocationTarget,\n requirement: OperationRuntimeRequirement,\n): Promise<InvocationRuntimeResolution>;\nexport async function createInvocationRuntime(\n target: InvocationTarget,\n requirement: OperationRuntimeRequirement = \"authenticated\",\n): Promise<InvocationRuntimeResolution> {\n const resolved = await resolveInvocationProfile(target);\n if (!resolved.ok) {\n return {\n ok: false,\n context: unresolvedSummary(target),\n error: resolved.error,\n };\n }\n\n const summary = resolved.context;\n if (requirement === \"inspection\") {\n return { ok: true, context: { summary } };\n }\n\n const profileName = summary.profile;\n try {\n // Keep the value import namespace-shaped so projection modules remain\n // compatible with lightweight node-sdk test doubles.\n const {\n TinyCloudNode: TinyCloudNodeConstructor,\n } = nodeSdk;\n const explicitPrivateKeyOverride = typeof target.privateKey === \"string\";\n const [session, key] = explicitPrivateKeyOverride\n ? [null, null]\n : await Promise.all([\n readSession<StoredSession>(profileName),\n readJson<Record<string, unknown>>(`${profilePath(profileName)}/key.json`),\n ]);\n const profile = resolved.profile;\n\n // The inspection summary and authenticated material are intentionally\n // separate reads. Fail closed if the profile changed posture between\n // them; otherwise local-owner-key could be authenticated under a stale\n // delegate-session summary and bypass the caller's posture policy.\n const actualPosture = resolvePosture(profile);\n if (!explicitPrivateKeyOverride && actualPosture !== summary.posture) {\n return failed(\n { ...summary, posture: actualPosture },\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The selected profile changed posture during runtime resolution.\",\n ),\n );\n }\n\n const privateKey = typeof target.privateKey === \"string\"\n ? target.privateKey\n : typeof profile.privateKey === \"string\"\n ? profile.privateKey\n : undefined;\n const selectedPosture = explicitPrivateKeyOverride || profile.authMethod === \"local\"\n ? \"local-owner-key\"\n : summary.posture;\n if (selectedPosture !== summary.posture && !explicitPrivateKeyOverride) {\n return failed(\n { ...summary, posture: selectedPosture },\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The selected profile authentication material does not match its posture.\",\n ),\n );\n }\n const node = new TinyCloudNodeConstructor({\n host: summary.host,\n ...(privateKey === undefined ? {} : { privateKey }),\n });\n\n const activeSession = session === null ? undefined : normalizeSession(session, key);\n if (explicitPrivateKeyOverride) {\n // An explicit key is a complete, non-persisted identity. Do not inherit\n // an OpenKey session (or require one) from the selected profile.\n await node.signIn();\n } else if (activeSession === undefined) {\n if (profile.authMethod === \"local\" && privateKey !== undefined) {\n await node.signIn();\n } else {\n return failed(summary, operationError(\n \"SESSION_NOT_FOUND\",\n \"The selected profile does not have an active session.\",\n ));\n }\n } else {\n try {\n await node.restoreSession(activeSession);\n } catch (error) {\n // node-sdk refuses expired or otherwise unusable persisted authority\n // (`AUTH_EXPIRED`) while verifying it locally, before any node request.\n // Only a new sign-in fixes that: the same non-retryable `AUTH_REQUIRED`\n // a node's 401 for a stale session produces.\n if (isRecord(error) && error.code === \"AUTH_EXPIRED\") {\n return failed(summary, operationError(\n \"AUTH_REQUIRED\",\n \"The stored session has expired or is no longer valid. Sign in again.\",\n { retryable: false },\n ));\n }\n throw error;\n }\n }\n\n // The restored node is the authority for the active session identity. In\n // particular, do not report the persisted verification method if SDK\n // restoration failed to install its key as the live session key.\n const activeSessionDid = normalizeDid(node.sessionDid);\n const livePrincipalDid = normalizeDid(node.did);\n const authenticatedSpace = explicitPrivateKeyOverride\n ? spaceForAuthenticatedPrincipal(livePrincipalDid)\n : undefined;\n // This API derives from the restored, verified base session rather than\n // from an SDK private field or a second parse of signed authority here.\n const livePermissions: PermissionEntry[] = [...node.getVerifiedSessionCapabilities()];\n const resolveSpace = operationSpaceResolver(node, authenticatedSpace ?? summary.space);\n const seenCids = new Set<string>();\n const warnings: OperationWarning[] = [];\n // An explicit key is another identity: it neither replays nor migrates\n // this profile's records.\n if (!explicitPrivateKeyOverride) {\n const activator = node as unknown as RuntimeDelegationActivator;\n // Migration runs before the records are read, so the records replayed\n // here and the migration marker agree.\n const migrated = await prepareStoredDelegationReplay(profileName, activator, {\n host: summary.host,\n // Only the profile's own restored session; a local sign-in without\n // one uses a fresh session key the stored records do not address.\n migrate: activeSession !== undefined,\n });\n // Elements are untrusted and may not even be objects; the shared rule\n // classifies each before reading any field.\n for (const entry of await readAdditionalDelegations<unknown>(profileName)) {\n const replay = await replayStoredDelegation(activator, entry, {\n host: summary.host,\n migrated,\n resolveSpace,\n });\n if (replay.status === \"installed\") {\n if (!seenCids.has(replay.delegation.cid)) {\n seenCids.add(replay.delegation.cid);\n livePermissions.push(...replay.delegation.effectivePermissions);\n }\n } else if (replay.status === \"skipped\") {\n // A skipped record never grants authority. Skipping (not failing)\n // keeps one stale record from blocking what the session or other\n // grants cover; the result says which grant and why, in fixed\n // codes only. An expired grant is routine and is not reported.\n warnings.push(skippedGrantWarning(node, entry, replay.reason));\n }\n }\n }\n\n const runtime: OperationRuntime = {\n node,\n granted: canonicalizeCapabilities(livePermissions),\n ...(warnings.length === 0 ? {} : { warnings }),\n };\n return {\n ok: true,\n context: {\n summary: {\n ...summary,\n posture: selectedPosture,\n ...(livePrincipalDid === undefined ? {} : { principalDid: livePrincipalDid }),\n ...(explicitPrivateKeyOverride && livePrincipalDid !== undefined\n ? { ownerDid: livePrincipalDid }\n : {}),\n ...(authenticatedSpace === undefined ? {} : { space: authenticatedSpace }),\n ...(activeSessionDid === undefined ? {} : { sessionDid: activeSessionDid }),\n },\n runtime,\n },\n };\n } catch {\n return failed(summary, operationError(\n \"NODE_ERROR\",\n \"The selected profile runtime could not be initialized.\",\n { retryable: true },\n ));\n }\n}\n\n/**\n * A stored CID is published only when it is the CID of the stored\n * authorization bytes, recomputed here. Any other value (free text, or a\n * well-formed CID of different bytes) is caller-controlled data and is omitted.\n */\nfunction skippedGrantWarning(node: unknown, entry: unknown, reason: StoredGrantSkipReason): OperationWarning {\n const grantCid = verifiedStoredCid(node, entry);\n return { code: \"STORED_GRANT_SKIPPED\", reason, ...(grantCid === undefined ? {} : { grantCid }) };\n}\n\nfunction verifiedStoredCid(node: unknown, entry: unknown): string | undefined {\n const delegation = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation : undefined;\n const header = isRecord(delegation?.delegationHeader) ? delegation.delegationHeader : undefined;\n const cid = delegation?.cid;\n const computeDelegationCid = isRecord(node) ? node.computeDelegationCid : undefined;\n if (typeof cid !== \"string\" || typeof header?.Authorization !== \"string\" || typeof computeDelegationCid !== \"function\") {\n return undefined;\n }\n try {\n return computeDelegationCid.call(node, header.Authorization) === cid && DELEGATION_CID.test(cid) ? cid : undefined;\n } catch {\n return undefined;\n }\n}\n\nconst DELEGATION_CID = new RegExp(DELEGATION_CID_PATTERN);\n\nfunction spaceForAuthenticatedPrincipal(principal: string | undefined): string | undefined {\n if (principal === undefined) return undefined;\n try {\n const pkh = nodeSdk.parsePkhDid(principal);\n return pkh === null ? undefined : nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, \"secrets\");\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeSession(\n session: StoredSession,\n key: Record<string, unknown> | null,\n): Parameters<TinyCloudNode[\"restoreSession\"]>[0] | undefined {\n const header = session.delegationHeader;\n const jwk = hasPrivateParameter(session.jwk) ? session.jwk : key;\n if (\n !isRecord(header) ||\n typeof header.Authorization !== \"string\" ||\n typeof session.delegationCid !== \"string\" ||\n typeof session.spaceId !== \"string\" ||\n !hasPrivateParameter(jwk) ||\n typeof session.verificationMethod !== \"string\"\n ) {\n return undefined;\n }\n\n return {\n delegationHeader: { Authorization: header.Authorization },\n delegationCid: session.delegationCid,\n spaceId: session.spaceId,\n jwk,\n verificationMethod: session.verificationMethod,\n ...(typeof session.address === \"string\" ? { address: session.address } : {}),\n ...(typeof session.chainId === \"number\" ? { chainId: session.chainId } : {}),\n ...(typeof session.siwe === \"string\" ? { siwe: session.siwe } : {}),\n ...(typeof session.signature === \"string\" ? { signature: session.signature } : {}),\n ...(Array.isArray(session.tinycloudHosts) && session.tinycloudHosts.every((host) => typeof host === \"string\")\n ? { tinycloudHosts: session.tinycloudHosts }\n : {}),\n };\n}\n\nfunction hasPrivateParameter(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && typeof value.d === \"string\" && value.d.length > 0;\n}\n\nfunction normalizeDid(value: string | undefined): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n return value.split(\"#\", 1)[0];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction failed(\n context: RuntimeOperationContext[\"summary\"],\n error: OperationError,\n): InvocationRuntimeResolution {\n return { ok: false, context, error };\n}\n\nfunction unresolvedSummary(target: InvocationTarget): RuntimeOperationContext[\"summary\"] {\n return {\n profile: target.profile ?? \"unresolved\",\n host: target.host ?? \"unresolved\",\n posture: \"unauthenticated\",\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { isAbsolute } from \"node:path\";\n\nimport {\n makePkhSpaceId,\n parsePkhDid,\n parseSpaceUri,\n type PermissionEntry,\n} from \"@tinycloud/node-sdk\";\nimport { jcsCanonicalize } from \"@tinycloud/sdk-core/policy\";\nimport type { ZodError } from \"zod\";\n\nimport {\n type ApprovalAction,\n type CapabilityRequirement,\n type InvocationTarget,\n type OperationContextSummary,\n type OperationDefinition,\n type OperationRef,\n type OperationResult,\n type OperationRuntimeRequirement,\n type RuntimeOperationContext,\n} from \"./contract.js\";\nimport {\n internalOperationError,\n operationError,\n sanitizeOperationError,\n sanitizeThrownOperationError,\n} from \"./errors.js\";\nimport {\n canonicalizeOperationCapabilities,\n evaluateOperationAuthority,\n isExactCapabilityMemberSubset,\n validateExactCapabilities,\n} from \"./authority.js\";\nimport {\n createOrReusePermissionRequest,\n buildPermissionRequestArtifact,\n type PermissionRequestArtifact,\n} from \"./artifacts.js\";\nimport { redactOperationError } from \"./redaction.js\";\nimport { safeOriginHost } from \"./safe-values.js\";\nimport { withTinyCloudStateRoot } from \"./state.js\";\nimport type { InvocationRuntimeResolution } from \"./runtime.js\";\nimport {\n operationSpaceResolver,\n resolveSecretReferenceForOperation,\n} from \"./secrets.js\";\n\n/** The sole projection-facing execution API. */\nexport async function invokeOperation(\n operationId: string,\n operationVersion: number,\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n const target = normalizeInvocationTarget(invocationTarget);\n if (target === undefined) {\n return errorResult(\n { operationId, operationVersion },\n unresolvedContextSummary(),\n operationError(\"INPUT_INVALID\", \"The invocation target is invalid.\"),\n );\n }\n return withTinyCloudStateRoot(target.stateRoot, async () => {\n const prepared = await prepareInvocation(\n operationId,\n operationVersion,\n target,\n unknownInput,\n );\n if (isPreparedError(prepared)) return prepared.result;\n return withRuntimeWarnings(await executePreparedInvocation(prepared), prepared);\n });\n}\n\n/**\n * CLI-only local-owner acquisition path. The runtime is deliberately created\n * and retained inside operations so a grant is installed on the exact session\n * that performs the one retry. The explicit key remains a non-persisted target\n * value and no runtime object crosses the operations boundary.\n */\nexport async function invokeOperationWithLocalAuthorityRetry(\n operationId: string,\n operationVersion: number,\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n const target = normalizeInvocationTarget(invocationTarget);\n if (target === undefined) {\n return errorResult(\n { operationId, operationVersion },\n unresolvedContextSummary(),\n operationError(\"INPUT_INVALID\", \"The invocation target is invalid.\"),\n );\n }\n if (typeof target.privateKey !== \"string\" || target.privateKey.length === 0) {\n return errorResult(\n { operationId, operationVersion },\n unresolvedContextSummary(target),\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"Local authority retry requires an explicit private key.\",\n ),\n );\n }\n\n return withTinyCloudStateRoot(target.stateRoot, () =>\n invokeLocalAuthorityRetry(\n operationId,\n operationVersion,\n target,\n unknownInput,\n )\n );\n}\n\nasync function invokeLocalAuthorityRetry(\n operationId: string,\n operationVersion: number,\n target: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n const prepared = await prepareInvocation(\n operationId,\n operationVersion,\n target,\n unknownInput,\n );\n if (isPreparedError(prepared)) return prepared.result;\n return withRuntimeWarnings(await retryWithLocalAuthority(prepared), prepared);\n}\n\nasync function retryWithLocalAuthority(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n): Promise<OperationResult<unknown>> {\n if (\n prepared.operation.operationId !== \"tinycloud.secrets.get\" ||\n prepared.operation.operationVersion !== 1\n ) {\n return errorResult(\n prepared.operation,\n prepared.runtimeResolution.context.summary,\n operationError(\n \"OPERATION_NOT_FOUND\",\n \"The local CLI authority helper supports only tinycloud.secrets.get@1.\",\n ),\n );\n }\n\n const runtimeContext = prepared.runtimeResolution.context;\n if (runtimeContext.runtime === undefined) return internalOperationErrorResult(prepared);\n const operationContext = runtimeContext as RuntimeOperationContext;\n let planned: CapabilityRequirement[] | undefined;\n try {\n planned = exactCapabilities(await prepared.definition.authority(\n operationContext,\n prepared.parsedInput.data,\n ));\n } catch {\n return errorResult(\n prepared.operation,\n operationContext.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The local CLI authority plan is invalid.\",\n ),\n );\n }\n const planStatus = planned === undefined\n ? \"invalid\"\n : isExactLocalSecretsGetPlan(prepared, planned, operationContext);\n if (planStatus === \"ineligible\") {\n return errorResult(\n prepared.operation,\n operationContext.summary,\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The explicit private key cannot authorize the requested owner space.\",\n ),\n );\n }\n if (planStatus !== \"valid\") {\n return errorResult(\n prepared.operation,\n operationContext.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The local CLI authority plan is invalid.\",\n ),\n );\n }\n\n const first = await executePreparedInvocation(prepared, { deferAuthorityRequest: true });\n if (first.status !== \"authority_required\") {\n return first;\n }\n if (\n operationContext.summary.posture !== \"local-owner-key\" ||\n !requirementsBelongToAuthenticatedOwner(\n first.missing as unknown as PermissionEntry[],\n operationContext.summary.space,\n )\n ) {\n return localAuthorityFailure(prepared);\n }\n\n try {\n const grantRuntimePermissions = (operationContext.runtime.node as {\n grantRuntimePermissions?: (\n permissions: PermissionEntry[],\n ) => Promise<unknown>;\n }).grantRuntimePermissions;\n if (typeof grantRuntimePermissions !== \"function\") {\n return localAuthorityFailure(prepared);\n }\n await grantRuntimePermissions.call(\n operationContext.runtime.node,\n first.missing as unknown as PermissionEntry[],\n );\n\n const resolveSpace = operationSpaceResolver(\n operationContext.runtime.node,\n operationContext.summary.space,\n );\n const refreshedGranted = refreshLiveRuntimeAuthority(\n operationContext.runtime.node,\n first.missing as unknown as PermissionEntry[],\n planned as unknown as PermissionEntry[],\n resolveSpace,\n );\n if (refreshedGranted === undefined) {\n return localAuthorityFailure(prepared);\n }\n const retryContext: RuntimeOperationContext = {\n ...operationContext,\n runtime: {\n ...operationContext.runtime,\n granted: refreshedGranted,\n },\n };\n const retry = await executePreparedInvocation({\n ...prepared,\n runtimeResolution: { ok: true, context: retryContext },\n }, { deferAuthorityRequest: true });\n return retry.status === \"authority_required\"\n ? localAuthorityFailure(prepared)\n : retry;\n } catch {\n return localAuthorityFailure(prepared);\n }\n}\n\n/** Diagnostics from building the runtime belong to the invocation's result. */\nfunction withRuntimeWarnings(\n result: OperationResult<unknown>,\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n): OperationResult<unknown> {\n const warnings = prepared.runtimeResolution.context.runtime?.warnings;\n return warnings === undefined || warnings.length === 0 ? result : { ...result, warnings: [...warnings] };\n}\n\ntype PreparedInvocation = Readonly<{\n operation: OperationRef;\n definition: OperationDefinition<any, any>;\n parsedInput: { data: any };\n runtimeResolution: Extract<InvocationRuntimeResolution, { ok: true }>;\n}> | Readonly<{\n status: \"error\";\n result: OperationResult<never>;\n}>;\n\nfunction isPreparedError(\n prepared: PreparedInvocation,\n): prepared is Extract<PreparedInvocation, { status: \"error\" }> {\n return \"status\" in prepared;\n}\n\nasync function prepareInvocation(\n operationId: string,\n operationVersion: number,\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<PreparedInvocation> {\n const operation: OperationRef = { operationId, operationVersion };\n const target = normalizeInvocationTarget(invocationTarget);\n if (target === undefined) {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(),\n operationError(\"INPUT_INVALID\", \"The invocation target is invalid.\"),\n ) };\n }\n // Load internal registry material only when invoking. This keeps the packed\n // root entrypoint free of auth/runtime SDK initialization until a call is\n // made, while preserving registry resolution before input or profile access.\n const { lookupOperation } = await import(\"./registry.js\");\n const lookup = lookupOperation(operationId, operationVersion);\n\n // Registry resolution is deliberately complete before any input parsing or\n // profile access. An unrecognized operation must not cause an invocation to\n // consult profile state.\n if (lookup.status === \"operation_not_found\") {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(target),\n operationError(\n \"OPERATION_NOT_FOUND\",\n \"The requested operation is not registered.\",\n ),\n ) };\n }\n if (lookup.status === \"operation_version_unsupported\") {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(target),\n operationError(\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"The requested operation version is not supported.\",\n { details: { supportedVersions: lookup.supportedVersions } },\n ),\n ) };\n }\n\n const definition = lookup.definition;\n const parsedInput = definition.input.safeParse(unknownInput);\n if (!parsedInput.success) {\n return { status: \"error\", result: errorResult(\n operation,\n unresolvedContextSummary(target),\n operationError(\n definition.invalidInputErrorCode ?? \"INPUT_INVALID\",\n \"The operation input is invalid.\",\n {\n details: zodIssueDetails(parsedInput.error),\n },\n ),\n ) };\n }\n\n // Only a registered operation with valid input may inspect the pinned\n // profile. Inspection is deliberately node-free, so owner opt-in and status\n // availability are decided before any authentication or external effect.\n const inspectionResolution = await resolveRuntime(target, \"inspection\");\n if (!inspectionResolution.ok) {\n return { status: \"error\", result: errorResult(\n operation,\n inspectionResolution.context,\n inspectionResolution.error,\n ) };\n }\n\n if (\n target.privateKey === undefined &&\n !definition.postures.includes(inspectionResolution.context.summary.posture)\n ) {\n return { status: \"error\", result: errorResult(\n operation,\n inspectionResolution.context.summary,\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The active profile posture cannot execute this operation.\",\n ),\n ) };\n }\n if (\n target.privateKey === undefined &&\n definition.runtime === \"authenticated\" &&\n isOwnerPosture(inspectionResolution.context.summary.posture) &&\n target.allowOwnerProfile !== true\n ) {\n return { status: \"error\", result: errorResult(\n operation,\n inspectionResolution.context.summary,\n operationError(\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"Owner-profile execution requires explicit opt-in.\",\n ),\n ) };\n }\n\n const runtimeResolution =\n definition.runtime === \"inspection\"\n ? inspectionResolution\n : await resolveRuntime(target, \"authenticated\");\n if (!runtimeResolution.ok) {\n return { status: \"error\", result: errorResult(\n operation,\n runtimeResolution.context,\n runtimeResolution.error,\n ) };\n }\n if (definition.runtime === \"authenticated\") {\n const actualPosture = runtimeResolution.context.summary.posture;\n if (!definition.postures.includes(actualPosture)) {\n return { status: \"error\", result: errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"The authenticated profile posture cannot execute this operation.\",\n ),\n ) };\n }\n if (isOwnerPosture(actualPosture) && target.allowOwnerProfile !== true) {\n return { status: \"error\", result: errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"Owner-profile execution requires explicit opt-in.\",\n ),\n ) };\n }\n }\n return {\n operation,\n definition,\n parsedInput,\n runtimeResolution,\n };\n}\n\nasync function executePreparedInvocation(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n options: Readonly<{ deferAuthorityRequest?: boolean }> = {},\n): Promise<OperationResult<unknown>> {\n const { operation, definition, parsedInput, runtimeResolution } = prepared;\n const runtimeContext =\n runtimeResolution.context.runtime === undefined\n ? undefined\n : (runtimeResolution.context as RuntimeOperationContext);\n const resolveSpace = runtimeContext === undefined\n ? undefined\n : operationSpaceResolver(\n runtimeContext.runtime.node,\n runtimeContext.summary.space,\n );\n\n try {\n const planned = await definition.authority(\n (runtimeContext ?? runtimeResolution.context) as RuntimeOperationContext,\n parsedInput.data,\n );\n const required = exactCapabilities(planned);\n if (required === undefined) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The operation returned an invalid permission requirement.\",\n ),\n );\n }\n\n const evaluation = evaluateOperationAuthority(\n (runtimeContext?.runtime.granted ?? []) as unknown as PermissionEntry[],\n required as unknown as PermissionEntry[],\n resolveSpace,\n );\n if (!evaluation.satisfied) {\n if (runtimeContext === undefined) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n if (options.deferAuthorityRequest) {\n try {\n const request = buildPermissionRequestArtifact({\n profile: runtimeContext.summary.profile,\n host: runtimeContext.summary.host,\n sessionDid: runtimeContext.summary.sessionDid!,\n posture: runtimeContext.summary.posture,\n operatorType: runtimeContext.summary.operatorType ?? \"human\",\n ...(runtimeContext.summary.ownerDid === undefined\n ? {}\n : { ownerDid: runtimeContext.summary.ownerDid }),\n ...(runtimeContext.summary.space === undefined\n ? {}\n : { spaceId: runtimeContext.summary.space }),\n missing: evaluation.missing as unknown as PermissionEntry[],\n });\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n request,\n evaluation.missing,\n runtimeContext.runtime.node,\n );\n } catch {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n }\n const authority = await persistAuthorityRequest(\n runtimeContext,\n evaluation.missing,\n );\n if (authority.status === \"error\") {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n authority.error,\n );\n }\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n authority.request,\n authority.missing,\n runtimeContext.runtime.node,\n );\n }\n\n const outcome = await definition.execute(\n runtimeResolution.context,\n parsedInput.data,\n );\n\n switch (outcome.status) {\n case \"ok\": {\n const parsedOutput = definition.output.safeParse(outcome.output);\n if (!parsedOutput.success) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"OUTPUT_INVALID\",\n \"The operation returned an invalid result.\",\n ),\n );\n }\n return {\n status: \"ok\",\n operation,\n context: runtimeResolution.context.summary,\n output: parsedOutput.data,\n };\n }\n case \"authority_required\": {\n const hinted = exactCapabilities(outcome.missing);\n if (\n hinted === undefined ||\n !isExactCapabilityMemberSubset(\n hinted as unknown as PermissionEntry[],\n required as unknown as PermissionEntry[],\n resolveSpace,\n )\n ) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n operationError(\n \"PERMISSION_HINT_INVALID\",\n \"The node returned an invalid permission hint.\",\n ),\n );\n }\n if (runtimeContext === undefined) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n if (options.deferAuthorityRequest) {\n try {\n const request = buildPermissionRequestArtifact({\n profile: runtimeContext.summary.profile,\n host: runtimeContext.summary.host,\n sessionDid: runtimeContext.summary.sessionDid!,\n posture: runtimeContext.summary.posture,\n operatorType: runtimeContext.summary.operatorType ?? \"human\",\n ...(runtimeContext.summary.ownerDid === undefined\n ? {}\n : { ownerDid: runtimeContext.summary.ownerDid }),\n ...(runtimeContext.summary.space === undefined\n ? {}\n : { spaceId: runtimeContext.summary.space }),\n missing: hinted as unknown as PermissionEntry[],\n });\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n request,\n hinted,\n runtimeContext.runtime.node,\n outcome.requiresCallerInput ?? false,\n );\n } catch {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n }\n const authority = await persistAuthorityRequest(\n runtimeContext,\n hinted,\n true,\n );\n if (authority.status === \"error\") {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n authority.error,\n );\n }\n return authorityRequiredResult(\n operation,\n runtimeResolution.context.summary,\n parsedInput.data,\n authority.request,\n authority.missing,\n runtimeContext.runtime.node,\n outcome.requiresCallerInput ?? false,\n );\n }\n case \"setup_required\":\n return {\n status: \"setup_required\",\n operation,\n context: runtimeResolution.context.summary,\n setup: outcome.setup,\n retry: retryDescriptor(\n operation,\n parsedInput.data,\n outcome.requiresCallerInput ?? false,\n ),\n };\n case \"error\":\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n redactOperationError(\n definition,\n sanitizeOperationError(outcome.error),\n ),\n );\n default:\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n internalOperationError(),\n );\n }\n } catch (error) {\n return errorResult(\n operation,\n runtimeResolution.context.summary,\n redactOperationError(definition, sanitizeThrownOperationError(error)),\n );\n }\n}\n\nfunction normalizeInvocationTarget(\n target: unknown,\n): InvocationTarget | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n\n try {\n const candidate = target as InvocationTarget;\n const profile = candidate.profile;\n const host = candidate.host;\n const stateRoot = candidate.stateRoot;\n const allowOwnerProfile = candidate.allowOwnerProfile;\n const privateKey = candidate.privateKey;\n\n if (\n (profile !== undefined && typeof profile !== \"string\") ||\n (host !== undefined && typeof host !== \"string\") ||\n (stateRoot !== undefined &&\n (typeof stateRoot !== \"string\" || !isAbsolute(stateRoot))) ||\n (allowOwnerProfile !== undefined &&\n typeof allowOwnerProfile !== \"boolean\") ||\n (privateKey !== undefined && typeof privateKey !== \"string\")\n ) {\n return undefined;\n }\n\n return {\n ...(profile === undefined ? {} : { profile }),\n ...(host === undefined ? {} : { host }),\n ...(stateRoot === undefined ? {} : { stateRoot }),\n ...(allowOwnerProfile === true ? { allowOwnerProfile: true } : {}),\n ...(privateKey === undefined ? {} : { privateKey }),\n };\n } catch {\n return undefined;\n }\n}\n\nasync function resolveRuntime(\n target: InvocationTarget,\n requirement: OperationRuntimeRequirement,\n): Promise<InvocationRuntimeResolution> {\n try {\n // Keep the root package loadable for projections that only inspect its\n // public invocation export. The SDK runtime is needed only once a valid\n // operation reaches runtime construction.\n const { createInvocationRuntime } = await import(\"./runtime.js\");\n return await createInvocationRuntime(target, requirement);\n } catch (error) {\n return {\n ok: false,\n context: unresolvedContextSummary(target),\n error: sanitizeThrownOperationError(error),\n };\n }\n}\n\nfunction unresolvedContextSummary(\n target: InvocationTarget = {},\n): OperationContextSummary {\n return {\n profile: typeof target.profile === \"string\" ? target.profile : \"unresolved\",\n host: safeOriginHost(target.host) ?? \"unresolved\",\n posture: \"unauthenticated\",\n };\n}\n\nfunction errorResult(\n operation: OperationRef,\n context: OperationContextSummary,\n error: ReturnType<typeof sanitizeOperationError>,\n): OperationResult<never> {\n return { status: \"error\", operation, context, error };\n}\n\nfunction retryDescriptor(\n operation: OperationRef,\n input: unknown,\n requiresCallerInput: boolean,\n): Readonly<{\n operationId: string;\n operationVersion: number;\n inputDigest: string;\n requiresCallerInput: boolean;\n}> {\n return {\n operationId: operation.operationId,\n operationVersion: operation.operationVersion,\n inputDigest: createHash(\"sha256\")\n .update(jcsCanonicalize(input), \"utf8\")\n .digest(\"hex\"),\n requiresCallerInput,\n };\n}\n\ntype PersistedAuthority =\n | Readonly<{\n status: \"ok\";\n request: PermissionRequestArtifact;\n missing: readonly CapabilityRequirement[];\n }>\n | Readonly<{\n status: \"error\";\n error: ReturnType<typeof sanitizeOperationError>;\n }>;\n\nasync function persistAuthorityRequest(\n context: RuntimeOperationContext,\n missing: readonly CapabilityRequirement[],\n force = false,\n): Promise<PersistedAuthority> {\n const sessionDid = context.summary.sessionDid;\n if (sessionDid === undefined) {\n return {\n status: \"error\",\n error: operationError(\n \"SESSION_NOT_FOUND\",\n \"The selected profile does not have an active session.\",\n ),\n };\n }\n try {\n const resolveSpace = operationSpaceResolver(\n context.runtime.node,\n context.summary.space,\n );\n const canonicalMissing = canonicalizeOperationCapabilities(missing as unknown as PermissionEntry[], resolveSpace);\n const canonicalGranted = canonicalizeOperationCapabilities(context.runtime.granted as unknown as PermissionEntry[], resolveSpace);\n const resolution = await createOrReusePermissionRequest({\n profile: context.summary.profile,\n posture: context.summary.posture,\n operatorType: context.summary.operatorType ?? \"human\",\n host: context.summary.host,\n sessionDid,\n ...(context.summary.ownerDid === undefined\n ? {}\n : { ownerDid: context.summary.ownerDid }),\n ...(context.summary.space === undefined\n ? {}\n : { spaceId: context.summary.space }),\n missing: canonicalMissing as unknown as PermissionEntry[],\n granted: (force\n ? []\n : canonicalGranted) as unknown as PermissionEntry[],\n resolveSpace,\n });\n if (resolution.status !== \"created\") {\n return {\n status: \"error\",\n error: operationError(\n \"INTERNAL_ERROR\",\n \"The authority request could not be created.\",\n ),\n };\n }\n return {\n status: \"ok\",\n request: resolution.request,\n missing: canonicalMissing as CapabilityRequirement[],\n };\n } catch {\n return {\n status: \"error\",\n error: operationError(\n \"INTERNAL_ERROR\",\n \"The authority request could not be created.\",\n ),\n };\n }\n}\n\nfunction authorityRequiredResult(\n operation: OperationRef,\n context: OperationContextSummary,\n input: unknown,\n request: PermissionRequestArtifact,\n missing: readonly CapabilityRequirement[],\n node: unknown,\n requiresCallerInput = false,\n): OperationResult<never> {\n return {\n status: \"authority_required\",\n operation,\n context,\n missing,\n request,\n approval: approvalAction(request, node),\n retry: retryDescriptor(operation, input, requiresCallerInput),\n };\n}\n\nfunction approvalAction(\n request: PermissionRequestArtifact,\n node: unknown,\n): ApprovalAction {\n const maybeNode = node as {\n getOpenKeyApprovalUrl?: (artifact: PermissionRequestArtifact) => unknown;\n };\n let url: string | undefined;\n try {\n const candidate = maybeNode.getOpenKeyApprovalUrl?.(request);\n if (typeof candidate === \"string\" && candidate.length > 0) url = candidate;\n } catch {\n // The stored request remains the source of truth when a runtime does not\n // expose a canonical OpenKey URL.\n }\n return {\n kind: \"openkey\",\n requestId: request.requestId,\n ...(url === undefined ? {} : { url }),\n fallback: \"tc auth grant <request-artifact>\",\n };\n}\n\nfunction exactCapabilities(\n value: unknown,\n): CapabilityRequirement[] | undefined {\n return validateExactCapabilities(value) as\n | CapabilityRequirement[]\n | undefined;\n}\n\nfunction requirementsBelongToAuthenticatedOwner(\n requirements: readonly PermissionEntry[],\n authenticatedSpace: string | undefined,\n): boolean {\n const authenticatedOwner = canonicalPkhOwner(authenticatedSpace);\n if (authenticatedOwner === undefined) return false;\n return requirements.every((requirement) => {\n if (requirement.service === \"tinycloud.encryption\") {\n return requirement.space === undefined;\n }\n const requirementOwner = canonicalPkhOwner(requirement.space);\n return requirement.service === \"tinycloud.kv\" && requirementOwner === authenticatedOwner;\n });\n}\n\nfunction canonicalPkhOwner(space: string | undefined): string | undefined {\n if (typeof space !== \"string\") return undefined;\n const parsedSpace = parseSpaceUri(space);\n if (parsedSpace === null) return undefined;\n try {\n const pkh = parsePkhDid(parsedSpace.owner);\n return pkh === null\n ? undefined\n : parseSpaceUri(makePkhSpaceId(pkh.address, pkh.chainId, parsedSpace.name))?.owner;\n } catch {\n return undefined;\n }\n}\n\nfunction isExactLocalSecretsGetPlan(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n planned: readonly CapabilityRequirement[],\n context: RuntimeOperationContext,\n): \"valid\" | \"ineligible\" | \"invalid\" {\n if (\n prepared.definition.id !== \"tinycloud.secrets.get\" ||\n prepared.definition.version !== 1 ||\n JSON.stringify(prepared.definition.effects) !== JSON.stringify([\"read\", \"local_write\"])\n ) return \"invalid\";\n\n const resolveSpace = operationSpaceResolver(context.runtime.node, context.summary.space);\n let reference;\n try {\n reference = resolveSecretReferenceForOperation(\n prepared.parsedInput.data,\n context.runtime.node,\n context.summary.space,\n );\n } catch {\n return \"invalid\";\n }\n const canonicalPlan = canonicalizeOperationCapabilities(\n planned as unknown as PermissionEntry[],\n resolveSpace,\n );\n if (canonicalPlan.length !== 2) return \"invalid\";\n const kv = canonicalPlan.find((permission) => permission.service === \"tinycloud.kv\");\n const decrypt = canonicalPlan.find((permission) => permission.service === \"tinycloud.encryption\");\n if (kv === undefined || decrypt === undefined) return \"invalid\";\n const requestedOwner = canonicalPkhOwner(kv.space);\n const authenticatedOwner = canonicalPkhOwner(context.summary.space);\n if (requestedOwner === undefined || authenticatedOwner === undefined || requestedOwner !== authenticatedOwner) {\n return \"ineligible\";\n }\n if (JSON.stringify(kv) !== JSON.stringify({\n service: \"tinycloud.kv\",\n space: resolveSpace(reference.space),\n path: reference.permissionPath,\n actions: [\"tinycloud.kv/get\"],\n })) return \"invalid\";\n if (\n JSON.stringify(decrypt) !== JSON.stringify({\n service: \"tinycloud.encryption\",\n path: decrypt.path,\n actions: [\"tinycloud.encryption/decrypt\"],\n }) ||\n typeof decrypt.path !== \"string\" ||\n !decrypt.path.startsWith(\"urn:tinycloud:encryption:\")\n ) return \"invalid\";\n return \"valid\";\n}\n\nfunction refreshLiveRuntimeAuthority(\n node: unknown,\n requested: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace: (space: string) => string,\n): readonly CapabilityRequirement[] | undefined {\n const candidate = node as {\n hasRuntimePermissions?: (permissions: PermissionEntry[]) => unknown;\n getVerifiedSessionCapabilities?: () => unknown;\n getEffectiveRuntimePermissionEntries?: () => unknown;\n };\n if (typeof candidate.hasRuntimePermissions !== \"function\") return undefined;\n if (candidate.hasRuntimePermissions([...requested]) !== true) return undefined;\n if (typeof candidate.getVerifiedSessionCapabilities !== \"function\" ||\n typeof candidate.getEffectiveRuntimePermissionEntries !== \"function\") return undefined;\n\n const base = candidate.getVerifiedSessionCapabilities();\n const activated = candidate.getEffectiveRuntimePermissionEntries();\n if (!Array.isArray(base) || !Array.isArray(activated)) return undefined;\n const exactActivated = validateExactCapabilities(activated);\n if (exactActivated === undefined) return undefined;\n const selectedActivated = exactActivated.filter((permission) =>\n isExactCapabilityMemberSubset([permission], planned, resolveSpace),\n );\n if (!isExactCapabilityMemberSubset(requested, selectedActivated, resolveSpace)) return undefined;\n const combined = canonicalizeOperationCapabilities(\n [...base, ...selectedActivated],\n resolveSpace,\n );\n return evaluateOperationAuthority(combined, planned as unknown as PermissionEntry[], resolveSpace).satisfied\n ? combined\n : undefined;\n}\n\nfunction localAuthorityFailure(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n): OperationResult<never> {\n return errorResult(\n prepared.operation,\n prepared.runtimeResolution.context.summary,\n operationError(\n \"NODE_ERROR\",\n \"The local owner could not acquire the requested secret permissions.\",\n { retryable: true },\n ),\n );\n}\n\nfunction internalOperationErrorResult(\n prepared: Exclude<PreparedInvocation, { status: \"error\" }>,\n): OperationResult<never> {\n return errorResult(\n prepared.operation,\n prepared.runtimeResolution.context.summary,\n internalOperationError(),\n );\n}\n\nfunction isOwnerPosture(posture: OperationContextSummary[\"posture\"]): boolean {\n return posture === \"owner-openkey\" || posture === \"local-owner-key\";\n}\n\nfunction zodIssueDetails(error: ZodError): Readonly<Record<string, unknown>> {\n return {\n // The canonical error channel carries only schema-owned issue codes.\n // Messages and paths can contain arbitrary input keys and values.\n issues: error.issues.map((issue) => ({ code: issue.code })),\n };\n}\n","export type SignedObjectErrorCode =\n | \"schema-invalid\"\n | \"canonicalization-mismatch\"\n | \"digest-mismatch\"\n | \"id-mismatch\"\n | \"signing-key-binding\"\n | \"signature-material-invalid\"\n | \"signature-suite-unsupported\"\n | \"signature-invalid\";\n\nexport class SignedObjectProfileError extends Error {\n public readonly code: SignedObjectErrorCode;\n\n constructor(code: SignedObjectErrorCode, message: string) {\n super(message);\n this.name = \"SignedObjectProfileError\";\n this.code = code;\n }\n}\n\nexport class SignedObjectSchemaError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"schema-invalid\", message);\n this.name = \"SignedObjectSchemaError\";\n }\n}\n\nexport class SignedObjectCanonicalizationError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"canonicalization-mismatch\", message);\n this.name = \"SignedObjectCanonicalizationError\";\n }\n}\n\nexport class SignedObjectDigestError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"digest-mismatch\", message);\n this.name = \"SignedObjectDigestError\";\n }\n}\n\nexport class SignedObjectIdError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"id-mismatch\", message);\n this.name = \"SignedObjectIdError\";\n }\n}\n\nexport class SigningKeyBindingError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signing-key-binding\", message);\n this.name = \"SigningKeyBindingError\";\n }\n}\n\nexport class SignatureMaterialError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signature-material-invalid\", message);\n this.name = \"SignatureMaterialError\";\n }\n}\n\nexport class UnsupportedSignatureSuiteError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signature-suite-unsupported\", message);\n this.name = \"UnsupportedSignatureSuiteError\";\n }\n}\n\nexport class SignatureVerificationError extends SignedObjectProfileError {\n constructor(message: string) {\n super(\"signature-invalid\", message);\n this.name = \"SignatureVerificationError\";\n }\n}\n\nexport function toSignedObjectError(error: unknown): SignedObjectProfileError {\n if (error instanceof SignedObjectProfileError) {\n return error;\n }\n return new SignedObjectProfileError(\n \"schema-invalid\",\n error instanceof Error ? error.message : String(error),\n );\n}\n","import { SignedObjectCanonicalizationError } from \"./errors\";\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { readonly [key: string]: JsonValue };\n\ntype MutableJsonObject = { [key: string]: JsonValue };\nconst objectHasOwn: (object: object, propertyKey: PropertyKey) => boolean =\n (Object as ObjectConstructor & {\n hasOwn?: (object: object, propertyKey: PropertyKey) => boolean;\n }).hasOwn ??\n (Object.prototype.hasOwnProperty.call.bind(\n Object.prototype.hasOwnProperty,\n ) as (object: object, propertyKey: PropertyKey) => boolean);\n\n/**\n * RFC 8785 JSON Canonicalization Scheme encoder for the signed-object profile.\n *\n * This local encoder is intentionally stricter than JSON.stringify:\n * it rejects non-plain JSON inputs, sparse arrays, undefined/functions/symbols,\n * non-finite numbers, BigInt, dangerous prototype keys, and lone surrogates.\n * Object keys are sorted lexicographically by their raw UTF-16 code units,\n * as required by RFC 8785 section 3.2.3, before serialization.\n */\nexport function jcsCanonicalize(input: unknown): string {\n return serialize(normalizeJson(input, \"$\"));\n}\n\nexport function normalizeJson(input: unknown, path = \"$\"): JsonValue {\n if (input === null) {\n return null;\n }\n\n switch (typeof input) {\n case \"boolean\":\n return input;\n case \"number\":\n if (!Number.isFinite(input)) {\n throw new SignedObjectCanonicalizationError(\n `${path} must be a finite JSON number`,\n );\n }\n return input;\n case \"string\":\n assertUnicodeScalarString(input, path);\n return input;\n case \"object\":\n return normalizeJsonObjectOrArray(input, path);\n case \"bigint\":\n case \"function\":\n case \"symbol\":\n case \"undefined\":\n default:\n throw new SignedObjectCanonicalizationError(\n `${path} is not a JSON value`,\n );\n }\n}\n\nexport function serialize(value: JsonValue): string {\n if (value === null) {\n return \"null\";\n }\n\n switch (typeof value) {\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"number\": {\n const encoded = JSON.stringify(value);\n if (encoded === undefined) {\n throw new SignedObjectCanonicalizationError(\n \"number could not be serialized as JSON\",\n );\n }\n return encoded;\n }\n case \"string\":\n return JSON.stringify(value);\n case \"object\":\n if (Array.isArray(value)) {\n return `[${value.map((item) => serialize(item)).join(\",\")}]`;\n }\n return serializeObject(value);\n default:\n throw new SignedObjectCanonicalizationError(\n `unsupported JSON value type ${typeof value}`,\n );\n }\n}\n\nfunction normalizeJsonObjectOrArray(input: object, path: string): JsonValue {\n assertNoSymbolKeys(input, path);\n\n if (Array.isArray(input)) {\n for (const key of Object.getOwnPropertyNames(input)) {\n if (key === \"length\") {\n continue;\n }\n if (!isArrayIndexKey(key, input.length)) {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} is not allowed on a JSON array`,\n );\n }\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor?.enumerable !== true) {\n throw new SignedObjectCanonicalizationError(\n `${path}[${key}] must be an enumerable JSON array item`,\n );\n }\n if (!(\"value\" in descriptor)) {\n throw new SignedObjectCanonicalizationError(\n `${path}[${key}] must be a JSON data property`,\n );\n }\n }\n const output: JsonValue[] = [];\n for (let index = 0; index < input.length; index++) {\n if (!objectHasOwn(input, index)) {\n throw new SignedObjectCanonicalizationError(\n `${path}[${index}] must not be a sparse array hole`,\n );\n }\n output.push(normalizeJson(input[index], `${path}[${index}]`));\n }\n return output;\n }\n\n const proto = Object.getPrototypeOf(input);\n if (proto !== Object.prototype && proto !== null) {\n throw new SignedObjectCanonicalizationError(\n `${path} must be a plain JSON object`,\n );\n }\n\n const output = Object.create(null) as MutableJsonObject;\n for (const key of Object.getOwnPropertyNames(input)) {\n assertUnicodeScalarString(key, `${path} key`);\n if (key === \"__proto__\" || key === \"constructor\") {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} is not allowed`,\n );\n }\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor?.enumerable !== true) {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} must be an enumerable JSON object property`,\n );\n }\n if (!(\"value\" in descriptor)) {\n throw new SignedObjectCanonicalizationError(\n `${path}.${key} must be a JSON data property`,\n );\n }\n const value = descriptor.value;\n output[key] = normalizeJson(value, `${path}.${key}`);\n }\n return output;\n}\n\nfunction assertNoSymbolKeys(input: object, path: string): void {\n if (Object.getOwnPropertySymbols(input).length > 0) {\n throw new SignedObjectCanonicalizationError(\n `${path} must not have symbol properties`,\n );\n }\n}\n\nfunction isArrayIndexKey(key: string, length: number): boolean {\n if (!/^(0|[1-9]\\d*)$/.test(key)) {\n return false;\n }\n const index = Number(key);\n return Number.isSafeInteger(index) && index >= 0 && index < length;\n}\n\nfunction serializeObject(value: { readonly [key: string]: JsonValue }): string {\n const keys = Object.keys(value).sort(compareUtf16CodeUnits);\n const parts = keys.map((key) => `${JSON.stringify(key)}:${serialize(value[key])}`);\n return `{${parts.join(\",\")}}`;\n}\n\nfunction compareUtf16CodeUnits(a: string, b: string): number {\n const max = Math.min(a.length, b.length);\n for (let index = 0; index < max; index++) {\n const leftCodeUnit = a.charCodeAt(index);\n const rightCodeUnit = b.charCodeAt(index);\n if (leftCodeUnit !== rightCodeUnit) {\n return leftCodeUnit - rightCodeUnit;\n }\n }\n return a.length - b.length;\n}\n\nfunction assertUnicodeScalarString(value: string, path: string): void {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (Number.isNaN(next) || next < 0xdc00 || next > 0xdfff) {\n throw new SignedObjectCanonicalizationError(\n `${path} contains a lone high surrogate`,\n );\n }\n index++;\n continue;\n }\n if (code >= 0xdc00 && code <= 0xdfff) {\n throw new SignedObjectCanonicalizationError(\n `${path} contains a lone low surrogate`,\n );\n }\n }\n}\n","/**\n * Values allowed to cross the operation error and context channels.\n *\n * These are intentionally strict. A mismatch detail is useful only when it\n * identifies the same kind of value the runtime actually compares; treating\n * every string as safe would turn the detail field into an exfiltration path.\n */\nexport function safeOriginHost(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return undefined;\n }\n\n if (\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n parsed.username !== \"\" ||\n parsed.password !== \"\" ||\n parsed.search !== \"\" ||\n parsed.hash !== \"\" ||\n (parsed.pathname !== \"\" && parsed.pathname !== \"/\") ||\n parsed.origin === \"null\"\n ) {\n return undefined;\n }\n\n const originWithOptionalSlash = `${parsed.origin}/`;\n if (value !== parsed.origin && value !== originWithOptionalSlash) {\n return undefined;\n }\n return parsed.origin;\n}\n\nexport function safeSessionDid(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n\n const [principal, fragment, ...extra] = value.split(\"#\");\n if (\n extra.length > 0 ||\n (fragment !== undefined && !/^[A-Za-z0-9._:-]+$/.test(fragment))\n ) {\n return undefined;\n }\n\n if (isEd25519DidKey(principal) || isEip155PkhDid(principal)) {\n return principal;\n }\n return undefined;\n}\n\nfunction isEd25519DidKey(value: string): boolean {\n if (!value.startsWith(\"did:key:z\")) return false;\n const bytes = decodeBase58(value.slice(\"did:key:z\".length));\n return (\n bytes !== undefined &&\n bytes.length === 34 &&\n bytes[0] === 0xed &&\n bytes[1] === 0x01\n );\n}\n\nfunction isEip155PkhDid(value: string): boolean {\n return /^did:pkh:eip155:[1-9][0-9]*:0x[0-9a-fA-F]{40}$/.test(value);\n}\n\nfunction decodeBase58(value: string): Uint8Array | undefined {\n if (value.length === 0) return undefined;\n const alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n const digits = [0];\n for (const character of value) {\n const index = alphabet.indexOf(character);\n if (index < 0) return undefined;\n let carry = index;\n for (let i = 0; i < digits.length; i += 1) {\n carry += digits[i]! * 58;\n digits[i] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n digits.push(carry & 0xff);\n carry >>= 8;\n }\n }\n for (const character of value) {\n if (character !== \"1\") break;\n digits.push(0);\n }\n return Uint8Array.from(digits.reverse());\n}\n","import type {\n OperationContextSummary,\n OperationDefinition,\n OperationRef,\n} from \"./contract.js\";\nimport type { OperationError, OperationErrorCode } from \"./errors.js\";\nimport { safeOriginHost, safeSessionDid } from \"./safe-values.js\";\n\nexport const REDACTED_VALUE = \"[REDACTED]\";\n\nexport interface SafeOperationDiagnostic {\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly input?: unknown;\n readonly output?: unknown;\n readonly error?: OperationError;\n}\n\n/**\n * Return a detached redacted value. A missing pointer is intentionally a no-op\n * so an operation can evolve an optional shape without leaking another field.\n */\nexport function redactOperationValue(\n definition: Pick<OperationDefinition<unknown, unknown>, \"sensitivity\">,\n value: unknown,\n): unknown {\n const clone = cloneValue(value);\n const pointers = [\n ...definition.sensitivity.input,\n ...definition.sensitivity.output,\n ];\n\n let redacted: unknown = clone;\n for (const pointer of pointers) {\n redacted = redactPointer(redacted, pointer);\n }\n return redacted;\n}\n\n/**\n * Diagnostic payloads are a supported non-result channel. They accept raw\n * operation values only through this helper, never an invocation target.\n */\nexport function createSafeOperationDiagnostic(\n definition: Pick<OperationDefinition<unknown, unknown>, \"sensitivity\">,\n diagnostic: Readonly<{\n operation: OperationRef;\n context: OperationContextSummary;\n input?: unknown;\n output?: unknown;\n error?: OperationError;\n }>,\n): SafeOperationDiagnostic {\n return {\n operation: {\n operationId: diagnostic.operation.operationId,\n operationVersion: diagnostic.operation.operationVersion,\n },\n context: {\n profile: diagnostic.context.profile,\n host: diagnostic.context.host,\n posture: diagnostic.context.posture,\n ...(diagnostic.context.operatorType === undefined\n ? {}\n : { operatorType: diagnostic.context.operatorType }),\n ...(diagnostic.context.principalDid === undefined\n ? {}\n : { principalDid: diagnostic.context.principalDid }),\n ...(diagnostic.context.sessionDid === undefined\n ? {}\n : { sessionDid: diagnostic.context.sessionDid }),\n ...(diagnostic.context.ownerDid === undefined\n ? {}\n : { ownerDid: diagnostic.context.ownerDid }),\n ...(diagnostic.context.space === undefined\n ? {}\n : { space: diagnostic.context.space }),\n },\n ...(diagnostic.input === undefined\n ? {}\n : { input: redactOperationValue(definition, diagnostic.input) }),\n ...(diagnostic.output === undefined\n ? {}\n : { output: redactOperationValue(definition, diagnostic.output) }),\n ...(diagnostic.error === undefined\n ? {}\n : { error: redactOperationError(definition, diagnostic.error) }),\n };\n}\n\nexport function redactOperationError(\n _definition: Pick<OperationDefinition<unknown, unknown>, \"sensitivity\">,\n error: OperationError,\n): OperationError {\n const details =\n error.details === undefined\n ? undefined\n : redactSafeErrorDetails(error.code, error.details);\n\n return {\n code: error.code,\n message: error.message,\n retryable: error.retryable,\n ...(details === undefined\n ? {}\n : {\n details: isRecord(details) ? details : { redacted: details },\n }),\n };\n}\n\n/**\n * Error details are a separate, code-owned channel. Only fields with an\n * explicit stable policy can cross the canonical result or diagnostic\n * boundary; arbitrary handler details are dropped rather than redacted by\n * input pointers, which could accidentally preserve a transport secret.\n */\nconst SAFE_ERROR_DETAIL_POLICIES: Readonly<\n Partial<\n Record<\n OperationErrorCode,\n Readonly<Record<string, (value: unknown) => unknown | undefined>>\n >\n >\n> = {\n INPUT_INVALID: {\n issues: (value) =>\n Array.isArray(value) ? safeIssueCodes(value) : undefined,\n },\n OPERATION_VERSION_UNSUPPORTED: {\n supportedVersions: (value) =>\n Array.isArray(value) && value.every((item) => Number.isInteger(item))\n ? value\n : undefined,\n },\n DELEGATION_AUDIENCE_MISMATCH: {\n expectedSessionDid: safeSessionDid,\n artifactAudience: safeSessionDid,\n },\n DELEGATION_HOST_MISMATCH: {\n expectedHost: safeOriginHost,\n artifactHost: safeOriginHost,\n },\n STORAGE_QUOTA_EXCEEDED: {\n account: safeStorageAccount,\n },\n};\n\n/** Account-wide totals only; a zero budget explains nothing and is dropped. */\nfunction safeStorageAccount(value: unknown): unknown | undefined {\n if (!isRecord(value)) return undefined;\n const { usedBytes, limitBytes, plan } = value;\n if (\n !Number.isSafeInteger(usedBytes) || (usedBytes as number) < 0 ||\n !Number.isSafeInteger(limitBytes) || (limitBytes as number) <= 0\n ) {\n return undefined;\n }\n return typeof plan === \"string\" && /^[A-Za-z0-9][A-Za-z0-9 _.-]{0,31}$/.test(plan)\n ? { usedBytes, limitBytes, plan }\n : { usedBytes, limitBytes };\n}\n\nfunction redactSafeErrorDetails(\n code: OperationErrorCode,\n details: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> | undefined {\n const policy = SAFE_ERROR_DETAIL_POLICIES[code];\n if (policy === undefined) return undefined;\n\n const safeDetails: Record<string, unknown> = {};\n for (const [key, sanitize] of Object.entries(policy)) {\n if (!hasOwn(details, key)) continue;\n const value = sanitize(details[key]);\n if (value !== undefined) safeDetails[key] = value;\n }\n return Object.keys(safeDetails).length === 0 ? undefined : safeDetails;\n}\n\nfunction safeIssueCodes(\n value: readonly unknown[],\n): readonly Readonly<{ code: string }>[] | undefined {\n const codes = value.map((issue) => {\n if (!isRecord(issue) || typeof issue.code !== \"string\") return undefined;\n return SAFE_ISSUE_CODES.has(issue.code) ? { code: issue.code } : undefined;\n });\n return codes.every(\n (issue): issue is Readonly<{ code: string }> => issue !== undefined,\n )\n ? codes\n : undefined;\n}\n\nconst SAFE_ISSUE_CODES = new Set([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\n\nfunction redactPointer(value: unknown, pointer: string): unknown {\n if (pointer === \"\") {\n return REDACTED_VALUE;\n }\n if (!pointer.startsWith(\"/\")) {\n return value;\n }\n\n const tokens = pointer.slice(1).split(\"/\").map(unescapePointerToken);\n const parent = getPointerParent(value, tokens);\n if (parent === undefined) {\n return value;\n }\n\n const key = tokens[tokens.length - 1];\n if (key === undefined || !hasOwn(parent, key)) {\n return value;\n }\n\n Reflect.set(parent, key, REDACTED_VALUE);\n return value;\n}\n\nfunction getPointerParent(\n value: unknown,\n tokens: readonly string[],\n): Record<string, unknown> | unknown[] | undefined {\n if (tokens.length === 0) {\n return undefined;\n }\n\n let cursor = value;\n for (const token of tokens.slice(0, -1)) {\n if (!isRecordOrArray(cursor) || !hasOwn(cursor, token)) {\n return undefined;\n }\n cursor = Reflect.get(cursor, token);\n }\n return isRecordOrArray(cursor) ? cursor : undefined;\n}\n\nfunction unescapePointerToken(token: string): string {\n return token.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\nfunction cloneValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => cloneValue(entry));\n }\n\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n Object.defineProperty(clone, key, {\n configurable: true,\n enumerable: true,\n value: cloneValue((value as Record<string, unknown>)[key]),\n writable: true,\n });\n }\n return clone;\n}\n\nfunction isRecordOrArray(\n value: unknown,\n): value is Record<string, unknown> | unknown[] {\n return value !== null && typeof value === \"object\";\n}\n\nfunction hasOwn(value: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(value, key);\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import type { InvocationTarget, OperationResult } from \"./contract.js\";\nimport { invokeOperationWithLocalAuthorityRetry } from \"./invoke.js\";\n\n/**\n * The only published CLI acquisition helper. Its fixed operation identity is\n * deliberate: adding a future registry operation cannot expand this seam.\n */\nexport function invokeSecretsGetWithLocalAuthorityRetry(\n invocationTarget: InvocationTarget,\n unknownInput: unknown,\n): Promise<OperationResult<unknown>> {\n return invokeOperationWithLocalAuthorityRetry(\n \"tinycloud.secrets.get\",\n 1,\n invocationTarget,\n unknownInput,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CO,SAAS,eACd,MACA,SACA,UAGK,CAAC,GACU;AAChB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,WAAW,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AAC9D,QAAM,iBAAiB,0BAA0B,SAAS;AAC1D,MAAI,mBAAmB,OAAW,QAAO;AACzC,QAAM,oBAAoB,eAAe;AAAA,IAAO,CAAC,eAC/C,8BAA8B,CAAC,UAAU,GAAG,SAASA,aAAY;AAAA,EACnE;AACA,MAAI,CAAC,8BAA8B,WAAW,mBAAmBA,aAAY,EAAG,QAAO;AACvF,QAAM,WAAW;AAAA,IACf,CAAC,GAAG,MAAM,GAAG,iBAAiB;AAAA,IAC9BA;AAAA,EACF;AACA,SAAO,2BAA2B,UAAU,SAAyCA,aAAY,EAAE,YAC/F,WACA;AACN;AAEA,SAAS,sBACP,UACwB;AACxB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,SAAS,kBAAkB,QAAQ;AAAA,IACnC;AAAA,MACE;AAAA,MACA;AAAA,MACA,EAAE,WAAW,KAAK;AAAA,IACpB;AAAA,EACF;AACF;AAEA,SAAS,6BACP,UACwB;AACxB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,SAAS,kBAAkB,QAAQ;AAAA,IACnC,uBAAuB;AAAA,EACzB;AACF;AAEA,SAAS,eAAe,SAAsD;AAC5E,SAAO,YAAY,mBAAmB,YAAY;AACpD;AAEA,SAAS,gBAAgB,OAAoD;AAC3E,SAAO;AAAA;AAAA;AAAA,IAGL,QAAQ,MAAM,OAAO,IAAI,CAAC,WAAW,EAAE,MAAM,MAAM,KAAK,EAAE;AAAA,EAC5D;AACF;;;AKrgCO,SAAS,wCACd,kBACA,cACmC;AACnC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["operationError","ms","resolveSpace","_a","ownership","resolve","randomUUID","resolveSpace","SECRET_NAME_RE","nodeSdk","z","resolveSpace","z","isRecord","EmptyInputSchema","z","z","runtimeContext","runtimeNode","isRecord","nodeFailure","isCanonicalBase64","SpaceSchema","AUTHENTICATED_POSTURES","join","nodeSdk","isRecord","z","isRecord","definition","profileNotFound","isRecord","nodeSdk","isRecord","resolveSpace","principal","isAbsolute","makePkhSpaceId","parsePkhDid","parseSpaceUri","output","principal","runtimeContext","exactCapabilities","resolveSpace","lookupOperation","isAbsolute","createInvocationRuntime","parseSpaceUri","parsePkhDid","makePkhSpaceId"]}