{"version":3,"sources":["../src/core.ts","../src/storage/MemorySessionStorage.ts","../src/storage/FileSessionStorage.ts","../src/authorization/NodeUserAuthorization.ts","../src/authorization/strategies.ts","../src/TinyCloudNode.ts","../src/account/AccountService.ts","../src/DelegatedAccess.ts","../src/keys/WasmKeyProvider.ts","../src/delegateToHelpers.ts","../src/NodeSecretsService.ts","../src/delegation.ts"],"sourcesContent":["/**\n * @tinycloud/node-sdk/core\n *\n * Platform-agnostic entry point for TinyCloud node-sdk.\n *\n * This entry point excludes Node.js-specific modules that depend on\n * @tinycloud/node-sdk-wasm (PrivateKeySigner, NodeWasmBindings), making it\n * safe to import in browser builds without webpack aliases or shims.\n *\n * Browser consumers (e.g., @tinycloud/web-sdk) should import from this\n * entry point instead of the root \"@tinycloud/node-sdk\".\n *\n * @packageDocumentation\n */\n\n// Re-export core values\nexport { TinyCloud } from \"@tinycloud/sdk-core\";\n\n// Re-export core types\nexport type {\n  TinyCloudConfig,\n  ISigner,\n  ISessionStorage,\n  IUserAuthorization,\n  ClientSession,\n  Extension,\n  SignInOptions,\n  PersistedSessionData,\n  TinyCloudSession,\n  INotificationHandler,\n  IENSResolver,\n  IWasmBindings,\n  ISessionManager,\n  ISpaceCreationHandler,\n  SpaceCreationContext,\n  CanonicalAddress,\n  CanonicalParsedNetworkId,\n  DidCacheKeyOptions,\n  DidEqualsOptions,\n  PkhDidParts,\n  TinyCloudDebugEvent,\n  TinyCloudDebugLevel,\n  TinyCloudDebugEnableOptions,\n  TinyCloudDebugTimer,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export core values for extensibility\nexport {\n  SilentNotificationHandler,\n  AutoApproveSpaceCreationHandler,\n  defaultSpaceCreationHandler,\n  IdentityParseError,\n  addressStorageKey,\n  canonicalizeAddress,\n  canonicalizeDid,\n  canonicalizeDidUrl,\n  canonicalizeNetworkId,\n  didCacheKey,\n  didEquals,\n  isEvmAddress,\n  makePkhSpaceId,\n  parsePkhDid,\n  pkhDid,\n  principalDid,\n  principalDidEquals,\n  parseCanonicalNetworkId,\n  TinyCloudDebugLogger,\n  tinyCloudDebugLogger,\n  enableTinyCloudDebug,\n  disableTinyCloudDebug,\n  getTinyCloudDebugLogs,\n  clearTinyCloudDebugLogs,\n  installTinyCloudDebugGlobals,\n} from \"@tinycloud/sdk-core\";\n\n// Storage implementations\nexport { MemorySessionStorage } from \"./storage/MemorySessionStorage\";\nexport { FileSessionStorage } from \"./storage/FileSessionStorage\";\n\n// Authorization\nexport {\n  NodeUserAuthorization,\n  type NodeUserAuthorizationConfig,\n} from \"./authorization/NodeUserAuthorization\";\n\n// Sign strategies — value exports\nexport {\n  createOpenKeyCallbackSigningStrategy,\n  defaultSignStrategy,\n} from \"./authorization/strategies\";\n\n// Sign strategies — type exports (re-exported from sdk-core + Node.js-specific types)\nexport type {\n  SignRequest,\n  SignResponse,\n  SignCallback,\n  AutoSignStrategy,\n  AutoRejectStrategy,\n  CallbackStrategy,\n  OpenKeySigningStrategyOptions,\n  OpenKeySigningRequestBody,\n  OpenKeySigningResponseBody,\n  OpenKeyCallbackStrategy,\n  NodeEventEmitterStrategy,\n  SignStrategy,\n} from \"./authorization/strategies\";\n\n// High-level API\nexport {\n  TinyCloudNode,\n  UnsupportedSessionRestoreError,\n  type TinyCloudNodeConfig,\n  type DelegateToOptions,\n  type DelegateToResult,\n  type RuntimePermissionGrantOptions,\n  type SecretReadInput,\n  type SecretPermissionHint,\n  type SecretReadResult,\n} from \"./TinyCloudNode\";\n\nexport { AccountService } from \"./account/AccountService\";\nexport type {\n  AccountApplication,\n  AccountApplicationListOptions,\n  AccountDelegation,\n  AccountDelegationListOptions,\n  AccountDelegationRevokeOptions,\n  AccountIndexEnsureResult,\n  AccountIndexRebuildResult,\n  AccountIndexStatus,\n  AccountIndexedReadOptions,\n  AccountServiceConfig,\n  AccountSpace,\n  AccountSpaceListOptions,\n  AccountStatus,\n} from \"./account/AccountService\";\n\n// Capability-chain primitives (spec: .claude/specs/capability-chain.md).\n// Re-exported here so TinyCloudWeb and other consumers can pass\n// `PermissionEntry[]` to `delegateTo` and catch the error classes without\n// also importing from `@tinycloud/sdk-core`.\nexport {\n  type PermissionEntry,\n  type Manifest,\n  type ManifestDefaults,\n  type ManifestSecretActions,\n  type ComposeManifestOptions,\n  type ComposedManifestRequest,\n  type ManifestRegistryRecord,\n  type ResolvedCapabilities,\n  type ResolvedDelegate,\n  type ResourceCapability,\n  type SpaceAbilitiesMap,\n  ACCOUNT_REGISTRY_PATH,\n  ACCOUNT_REGISTRY_SPACE,\n  DEFAULT_MANIFEST_SPACE,\n  DEFAULT_MANIFEST_VERSION,\n  VAULT_PERMISSION_SERVICE,\n  CaveatedDelegationUnsupportedError,\n  PermissionNotInManifestError,\n  SessionExpiredError,\n  ManifestValidationError,\n  composeManifestRequest,\n  resolveManifest,\n  validateManifest,\n  loadManifest,\n  isCapabilitySubset,\n  expandActionShortNames,\n  expandPermissionEntries,\n  expandPermissionEntry,\n  parseExpiry,\n  resourceCapabilitiesToSpaceAbilitiesMap,\n} from \"@tinycloud/sdk-core\";\n\n// Delegation\nexport { DelegatedAccess } from \"./DelegatedAccess\";\nexport { serializeDelegation, deserializeDelegation } from \"./delegation\";\nexport type { PortableDelegation } from \"./delegation\";\n\n// Re-export KV service values\nexport {\n  DEFAULT_SIGNED_READ_URL_EXPIRY_MS,\n  KVService,\n  PrefixedKVService,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export KV service types\nexport type {\n  IKVService,\n  KVServiceConfig,\n  KVCreateSignedReadUrlOptions,\n  KVResponse,\n  KVSignedReadUrlResponse,\n  IPrefixedKVService,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export SQL service values\nexport { SQLService, SQLAction, DatabaseHandle } from \"@tinycloud/sdk-core\";\n\n// Re-export SQL service types\nexport type {\n  ISQLService,\n  IDatabaseHandle,\n  SQLServiceConfig,\n  SqlValue,\n  SqlStatement,\n  QueryOptions,\n  ExecuteOptions,\n  BatchOptions,\n  QueryResponse,\n  ExecuteResponse,\n  BatchResponse,\n  SQLActionType,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export DuckDB service values\nexport {\n  DuckDbService,\n  DuckDbDatabaseHandle,\n  DuckDbAction,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export DuckDB service types\nexport type {\n  IDuckDbService,\n  IDuckDbDatabaseHandle,\n  DuckDbServiceConfig,\n  DuckDbQueryOptions,\n  DuckDbExecuteOptions,\n  DuckDbBatchOptions,\n  DuckDbOptions,\n  DuckDbValue,\n  DuckDbStatement,\n  DuckDbQueryResponse,\n  DuckDbExecuteResponse,\n  DuckDbBatchResponse,\n  DuckDbActionType,\n  SchemaInfo,\n  TableInfo,\n  ColumnInfo,\n  ViewInfo,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export Vault and Secrets service values\nexport {\n  DataVaultService,\n  VaultHeaders,\n  VaultPublicSpaceKVActions,\n  createVaultCrypto,\n  SecretsService,\n  SECRET_NAME_RE,\n  canonicalizeSecretScope,\n  resolveSecretListPrefix,\n  resolveSecretPath,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export Vault and Secrets service types\nexport type {\n  IDataVaultService,\n  VaultCrypto,\n  WasmVaultFunctions,\n  DataVaultConfig,\n  VaultPutOptions,\n  VaultGetOptions,\n  VaultListOptions,\n  VaultGrantOptions,\n  VaultEntry,\n  VaultNetworkReadResult,\n  VaultError,\n  ISecretsService,\n  SecretPayload,\n  SecretsError,\n  ResolvedSecretPath,\n  SecretScopeOptions,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export v2 Delegation service values\nexport {\n  DelegationManager,\n  SharingService,\n  createSharingService,\n  DelegationErrorCodes,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export v2 Delegation types\nexport type {\n  DelegationManagerConfig,\n  ISharingService,\n  SharingServiceConfig,\n  EncodedShareData,\n  ReceiveOptions,\n  ShareAccess,\n  DelegateReceivedShareParams,\n  DelegatedShareAccess,\n  Delegation,\n  CreateDelegationParams,\n  DelegationResult,\n  DelegationError,\n  DelegationErrorCode,\n  JWK,\n  KeyType,\n  KeyInfo,\n  CapabilityEntry,\n  DelegationRecord,\n  SpaceOwnership,\n  SpaceInfo,\n  ShareSchema,\n  ShareLink,\n  ShareLinkData,\n  IngestOptions,\n  GenerateShareParams,\n  DelegationChain,\n  DelegationChainV2,\n  DelegationDirection,\n  DelegationFilters,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export CapabilityKeyRegistry values (v2)\nexport {\n  CapabilityKeyRegistry,\n  createCapabilityKeyRegistry,\n  CapabilityKeyRegistryErrorCodes,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export CapabilityKeyRegistry types (v2)\nexport type {\n  ICapabilityKeyRegistry,\n  StoredDelegationChain,\n  CapabilityKeyRegistryErrorCode,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export SpaceService values (v2)\nexport {\n  SpaceService,\n  SpaceErrorCodes,\n  createSpaceService,\n  parseSpaceUri,\n  buildSpaceUri,\n  makePublicSpaceId,\n  Space,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export SpaceService types (v2)\nexport type {\n  ISpaceService,\n  SpaceServiceConfig,\n  SpaceErrorCode,\n  ISpace,\n  SpaceConfig,\n  ISpaceScopedDelegations,\n  ISpaceScopedSharing,\n} from \"@tinycloud/sdk-core\";\n\n// Protocol version checking\nexport {\n  ProtocolMismatchError,\n  VersionCheckError,\n  UnsupportedFeatureError,\n  checkNodeInfo,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export ServiceContext value for advanced usage\nexport { ServiceContext } from \"@tinycloud/sdk-core\";\n\n// Re-export ServiceContext types for advanced usage\nexport type {\n  ServiceContextConfig,\n  ServiceSession,\n  InvokeFunction,\n  FetchFunction,\n  TelemetryConfig,\n  TelemetryEventHandler,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export KeyProvider interface from sdk-core\nexport type { KeyProvider } from \"@tinycloud/sdk-core\";\n\n// Key management for node-sdk\nexport {\n  WasmKeyProvider,\n  type WasmKeyProviderConfig,\n  createWasmKeyProvider,\n} from \"./keys/WasmKeyProvider\";\n","import { ISessionStorage, PersistedSessionData } from \"@tinycloud/sdk-core\";\n\n/**\n * In-memory session storage for Node.js.\n *\n * Sessions are stored in memory and lost when the process exits.\n * Suitable for:\n * - Development and testing\n * - Stateless server deployments\n * - Short-lived processes\n *\n * @example\n * ```typescript\n * const storage = new MemorySessionStorage();\n * await storage.save(\"0x123...\", sessionData);\n * const session = await storage.load(\"0x123...\");\n * ```\n */\nexport class MemorySessionStorage implements ISessionStorage {\n  private sessions: Map<string, PersistedSessionData> = new Map();\n\n  /**\n   * Save a session for an address.\n   */\n  async save(address: string, session: PersistedSessionData): Promise<void> {\n    const normalizedAddress = address.toLowerCase();\n    this.sessions.set(normalizedAddress, session);\n  }\n\n  /**\n   * Load a session for an address.\n   */\n  async load(address: string): Promise<PersistedSessionData | null> {\n    const normalizedAddress = address.toLowerCase();\n    const session = this.sessions.get(normalizedAddress);\n\n    if (!session) {\n      return null;\n    }\n\n    // Check if session is expired\n    const expiresAt = new Date(session.expiresAt);\n    if (expiresAt < new Date()) {\n      this.sessions.delete(normalizedAddress);\n      return null;\n    }\n\n    return session;\n  }\n\n  /**\n   * Clear a session for an address.\n   */\n  async clear(address: string): Promise<void> {\n    const normalizedAddress = address.toLowerCase();\n    this.sessions.delete(normalizedAddress);\n  }\n\n  /**\n   * Check if a session exists for an address.\n   */\n  exists(address: string): boolean {\n    const normalizedAddress = address.toLowerCase();\n    const session = this.sessions.get(normalizedAddress);\n\n    if (!session) {\n      return false;\n    }\n\n    // Check if session is expired\n    const expiresAt = new Date(session.expiresAt);\n    if (expiresAt < new Date()) {\n      this.sessions.delete(normalizedAddress);\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Memory storage is always available.\n   */\n  isAvailable(): boolean {\n    return true;\n  }\n\n  /**\n   * Clear all sessions.\n   */\n  clearAll(): void {\n    this.sessions.clear();\n  }\n\n  /**\n   * Get the number of stored sessions.\n   */\n  size(): number {\n    return this.sessions.size;\n  }\n}\n","import { ISessionStorage, PersistedSessionData, validatePersistedSessionData } from \"@tinycloud/sdk-core\";\nimport { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\n/**\n * File-based session storage for Node.js.\n *\n * Sessions are persisted to the file system and survive process restarts.\n * Suitable for:\n * - CLI applications\n * - Long-running server processes\n * - Development environments\n *\n * @example\n * ```typescript\n * const storage = new FileSessionStorage(\"/tmp/tinycloud-sessions\");\n * await storage.save(\"0x123...\", sessionData);\n * // Session persists across process restarts\n * ```\n */\nexport class FileSessionStorage implements ISessionStorage {\n  private readonly baseDir: string;\n\n  /**\n   * Create a new FileSessionStorage.\n   *\n   * @param baseDir - Directory to store session files (default: ~/.tinycloud/sessions)\n   */\n  constructor(baseDir?: string) {\n    this.baseDir = baseDir || this.getDefaultDir();\n    this.ensureDirectoryExists();\n  }\n\n  /**\n   * Get the default session storage directory.\n   */\n  private getDefaultDir(): string {\n    const home = process.env.HOME || process.env.USERPROFILE || \"/tmp\";\n    return join(home, \".tinycloud\", \"sessions\");\n  }\n\n  /**\n   * Ensure the storage directory exists.\n   */\n  private ensureDirectoryExists(): void {\n    if (!existsSync(this.baseDir)) {\n      mkdirSync(this.baseDir, { recursive: true });\n    }\n  }\n\n  /**\n   * Get the file path for an address.\n   */\n  private getFilePath(address: string): string {\n    const normalizedAddress = address.toLowerCase();\n    // Use a hash of the address to avoid filesystem issues\n    const filename = `${normalizedAddress.replace(\"0x\", \"\")}.json`;\n    return join(this.baseDir, filename);\n  }\n\n  /**\n   * Save a session for an address.\n   */\n  async save(address: string, session: PersistedSessionData): Promise<void> {\n    const filePath = this.getFilePath(address);\n    const data = JSON.stringify(session, null, 2);\n    writeFileSync(filePath, data, \"utf-8\");\n  }\n\n  /**\n   * Load a session for an address.\n   */\n  async load(address: string): Promise<PersistedSessionData | null> {\n    const filePath = this.getFilePath(address);\n\n    if (!existsSync(filePath)) {\n      return null;\n    }\n\n    try {\n      const data = readFileSync(filePath, \"utf-8\");\n      const parsed = JSON.parse(data);\n\n      // Validate loaded data against schema\n      const validation = validatePersistedSessionData(parsed);\n      if (!validation.ok) {\n        console.warn(`Invalid session data for ${address}:`, validation.error.message);\n        // Clean up invalid session\n        unlinkSync(filePath);\n        return null;\n      }\n\n      const session = validation.data;\n\n      // Check if session is expired\n      const expiresAt = new Date(session.expiresAt);\n      if (expiresAt < new Date()) {\n        // Clean up expired session\n        unlinkSync(filePath);\n        return null;\n      }\n\n      return session;\n    } catch (error) {\n      // Invalid JSON or read error - remove the file\n      try {\n        unlinkSync(filePath);\n      } catch {\n        // Ignore cleanup errors\n      }\n      return null;\n    }\n  }\n\n  /**\n   * Clear a session for an address.\n   */\n  async clear(address: string): Promise<void> {\n    const filePath = this.getFilePath(address);\n    if (existsSync(filePath)) {\n      unlinkSync(filePath);\n    }\n  }\n\n  /**\n   * Check if a session exists for an address.\n   */\n  exists(address: string): boolean {\n    const filePath = this.getFilePath(address);\n    if (!existsSync(filePath)) {\n      return false;\n    }\n\n    try {\n      const data = readFileSync(filePath, \"utf-8\");\n      const session: PersistedSessionData = JSON.parse(data);\n\n      // Check if session is expired\n      const expiresAt = new Date(session.expiresAt);\n      if (expiresAt < new Date()) {\n        // Clean up expired session\n        unlinkSync(filePath);\n        return false;\n      }\n\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Check if file system storage is available.\n   */\n  isAvailable(): boolean {\n    try {\n      this.ensureDirectoryExists();\n      return existsSync(this.baseDir);\n    } catch {\n      return false;\n    }\n  }\n}\n","import { EventEmitter } from \"events\";\nimport {\n  IUserAuthorization,\n  ISigner,\n  ISessionStorage,\n  ClientSession,\n  Extension,\n  PersistedSessionData,\n  TinyCloudSession,\n  SiweConfig,\n  SignInOptions,\n  SpaceHostResult,\n  fetchPeerId,\n  submitHostDelegation,\n  activateSessionWithHost,\n  checkNodeInfo,\n  ISpaceCreationHandler,\n  AutoApproveSpaceCreationHandler,\n  IWasmBindings,\n  ISessionManager,\n  Manifest,\n  ComposedManifestRequest,\n  AbilitiesMap,\n  DEFAULT_MANIFEST_SPACE,\n  ENCRYPTION_PERMISSION_SERVICE,\n  composeManifestRequest,\n  parseNetworkId,\n  principalDidEquals,\n  resourceCapabilitiesToAbilitiesMap,\n  resourceCapabilitiesToSpaceAbilitiesMap,\n  resolveTinyCloudHosts,\n  type LocalNodeIdentityStore,\n  EXPIRY,\n  canonicalizeAddress,\n  makePkhSpaceId,\n  pkhDid,\n  KV,\n  SQL,\n  DUCKDB,\n  CAPABILITIES,\n  HOOKS,\n  ENCRYPTION,\n} from \"@tinycloud/sdk-core\";\nimport {\n  SignStrategy,\n  SignRequest,\n  SignResponse,\n  defaultSignStrategy,\n} from \"./strategies\";\nimport { MemorySessionStorage } from \"../storage/MemorySessionStorage\";\n\nconst DECRYPT_ACTION = ENCRYPTION.DECRYPT;\nconst NETWORK_CREATE_ACTION = ENCRYPTION.NETWORK_CREATE;\n\nfunction didPrincipalMatches(actual: string, expected: string): boolean {\n  try {\n    return principalDidEquals(actual, expected);\n  } catch {\n    return actual === expected;\n  }\n}\n\nfunction addRawAbility(\n  rawAbilities: Record<string, string[]>,\n  resource: string,\n  action: string,\n): void {\n  const actions = rawAbilities[resource];\n  if (actions === undefined) {\n    rawAbilities[resource] = [action];\n    return;\n  }\n  if (!actions.includes(action)) {\n    actions.push(action);\n  }\n}\n\n/**\n * Configuration for NodeUserAuthorization.\n */\nexport interface NodeUserAuthorizationConfig {\n  /** The signer used for signing messages */\n  signer: ISigner;\n  /** Sign strategy for handling sign requests */\n  signStrategy?: SignStrategy;\n  /** Session storage implementation */\n  sessionStorage?: ISessionStorage;\n  /** Domain for SIWE messages */\n  domain: string;\n  /** URI for SIWE messages (default: domain) */\n  uri?: string;\n  /** Statement included in SIWE messages */\n  statement?: string;\n  /** Space prefix for new sessions */\n  spacePrefix?: string;\n  /** Default actions for sessions */\n  defaultActions?: Record<string, Record<string, string[]>>;\n  /** Session expiration time in milliseconds (default: 1 hour) */\n  sessionExpirationMs?: number;\n  /** Automatically create space if it doesn't exist (default: false) */\n  autoCreateSpace?: boolean;\n  /** Custom space creation handler. If provided, takes precedence over autoCreateSpace. */\n  spaceCreationHandler?: ISpaceCreationHandler;\n  /** Explicit TinyCloud server endpoints. When omitted, signIn resolves the user's host. */\n  tinycloudHosts?: string[];\n  /** TinyCloud location registry URL. Default: https://registry.tinycloud.xyz. */\n  tinycloudRegistryUrl?: string | null;\n  /** Fallback TinyCloud hosts. Default: hosted TinyCloud node. */\n  tinycloudFallbackHosts?: string[] | null;\n  /** Probe for a locally-running TinyCloud node before registry/fallback resolution. Default: true. */\n  autoDiscoverLocalNode?: boolean;\n  /** Local loopback node URL to probe. Default: http://127.0.0.1:8000. */\n  localNodeUrl?: string;\n  /** Known `*.local.tinycloud.link` subdomain name, probed directly. */\n  localLinkName?: string;\n  /** Expected local node DID. A locally-discovered node whose DID differs is rejected. */\n  expectedNodeDid?: string;\n  /** Pin store for trust-on-first-use local node identity verification. Defaults to an in-memory store. */\n  localNodeIdentityStore?: LocalNodeIdentityStore;\n  /** Whether to include public space capabilities in the session (default: true) */\n  enablePublicSpace?: boolean;\n  /** WASM bindings for cryptographic operations. Required. */\n  wasmBindings: IWasmBindings;\n  /** Existing session manager to share with a higher-level SDK client. */\n  sessionManager?: ISessionManager;\n  /**\n   * SIWE nonce override. If omitted, the WASM layer generates a random nonce.\n   * If `siweConfig.nonce` is also provided, `siweConfig.nonce` wins.\n   */\n  nonce?: string;\n  /** Optional SIWE configuration overrides (e.g., nonce for server-provided nonces) */\n  siweConfig?: SiweConfig;\n  /**\n   * App manifest used to drive the SIWE recap at sign-in.\n   *\n   * When set, `signIn` resolves the manifest (via\n   * {@link resolveManifest}), unions the app's own permissions with\n   * every `delegations[*].permissions` list, converts to the WASM\n   * abilities shape, and uses that map as the session's granted\n   * capabilities — *instead* of `defaultActions`.\n   *\n   * This is what makes manifest-declared pre-delegations usable: the\n   * session key's recap covers both the app's runtime needs and the\n   * downstream delegation targets, so `delegateTo` can issue the\n   * sub-delegation via the session-key UCAN path without a wallet\n   * prompt.\n   *\n   * When omitted, `signIn` falls back to `defaultActions` for\n   * backwards compatibility.\n   */\n  manifest?: Manifest | Manifest[];\n  /** Pre-composed manifest request. Takes precedence over `manifest`. */\n  capabilityRequest?: ComposedManifestRequest;\n  /** Include implicit account registry permissions when composing `manifest`. Default true. */\n  includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface CreateBootstrapSessionOptions {\n  spaceId: string;\n  capabilityRequest: ComposedManifestRequest;\n  rawAbilities?: Record<string, string[]>;\n}\n\n/**\n * Node.js implementation of IUserAuthorization.\n *\n * Supports multiple sign strategies for different use cases:\n * - auto-sign: Automatically approve all sign requests (trusted backends)\n * - auto-reject: Reject all sign requests (read-only mode)\n * - callback: Delegate to a custom callback function (CLI prompts)\n * - event-emitter: Emit sign requests as events (async workflows)\n *\n * @example\n * ```typescript\n * // Auto-sign for backend services\n * const auth = new NodeUserAuthorization({\n *   signer: new PrivateKeySigner(process.env.PRIVATE_KEY),\n *   signStrategy: { type: 'auto-sign' },\n *   domain: 'api.myapp.com',\n * });\n *\n * // Callback for CLI prompts\n * const auth = new NodeUserAuthorization({\n *   signer,\n *   signStrategy: {\n *     type: 'callback',\n *     handler: async (req) => {\n *       const approved = await promptUser(`Sign for ${req.address}?`);\n *       return { approved };\n *     }\n *   },\n *   domain: 'cli.myapp.com',\n * });\n * ```\n */\nexport class NodeUserAuthorization implements IUserAuthorization {\n  private readonly signer: ISigner;\n  private readonly signStrategy: SignStrategy;\n  private readonly sessionStorage: ISessionStorage;\n  private readonly domain: string;\n  private readonly uri: string;\n  private readonly statement?: string;\n  private readonly spacePrefix: string;\n  private readonly defaultActions: Record<string, Record<string, string[]>>;\n  private readonly sessionExpirationMs: number;\n  private readonly autoCreateSpace: boolean;\n  private readonly spaceCreationHandler?: ISpaceCreationHandler;\n  private tinycloudHosts?: string[];\n  private readonly tinycloudRegistryUrl?: string | null;\n  private readonly tinycloudFallbackHosts?: string[] | null;\n  private readonly autoDiscoverLocalNode?: boolean;\n  private readonly localNodeUrl?: string;\n  private readonly localLinkName?: string;\n  private readonly expectedNodeDid?: string;\n  private readonly localNodeIdentityStore?: LocalNodeIdentityStore;\n  private readonly enablePublicSpace: boolean;\n  private readonly nonce?: string;\n  private readonly siweConfig?: SiweConfig;\n  private readonly wasm: IWasmBindings;\n  /**\n   * Stored manifest, if one was provided at construction time. Used by\n   * {@link signIn} to derive the session's granted capabilities instead\n   * of falling back to {@link defaultActions}.\n   */\n  private _manifest?: Manifest | Manifest[];\n  private _capabilityRequest?: ComposedManifestRequest;\n  private readonly includeAccountRegistryPermissions: boolean;\n\n  private sessionManager: ISessionManager;\n  private activeSessionKeyId = \"default\";\n  private extensions: Extension[] = [];\n  private _session?: ClientSession;\n  private _tinyCloudSession?: TinyCloudSession;\n  private _address?: string;\n  private _chainId?: number;\n  private _nodeFeatures: string[] = [];\n  private _lastActivationSkippedSpaceIds: string[] = [];\n\n  constructor(config: NodeUserAuthorizationConfig) {\n    this.wasm = config.wasmBindings;\n\n    this.signer = config.signer;\n    this.signStrategy = config.signStrategy ?? defaultSignStrategy;\n    this.sessionStorage = config.sessionStorage ?? new MemorySessionStorage();\n    this.domain = config.domain;\n    this.uri = config.uri ?? `https://${config.domain}`;\n    this.statement = config.statement;\n    this.spacePrefix = config.spacePrefix ?? \"default\";\n    this.defaultActions = config.defaultActions ?? {\n      kv: {\n        \"\": [KV.PUT, KV.GET, KV.DEL, KV.LIST, KV.METADATA],\n      },\n      sql: {\n        \"\": [SQL.READ, SQL.WRITE, SQL.SCHEMA, SQL.ADMIN, SQL.EXPORT],\n      },\n      duckdb: {\n        \"\": [\n          DUCKDB.READ,\n          DUCKDB.WRITE,\n          DUCKDB.ADMIN,\n          DUCKDB.DESCRIBE,\n          DUCKDB.EXPORT,\n          DUCKDB.IMPORT,\n          DUCKDB.EXECUTE,\n        ],\n      },\n      capabilities: {\n        \"\": [CAPABILITIES.READ],\n      },\n      hooks: {\n        \"\": [HOOKS.SUBSCRIBE, HOOKS.REGISTER, HOOKS.LIST, HOOKS.UNREGISTER],\n      },\n    };\n    this.sessionExpirationMs = config.sessionExpirationMs ?? EXPIRY.SESSION_MS;\n    this.autoCreateSpace = config.autoCreateSpace ?? false;\n    this.spaceCreationHandler = config.spaceCreationHandler;\n    this.tinycloudHosts = config.tinycloudHosts;\n    this.tinycloudRegistryUrl = config.tinycloudRegistryUrl;\n    this.tinycloudFallbackHosts = config.tinycloudFallbackHosts;\n    this.autoDiscoverLocalNode = config.autoDiscoverLocalNode;\n    this.localNodeUrl = config.localNodeUrl;\n    this.localLinkName = config.localLinkName;\n    this.expectedNodeDid = config.expectedNodeDid;\n    this.localNodeIdentityStore = config.localNodeIdentityStore;\n    this.enablePublicSpace = config.enablePublicSpace ?? true;\n    this.nonce = config.nonce;\n    this.siweConfig = config.siweConfig;\n    this.includeAccountRegistryPermissions =\n      config.includeAccountRegistryPermissions ?? true;\n    this._manifest = config.manifest;\n    this._capabilityRequest = config.capabilityRequest;\n\n    // Reuse the caller's manager when authorization is owned by a higher-level\n    // client so both layers address the same session keys.\n    this.sessionManager = config.sessionManager ?? this.wasm.createSessionManager();\n  }\n\n  /**\n   * Return the manifest currently driving sign-in behavior, or\n   * `undefined` if none is set. Used by TinyCloudWeb/TinyCloudNode\n   * internals to surface the manifest for requestPermissions flows\n   * without forcing the caller to track it separately.\n   */\n  get manifest(): Manifest | Manifest[] | undefined {\n    return this._manifest;\n  }\n\n  get capabilityRequest(): ComposedManifestRequest | undefined {\n    return this.getCapabilityRequest();\n  }\n\n  get hosts(): string[] {\n    return this.tinycloudHosts ? [...this.tinycloudHosts] : [];\n  }\n\n  /**\n   * Install or replace the stored manifest. Takes effect on the next\n   * `signIn()` call — the current session (if any) is not touched.\n   */\n  setManifest(manifest: Manifest | Manifest[] | undefined): void {\n    this._manifest = manifest;\n    this._capabilityRequest = undefined;\n  }\n\n  setCapabilityRequest(request: ComposedManifestRequest | undefined): void {\n    this._capabilityRequest = request;\n  }\n\n  /**\n   * The current active session (web-core compatible).\n   */\n  get session(): ClientSession | undefined {\n    return this._session;\n  }\n\n  /**\n   * The current TinyCloud session with full delegation data.\n   * Includes spaceId, delegationHeader, and delegationCid.\n   */\n  get tinyCloudSession(): TinyCloudSession | undefined {\n    return this._tinyCloudSession;\n  }\n\n  /**\n   * Rehydrate the auth-layer session from previously-persisted delegation\n   * data. Used by {@link TinyCloudNode.restoreSession} so that downstream\n   * surfaces that read from `tinyCloudSession` (notably\n   * `grantRuntimePermissions`, which extracts the SIWE expiry from it) work\n   * without re-running the full sign-in flow.\n   *\n   * Caller must supply the same fields that `signIn` would have written —\n   * `siwe` is the load-bearing one because `extractSiweExpiration` returns\n   * undefined for missing SIWEs and the SDK then treats the session as\n   * expired-at-epoch-zero.\n   *\n   * @param hosts - The TinyCloud hosts this session was created against,\n   *   as persisted in {@link PersistedSessionData.tinycloudHosts}. When\n   *   present (and non-empty) they are adopted directly so the restored\n   *   session resolves to the same node as the original sign-in without\n   *   re-running registry/fallback resolution. When absent (old session)\n   *   hosts are resolved lazily on the first host-needing call via\n   *   {@link ensureTinyCloudHosts}.\n   */\n  setRestoredTinyCloudSession(\n    session: TinyCloudSession,\n    hosts?: string[],\n  ): void {\n    const address = canonicalizeAddress(session.address);\n    this._tinyCloudSession = { ...session, address };\n    this._address = address;\n    this._chainId = session.chainId;\n    // Don't overwrite an explicitly-configured host (e.g. local dev) with a\n    // possibly-stale persisted value: only adopt persisted hosts when none\n    // are already set.\n    if (\n      (!this.tinycloudHosts || this.tinycloudHosts.length === 0) &&\n      hosts &&\n      hosts.length > 0\n    ) {\n      this.tinycloudHosts = [...hosts];\n    }\n  }\n\n  /** @internal Atomically adopt the state staged by TinyCloudNode.restoreSession. */\n  installRestoredSession(\n    sessionManager: ISessionManager,\n    session: TinyCloudSession | undefined,\n    hosts?: string[],\n  ): void {\n    this.sessionManager = sessionManager;\n    // Restore is a complete session replacement, not an additive update. In\n    // particular, a second restore may target a different host and must not\n    // retain skip decisions from the previous activation.\n    this.tinycloudHosts = hosts && hosts.length > 0 ? [...hosts] : undefined;\n    this._lastActivationSkippedSpaceIds = [];\n    if (!session) {\n      this._session = undefined;\n      this._tinyCloudSession = undefined;\n      this._address = undefined;\n      this._chainId = undefined;\n      return;\n    }\n    this._tinyCloudSession = { ...session };\n    this._address = session.address;\n    this._chainId = session.chainId;\n    this._session = {\n      address: session.address,\n      walletAddress: session.address,\n      chainId: session.chainId,\n      sessionKey: session.sessionKey,\n      siwe: session.siwe,\n      signature: session.signature,\n    };\n  }\n\n  /**\n   * Ensure `tinycloudHosts` are resolved before a host-needing call.\n   *\n   * Fresh sign-in resolves hosts up front; a restored session may not have\n   * (old persisted sessions predate {@link PersistedSessionData.tinycloudHosts}).\n   * This guard makes a restored session resolve the node exactly like a fresh\n   * sign-in — persisted hosts are preferred (already set by\n   * {@link setRestoredTinyCloudSession}), otherwise the registry/fallback\n   * resolution runs lazily here. Idempotent: {@link resolveTinyCloudHostsForSignIn}\n   * early-returns when hosts are already set.\n   *\n   * Throws if hosts are unset and the restored session has no address/chainId\n   * to resolve from — a real failure that must surface, not be masked.\n   */\n  async ensureTinyCloudHosts(): Promise<void> {\n    if (this.tinycloudHosts && this.tinycloudHosts.length > 0) {\n      return;\n    }\n    if (this._address === undefined || this._chainId === undefined) {\n      throw new Error(\n        \"Cannot resolve TinyCloud hosts: no address/chainId available. \" +\n          \"Sign in or restore a session first.\",\n      );\n    }\n    await this.resolveTinyCloudHostsForSignIn(this._address, this._chainId);\n  }\n\n  private async resolveTinyCloudHostsForSignIn(\n    address: string,\n    chainId: number,\n  ): Promise<void> {\n    if (this.tinycloudHosts && this.tinycloudHosts.length > 0) {\n      return;\n    }\n\n    const subject = pkhDid(address, chainId);\n    const resolved = await resolveTinyCloudHosts(subject, {\n      registryUrl: this.tinycloudRegistryUrl,\n      fallbackHosts: this.tinycloudFallbackHosts,\n      autoDiscoverLocalNode: this.autoDiscoverLocalNode,\n      localNodeUrl: this.localNodeUrl,\n      localLinkName: this.localLinkName,\n      expectedNodeDid: this.expectedNodeDid,\n      localNodeIdentityStore: this.localNodeIdentityStore,\n    });\n    this.tinycloudHosts = resolved.hosts;\n  }\n\n  private requireTinyCloudHosts(): string[] {\n    if (!this.tinycloudHosts || this.tinycloudHosts.length === 0) {\n      throw new Error(\"TinyCloud hosts have not been resolved. Call signIn() first.\");\n    }\n    return this.tinycloudHosts;\n  }\n\n  private get primaryTinyCloudHost(): string {\n    return this.requireTinyCloudHosts()[0];\n  }\n\n  get nodeFeatures(): string[] {\n    return this._nodeFeatures;\n  }\n\n  get lastActivationSkippedSpaceIds(): string[] {\n    return [...this._lastActivationSkippedSpaceIds];\n  }\n\n  /**\n   * Compute the `abilities` map the WASM `prepareSession` call should\n   * see at sign-in time.\n   *\n   * When a manifest is installed, we resolve it and union together:\n   * - the app's own `resources` (what it needs at runtime)\n   * - every `additionalDelegates[*].permissions` list (what it will\n   *   re-delegate to other DIDs post sign-in)\n   *\n   * into the short-service / path / full-URN-actions shape the WASM\n   * layer expects. This is the key invariant that lets\n   * {@link TinyCloudNode.delegateTo} issue manifest-declared\n   * delegations via the session key (no wallet prompt): the session's\n   * own recap already covers every action those delegations need.\n   *\n   * When no manifest is installed, we fall back to the\n   * {@link defaultActions} table so existing callers see no change.\n   *\n   * This is a pure function of `this._manifest` + `this.defaultActions`\n   * — the manifest resolution performs no I/O and throws a\n   * {@link ManifestValidationError} on structural problems (missing\n   * id/name, unparseable expiry, etc), which will surface at sign-in\n   * rather than being silently swallowed.\n   *\n   * @internal\n   */\n  private getCapabilityRequest(): ComposedManifestRequest | undefined {\n    if (this._capabilityRequest !== undefined) {\n      return this._capabilityRequest;\n    }\n    if (this._manifest === undefined) {\n      return undefined;\n    }\n    this._capabilityRequest = composeManifestRequest(\n      Array.isArray(this._manifest) ? this._manifest : [this._manifest],\n      {\n        includeAccountRegistryPermissions:\n          this.includeAccountRegistryPermissions,\n      }\n    );\n    return this._capabilityRequest;\n  }\n\n  private resolveSpaceName(space: string, address: string, chainId: number): string {\n    if (space.startsWith(\"tinycloud:\")) {\n      return space;\n    }\n    return makePkhSpaceId(address, chainId, space);\n  }\n\n  private defaultEncryptionNetworkId(address: string, chainId: number): string {\n    return `urn:tinycloud:encryption:${pkhDid(address, chainId)}:default`;\n  }\n\n  private resolveSignInCapabilities(\n    address: string,\n    chainId: number,\n  ): {\n    abilities: AbilitiesMap;\n    spaceId: string;\n    spaceAbilities?: Record<string, AbilitiesMap>;\n    rawAbilities?: Record<string, string[]>;\n  } {\n    const request = this.getCapabilityRequest();\n    if (request === undefined) {\n      const defaultNetworkId = this.defaultEncryptionNetworkId(address, chainId);\n      const primarySpaceId = makePkhSpaceId(address, chainId, this.spacePrefix);\n      const secretsSpaceId = makePkhSpaceId(address, chainId, \"secrets\");\n      return {\n        abilities: this.defaultActions,\n        spaceId: primarySpaceId,\n        spaceAbilities: {\n          [primarySpaceId]: this.defaultActions,\n          [secretsSpaceId]: {\n            kv: {\n              \"vault/secrets/\": [\n                KV.GET,\n                KV.PUT,\n                KV.DEL,\n                KV.LIST,\n                KV.METADATA,\n              ],\n            },\n          },\n        },\n        rawAbilities: {\n          [defaultNetworkId]: [DECRYPT_ACTION, NETWORK_CREATE_ACTION],\n        },\n      };\n    }\n\n    const rawAbilities: Record<string, string[]> = {};\n    const currentDid = pkhDid(address, chainId);\n    const spaceResources = request.resources.filter((entry) => {\n      if (entry.service !== ENCRYPTION_PERMISSION_SERVICE) {\n        return true;\n      }\n      for (const action of entry.actions) {\n        addRawAbility(rawAbilities, entry.path, action);\n      }\n      if (entry.actions.includes(DECRYPT_ACTION)) {\n        const parsed = parseNetworkId(entry.path);\n        if (didPrincipalMatches(parsed.ownerDid, currentDid)) {\n          addRawAbility(rawAbilities, entry.path, NETWORK_CREATE_ACTION);\n        }\n      }\n      return false;\n    });\n\n    const primarySpaceName =\n      spaceResources.find((entry) => entry.space !== \"account\")?.space ??\n      DEFAULT_MANIFEST_SPACE;\n    const primarySpaceId = this.resolveSpaceName(\n      primarySpaceName,\n      address,\n      chainId,\n    );\n\n    const bySpace = resourceCapabilitiesToSpaceAbilitiesMap(spaceResources);\n    const spaceAbilities: Record<string, AbilitiesMap> = {};\n    for (const [space, abilities] of Object.entries(bySpace)) {\n      spaceAbilities[this.resolveSpaceName(space, address, chainId)] = abilities;\n    }\n\n    return {\n      abilities:\n        spaceAbilities[primarySpaceId] ??\n        resourceCapabilitiesToAbilitiesMap([]),\n      spaceId: primarySpaceId,\n      spaceAbilities,\n      rawAbilities:\n        Object.keys(rawAbilities).length > 0 ? rawAbilities : undefined,\n    };\n  }\n\n  /**\n   * Build SIWE overrides from the top-level nonce and siweConfig.\n   * - Top-level `nonce` is seeded first so `siweConfig.nonce` wins if both are set.\n   * - statement is prepended to the default statement\n   * - resources are appended to the default resources\n   * - uri triggers a warning (overwriting delegation target)\n   * - all other fields override directly\n   * - per-call nonce overrides siweConfig.nonce when provided\n   */\n  private buildSiweOverrides(options?: SignInOptions): Record<string, unknown> {\n    const base: Record<string, unknown> = { uri: this.uri };\n    if (this.nonce !== undefined) {\n      base.nonce = this.nonce;\n    }\n\n    if (!this.siweConfig && !options?.nonce) {\n      return base;\n    }\n\n    const { statement, resources, uri, ...rest } = this.siweConfig ?? {};\n    const overrides: Record<string, unknown> = { ...base, ...rest };\n\n    if (statement) {\n      overrides.statement = this.statement\n        ? `${statement} ${this.statement}`\n        : statement;\n    }\n\n    if (resources && resources.length > 0) {\n      overrides.resources = resources;\n    }\n\n    if (uri) {\n      console.warn(\n        \"[tinycloud] siweConfig.uri is overwriting the delegation target URI. \" +\n          \"This may break delegation chain validation if the URI does not match the session key DID.\",\n      );\n      overrides.uri = uri;\n    }\n\n    if (options?.nonce) {\n      overrides.nonce = options.nonce;\n    }\n\n    return overrides;\n  }\n\n  /**\n   * Add an extension to the authorization flow.\n   */\n  extend(extension: Extension): void {\n    this.extensions.push(extension);\n  }\n\n  /**\n   * Get the space ID for the current session.\n   */\n  getSpaceId(): string | undefined {\n    return this._tinyCloudSession?.spaceId;\n  }\n\n  /**\n   * Create the space on the TinyCloud server (host delegation).\n   * This registers the user as the owner of the space.\n   */\n  private async hostSpace(\n    targetSpaceId?: string,\n    purpose?: SignRequest[\"purpose\"],\n  ): Promise<boolean> {\n    if (!this._tinyCloudSession || !this._address || !this._chainId) {\n      throw new Error(\"Must be signed in to host space\");\n    }\n\n    await this.ensureTinyCloudHosts();\n    const host = this.primaryTinyCloudHost;\n    const spaceId = targetSpaceId ?? this._tinyCloudSession.spaceId;\n\n    // Get peer ID from TinyCloud server\n    const peerId = await fetchPeerId(host, spaceId);\n\n    // Generate host SIWE message\n    const siwe = this.wasm.generateHostSIWEMessage({\n      address: this._address,\n      chainId: this._chainId,\n      domain: this.domain,\n      issuedAt: new Date().toISOString(),\n      spaceId,\n      peerId,\n    });\n\n    // Sign the message\n    const signature = await this.signMessage(siwe, purpose);\n\n    // Convert to delegation headers and submit\n    const headers = this.wasm.siweToDelegationHeaders({ siwe, signature });\n    const result = await submitHostDelegation(host, headers);\n\n    return result.success;\n  }\n\n  /**\n   * Create a specific space on the server via host delegation.\n   * Used for lazy creation of additional spaces (e.g., public).\n   */\n  async hostPublicSpace(spaceId: string): Promise<boolean> {\n    return this.hostSpace(spaceId);\n  }\n\n  /**\n   * Create a specific owned space on the server via host delegation.\n   * Used by manifest registry setup for the account space.\n   */\n  async hostOwnedSpace(\n    spaceId: string,\n    purpose?: SignRequest[\"purpose\"],\n  ): Promise<boolean> {\n    return this.hostSpace(spaceId, purpose);\n  }\n\n  /**\n   * Ensure the user's space exists on the TinyCloud server.\n   * Creates the space if it doesn't exist and autoCreateSpace is enabled.\n   * If autoCreateSpace is false and space doesn't exist, silently returns\n   * (user may be using delegations to access other spaces).\n   *\n   * @throws Error if space creation fails\n   */\n  async ensureSpaceExists(): Promise<void> {\n    if (!this._tinyCloudSession) {\n      throw new Error(\"Must be signed in to ensure space exists\");\n    }\n\n    await this.ensureTinyCloudHosts();\n    const host = this.primaryTinyCloudHost;\n    const primarySpaceId = this._tinyCloudSession.spaceId;\n\n    // Try to activate the session\n    const result = await activateSessionWithHost(\n      host,\n      this._tinyCloudSession.delegationHeader,\n    );\n    this.recordActivationSkippedSpaces(result, primarySpaceId);\n\n    // Determine the effective space creation handler:\n    // 1. Explicit spaceCreationHandler takes precedence\n    // 2. autoCreateSpace: true uses AutoApproveSpaceCreationHandler\n    // 3. Otherwise, no handler (space creation skipped silently)\n    const handler: ISpaceCreationHandler | undefined =\n      this.spaceCreationHandler ??\n      (this.autoCreateSpace\n        ? new AutoApproveSpaceCreationHandler()\n        : undefined);\n\n    const creationContext = {\n      spaceId: primarySpaceId,\n      address: this._address!,\n      chainId: this._chainId!,\n      host,\n    };\n\n    if (result.success) {\n      // Check if primary space was actually activated or just skipped\n      const primarySkipped = result.skipped?.includes(primarySpaceId);\n\n      if (!primarySkipped) {\n        // Primary space exists and session is activated\n        return;\n      }\n\n      // Primary space was skipped (doesn't exist yet)\n      if (!handler) {\n        return;\n      }\n\n      const confirmed = await handler.confirmSpaceCreation(creationContext);\n      if (!confirmed) {\n        return;\n      }\n\n      // Create the primary space\n      try {\n        const created = await this.hostSpace();\n        if (!created) {\n          const err = new Error(`Failed to create space: ${primarySpaceId}`);\n          handler.onSpaceCreationFailed?.(creationContext, err);\n          throw err;\n        }\n      } catch (error) {\n        handler.onSpaceCreationFailed?.(\n          creationContext,\n          error instanceof Error ? error : new Error(String(error)),\n        );\n        throw error;\n      }\n\n      // Small delay to allow space creation to propagate\n      await new Promise((resolve) => setTimeout(resolve, 100));\n\n      // Retry activation\n      const retryResult = await activateSessionWithHost(\n        host,\n        this._tinyCloudSession.delegationHeader,\n      );\n\n      if (!retryResult.success) {\n        const err = new Error(\n          `Failed to activate session after creating space: ${retryResult.error}`,\n        );\n        handler.onSpaceCreationFailed?.(creationContext, err);\n        throw err;\n      }\n\n      handler.onSpaceCreated?.(creationContext);\n      return;\n    }\n\n    // Handle 404 (backwards compat with older servers)\n    if (result.status === 404) {\n      if (!handler) {\n        return;\n      }\n\n      const confirmed = await handler.confirmSpaceCreation(creationContext);\n      if (!confirmed) {\n        return;\n      }\n\n      try {\n        const created = await this.hostSpace();\n        if (!created) {\n          const err = new Error(`Failed to create space: ${primarySpaceId}`);\n          handler.onSpaceCreationFailed?.(creationContext, err);\n          throw err;\n        }\n      } catch (error) {\n        handler.onSpaceCreationFailed?.(\n          creationContext,\n          error instanceof Error ? error : new Error(String(error)),\n        );\n        throw error;\n      }\n\n      await new Promise((resolve) => setTimeout(resolve, 100));\n\n      const retryResult = await activateSessionWithHost(\n        host,\n        this._tinyCloudSession.delegationHeader,\n      );\n\n      if (!retryResult.success) {\n        const err = new Error(\n          `Failed to activate session after creating space: ${retryResult.error}`,\n        );\n        handler.onSpaceCreationFailed?.(creationContext, err);\n        throw err;\n      }\n\n      handler.onSpaceCreated?.(creationContext);\n      return;\n    }\n\n    throw new Error(`Failed to activate session: ${result.error}`);\n  }\n\n  private recordActivationSkippedSpaces(\n    result: SpaceHostResult,\n    primarySpaceId: string,\n  ): void {\n    if (result.success) {\n      this._lastActivationSkippedSpaceIds = result.skipped ?? [];\n      return;\n    }\n    this._lastActivationSkippedSpaceIds = result.status === 404\n      ? [primarySpaceId]\n      : [];\n  }\n\n  async createBootstrapSession(\n    options: CreateBootstrapSessionOptions,\n  ): Promise<TinyCloudSession> {\n    if (!this._address || !this._chainId) {\n      throw new Error(\"Must be signed in before creating bootstrap sessions\");\n    }\n\n    const address = this._address;\n    const chainId = this._chainId;\n    const keyId = `bootstrap-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n    this.sessionManager.createSessionKey(keyId);\n    const jwkString = this.sessionManager.jwk(keyId);\n    if (!jwkString) {\n      throw new Error(\"Failed to create bootstrap session key\");\n    }\n    const jwk = JSON.parse(jwkString);\n    const now = new Date();\n    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);\n    const abilities = resourceCapabilitiesToAbilitiesMap(\n      options.capabilityRequest.resources,\n    );\n    const prepared = this.wasm.prepareSession({\n      abilities,\n      ...(options.rawAbilities !== undefined\n        ? { rawAbilities: options.rawAbilities }\n        : {}),\n      address,\n      chainId,\n      domain: this.domain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: options.spaceId,\n      jwk,\n      ...this.buildSiweOverrides(),\n    });\n    const signature = await this.requestSignature({\n      address,\n      chainId,\n      message: prepared.siwe,\n      type: \"siwe\",\n      purpose: \"bootstrap-session\",\n    });\n    const session = this.wasm.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    return {\n      address,\n      chainId,\n      sessionKey: keyId,\n      spaceId: options.spaceId,\n      delegationCid: session.delegationCid,\n      delegationHeader: session.delegationHeader,\n      verificationMethod: this.sessionManager.getDID(keyId),\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n  }\n\n  /**\n   * Sign in and create a new session.\n   *\n   * This follows the correct SIWE-ReCap flow:\n   * 1. Create session key and get JWK\n   * 2. Call prepareSession() which generates the SIWE with ReCap capabilities\n   * 3. Sign the SIWE string from prepareSession\n   * 4. Call completeSessionSetup() with the prepared session + signature\n   *\n   * @param options - Optional per-call SIWE overrides for this sign-in only\n   */\n  async signIn(options?: SignInOptions): Promise<ClientSession> {\n    // Get signer address and chain ID\n    this._address = canonicalizeAddress(await this.signer.getAddress());\n    this._chainId = await this.signer.getChainId();\n\n    const address = this._address;\n    const chainId = this._chainId;\n\n    await this.resolveTinyCloudHostsForSignIn(address, chainId);\n\n    // Create a session key\n    const keyId = `session-${Date.now()}`;\n    this.sessionManager.renameSessionKeyId(this.activeSessionKeyId, keyId);\n    this.activeSessionKeyId = keyId;\n\n    // Get JWK for session key\n    const jwkString = this.sessionManager.jwk(keyId);\n    if (!jwkString) {\n      throw new Error(\"Failed to create session key\");\n    }\n    const jwk = JSON.parse(jwkString);\n\n    const capabilityPlan = this.resolveSignInCapabilities(address, chainId);\n    const spaceId = capabilityPlan.spaceId;\n\n    const now = new Date();\n    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);\n\n    // Prepare session - this creates the SIWE message with ReCap capabilities.\n    //\n    // When a manifest is installed, `resolveSignInAbilities()` returns\n    // the union of app permissions + every manifest-declared\n    // delegation's permissions in the shape `prepareSession` accepts.\n    // Otherwise it returns `defaultActions` unchanged (legacy path).\n    const prepared = this.wasm.prepareSession({\n      abilities: capabilityPlan.abilities,\n      ...(capabilityPlan.spaceAbilities !== undefined\n        ? { spaceAbilities: capabilityPlan.spaceAbilities }\n        : {}),\n      ...(capabilityPlan.rawAbilities !== undefined\n        ? { rawAbilities: capabilityPlan.rawAbilities }\n        : {}),\n      address,\n      chainId,\n      domain: this.domain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId,\n      jwk,\n      ...this.buildSiweOverrides(options),\n    });\n\n    // Sign the SIWE message from prepareSession (NOT a separately generated SIWE)\n    const signature = await this.requestSignature({\n      address,\n      chainId,\n      message: prepared.siwe,\n      type: \"siwe\",\n      purpose: \"sign-in\",\n    });\n\n    // Complete session setup with the prepared session + signature\n    const session = this.wasm.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Create client session (web-core compatible)\n    const clientSession: ClientSession = {\n      address,\n      walletAddress: address,\n      chainId,\n      sessionKey: keyId,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Compute additional spaces as metadata (not in the delegation itself).\n    // The public space delegation is created lazily via ensurePublicSpace(),\n    // not at signIn time, to avoid creating spaces the user may never use.\n    const spacesMetadata: Record<string, string> | undefined = this\n      .enablePublicSpace\n      ? { public: makePkhSpaceId(address, chainId, \"public\") }\n      : undefined;\n\n    // Create TinyCloud session with full delegation data\n    // Use sessionManager.getDID(keyId) for verificationMethod to get properly formatted DID URL\n    // The prepared.verificationMethod from Rust WASM has a bug that doubles the DID fragment\n    const tinyCloudSession: TinyCloudSession = {\n      address,\n      chainId,\n      sessionKey: keyId,\n      spaceId,\n      spaces: spacesMetadata,\n      delegationCid: session.delegationCid,\n      delegationHeader: session.delegationHeader,\n      verificationMethod: this.sessionManager.getDID(keyId),\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Persist session with TinyCloud-specific data\n    const persistedData: PersistedSessionData = {\n      address,\n      chainId,\n      sessionKey: JSON.stringify(jwk),\n      siwe: prepared.siwe,\n      signature,\n      tinycloudSession: {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId,\n        spaces: spacesMetadata,\n        verificationMethod: this.sessionManager.getDID(keyId),\n      },\n      expiresAt: expirationTime.toISOString(),\n      createdAt: now.toISOString(),\n      version: \"1.0\",\n      tinycloudHosts: this.tinycloudHosts,\n    };\n    await this.sessionStorage.save(address, persistedData);\n\n    // Set current session\n    this._session = clientSession;\n    this._tinyCloudSession = tinyCloudSession;\n    this._address = address;\n    this._chainId = chainId;\n\n    // Verify SDK-node protocol compatibility and discover supported features\n    const nodeInfo = await checkNodeInfo(\n      this.primaryTinyCloudHost,\n      this.wasm.protocolVersion(),\n    );\n    this._nodeFeatures = nodeInfo.features;\n\n    // Call extension hooks\n    for (const ext of this.extensions) {\n      if (ext.afterSignIn) {\n        await ext.afterSignIn(clientSession);\n      }\n    }\n\n    // Ensure space exists (creates if needed when autoCreateSpace is true)\n    await this.ensureSpaceExists();\n\n    return clientSession;\n  }\n\n  /**\n   * Sign out and clear the current session.\n   */\n  async signOut(): Promise<void> {\n    if (this._address) {\n      await this.clearPersistedSession(this._address);\n    }\n    this._session = undefined;\n  }\n\n  /**\n   * Get the current wallet/signer address.\n   */\n  address(): string | undefined {\n    return this._address;\n  }\n\n  /**\n   * Get the current chain ID.\n   */\n  chainId(): number | undefined {\n    return this._chainId;\n  }\n\n  /**\n   * Sign a message with the connected signer.\n   */\n  async signMessage(\n    message: string,\n    purpose?: SignRequest[\"purpose\"],\n  ): Promise<string> {\n    if (!this._address) {\n      this._address = canonicalizeAddress(await this.signer.getAddress());\n    }\n    if (!this._chainId) {\n      this._chainId = await this.signer.getChainId();\n    }\n\n    return this.requestSignature({\n      address: this._address,\n      chainId: this._chainId,\n      message,\n      type: \"message\",\n      ...(purpose ? { purpose } : {}),\n    });\n  }\n\n  /**\n   * Prepare a session for external signing.\n   *\n   * Use this method when you need to sign the SIWE message externally (e.g., via\n   * a hardware wallet, multi-sig, or external service). After obtaining the signature,\n   * call `signInWithPreparedSession()` to complete the sign-in.\n   *\n   * @example\n   * ```typescript\n   * const { prepared, keyId, jwk } = await auth.prepareSessionForSigning();\n   * const signature = await externalSigner.signMessage(prepared.siwe);\n   * const session = await auth.signInWithPreparedSession(prepared, signature, keyId, jwk);\n   * ```\n   */\n  async prepareSessionForSigning(): Promise<{\n    prepared: {\n      siwe: string;\n      jwk: Record<string, unknown>;\n      spaceId: string;\n      verificationMethod: string;\n    };\n    keyId: string;\n    jwk: Record<string, unknown>;\n    address: string;\n    chainId: number;\n  }> {\n    const address = canonicalizeAddress(await this.signer.getAddress());\n    const chainId = await this.signer.getChainId();\n\n    // Create a session key\n    const keyId = `session-${Date.now()}`;\n    this.sessionManager.renameSessionKeyId(this.activeSessionKeyId, keyId);\n    this.activeSessionKeyId = keyId;\n\n    // Get JWK for session key\n    const jwkString = this.sessionManager.jwk(keyId);\n    if (!jwkString) {\n      throw new Error(\"Failed to create session key\");\n    }\n    const jwk = JSON.parse(jwkString);\n\n    const capabilityPlan = this.resolveSignInCapabilities(address, chainId);\n    const spaceId = capabilityPlan.spaceId;\n\n    const now = new Date();\n    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);\n\n    // Prepare session - this creates the SIWE message with ReCap capabilities.\n    //\n    // When a manifest is installed, `resolveSignInAbilities()` returns\n    // the union of app permissions + every manifest-declared\n    // delegation's permissions in the shape `prepareSession` accepts.\n    // Otherwise it returns `defaultActions` unchanged (legacy path).\n    const prepared = this.wasm.prepareSession({\n      abilities: capabilityPlan.abilities,\n      ...(capabilityPlan.spaceAbilities !== undefined\n        ? { spaceAbilities: capabilityPlan.spaceAbilities }\n        : {}),\n      ...(capabilityPlan.rawAbilities !== undefined\n        ? { rawAbilities: capabilityPlan.rawAbilities }\n        : {}),\n      address,\n      chainId,\n      domain: this.domain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId,\n      jwk,\n      ...this.buildSiweOverrides(),\n    });\n\n    return {\n      prepared,\n      keyId,\n      jwk,\n      address,\n      chainId,\n    };\n  }\n\n  /**\n   * Complete sign-in with a prepared session and signature.\n   *\n   * Use this method after obtaining a signature for the SIWE message from\n   * `prepareSessionForSigning()`. The signature MUST be over `prepared.siwe`.\n   *\n   * @param prepared - The prepared session from `prepareSessionForSigning()`\n   * @param signature - The signature over `prepared.siwe`\n   * @param keyId - The session key ID from `prepareSessionForSigning()`\n   * @param jwk - The JWK from `prepareSessionForSigning()`\n   */\n  async signInWithPreparedSession(\n    prepared: {\n      siwe: string;\n      jwk: Record<string, unknown>;\n      spaceId: string;\n      verificationMethod: string;\n    },\n    signature: string,\n    keyId: string,\n    jwk: Record<string, unknown>,\n  ): Promise<ClientSession> {\n    // Complete session setup with the prepared session + signature\n    const session = this.wasm.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Parse address and chainId from the prepared session\n    // The SIWE message contains this info, but we need to extract it\n    // For now, we'll get it from the signer since it should match\n    const address = canonicalizeAddress(await this.signer.getAddress());\n    const chainId = await this.signer.getChainId();\n\n    await this.resolveTinyCloudHostsForSignIn(address, chainId);\n\n    // Create client session (web-core compatible)\n    const clientSession: ClientSession = {\n      address,\n      walletAddress: address,\n      chainId,\n      sessionKey: keyId,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Compute additional spaces as metadata (not in the delegation itself).\n    const spacesMetadata: Record<string, string> | undefined = this\n      .enablePublicSpace\n      ? { public: makePkhSpaceId(address, chainId, \"public\") }\n      : undefined;\n\n    // Create TinyCloud session with full delegation data\n    // Use sessionManager.getDID(keyId) for properly formatted DID URL\n    const tinyCloudSession: TinyCloudSession = {\n      address,\n      chainId,\n      sessionKey: keyId,\n      spaceId: prepared.spaceId,\n      spaces: spacesMetadata,\n      delegationCid: session.delegationCid,\n      delegationHeader: session.delegationHeader,\n      verificationMethod: this.sessionManager.getDID(keyId),\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Extract expiration from SIWE message (parse the string)\n    const expirationMatch = prepared.siwe.match(/Expiration Time: (.+)/);\n    const issuedAtMatch = prepared.siwe.match(/Issued At: (.+)/);\n    const expiresAt =\n      expirationMatch?.[1] ??\n      new Date(Date.now() + this.sessionExpirationMs).toISOString();\n    const createdAt = issuedAtMatch?.[1] ?? new Date().toISOString();\n\n    // Persist session with TinyCloud-specific data\n    const persistedData: PersistedSessionData = {\n      address,\n      chainId,\n      sessionKey: JSON.stringify(jwk),\n      siwe: prepared.siwe,\n      signature,\n      tinycloudSession: {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId: prepared.spaceId,\n        spaces: spacesMetadata,\n        verificationMethod: this.sessionManager.getDID(keyId),\n      },\n      expiresAt,\n      createdAt,\n      version: \"1.0\",\n      tinycloudHosts: this.tinycloudHosts,\n    };\n    await this.sessionStorage.save(address, persistedData);\n\n    // Set current session\n    this._session = clientSession;\n    this._tinyCloudSession = tinyCloudSession;\n    this._address = address;\n    this._chainId = chainId;\n\n    // Verify SDK-node protocol compatibility and discover supported features\n    const nodeInfo = await checkNodeInfo(\n      this.primaryTinyCloudHost,\n      this.wasm.protocolVersion(),\n    );\n    this._nodeFeatures = nodeInfo.features;\n\n    // Call extension hooks\n    for (const ext of this.extensions) {\n      if (ext.afterSignIn) {\n        await ext.afterSignIn(clientSession);\n      }\n    }\n\n    // Ensure space exists (creates if needed when autoCreateSpace is true)\n    await this.ensureSpaceExists();\n\n    return clientSession;\n  }\n\n  /**\n   * Clear persisted session data.\n   */\n  async clearPersistedSession(address?: string): Promise<void> {\n    const targetAddress = address ?? this._address;\n    if (targetAddress) {\n      await this.sessionStorage.clear(targetAddress);\n    }\n  }\n\n  /**\n   * Check if a session is persisted for an address.\n   */\n  isSessionPersisted(address: string): boolean {\n    return this.sessionStorage.exists(address);\n  }\n\n  /**\n   * Request a signature based on the configured strategy.\n   */\n  private async requestSignature(request: SignRequest): Promise<string> {\n    switch (this.signStrategy.type) {\n      case \"auto-sign\":\n        return this.signer.signMessage(request.message);\n\n      case \"auto-reject\":\n        throw new Error(\"Sign request rejected by auto-reject strategy\");\n\n      case \"callback\": {\n        const response = await this.signStrategy.handler(request);\n        if (!response.approved) {\n          throw new Error(\n            response.reason ?? \"Sign request rejected by callback\",\n          );\n        }\n        // If callback provides signature, use it; otherwise sign with signer\n        return (\n          response.signature ?? (await this.signer.signMessage(request.message))\n        );\n      }\n\n      case \"event-emitter\": {\n        return this.requestSignatureViaEmitter(\n          request,\n          this.signStrategy.emitter,\n          this.signStrategy.timeout ?? 60000,\n        );\n      }\n\n      default:\n        throw new Error(\n          `Unknown sign strategy: ${(this.signStrategy as any).type}`,\n        );\n    }\n  }\n\n  /**\n   * Request signature via event emitter with timeout.\n   */\n  private requestSignatureViaEmitter(\n    request: SignRequest,\n    emitter: EventEmitter,\n    timeout: number,\n  ): Promise<string> {\n    return new Promise((resolve, reject) => {\n      const timeoutId = setTimeout(() => {\n        reject(new Error(\"Sign request timed out\"));\n      }, timeout);\n\n      const respond = async (response: SignResponse) => {\n        clearTimeout(timeoutId);\n        if (!response.approved) {\n          reject(\n            new Error(response.reason ?? \"Sign request rejected via emitter\"),\n          );\n        } else {\n          // If response provides signature, use it; otherwise sign with signer\n          const signature =\n            response.signature ??\n            (await this.signer.signMessage(request.message));\n          resolve(signature);\n        }\n      };\n\n      emitter.emit(\"sign-request\", request, respond);\n    });\n  }\n}\n","/**\n * Node.js-specific SignStrategy types for TinyCloud authorization.\n *\n * This module re-exports common types from sdk-core and provides\n * Node.js-specific implementations (e.g., NodeEventEmitterStrategy\n * using Node's EventEmitter instead of browser EventTarget).\n *\n * @packageDocumentation\n */\n\nimport { EventEmitter } from \"events\";\n\n// Import types for local use in SignStrategy union\nimport type {\n  AutoSignStrategy,\n  AutoRejectStrategy,\n  CallbackStrategy,\n} from \"@tinycloud/sdk-core\";\n\n// Re-export common types from sdk-core (type-only — erased at runtime in sdk-core dist)\nexport type {\n  SignRequest,\n  SignResponse,\n  SignCallback,\n  AutoSignStrategy,\n  AutoRejectStrategy,\n  CallbackStrategy,\n  OpenKeySigningStrategyOptions,\n  OpenKeySigningRequestBody,\n  OpenKeySigningResponseBody,\n  OpenKeyCallbackStrategy,\n} from \"@tinycloud/sdk-core\";\n\nexport { createOpenKeyCallbackSigningStrategy } from \"@tinycloud/sdk-core\";\n\n/**\n * Node.js event emitter strategy: emits sign requests as events.\n *\n * Uses Node.js EventEmitter for compatibility with Node.js applications.\n * For browser environments, use the EventEmitterStrategy from sdk-core\n * which uses EventTarget.\n *\n * Events emitted:\n * - 'sign-request': When a sign request is received\n *\n * Use cases:\n * - Async approval workflows in Node.js\n * - External signing services\n * - Multi-step authorization flows\n *\n * @example\n * ```typescript\n * const emitter = new EventEmitter();\n * const strategy: NodeEventEmitterStrategy = { type: 'event-emitter', emitter };\n *\n * emitter.on('sign-request', async (req, respond) => {\n *   const approved = await externalApprovalService.check(req);\n *   respond({ approved, signature: approved ? await sign(req.message) : undefined });\n * });\n * ```\n */\nexport interface NodeEventEmitterStrategy {\n  type: \"event-emitter\";\n  emitter: EventEmitter;\n  /** Timeout in milliseconds for waiting on event response (default: 60000) */\n  timeout?: number;\n}\n\n/**\n * Node.js sign strategy union type.\n *\n * Determines how sign requests are handled in NodeUserAuthorization.\n * Uses Node.js EventEmitter for the event-emitter strategy.\n */\nexport type SignStrategy =\n  | AutoSignStrategy\n  | AutoRejectStrategy\n  | CallbackStrategy\n  | NodeEventEmitterStrategy;\n\n/**\n * Default sign strategy is auto-sign for convenience.\n * This is the Node.js-specific version typed with SignStrategy.\n */\nexport const defaultSignStrategy: SignStrategy = { type: \"auto-sign\" };\n","/**\n * TinyCloudNode - High-level API for Node.js users.\n *\n * Each user has their own TinyCloudNode instance with their own key.\n * This class provides a simplified interface for:\n * - Signing in and managing sessions\n * - Key-value storage operations on own space\n * - Creating and using delegations\n *\n * @example\n * ```typescript\n * const alice = new TinyCloudNode({\n *   privateKey: process.env.ALICE_PRIVATE_KEY,\n *   host: \"https://node.tinycloud.xyz\",\n *   prefix: \"myapp\",\n * });\n *\n * await alice.signIn();\n * await alice.kv.put(\"greeting\", \"Hello, world!\");\n *\n * // Delegate access to Bob\n * const delegation = await alice.createDelegation({\n *   path: \"shared/\",\n *   actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\"],\n *   delegateDID: bob.did,\n * });\n *\n * // Bob uses the delegation\n * const access = await bob.useDelegation(delegation);\n * const data = await access.kv.get(\"shared/data\");\n * ```\n */\n\nimport {\n  TinyCloud,\n  TinyCloudSession,\n  activateSessionWithHost,\n  KVService,\n  IKVService,\n  SQLService,\n  ISQLService,\n  DuckDbService,\n  IDuckDbService,\n  HooksService,\n  DataVaultService,\n  IDataVaultService,\n  EncryptionService,\n  DecryptTransportResponseError,\n  SecretsService,\n  ISecretsService,\n  IEncryptionService,\n  IHooksService,\n  createVaultCrypto,\n  ServiceSession,\n  ServiceContext,\n  type TelemetryConfig,\n  ISessionStorage,\n  ISigner,\n  type InvokeAnyFunction,\n  type InvokeFunction,\n  type FetchFunction,\n  INotificationHandler,\n  SilentNotificationHandler,\n  IENSResolver,\n  IWasmBindings,\n  ISessionManager,\n  type WasmRecapEntry,\n  ISpaceCreationHandler,\n  SignInOptions,\n  // v2 services\n  DelegationManager,\n  SpaceService,\n  ISpaceService,\n  ISpace,\n  CapabilityKeyRegistry,\n  ICapabilityKeyRegistry,\n  SharingService,\n  ISharingService,\n  // v2 types\n  SiweConfig,\n  Delegation,\n  DelegationStatus,\n  DelegationRevocationReceipt,\n  CreateDelegationParams,\n  KeyInfo,\n  JWK,\n  DelegationResult,\n  CreateDelegationWasmParams,\n  CreateDelegationWasmResult,\n  type DelegatedResource,\n  UnsupportedFeatureError,\n  makePublicSpaceId,\n  ACCOUNT_REGISTRY_SPACE,\n  BOOTSTRAP_SESSION_REQUESTS,\n  SECRET_RECORDS_SCHEMA,\n  SECRETS_SPACE,\n  TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,\n  bootstrapSteps,\n  type BootstrapSpaceName,\n  type BootstrapStep,\n  type ComposedManifestRequest,\n  type ResolvedDelegate,\n  // Capability-chain delegation\n  type PermissionEntry,\n  ENCRYPTION_PERMISSION_SERVICE,\n  CaveatedDelegationUnsupportedError,\n  PermissionNotInManifestError,\n  SessionExpiredError,\n  canonicalizeRecapCaveats,\n  recapCaveatsEqual,\n  expandPermissionEntries as expandPermissionEntriesCore,\n  isCapabilitySubset,\n  parseRecapCapabilities,\n  // Manifest-driven sign-in\n  type Manifest,\n  type AbilitiesMap,\n  resourceCapabilitiesToAbilitiesMap,\n  SERVICE_LONG_TO_SHORT,\n  SERVICE_SHORT_TO_LONG,\n  KV,\n  SQL,\n  DUCKDB,\n  ENCRYPTION,\n  EXPIRY,\n  canonicalHashHex,\n  canonicalizeEncryptionJson,\n  verifyDidKeyEd25519Signature,\n  canonicalizeAddress,\n  pkhDid,\n  resolveTinyCloudHosts,\n  type LocalNodeIdentityStore,\n  principalDidEquals,\n  parseNetworkId,\n  resolveSecretPath,\n  type BuildDecryptInvocationInput,\n  type BuiltDecryptInvocation,\n  type CanonicalJson,\n  type DecryptResponseBody,\n  type DecryptTransport,\n  type EncryptionCrypto,\n  type NetworkDescriptor,\n} from \"@tinycloud/sdk-core\";\nimport {\n  parsePermissionHint,\n  type PermissionHint,\n} from \"@tinycloud/sdk-services\";\nimport { NodeUserAuthorization } from \"./authorization/NodeUserAuthorization\";\nimport type { SignStrategy } from \"./authorization/strategies\";\nimport { AccountService } from \"./account/AccountService\";\nimport { FileSessionStorage } from \"./storage/FileSessionStorage\";\nimport { MemorySessionStorage } from \"./storage/MemorySessionStorage\";\nimport { PortableDelegation } from \"./delegation\";\nimport { DelegatedAccess } from \"./DelegatedAccess\";\nimport { WasmKeyProvider } from \"./keys/WasmKeyProvider\";\nimport {\n  legacyParamsToPermissionEntries,\n  resolveExpiryMs,\n  extractSiweExpiration,\n} from \"./delegateToHelpers\";\nimport { NodeSecretsService } from \"./NodeSecretsService\";\n\n/** Default TinyCloud host */\nconst DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nconst DEFAULT_ENCRYPTION_NETWORK_NAME = \"default\";\nconst NETWORK_CREATE_ACTION = ENCRYPTION.NETWORK_CREATE;\nconst DECRYPT_ACTION = ENCRYPTION.DECRYPT;\nconst NETWORK_ADMIN_TYPE = \"tinycloud.encryption.network-admin/v1\";\n\n/** Input for {@link TinyCloudNode.readSecret}. The target space is required. */\nexport interface SecretReadInput {\n  /** Explicit full space URI or an owned-space name. */\n  space: string;\n  /** Env-style secret name. */\n  name: string;\n  /** Optional logical secret scope. */\n  scope?: string;\n}\n\n/** Safe, validated capability hint returned when the node denies one read phase. */\nexport interface SecretPermissionHint {\n  readonly service: \"tinycloud.kv\" | \"tinycloud.encryption\";\n  readonly space?: string;\n  readonly path: string;\n  readonly actions: readonly string[];\n}\n\n/**\n * Safe classified result for an explicit-space secret read.\n *\n * Failure variants contain no raw node response, envelope, plaintext, keys,\n * tokens, or delegation data.\n */\nexport type SecretReadResult =\n  | { status: \"ok\"; value: string }\n  | { status: \"not_found\" }\n  | { status: \"permission_required\"; hint: SecretPermissionHint }\n  | { status: \"node_unreachable\" }\n  | { status: \"read_failed\" }\n  | { status: \"corrupt_envelope\" }\n  | { status: \"decrypt_failed\" }\n  | { status: \"invalid_payload\" };\n\nfunction isSecretPayload(\n  value: unknown,\n): value is { value: string; createdAt: string; updatedAt: string } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"value\" in value &&\n    typeof (value as { value?: unknown }).value === \"string\" &&\n    \"createdAt\" in value &&\n    typeof (value as { createdAt?: unknown }).createdAt === \"string\" &&\n    \"updatedAt\" in value &&\n    typeof (value as { updatedAt?: unknown }).updatedAt === \"string\"\n  );\n}\n\n/**\n * Full actions the session key's root delegation grants over a space. Used for\n * both the primary space and any additional (e.g. public) spaces registered in\n * {@link TinyCloudNode.initializeV2Services}. URNs come from the canonical\n * capability registry in `@tinycloud/bootstrap` (TC-112).\n */\nconst ROOT_DELEGATION_ACTIONS: string[] = [\n  KV.PUT,\n  KV.GET,\n  KV.DEL,\n  KV.LIST,\n  KV.METADATA,\n  SQL.READ,\n  SQL.WRITE,\n  SQL.ADMIN,\n  SQL.ALL,\n  DUCKDB.READ,\n  DUCKDB.WRITE,\n  DUCKDB.ADMIN,\n  DUCKDB.DESCRIBE,\n  DUCKDB.EXPORT,\n  DUCKDB.IMPORT,\n  DUCKDB.ALL,\n];\n\n/**\n * Default lifetime of a SIWE session when {@link TinyCloudNodeConfig.sessionExpirationMs}\n * is not set. Sourced from the shared SESSION tier so all sign-in code\n * paths land on the same number — see `@tinycloud/sdk-core/expiry.ts`\n * for the tier rationale.\n */\nconst DEFAULT_SESSION_EXPIRATION_MS = EXPIRY.SESSION_MS;\n\nexport interface CreateOwnerDelegationParams {\n  readonly delegateDid: string;\n  readonly spaceId: string;\n  readonly path: string;\n  readonly actions: readonly string[];\n  readonly expiresAt: Date;\n}\n\nexport function decodeAuthorizationBytes(authorization: string): Uint8Array {\n  const encoded = authorization.replace(/^Bearer /i, \"\");\n  const match = /^([A-Za-z0-9_-]+)(={1,2})?$/.exec(encoded);\n  const unpadded = match?.[1];\n  const paddingLength = match?.[2]?.length ?? 0;\n  const remainder = unpadded === undefined ? 1 : unpadded.length % 4;\n  const expectedPaddingLength = remainder === 2 ? 2 : remainder === 3 ? 1 : 0;\n  if (\n    unpadded === undefined ||\n    remainder === 1 ||\n    (paddingLength !== 0 && paddingLength !== expectedPaddingLength)\n  ) {\n    throw new Error(\"Delegation Authorization is not canonical base64url DAG-CBOR\");\n  }\n  const decoded = Uint8Array.from(Buffer.from(unpadded, \"base64url\"));\n  if (Buffer.from(decoded).toString(\"base64url\") !== unpadded) {\n    throw new Error(\"Delegation Authorization is not canonical base64url DAG-CBOR\");\n  }\n  return decoded;\n}\n\nexport interface OwnerDelegationReceipt {\n  readonly delegation: Delegation;\n  /** Exact signed DAG-CBOR bytes submitted in the Authorization header. */\n  readonly signedDagCbor: Uint8Array;\n  /** Locally derived by the node WASM implementation; this is delegation identity. */\n  readonly delegationCid: string;\n  readonly nodeReceipt: {\n    /** Raw /delegate response CID: a commit-event id, not delegation identity. */\n    readonly commitEventCid?: string;\n    readonly activated: readonly string[];\n    readonly skipped: readonly string[];\n  };\n}\n\nfunction isOpenKeyAutoSignStrategy(strategy: SignStrategy | undefined): boolean {\n  return (strategy as { openKeyAutoSign?: unknown } | undefined)?.openKeyAutoSign === true;\n}\n\n/**\n * Returns true when the signer is an external/interactive signer (browser\n * wallet, EIP-1193 provider, etc.) that will open a UI prompt for every\n * `signMessage()` call.\n *\n * Detection: the config provides a `signer` but NOT a `privateKey`, and the\n * `signStrategy` is neither the OpenKey auto-sign callback nor the auto-sign\n * strategy backed by a local key. In practice:\n * - `privateKey` present → local PrivateKeySigner → non-interactive\n * - `signStrategy.openKeyAutoSign === true` → OpenKey /api/delegate/sign → non-interactive\n * - `signer` only, no `privateKey`, no OpenKey strategy → interactive (browser wallet)\n */\nfunction isInteractiveSigner(config: TinyCloudNodeConfig): boolean {\n  if (config.privateKey) {\n    // Local key: always non-interactive.\n    return false;\n  }\n  if (isOpenKeyAutoSignStrategy(config.signStrategy)) {\n    // OpenKey auto-sign path: non-interactive.\n    return false;\n  }\n  // External signer with no auto-sign strategy. Treat as interactive.\n  return config.signer !== undefined;\n}\n\nfunction didPrincipalMatches(actual: string, expected: string): boolean {\n  try {\n    return principalDidEquals(actual, expected);\n  } catch {\n    return actual === expected;\n  }\n}\n\nfunction clonePersistedSessionJwk(jwk: unknown): object {\n  if (jwk === null || typeof jwk !== \"object\" || Array.isArray(jwk)) {\n    throw new Error(\"Persisted session has an invalid private Ed25519 session key.\");\n  }\n\n  try {\n    const serialized = JSON.stringify(jwk);\n    const cloned = serialized === undefined ? undefined : JSON.parse(serialized);\n    if (cloned === null || typeof cloned !== \"object\" || Array.isArray(cloned)) {\n      throw new Error(\"invalid JWK object\");\n    }\n    return cloned;\n  } catch {\n    throw new Error(\"Persisted session has an invalid private Ed25519 session key.\");\n  }\n}\n\nfunction cloneRecapCaveats(\n  caveats: readonly Record<string, unknown>[] | undefined,\n): Record<string, unknown>[] {\n  if (!caveats) return [];\n  const cloneJson = (value: unknown): unknown => {\n    if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n      return value;\n    }\n    if (typeof value === \"number\") {\n      if (Number.isFinite(value)) return value;\n      throw new Error(\"ReCap caveats must contain only JSON values.\");\n    }\n    if (Array.isArray(value)) return value.map(cloneJson);\n    if (typeof value === \"object\") {\n      const prototype = Object.getPrototypeOf(value);\n      if (prototype !== Object.prototype && prototype !== null) {\n        throw new Error(\"ReCap caveats must contain only JSON values.\");\n      }\n      const copy: Record<string, unknown> = Object.create(null);\n      for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {\n        copy[key] = cloneJson(nested);\n      }\n      return copy;\n    }\n    throw new Error(\"ReCap caveats must contain only JSON values.\");\n  };\n  try {\n    return JSON.parse(JSON.stringify(caveats.map(cloneJson))) as Record<string, unknown>[];\n  } catch {\n    throw new Error(\"Verified persisted session ReCap contains invalid caveats.\");\n  }\n}\n\n/** One replaceable set of services bound to a single host/session authority. */\nclass ServiceGraphLifetime {\n  private readonly abortController = new AbortController();\n  private readonly contexts = new Set<ServiceContext>();\n  private retired = false;\n\n  constructor(\n    private readonly invokeFn: InvokeFunction,\n    private readonly invokeAnyFn: InvokeAnyFunction,\n    private readonly fetchFn: FetchFunction,\n  ) {}\n\n  readonly invoke: InvokeFunction = (session, service, path, action, facts) => {\n    this.assertActive();\n    return this.invokeFn(session, service, path, action, facts);\n  };\n\n  readonly invokeAny: InvokeAnyFunction = (session, entries, facts) => {\n    this.assertActive();\n    return this.invokeAnyFn(session, entries, facts);\n  };\n\n  readonly fetch: FetchFunction = (url, init) => {\n    this.assertActive();\n    return this.fetchFn(url, {\n      ...init,\n      signal: this.combineSignals(init?.signal),\n    });\n  };\n\n  track(context: ServiceContext): ServiceContext {\n    this.assertActive();\n    this.contexts.add(context);\n    return context;\n  }\n\n  retire(): void {\n    if (this.retired) return;\n    this.retired = true;\n    this.abortController.abort();\n    try {\n      for (const context of this.contexts) {\n        try {\n          const retire = (context as ServiceContext & { retire?: () => void }).retire;\n          if (retire) retire.call(context);\n          else context.abort();\n        } catch (error) {\n          // Graph replacement is committed before retirement. A custom\n          // service's best-effort cleanup must not roll that replacement back\n          // or leave later contexts active.\n          console.error(\"Error retiring service graph context:\", error);\n        }\n      }\n    } finally {\n      this.contexts.clear();\n    }\n  }\n\n  assertActive(): void {\n    if (this.retired) {\n      throw new Error(\"Service graph has been retired by session replacement.\");\n    }\n  }\n\n  private combineSignals(signal?: AbortSignal): AbortSignal {\n    if (!signal) return this.abortController.signal;\n    const combined = new AbortController();\n    const abort = () => combined.abort();\n    if (signal.aborted || this.abortController.signal.aborted) {\n      abort();\n    } else {\n      signal.addEventListener(\"abort\", abort, { once: true });\n      this.abortController.signal.addEventListener(\"abort\", abort, { once: true });\n    }\n    return combined.signal;\n  }\n}\n\nexport class UnsupportedSessionRestoreError extends Error {\n  readonly code = \"RESTORE_SESSION_KEY_REPLACEMENT_UNSUPPORTED\" as const;\n\n  constructor(reason = \"it cannot replace and enumerate every live session signer\") {\n    super(`Persisted session restore is unsupported by this WASM binding because ${reason}.`);\n    this.name = \"UnsupportedSessionRestoreError\";\n  }\n}\n\nfunction canonicalRestoredVerificationMethod(\n  canonicalVerificationMethod: string,\n  persistedVerificationMethod: unknown,\n): string | undefined {\n  if (typeof persistedVerificationMethod !== \"string\") return undefined;\n  const principal = canonicalVerificationMethod.split(\"#\", 1)[0];\n  return persistedVerificationMethod === principal ||\n    persistedVerificationMethod === canonicalVerificationMethod\n    ? canonicalVerificationMethod\n    : undefined;\n}\n\nfunction persistedExpiry(value: unknown): Date {\n  if (typeof value !== \"string\") {\n    throw new Error(\"Persisted session without a SIWE expiration must include expiresAt.\");\n  }\n  const expiry = new Date(value);\n  if (!Number.isFinite(expiry.getTime()) || expiry.getTime() <= Date.now()) {\n    throw new Error(\"Persisted session expiry is invalid or expired.\");\n  }\n  return expiry;\n}\n\nfunction sameInstant(left: Date, right: Date): boolean {\n  return left.getTime() === right.getTime();\n}\n\nfunction sharingActionsToAbilities(path: string, actions: string[]): AbilitiesMap | undefined {\n  const abilities: AbilitiesMap = {};\n\n  for (const action of actions) {\n    const slash = action.indexOf(\"/\");\n    if (slash === -1) return undefined;\n\n    const shortService = SERVICE_LONG_TO_SHORT[action.slice(0, slash)];\n    if (shortService === undefined) return undefined;\n\n    abilities[shortService] ??= {};\n    abilities[shortService][path] ??= [];\n    abilities[shortService][path].push(action);\n  }\n\n  return Object.keys(abilities).length > 0 ? abilities : undefined;\n}\n\n/**\n * Configuration for TinyCloudNode.\n * All fields are optional - TinyCloudNode can work with zero configuration.\n */\nexport interface TinyCloudNodeConfig {\n  /** Hex-encoded private key (with or without 0x prefix). Optional - only needed for wallet mode and signIn() */\n  privateKey?: string;\n  /** Custom signer implementation. If provided, takes precedence over privateKey. */\n  signer?: ISigner;\n  /** Strategy for root signature requests. Defaults to auto-sign for local keys. */\n  signStrategy?: SignStrategy;\n  /** Explicit TinyCloud server URL. When omitted, signIn resolves the user's host. */\n  host?: string;\n  /** TinyCloud location registry URL. Default: https://registry.tinycloud.xyz. */\n  tinycloudRegistryUrl?: string | null;\n  /** Fallback TinyCloud hosts. Default: hosted TinyCloud node. */\n  tinycloudFallbackHosts?: string[] | null;\n  /** Probe for a locally-running TinyCloud node before registry/fallback resolution. Default: true. */\n  autoDiscoverLocalNode?: boolean;\n  /** Local loopback node URL to probe. Default: http://127.0.0.1:8000. */\n  localNodeUrl?: string;\n  /** Known `*.local.tinycloud.link` subdomain name, probed directly. */\n  localLinkName?: string;\n  /** Expected local node DID. A locally-discovered node whose DID differs is rejected. */\n  expectedNodeDid?: string;\n  /** Pin store for trust-on-first-use local node identity verification. Defaults to an in-memory store. */\n  localNodeIdentityStore?: LocalNodeIdentityStore;\n  /** Space prefix for this user's space. Optional - only needed for signIn() */\n  prefix?: string;\n  /** Domain for SIWE messages (default: derived from host) */\n  domain?: string;\n  /** Session expiration time in milliseconds (default: 1 hour) */\n  sessionExpirationMs?: number;\n  /** Whether to automatically create space if it doesn't exist (default: false) */\n  autoCreateSpace?: boolean;\n  /** Custom session storage implementation (default: MemorySessionStorage) */\n  sessionStorage?: ISessionStorage;\n  /** Whether to include public space capabilities in the session (default: true).\n   * When true, signIn() automatically includes capabilities for the user's public space,\n   * accessible via spaces.get('public').kv */\n  enablePublicSpace?: boolean;\n  /** Custom WASM bindings (default: @tinycloud/node-sdk-wasm). Used by browser wrapper. */\n  wasmBindings?: IWasmBindings;\n  /** Notification handler for sign-in/sign-out/error events (default: SilentNotificationHandler) */\n  notificationHandler?: INotificationHandler;\n  /** ENS resolver for resolving .eth names in delegation methods */\n  ensResolver?: IENSResolver;\n  /** Custom space creation handler (default: auto-approve when autoCreateSpace is true) */\n  spaceCreationHandler?: ISpaceCreationHandler;\n  /**\n   * SIWE nonce override. If omitted, the WASM layer generates a random nonce.\n   * If `siweConfig.nonce` is also provided, `siweConfig.nonce` wins.\n   */\n  nonce?: string;\n  /** Optional SIWE configuration overrides (e.g., nonce for server-provided nonces) */\n  siweConfig?: SiweConfig;\n  /**\n   * App manifest driving the SIWE recap at sign-in.\n   *\n   * When set, `signIn()` resolves the manifest, unions the app's own\n   * permissions with every manifest-declared delegation's permissions,\n   * and uses that union as the session's granted capabilities — NOT\n   * the legacy `defaultActions` table. This is what makes\n   * `delegateTo(manifestDeclaredDid, permissions)` work without a\n   * wallet prompt: the session key's recap already covers the\n   * delegation target's needs at sign-in time.\n   *\n   * When omitted, `signIn()` falls back to `defaultActions` for\n   * backwards compatibility with callers that pre-date the manifest\n   * flow.\n   */\n  manifest?: Manifest | Manifest[];\n  /** Pre-composed manifest request. Takes precedence over `manifest`. */\n  capabilityRequest?: ComposedManifestRequest;\n  /** Include implicit account registry permissions when composing `manifest`. Default true. */\n  includeAccountRegistryPermissions?: boolean;\n  /** Run canonical first-account bootstrap when fresh account state is detected. Default true. */\n  autoBootstrapAccount?: boolean;\n  /** Default-off service telemetry. */\n  telemetry?: TelemetryConfig;\n}\n\n/**\n * Options for {@link TinyCloudNode.delegateTo}.\n *\n * `expiry` accepts either an ms-format duration string (e.g. `\"7d\"`, `\"1h\"`)\n * or a raw number of milliseconds. When omitted, the default is 1 hour.\n *\n * `forceWalletSign` bypasses the derivability check and sends the\n * delegation through the legacy wallet-signed SIWE path, which always\n * triggers a wallet prompt. Used for testing, for explicit wallet\n * confirmation flows, and by the legacy `createDelegation` fallback.\n */\nexport interface DelegateToOptions {\n  /** Override expiry. ms-format string (\"7d\", \"1h\") or raw milliseconds. */\n  expiry?: string | number;\n  /** Force the wallet-signed SIWE path even if the caps are derivable. Default false. */\n  forceWalletSign?: boolean;\n}\n\n/**\n * Result of {@link TinyCloudNode.delegateTo}.\n *\n * `prompted` indicates whether a wallet prompt was shown — `true` for the\n * legacy wallet path (always), `false` for the session-key UCAN path (never).\n * Callers wiring single-prompt sign-in flows use this to assert that their\n * capability chain was derivable.\n */\nexport interface DelegateToResult {\n  delegation: PortableDelegation;\n  prompted: boolean;\n}\n\n/**\n * Options for runtime permission escalation.\n */\nexport interface RuntimePermissionGrantOptions {\n  /** Override expiry. ms-format string (\"7d\", \"1h\") or raw milliseconds. */\n  expiry?: string | number;\n}\n\ninterface RuntimePermissionOperation {\n  spaceId?: string;\n  resource?: string;\n  service: string;\n  path: string;\n  action: string;\n  /** Exact signed ReCap attenuation for this action, if any. */\n  caveats?: Record<string, unknown>[];\n}\n\ninterface RuntimePermissionGrant {\n  session: ServiceSession;\n  delegation: PortableDelegation;\n  operations: RuntimePermissionOperation[];\n  expiresAt: Date;\n  /**\n   * Where this grant came from. Drives precedence in\n   * {@link TinyCloudNode.findGrantForOperations} (a `\"primary\"` grant — the\n   * synthetic representation of the base session's own recap — always\n   * out-ranks other covering grants) and gates the public-surface guardrails\n   * that must never surface the synthetic primary grant. Optional so existing\n   * test constructors and older call sites remain valid.\n   */\n  provenance?: \"primary\" | \"bootstrap\" | \"delegated\" | \"runtime\";\n}\n\ntype CanonicalizableEncryptionJson = CanonicalJson;\ntype NetworkInvocationFact = object;\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n  const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n  let output = \"\";\n  for (let i = 0; i < bytes.length; i += 3) {\n    const a = bytes[i];\n    const b = bytes[i + 1];\n    const c = bytes[i + 2];\n    const triplet = (a << 16) | ((b ?? 0) << 8) | (c ?? 0);\n    output += alphabet[(triplet >> 18) & 63];\n    output += alphabet[(triplet >> 12) & 63];\n    if (i + 1 < bytes.length) output += alphabet[(triplet >> 6) & 63];\n    if (i + 2 < bytes.length) output += alphabet[triplet & 63];\n  }\n  return output;\n}\n\nfunction base64UrlDecode(value: string): Uint8Array {\n  const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n  const bytes: number[] = [];\n  let buffer = 0;\n  let bits = 0;\n  for (const char of value) {\n    const index = alphabet.indexOf(char);\n    if (index < 0) {\n      throw new Error(\"invalid base64url input\");\n    }\n    buffer = (buffer << 6) | index;\n    bits += 6;\n    if (bits >= 8) {\n      bits -= 8;\n      bytes.push((buffer >> bits) & 0xff);\n    }\n  }\n  return new Uint8Array(bytes);\n}\n\nasync function signJwtInputWithJwk(\n  signingInput: string,\n  jwk: object,\n): Promise<Uint8Array> {\n  const bytes = new TextEncoder().encode(signingInput);\n  try {\n    const subtle = globalThis.crypto?.subtle;\n    if (!subtle) {\n      throw new Error(\"WebCrypto subtle API is unavailable\");\n    }\n    const key = await subtle.importKey(\n      \"jwk\",\n      jwk as any,\n      { name: \"Ed25519\" },\n      false,\n      [\"sign\"],\n    );\n    return new Uint8Array(await subtle.sign({ name: \"Ed25519\" }, key, bytes));\n  } catch {\n    const nodeCrypto = await import(\"node:crypto\");\n    const key = nodeCrypto.createPrivateKey({ key: jwk as any, format: \"jwk\" });\n    return new Uint8Array(nodeCrypto.sign(null, Buffer.from(bytes), key));\n  }\n}\n\nasync function rewriteInvocationAudience(\n  authorization: string,\n  audience: string,\n  jwk: object,\n): Promise<string> {\n  const [headerPart, payloadPart] = authorization.split(\".\");\n  if (!headerPart || !payloadPart) {\n    throw new Error(\"invalid invocation authorization\");\n  }\n  const header = JSON.parse(new TextDecoder().decode(base64UrlDecode(headerPart)));\n  const payload = JSON.parse(new TextDecoder().decode(base64UrlDecode(payloadPart)));\n  payload.aud = audience;\n  const signingInput = `${base64UrlEncode(\n    new TextEncoder().encode(JSON.stringify(header)),\n  )}.${base64UrlEncode(new TextEncoder().encode(JSON.stringify(payload)))}`;\n  const signature = await signJwtInputWithJwk(signingInput, jwk);\n  return `${signingInput}.${base64UrlEncode(signature)}`;\n}\n\nfunction authorizationHeader(headers: Record<string, string> | [string, string][]): string {\n  if (Array.isArray(headers)) {\n    const entry = headers.find(([name]) => name.toLowerCase() === \"authorization\");\n    if (!entry) {\n      throw new Error(\"network invocation did not include an Authorization header\");\n    }\n    return entry[1];\n  }\n  const value = headers.Authorization ?? headers.authorization;\n  if (!value) {\n    throw new Error(\"network invocation did not include an Authorization header\");\n  }\n  return value;\n}\n\n/**\n * High-level TinyCloud API for Node.js environments.\n *\n * Each user creates their own TinyCloudNode instance with their private key.\n * The instance manages the user's session and provides access to their space.\n */\n/** @internal */\nexport interface NodeDefaults {\n  createWasmBindings: () => IWasmBindings;\n  createSigner: (privateKey: string, chainId?: number) => ISigner;\n}\n\nexport class TinyCloudNode {\n  /** @internal Registered by importing @tinycloud/node-sdk (not /core) */\n  private static nodeDefaults?: NodeDefaults;\n\n  /** @internal Register Node.js-specific defaults (NodeWasmBindings, PrivateKeySigner) */\n  static registerNodeDefaults(defaults: NodeDefaults): void {\n    TinyCloudNode.nodeDefaults = defaults;\n  }\n\n  private config: TinyCloudNodeConfig;\n  private readonly explicitHost?: string;\n  private signer: ISigner | null = null;\n  private auth: NodeUserAuthorization | null = null;\n  private tc: TinyCloud | null = null;\n  private _address?: string;\n  private _chainId: number = 1;\n  private wasmBindings: IWasmBindings;\n  private sessionManager: ISessionManager;\n  private _serviceGraph!: ServiceGraphLifetime;\n  private _serviceContext?: ServiceContext;\n  private _kv?: KVService;\n  private _sql?: SQLService;\n  private _duckdb?: DuckDbService;\n  private _hooks?: HooksService;\n  private _vault?: DataVaultService;\n  private _encryption?: EncryptionService;\n  private _baseVaults = new Map<string, DataVaultService>();\n  private _baseSecrets = new Map<string, ISecretsService>();\n  private _secrets = new Map<string, ISecretsService>();\n  private _account?: AccountService;\n  /** Cached public KV with proper delegation (set by ensurePublicSpace) */\n  private _publicKV?: KVService;\n\n  /** Session key ID - always available */\n  private sessionKeyId: string;\n  /** Session key JWK as object - always available */\n  private sessionKeyJwk: object;\n\n  /** Notification handler for user-facing events */\n  private notificationHandler: INotificationHandler;\n\n  // v2 services (initialized in constructor)\n  private _capabilityRegistry: CapabilityKeyRegistry;\n  private _keyProvider: WasmKeyProvider;\n  private _sharingService: SharingService;\n  // These are initialized after signIn()\n  private _delegationManager?: DelegationManager;\n  private _spaceService?: SpaceService;\n  private runtimePermissionGrants: RuntimePermissionGrant[] = [];\n  /**\n   * Memoized `recapOperationsFromSession` result, keyed by the exact SIWE it\n   * was parsed from. The primary session is stable for the life of a sign-in,\n   * so this avoids re-parsing the recap on every registration.\n   */\n  private _recapOperationsCache?: { siwe: string; operations: RuntimePermissionOperation[] };\n\n  /**\n   * TinyCloudSession captured by {@link restoreSession} when there's no\n   * auth-layer signer available (session-only mode used by OpenKey-backed\n   * CLI restores, public-space replays, …). Read by\n   * {@link currentTinyCloudSession} as a fallback for `auth.tinyCloudSession`.\n   */\n  private _restoredTcSession?: TinyCloudSession;\n\n  /**\n   * True when the last signIn() detected an interactive signer and skipped\n   * client-side bootstrap. Apps can read this to know whether bootstrap was\n   * deferred to the server (OpenKey) or requires a separate user action.\n   */\n  private _bootstrapSkipped = false;\n\n  /**\n   * Outcome of the last signIn()'s account-bootstrap attempt. `skipped` is\n   * true when bootstrap did not complete (interactive signer, auto-sign\n   * denied, or a bootstrap step failed); `reason` carries the cause so apps\n   * can surface a \"finish account setup\" call-to-action.\n   */\n  private _bootstrapStatus: { skipped: boolean; reason?: string } = {\n    skipped: false,\n  };\n\n  /** Whether the last signIn() skipped client-side bootstrap because the\n   * signer is interactive (browser wallet / EIP-1193 provider). */\n  get bootstrapSkipped(): boolean {\n    return this._bootstrapSkipped;\n  }\n\n  /** Outcome of the last signIn()'s account-bootstrap attempt. */\n  get bootstrapStatus(): { skipped: boolean; reason?: string } {\n    return this._bootstrapStatus;\n  }\n\n  private get nodeFeatures(): string[] {\n    return this.auth?.nodeFeatures ?? [];\n  }\n\n  /** SIWE domain — uses config override or defaults to app.tinycloud.xyz */\n  private get siweDomain(): string {\n    return this.config.domain ?? 'app.tinycloud.xyz';\n  }\n\n  private readonly invokeWithRuntimePermissions: InvokeFunction = (\n    session,\n    service,\n    path,\n    action,\n    facts,\n  ) => {\n    const operation: RuntimePermissionOperation = {\n      spaceId: session.spaceId,\n      service: this.invocationServiceName(service),\n      path,\n      action,\n    };\n    const grant = this.findGrantForOperation(operation);\n    const grantedOperation = grant?.operations.find((candidate) =>\n      this.operationCovers(candidate, operation),\n    );\n    const invocationSession = !grant || grant.provenance === \"primary\"\n      ? session\n      : grant.session;\n\n    // The legacy single-capability binding has no caveat parameter.  Calling\n    // it for a restored caveated grant would silently broaden the authority,\n    // so mint the equivalent one-entry aggregate invocation instead.\n    if ((grantedOperation?.caveats?.length ?? 0) > 0) {\n      if (!this.wasmBindings.invokeAny) {\n        throw new Error(\"WASM binding does not support caveat-preserving invocation\");\n      }\n      return this.wasmBindings.invokeAny(invocationSession, [{\n        spaceId: invocationSession.spaceId,\n        service,\n        path,\n        action,\n        caveats: cloneRecapCaveats(grantedOperation!.caveats),\n      }], facts);\n    }\n\n    return this.wasmBindings.invoke(invocationSession, service, path, action, facts);\n  };\n\n  private readonly invokeAnyWithRuntimePermissions: InvokeAnyFunction = (\n    session,\n    entries,\n    facts,\n  ) => {\n    if (!this.wasmBindings.invokeAny) {\n      throw new Error(\"WASM binding does not support invokeAny\");\n    }\n    const operations = entries.flatMap((entry) => {\n      const operation = this.operationFromInvokeAnyEntry(entry);\n      return operation ? [operation] : [];\n    });\n    const grant = this.findGrantForOperations(operations);\n    // When the primary grant wins, invoke with the PASSED session (its scoped\n    // target `spaceId`), not the stored primary `ServiceSession` — see\n    // `selectInvocationSession` for the wrong-space rationale (TC-111 follow-up).\n    const invocationSession =\n      !grant || grant.provenance === \"primary\" ? session : grant.session;\n    const caveatPreservingEntries = grant\n      ? entries.map((entry) => {\n        const requested = this.operationFromInvokeAnyEntry(entry);\n        const granted = requested && grant.operations.find((candidate) =>\n          this.operationCovers(candidate, requested),\n        );\n        if (!granted?.caveats?.length) {\n          return entry;\n        }\n        if (entry.caveats !== undefined &&\n          !recapCaveatsEqual(entry.caveats, granted.caveats)) {\n          throw new Error(\"Invocation caveats do not match signed ReCap authority.\");\n        }\n        return { ...entry, caveats: cloneRecapCaveats(granted.caveats) };\n      })\n      : entries;\n    return this.wasmBindings.invokeAny(invocationSession, caveatPreservingEntries, facts);\n  };\n\n  /**\n   * Create a new TinyCloudNode instance.\n   *\n   * All configuration is optional. Without a privateKey, the instance operates\n   * in \"session-only\" mode where it can receive delegations but cannot create\n   * its own space via signIn().\n   *\n   * @param config - Configuration options (all optional)\n   *\n   * @example\n   * ```typescript\n   * // Session-only mode - can receive delegations\n   * const bob = new TinyCloudNode();\n   * console.log(bob.did); // did:key:z6Mk... - available immediately\n   *\n   * // Wallet mode - can create own space\n   * const alice = new TinyCloudNode({\n   *   privateKey: process.env.ALICE_PRIVATE_KEY,\n   *   prefix: \"myapp\",\n   * });\n   * await alice.signIn();\n   * ```\n   */\n  constructor(config: TinyCloudNodeConfig = {}) {\n    this.explicitHost = config.host;\n\n    // Store config with default host\n    this.config = {\n      ...config,\n      host: config.host ?? DEFAULT_HOST,\n    };\n\n    // Initialize WASM bindings (uses registered Node defaults if not provided)\n    if (config.wasmBindings) {\n      this.wasmBindings = config.wasmBindings;\n    } else if (TinyCloudNode.nodeDefaults) {\n      this.wasmBindings = TinyCloudNode.nodeDefaults.createWasmBindings();\n    } else {\n      throw new Error(\n        \"wasmBindings must be provided in config. \" +\n        \"Import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults.\"\n      );\n    }\n\n    // Always create session manager and session key immediately\n    this.sessionManager = this.wasmBindings.createSessionManager();\n\n    // Try to use \"default\" key, create if it doesn't exist\n    const defaultKeyId = \"default\";\n    let jwkStr = this.sessionManager.jwk(defaultKeyId);\n    if (jwkStr) {\n      // Key already exists, reuse it\n      this.sessionKeyId = defaultKeyId;\n    } else {\n      // Create new key\n      this.sessionKeyId = this.sessionManager.createSessionKey(defaultKeyId);\n      jwkStr = this.sessionManager.jwk(this.sessionKeyId);\n    }\n\n    if (!jwkStr) {\n      throw new Error(\"Failed to get session key JWK\");\n    }\n    this.sessionKeyJwk = JSON.parse(jwkStr);\n\n    this._serviceGraph = this.createServiceGraphLifetime();\n\n    // Initialize capability registry for all users (needed for tracking received delegations)\n    this._capabilityRegistry = new CapabilityKeyRegistry();\n\n    // Initialize KeyProvider for SharingService\n    this._keyProvider = new WasmKeyProvider({\n      sessionManager: this.sessionManager,\n    });\n\n    // Initialize notification handler\n    this.notificationHandler = config.notificationHandler ?? new SilentNotificationHandler();\n\n    // Initialize SharingService for receive-only access (no session required)\n    // This allows session-only users to receive sharing links without signIn()\n    // Full capabilities (generate) are added after signIn()\n    const receiveOnlyGraph = this._serviceGraph;\n    this._sharingService = new SharingService({\n      hosts: [this.config.host!],\n      // session: undefined - not needed for receive()\n      invoke: receiveOnlyGraph.invoke,\n      fetch: receiveOnlyGraph.fetch,\n      assertActive: () => receiveOnlyGraph.assertActive(),\n      keyProvider: this._keyProvider,\n      registry: this._capabilityRegistry,\n      createDelegationWasm: (params) => this.createDelegationWrapper(params),\n      computeCid: (data, codec) => {\n        if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n        return this.wasmBindings.computeCid(data, codec);\n      },\n      // delegationManager: undefined - not needed for receive()\n      createKVService: (config) => {\n        // Use pathPrefix as the KV service prefix for sharing links\n        // Strip trailing slash to match DelegatedAccess behavior\n        const prefix = config.pathPrefix?.replace(/\\/$/, '');\n        const kvService = new KVService({ prefix });\n        // Create a new service context for the KV service\n        const kvContext = receiveOnlyGraph.track(new ServiceContext({\n          invoke: config.invoke,\n          fetch: config.fetch ?? globalThis.fetch.bind(globalThis),\n          hosts: config.hosts,\n          telemetry: this.config.telemetry,\n        }));\n        kvContext.setSession(config.session);\n        kvService.initialize(kvContext);\n        return kvService;\n      },\n    });\n\n    // Set up wallet/auth if signer or privateKey is provided\n    if (config.signer) {\n      this.signer = config.signer;\n      this.setupAuth(config);\n    } else if (config.privateKey) {\n      if (!TinyCloudNode.nodeDefaults) {\n        throw new Error(\n          \"privateKey requires PrivateKeySigner. Either provide a signer in config, \" +\n          \"or import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults.\"\n        );\n      }\n      this.signer = TinyCloudNode.nodeDefaults.createSigner(config.privateKey, this._chainId);\n      this.setupAuth(config);\n    }\n  }\n\n  /**\n   * Set up authorization handler and TinyCloud instance.\n   * @internal\n   */\n  private setupAuth(config: TinyCloudNodeConfig): void {\n    const useBootstrapSignInRequest = this.shouldUseBootstrapSignInRequest(config);\n    this.auth = new NodeUserAuthorization({\n      signer: this.signer!,\n      signStrategy: config.signStrategy ?? { type: \"auto-sign\" },\n      wasmBindings: this.wasmBindings,\n      sessionManager: this.sessionManager,\n      sessionStorage: config.sessionStorage ?? new MemorySessionStorage(),\n      domain: this.siweDomain,\n      spacePrefix: config.prefix,\n      sessionExpirationMs: config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS,\n      tinycloudHosts: this.explicitHost ? [this.explicitHost] : undefined,\n      tinycloudRegistryUrl: config.tinycloudRegistryUrl,\n      tinycloudFallbackHosts: config.tinycloudFallbackHosts,\n      autoDiscoverLocalNode: config.autoDiscoverLocalNode,\n      localNodeUrl: config.localNodeUrl,\n      localLinkName: config.localLinkName,\n      expectedNodeDid: config.expectedNodeDid,\n      localNodeIdentityStore: config.localNodeIdentityStore,\n      autoCreateSpace: useBootstrapSignInRequest ? false : config.autoCreateSpace,\n      enablePublicSpace: config.enablePublicSpace ?? true,\n      spaceCreationHandler: useBootstrapSignInRequest\n        ? undefined\n        : config.spaceCreationHandler,\n      nonce: config.nonce,\n      siweConfig: config.siweConfig,\n      manifest: useBootstrapSignInRequest ? undefined : config.manifest,\n      capabilityRequest: useBootstrapSignInRequest\n        ? BOOTSTRAP_SESSION_REQUESTS.default\n        : config.capabilityRequest,\n      includeAccountRegistryPermissions: useBootstrapSignInRequest\n        ? false\n        : config.includeAccountRegistryPermissions,\n    });\n\n    this.tc = new TinyCloud(this.auth, {\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      telemetry: config.telemetry,\n    });\n  }\n\n  private shouldUseBootstrapSignInRequest(config: TinyCloudNodeConfig): boolean {\n    return config.autoBootstrapAccount !== false &&\n      config.manifest === undefined &&\n      config.capabilityRequest === undefined &&\n      (config.prefix ?? \"default\") === \"default\" &&\n      isOpenKeyAutoSignStrategy(config.signStrategy);\n  }\n\n  private createServiceGraphLifetime(): ServiceGraphLifetime {\n    return new ServiceGraphLifetime(\n      this.invokeWithRuntimePermissions,\n      this.invokeAnyWithRuntimePermissions,\n      // Resolve fetch at request time. This keeps the graph-owned lifetime\n      // signal while preserving the SDK's existing injectable global fetch\n      // behavior (including adapters that install it after construction).\n      (url, init) => globalThis.fetch(url, init),\n    );\n  }\n\n  private syncResolvedHostFromAuth(): void {\n    const host = this.auth?.hosts[0];\n    if (host) {\n      this.config.host = host;\n    }\n  }\n\n  /**\n   * Install or replace the manifest that drives the SIWE recap at\n   * sign-in. Takes effect on the next `signIn()` call — the current\n   * session (if any) is not touched. Wire this up from a higher\n   * layer (e.g. TinyCloudWeb.setManifest) so the manifest is kept\n   * in sync across the stack.\n   */\n  setManifest(manifest: Manifest | Manifest[] | undefined): void {\n    if (!this.auth) {\n      // Session-only mode has no auth handler, so there's nothing to\n      // update. The caller almost certainly wanted wallet mode — fail\n      // loudly rather than silently dropping the manifest.\n      throw new Error(\n        \"setManifest requires wallet mode. Provide a signer or privateKey in the TinyCloudNode config.\",\n      );\n    }\n    this.config.manifest = manifest;\n    this.config.capabilityRequest = undefined;\n    this.auth.setManifest(manifest);\n  }\n\n  setCapabilityRequest(request: ComposedManifestRequest | undefined): void {\n    if (!this.auth) {\n      throw new Error(\n        \"setCapabilityRequest requires wallet mode. Provide a signer or privateKey in the TinyCloudNode config.\",\n      );\n    }\n    this.config.capabilityRequest = request;\n    this.config.manifest = request?.manifests;\n    this.auth.setCapabilityRequest(request);\n  }\n\n  /**\n   * Return the manifest currently installed on the auth handler,\n   * or `undefined` if none is set.\n   */\n  get manifest(): Manifest | Manifest[] | undefined {\n    return this.auth?.manifest;\n  }\n\n  get capabilityRequest(): ComposedManifestRequest | undefined {\n    return this.auth?.capabilityRequest;\n  }\n\n  get hosts(): string[] {\n    const authHosts = this.auth?.hosts ?? [];\n    return authHosts.length > 0 ? authHosts : [this.config.host!];\n  }\n\n  /**\n   * Get the primary identity DID for this user.\n   * - If wallet connected and signed in: returns PKH DID (did:pkh:eip155:{chainId}:{address})\n   * - If session-only mode: returns session key DID (did:key:z6Mk...)\n   *\n   * Use this for delegations - it always returns the appropriate identity.\n   */\n  get did(): string {\n    // If wallet is connected and signed in, return PKH (persistent identity)\n    if (this._address) {\n      return pkhDid(this._address, this._chainId);\n    }\n    // Session-only mode: return session key DID (ephemeral identity)\n    return this.sessionManager.getDID(this.sessionKeyId);\n  }\n\n  /**\n   * Get the session key DID. Always available.\n   * Format: did:key:z6Mk...#z6Mk...\n   *\n   * Use this when you specifically need the session key, not the user identity.\n   */\n  get sessionDid(): string {\n    return this.sessionManager.getDID(this.sessionKeyId);\n  }\n\n  /**\n   * Return the current session's signed ReCap capabilities after the session\n   * has been authenticated or restored. This is intentionally distinct from\n   * installed runtime delegations: it reports base-session authority only.\n   *\n   * Invalid or unparseable signed ReCap material throws so callers fail closed\n   * rather than treating a malformed session as unrestricted authority.\n   */\n  getVerifiedSessionCapabilities(): PermissionEntry[] {\n    const session = this.currentTinyCloudSession();\n    if (!session || !session.siwe) return [];\n    return parseRecapCapabilities(\n      (siwe: string) => this.parseRecapWithCaveats(siwe),\n      session.siwe,\n    ).map((entry) => entry.service === \"tinycloud.encryption\"\n      ? {\n        service: entry.service,\n        path: entry.path,\n        actions: [...entry.actions],\n        ...(entry.caveats === undefined ? {} : { caveats: entry.caveats }),\n      }\n      : entry);\n  }\n\n  /**\n   * Get the Ethereum address for this user.\n   */\n  get address(): string | undefined {\n    return this.auth?.address() ?? this._address;\n  }\n\n  /**\n   * Check if this instance is in session-only mode (no wallet).\n   * In session-only mode, the instance can receive delegations but cannot\n   * create its own space via signIn().\n   */\n  get isSessionOnly(): boolean {\n    return this.signer === null;\n  }\n\n  /**\n   * Get the space ID for this user.\n   * Available after signIn().\n   */\n  get spaceId(): string | undefined {\n    return this.auth?.tinyCloudSession?.spaceId;\n  }\n\n  /**\n   * Get the account space ID for this wallet identity.\n   * Available after wallet-backed sign-in or a restored session with address metadata.\n   */\n  get accountSpaceId(): string | undefined {\n    if (!this._address) {\n      return undefined;\n    }\n    return this.wasmBindings.makeSpaceId(this._address, this._chainId, ACCOUNT_REGISTRY_SPACE);\n  }\n\n  /**\n   * Account-level application and delegation helpers.\n   */\n  get account(): AccountService {\n    if (!this._account) {\n      this._account = new AccountService({\n        getDid: () => this.did,\n        getHost: () => this.hosts[0] ?? this.config.host!,\n        getPrimarySpaceId: () => this.spaceId,\n        getAccountSpaceId: () => this.accountSpaceId,\n        getSpaces: () => this.spaces,\n        getDelegationManager: () => this.delegationManager,\n        getAccountDb: () =>\n          this.accountSpaceId\n            ? this.sqlForSpace(this.accountSpaceId).db(\"account\")\n            : undefined,\n        ensureAccountSpaceHosted: async () => {\n          if (this.accountSpaceId && this.auth) {\n            await this.ensureOwnedSpaceHostedById(this.accountSpaceId);\n          }\n        },\n      });\n    }\n    return this._account;\n  }\n\n  /**\n   * Get the current TinyCloud session.\n   * Available after signIn().\n   */\n  get session(): TinyCloudSession | undefined {\n    return this.auth?.tinyCloudSession;\n  }\n\n  /**\n   * Get the currently active session in the shape callers can persist and later\n   * pass back to {@link restoreSession}.\n   */\n  get restorableSession(): TinyCloudSession | undefined {\n    return this.currentTinyCloudSession();\n  }\n\n  /**\n   * Sign in and create a new session.\n   * This creates the user's space if it doesn't exist.\n   * Requires wallet mode (privateKey in config).\n   *\n   * @param options - Optional per-call SIWE overrides for this sign-in only\n   */\n  async signIn(options?: SignInOptions): Promise<void> {\n    if (!this.signer || !this.tc) {\n      throw new Error(\n        \"Cannot signIn() in session-only mode. Provide a privateKey in config to create your own space.\"\n      );\n    }\n\n    // Ensure WASM is ready (critical for browser where WASM loads asynchronously)\n    await this.wasmBindings.ensureInitialized?.();\n\n    this._address = canonicalizeAddress(await this.signer.getAddress());\n    this._chainId = await this.signer.getChainId();\n\n    // Reset services so they get recreated with new session\n    this._kv = undefined;\n    this._sql = undefined;\n    this._duckdb = undefined;\n    this._hooks = undefined;\n    this._vault = undefined;\n    this._encryption = undefined;\n    this._baseVaults.clear();\n    this._baseSecrets.clear();\n    this._secrets.clear();\n    this._spaceService = undefined;\n    this._serviceContext = undefined;\n    this.runtimePermissionGrants = [];\n\n    await this.tc.signIn(options);\n    this.syncResolvedHostFromAuth();\n\n    // Bind the replacement services to the runtime dependencies active for\n    // this sign-in and permanently retire anything captured from the previous\n    // session. The authorization flow above remains transactional: a rejected\n    // sign-in leaves the existing graph untouched.\n    const oldGraph = this._serviceGraph;\n    this._serviceGraph = this.createServiceGraphLifetime();\n    oldGraph.retire();\n    this.tc.retireServices();\n\n    // NodeUserAuthorization renames the constructor's \"default\" key when it\n    // creates the signed-in session. Keep node-level key accessors in sync so\n    // sessionDid and delegation flows use the active key instead of the old ID.\n    const signedInSession = this.currentTinyCloudSession();\n    if (signedInSession) {\n      this.sessionKeyId = signedInSession.sessionKey;\n      this.sessionKeyJwk = signedInSession.jwk;\n    }\n\n    // Initialize service context with session\n    this.initializeServices();\n\n    // Register the primary session's own recap as the highest-trust\n    // (`provenance: \"primary\"`) runtime grant so it always wins invocation\n    // selection over broader bootstrap/delegated grants (TC-111). Must run\n    // after the primary session is established and after grants were cleared\n    // above, so no dupes. `lastActivationSkippedSpaceIds` was already\n    // populated by the auth layer's session activation inside `tc.signIn`\n    // above, so the skipped-activation exclusion sees the real skip set here.\n    const primarySession = this.currentTinyCloudSession();\n    if (primarySession) {\n      this.registerPrimarySessionGrant(primarySession);\n    }\n\n    const bootstrapped = await this.bootstrapAccountIfNeeded();\n\n    await this.ensureRequestedEncryptionNetworks();\n\n    if (\n      !bootstrapped &&\n      this.config.manifest === undefined &&\n      this.config.capabilityRequest === undefined\n    ) {\n      await this.ensureOwnedSpaceHostedById(this.ownedSpaceId(SECRETS_SPACE));\n    }\n\n    if (!bootstrapped) {\n      this.scheduleAccountRegistrySync();\n    }\n\n    this.notificationHandler.success(\"Successfully signed in\");\n  }\n\n  private ownedSpaceId(name: string): string {\n    if (!this._address) {\n      throw new Error(\"Cannot resolve owned space before sign-in\");\n    }\n    return this.wasmBindings.makeSpaceId(this._address, this._chainId, name);\n  }\n\n  private async bootstrapAccountIfNeeded(): Promise<boolean> {\n    this._bootstrapSkipped = false;\n    this._bootstrapStatus = { skipped: false };\n\n    if (this.config.autoBootstrapAccount === false) {\n      return false;\n    }\n    if (!this.auth || !this._address) {\n      return false;\n    }\n\n    // Interactive signers (browser wallet / EIP-1193) prompt the user for\n    // every signMessage() call. Running bootstrap through an interactive\n    // signer would open 10+ sequential sign prompts. Skip client-side\n    // bootstrap entirely: the server (OpenKey) handles bootstrap inside\n    // POST /api/keys/{keyId}/sign before returning the first signature.\n    if (isInteractiveSigner(this.config)) {\n      console.debug(\n        \"[TinyCloudNode] bootstrap skipped: interactive signer detected. \" +\n        \"Server-side bootstrap (OpenKey) is expected to have provisioned the account.\",\n      );\n      this._bootstrapSkipped = true;\n      this._bootstrapStatus = { skipped: true, reason: \"interactive-signer\" };\n      return false;\n    }\n\n    const steps = bootstrapSteps(this._address, this._chainId);\n    if (!(await this.isFreshBootstrapAccount(steps))) {\n      return false;\n    }\n\n    try {\n      await this.runAccountBootstrap(steps);\n    } catch (err) {\n      // Bootstrap is provisioning, not a precondition of the session the\n      // user just signed: never fail signIn() because of it. Surface the\n      // outcome instead so apps can offer a \"finish account setup\" action.\n      const reason = err instanceof Error ? err.message : String(err);\n      this._bootstrapSkipped = true;\n      this._bootstrapStatus = { skipped: true, reason };\n      this.notificationHandler.warning(\n        `Account bootstrap did not complete: ${reason}`,\n      );\n      console.warn(`[TinyCloudNode] account bootstrap failed: ${reason}`);\n      return false;\n    }\n    return true;\n  }\n\n  private async isFreshBootstrapAccount(steps: BootstrapStep[]): Promise<boolean> {\n    const enshrinedSpaceIds = new Set<string>();\n    for (const step of steps) {\n      if (step.kind === \"session\") {\n        enshrinedSpaceIds.add(step.spaceId);\n      }\n    }\n    const skipped = (this.auth as NodeUserAuthorization).lastActivationSkippedSpaceIds;\n    if (skipped.some((spaceId) => enshrinedSpaceIds.has(spaceId))) {\n      return true;\n    }\n\n    try {\n      const indexed = await this.account.index.spaces.list();\n      if (indexed.ok && indexed.data.length === 0) {\n        return true;\n      }\n    } catch {\n      // A missing account index is expected before bootstrap; fall through to KV.\n    }\n\n    try {\n      const spaces = await this.account.spaces.list();\n      return spaces.ok && spaces.data.length === 0;\n    } catch {\n      return false;\n    }\n  }\n\n  private async runAccountBootstrap(steps: BootstrapStep[]): Promise<void> {\n    if (!this.auth || !this._address) {\n      throw new Error(\"Account bootstrap requires an active wallet session\");\n    }\n\n    const host = this.hosts[0] ?? this.config.host;\n    if (!host) {\n      throw new Error(\"Account bootstrap requires a TinyCloud host\");\n    }\n\n    const auth = this.auth as NodeUserAuthorization;\n    const sessions = new Map<BootstrapSpaceName, TinyCloudSession>();\n    const rawAbilitiesBySpace = new Map<BootstrapSpaceName, Record<string, string[]>>();\n    const primarySession = auth.tinyCloudSession;\n    const defaultSpaceId = this.ownedSpaceId(\"default\");\n    const canReusePrimaryBootstrapSession =\n      primarySession?.spaceId === defaultSpaceId &&\n      auth.capabilityRequest === BOOTSTRAP_SESSION_REQUESTS.default;\n\n    for (const step of steps) {\n      if (step.kind !== \"session\") continue;\n      if (step.space === \"default\" && canReusePrimaryBootstrapSession && primarySession) {\n        sessions.set(step.space, primarySession);\n        continue;\n      }\n      const rawAbilities = step.rawAbilities;\n      if (rawAbilities) {\n        rawAbilitiesBySpace.set(step.space, rawAbilities);\n      }\n      let session: TinyCloudSession;\n      try {\n        session = await auth.createBootstrapSession({\n          spaceId: step.spaceId,\n          capabilityRequest: step.request ?? BOOTSTRAP_SESSION_REQUESTS[step.space],\n          rawAbilities,\n        });\n      } catch (err) {\n        // Abort immediately — do not cascade into remaining bootstrap steps.\n        // A single clear error is surfaced instead of one error per space.\n        throw new Error(\n          `Account bootstrap aborted: signature rejected for space \"${step.space}\". ` +\n          `Cause: ${err instanceof Error ? err.message : String(err)}`,\n        );\n      }\n      sessions.set(step.space, session);\n    }\n\n    for (const step of steps) {\n      if (step.kind !== \"host\") continue;\n      const hosted = await auth.hostOwnedSpace(step.spaceId, \"bootstrap-host\");\n      if (!hosted) {\n        throw new Error(`Failed to host bootstrap space: ${step.spaceId}`);\n      }\n    }\n\n    await new Promise((resolve) => setTimeout(resolve, 100));\n\n    for (const step of steps) {\n      if (step.kind !== \"activate\") continue;\n      const session = sessions.get(step.space);\n      if (!session) {\n        throw new Error(`Missing bootstrap session for ${step.space}`);\n      }\n      const activated = await activateSessionWithHost(host, session.delegationHeader);\n      if (!activated.success || activated.skipped?.includes(step.spaceId)) {\n        throw new Error(\n          `Failed to activate bootstrap session for ${step.spaceId}: ${\n            activated.error ?? \"space was skipped\"\n          }`,\n        );\n      }\n      this.registerBootstrapRuntimeGrant(\n        session,\n        BOOTSTRAP_SESSION_REQUESTS[step.space],\n        rawAbilitiesBySpace.get(step.space),\n      );\n    }\n\n    for (const step of steps) {\n      if (step.kind === \"account-index-schema\") {\n        const ensured = await this.account.index.ensure();\n        if (!ensured.ok) {\n          throw new Error(`Failed to create account index schema: ${ensured.error.message}`);\n        }\n      }\n\n      if (step.kind === \"seed-spaces\") {\n        for (const space of step.spaces) {\n          const registered = await this.account.spaces.register({\n            spaceId: space.spaceId,\n            name: space.name,\n            ownerDid: this.did,\n            type: \"owned\",\n            permissions: [\"*\"],\n            status: \"active\",\n          });\n          if (!registered.ok) {\n            throw new Error(\n              `Failed to seed account space ${space.spaceId}: ${registered.error.message}`,\n            );\n          }\n        }\n      }\n\n      if (step.kind === \"seed-applications\") {\n        const registered = await this.account.applications.register(\n          step.manifests.length > 0\n            ? [...step.manifests]\n            : TINYCLOUD_SECRETS_BOOTSTRAP_MANIFEST,\n        );\n        if (!registered.ok) {\n          throw new Error(`Failed to seed bootstrap applications: ${registered.error.message}`);\n        }\n      }\n\n      if (step.kind === \"encryption-network-create\") {\n        await this.ensureEncryptionNetwork(step.networkId);\n      }\n\n      if (step.kind === \"secret-records-schema\") {\n        const db = this.sqlForSpace(step.spaceId).db(step.database);\n        const migrated = await db.migrations.apply({\n          namespace: \"tinycloud.secrets.records\",\n          migrations: [\n            {\n              id: \"001_initial\",\n              sql: [...SECRET_RECORDS_SCHEMA],\n            },\n          ],\n        });\n        if (!migrated.ok) {\n          throw new Error(\n            `Failed to create secret_records schema: ${migrated.error.message}`,\n          );\n        }\n      }\n    }\n  }\n\n  private registerBootstrapRuntimeGrant(\n    session: TinyCloudSession,\n    request: { resources: readonly { service: string; space: string; path: string; actions: readonly string[] }[] },\n    rawAbilities?: Record<string, string[]>,\n  ): void {\n    const operations: RuntimePermissionOperation[] = [];\n    for (const resource of request.resources) {\n      const service = resource.service.startsWith(\"tinycloud.\")\n        ? this.shortServiceName(resource.service)\n        : resource.service;\n      const spaceId = resource.space.startsWith(\"tinycloud:\")\n        ? resource.space\n        : this.ownedSpaceId(resource.space);\n      for (const action of resource.actions) {\n        operations.push({\n          spaceId,\n          service,\n          path: resource.path,\n          action,\n        });\n      }\n    }\n    for (const [resource, actions] of Object.entries(rawAbilities ?? {})) {\n      for (const action of actions) {\n        operations.push({\n          resource,\n          service: \"encryption\",\n          path: resource,\n          action,\n        });\n      }\n    }\n\n    const expiresAt = extractSiweExpiration(session.siwe) ?? this.getSessionExpiry();\n    const actions = [...new Set(operations.map((operation) => operation.action))];\n    this.runtimePermissionGrants.push({\n      session: {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId: session.spaceId,\n        verificationMethod: session.verificationMethod,\n        jwk: session.jwk,\n      },\n      delegation: {\n        cid: session.delegationCid,\n        delegationHeader: session.delegationHeader,\n        delegateDID: session.verificationMethod,\n        delegatorDID: this.did,\n        spaceId: session.spaceId,\n        path: \"\",\n        actions,\n        expiry: expiresAt,\n        allowSubDelegation: true,\n        ownerAddress: session.address,\n        chainId: session.chainId,\n        host: this.config.host,\n      },\n      operations,\n      expiresAt,\n      provenance: \"bootstrap\",\n    });\n  }\n\n  /**\n   * Map the base session's OWN recap into runtime permission operations.\n   *\n   * Uses the RAW `parseRecapFromSiwe` binding — NOT `parseRecapCapabilities`,\n   * whose `normalizeSpace` collapses `tinycloud:pkh:...:<owner>:<space>` to a\n   * bare short name and would conflate two owners' identically-named spaces.\n   * We must keep the full owner-scoped URI so a synthetic primary grant can\n   * never cover an operation on a different owner's space.\n   *\n   * Mirrors {@link operationsFromDelegation}'s op shape: encryption network\n   * entries (`urn:tinycloud:encryption:` paths) become `resource` ops; every\n   * other entry becomes a `spaceId` op carrying the raw recap `space` URI.\n   * One op per action.\n   *\n   * Returns `[]` for session-only / restored-without-siwe modes and for any\n   * unparseable SIWE — the primary grant is simply not registered in that case.\n   */\n  private recapOperationsFromSession(\n    session: TinyCloudSession,\n  ): RuntimePermissionOperation[] {\n    const siwe = session.siwe;\n    if (!siwe) {\n      return [];\n    }\n    if (this._recapOperationsCache?.siwe === siwe) {\n      return this._recapOperationsCache.operations;\n    }\n    let operations: RuntimePermissionOperation[] = [];\n    try {\n      const entries = this.parseRecapWithCaveats(siwe);\n      if (Array.isArray(entries)) {\n        operations = entries.flatMap((entry) => {\n          const service = this.invocationServiceName(entry.service);\n          return entry.actions.map((action) => ({\n            ...(this.isEncryptionNetworkOperation(service, entry.path)\n              ? { resource: entry.path }\n              : { spaceId: entry.space }),\n            service,\n            path: entry.path,\n            action,\n            caveats: cloneRecapCaveats(entry.caveats),\n          }));\n        });\n      }\n    } catch {\n      operations = [];\n    }\n    this._recapOperationsCache = { siwe, operations };\n    return operations;\n  }\n\n  /**\n   * Register the base (primary) session's own recap as a synthetic runtime\n   * grant tagged `provenance: \"primary\"` so it always out-ranks other covering\n   * grants in {@link findGrantForOperations}. This closes the selection-design\n   * hazard where a broad — possibly broken — bootstrap/delegated grant could\n   * hijack an operation the primary session itself already authorized (TC-111).\n   *\n   * Two safety exclusions:\n   *  - Ops whose space is in `lastActivationSkippedSpaceIds` are dropped: the\n   *    node refused to activate those spaces this sign-in even though the recap\n   *    claims them. Including them would let the synthetic primary out-rank a\n   *    working grant and 401 (the \"skipped-activation inverted hijack\").\n   *  - Encryption `resource` ops are kept as-is (space-independent).\n   *\n   * No-ops when nothing remains after exclusion. Callers (`signIn`,\n   * `restoreSession`) clear `runtimePermissionGrants` first, so no dupes.\n   */\n  private registerPrimarySessionGrant(session: TinyCloudSession): void {\n    const skipped = this.auth\n      ? (this.auth as NodeUserAuthorization).lastActivationSkippedSpaceIds ?? []\n      : [];\n    const operations = this.recapOperationsFromSession(session).filter(\n      (operation) =>\n        operation.spaceId === undefined ||\n        !skipped.some((spaceId) => this.spaceIdsEqual(spaceId, operation.spaceId!)),\n    );\n    if (operations.length === 0) {\n      return;\n    }\n\n    const expiresAt = extractSiweExpiration(session.siwe) ?? this.getSessionExpiry();\n    const actions = [...new Set(operations.map((operation) => operation.action))];\n    this.runtimePermissionGrants.push({\n      session: {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId: session.spaceId,\n        verificationMethod: session.verificationMethod,\n        jwk: session.jwk,\n      },\n      delegation: {\n        cid: session.delegationCid,\n        delegationHeader: session.delegationHeader,\n        delegateDID: session.verificationMethod,\n        delegatorDID: this.did,\n        spaceId: session.spaceId,\n        path: \"\",\n        actions,\n        expiry: expiresAt,\n        allowSubDelegation: true,\n        ownerAddress: session.address,\n        chainId: session.chainId,\n        host: this.config.host,\n      },\n      operations,\n      expiresAt,\n      provenance: \"primary\",\n    });\n  }\n\n  private async writeManifestRegistryRecords(): Promise<void> {\n    const request = this.capabilityRequest;\n    if (!request || request.registryRecords.length === 0) {\n      return;\n    }\n    if (!this.auth || !this.signer) {\n      throw new Error(\"Manifest registry write requires wallet mode\");\n    }\n\n    const accountSpaceId = this.ownedSpaceId(ACCOUNT_REGISTRY_SPACE);\n    await this.ensureOwnedSpaceHostedById(accountSpaceId);\n\n    const result = await this.account.applications.register(request.manifests);\n    if (!result.ok) {\n      throw new Error(\n        `Failed to write manifest registry records: ${result.error.message}`,\n      );\n    }\n  }\n\n  private scheduleAccountRegistrySync(): void {\n    void this.withAccountRegistryRetry(async () => {\n      void this.account.index.ensure();\n      await this.writeManifestRegistryRecords();\n\n      if (this.currentSessionCanListSpaces()) {\n        const spaces = await this.account.spaces.syncAccessible();\n        if (!spaces.ok) {\n          throw new Error(`Failed to sync account spaces: ${spaces.error.message}`);\n        }\n      }\n      // Else: the current session carries a recap that does not grant\n      // `tinycloud.space/list` (every manifest/recap session, and the default\n      // non-manifest recap alike — its abilities table has no `space` service).\n      // `syncAccessible()` depends on `tinycloud.space/list`, which such a\n      // session does not hold — see {@link isOwnedSpaceRegistered} — so the\n      // owned-space listing is a doomed request that 401s on the wire\n      // (`Unauthorized Action: …/space/ tinycloud.space/list`). The account\n      // spaces registry is instead maintained by bootstrap seeding +\n      // `spaces.register()`, so we skip the invoke entirely rather than emit it.\n    });\n  }\n\n  /**\n   * Whether the current primary session may invoke `tinycloud.space/list`.\n   *\n   * A session with NO parseable recap (session-only / restored-without-siwe)\n   * yields zero recap operations — we preserve today's behavior and let\n   * `syncAccessible()` run. A session whose parseable recap has entries but\n   * none granting `tinycloud.space/list` cannot list owned spaces; the guard\n   * skips. Every wallet SIWE session in this stack carries a recap (manifest\n   * sessions and the default non-manifest recap alike), and none grant\n   * `space/list`, so all of them skip.\n   *\n   * Reuses the TC-111 {@link recapOperationsFromSession} primitive — no second\n   * recap parser.\n   */\n  private currentSessionCanListSpaces(): boolean {\n    const session = this.currentTinyCloudSession();\n    const operations = session\n      ? this.recapOperationsFromSession(session)\n      : [];\n    if (operations.length === 0) {\n      return true;\n    }\n    return operations.some(\n      (operation) =>\n        operation.service === \"space\" &&\n        this.actionContains(operation.action, \"tinycloud.space/list\"),\n    );\n  }\n\n  private async withAccountRegistryRetry(task: () => Promise<void>): Promise<void> {\n    const delays = [250, 1_000, 3_000];\n    let lastError: unknown;\n    for (let attempt = 0; attempt < delays.length; attempt += 1) {\n      try {\n        await task();\n        return;\n      } catch (error) {\n        // Authorization verdicts are deterministic, not transient: retrying an\n        // `Unauthorized Action` / 401 only re-emits the doomed request (the\n        // 2026-07-03 recap-storm incident). Warn once and stop; generic errors\n        // still get the full retry budget below.\n        const message = error instanceof Error ? error.message : String(error);\n        if (/Unauthorized Action|\\b401\\b/.test(message)) {\n          console.warn(\n            \"TinyCloud account registry sync stopped: authorization verdict is not retryable\",\n            error,\n          );\n          return;\n        }\n        lastError = error;\n        if (attempt < delays.length - 1) {\n          await new Promise((resolve) => setTimeout(resolve, delays[attempt]));\n        }\n      }\n    }\n\n    console.warn(\n      \"TinyCloud account registry sync failed after retries\",\n      lastError,\n    );\n  }\n\n  private requestedEncryptionNetworkIds(): string[] {\n    const request = this.capabilityRequest;\n    if (!request) {\n      return [];\n    }\n\n    const networkIds = new Set<string>();\n    for (const resource of request.resources) {\n      if (\n        resource.service === ENCRYPTION_PERMISSION_SERVICE &&\n        resource.path.startsWith(\"urn:tinycloud:encryption:\") &&\n        resource.actions.includes(DECRYPT_ACTION)\n      ) {\n        networkIds.add(resource.path);\n      }\n    }\n    return [...networkIds];\n  }\n\n  private async ensureRequestedEncryptionNetworks(): Promise<void> {\n    if (!this.signer || !this.auth) {\n      return;\n    }\n\n    for (const networkId of this.requestedEncryptionNetworkIds()) {\n      const parsed = parseNetworkId(networkId);\n      if (!didPrincipalMatches(parsed.ownerDid, this.did)) {\n        continue;\n      }\n      await this.ensureEncryptionNetwork(networkId);\n    }\n  }\n\n  private async ensureOwnedSpaceHostedById(spaceId: string): Promise<void> {\n    if (!this.auth) {\n      throw new Error(\"Owned space hosting requires wallet mode\");\n    }\n\n    const session = this.auth.tinyCloudSession;\n    if (!session) {\n      throw new Error(\"Owned space hosting requires an active session\");\n    }\n\n    const host = this.hosts[0] ?? this.config.host;\n    if (!host) {\n      throw new Error(\"Owned space hosting requires a TinyCloud host\");\n    }\n\n    const activation = await activateSessionWithHost(host, session.delegationHeader);\n    if (activation.success && !activation.skipped?.includes(spaceId)) {\n      return;\n    }\n\n    if (!activation.success && activation.status !== 404) {\n      throw new Error(\n        `Failed to check owned space ${spaceId}: ${activation.error ?? activation.status}`,\n      );\n    }\n\n    const created = await (this.auth as NodeUserAuthorization).hostOwnedSpace(spaceId);\n    if (!created) {\n      throw new Error(`Failed to create owned space: ${spaceId}`);\n    }\n\n    await new Promise((resolve) => setTimeout(resolve, 100));\n\n    const retry = await activateSessionWithHost(host, session.delegationHeader);\n    if (!retry.success || retry.skipped?.includes(spaceId)) {\n      throw new Error(\n        `Failed to activate session after creating owned space ${spaceId}: ${\n          retry.error ?? \"space was skipped\"\n        }`,\n      );\n    }\n  }\n\n  /**\n   * Host one of this user's owned spaces by name (e.g. `\"applications\"`).\n   *\n   * Resolves the name to the owned space URI\n   * (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`) and registers it on the\n   * server via the host-SIWE delegation flow, so subsequent KV/SQL writes to\n   * that space succeed instead of returning `404 - Space not found`. The\n   * caller is the root authority of their own owned spaces, so no additional\n   * delegation is required.\n   *\n   * Unlike {@link ensureOwnedSpaceHostedById}, this always submits the host\n   * delegation rather than inferring hosting from session activation: a space\n   * the current session has never referenced is reported neither as\n   * `activated` nor `skipped`, so activation-based detection would wrongly\n   * skip the host. The host SIWE is idempotent server-side, so re-hosting an\n   * existing space is a safe no-op. Must be called after {@link signIn}.\n   *\n   * @param name - The owned space name (e.g. `\"applications\"`).\n   * @returns The hosted space URI.\n   */\n  async hostOwnedSpace(name: string): Promise<string> {\n    if (!this.auth || !this.auth.tinyCloudSession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const spaceId = this.ownedSpaceId(name);\n\n    const host = this.hosts[0] ?? this.config.host;\n    if (!host) {\n      throw new Error(\"Owned space hosting requires a TinyCloud host\");\n    }\n\n    const hosted = await (this.auth as NodeUserAuthorization).hostOwnedSpace(\n      spaceId,\n    );\n    if (!hosted) {\n      throw new Error(`Failed to host owned space: ${spaceId}`);\n    }\n\n    // Re-activate the session so it covers the newly hosted space, and prove\n    // the session can actually use it before reporting success: a successful\n    // /delegate that still lists the space under `skipped` means it is not\n    // hosted for this session.\n    const activation = await activateSessionWithHost(\n      host,\n      this.auth.tinyCloudSession.delegationHeader,\n    );\n    if (!activation.success || activation.skipped?.includes(spaceId)) {\n      throw new Error(\n        `Failed to activate session for owned space ${spaceId}: ${\n          activation.error ?? \"space was skipped\"\n        }`,\n      );\n    }\n\n    void this.account.spaces\n      .register({\n        spaceId,\n        name,\n        ownerDid: this.did,\n        type: \"owned\",\n        permissions: [\"*\"],\n        status: \"active\",\n      })\n      .catch(() => {});\n\n    return spaceId;\n  }\n\n  /**\n   * Ensure one of this user's owned spaces (e.g. `\"secrets\"`) is hosted on the\n   * server.\n   *\n   * At sign-in, a full-authority session auto-hosts the owner's `secrets`\n   * space, but a session created with a manifest / capabilityRequest does not.\n   * Such a session can therefore hold valid `tinycloud.kv/*` capabilities for\n   * the owned `secrets` space yet still fail its first scoped\n   * `secrets.put(...)` with `404 Space not found`, because the space was never\n   * registered on the node.\n   *\n   * Calling this resolves `name` to the owner's owned-space URI\n   * (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`). It first consults the\n   * account-space spaces registry (`account/spaces/{space_id}`, the canonical\n   * KV source of truth, fronted by a best-effort SQLite index): if the space is\n   * already registered/hosted it returns the URI WITHOUT submitting a host\n   * delegation, avoiding a redundant host-SIWE signature prompt for owners who\n   * already use the space. Only when the space is absent — or the registry\n   * check fails for any reason (e.g. a cold SQLite index reporting\n   * `no such table: spaces`) — does it fall through to {@link hostOwnedSpace}.\n   *\n   * The registry check is purely an optimization: any failure falls back to\n   * hosting, and the host SIWE is idempotent server-side, so re-hosting an\n   * existing space remains a safe no-op. Must be called after {@link signIn}.\n   *\n   * @param name - The owned space name (e.g. `\"secrets\"`).\n   * @returns The hosted owned-space URI.\n   */\n  async ensureOwnedSpaceHosted(name: string): Promise<string> {\n    if (!this.auth || !this.auth.tinyCloudSession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const spaceId = this.ownedSpaceId(name);\n\n    if (await this.isOwnedSpaceRegistered(spaceId)) {\n      return spaceId;\n    }\n\n    const hosted = await this.hostOwnedSpace(name);\n\n    // hostOwnedSpace registers best-effort and fire-and-forget; await an\n    // explicit registry write here so the canonical `account/spaces/{id}`\n    // record is durably present and a subsequent ensure short-circuits on the\n    // registry instead of re-hosting. The host already succeeded, so a failed\n    // registry write must not fail this call.\n    try {\n      await this.account.spaces.register({\n        spaceId,\n        name,\n        ownerDid: this.did,\n        type: \"owned\",\n        permissions: [\"*\"],\n        status: \"active\",\n      });\n    } catch {\n      // Registry write is best-effort; the space is hosted regardless.\n    }\n\n    return hosted;\n  }\n\n  /**\n   * Check whether an owned space is already registered/hosted by consulting the\n   * account spaces registry.\n   *\n   * Source of truth is the canonical KV registry record\n   * `account/spaces/{space_id}`, read here via `account.spaces.get(spaceId)`.\n   * The KV path is used (rather than `syncAccessible()`) because it works under\n   * a manifest/recap session with NO extra prompt: the composed manifest recap\n   * already grants `tinycloud.kv get/list` on the account space `spaces/`\n   * prefix, whereas `syncAccessible()` depends on `tinycloud.space/list`, which\n   * a recap session does not hold. Before reading, it consults the fast SQLite\n   * index (`account.index.spaces.list()`) as a best-effort short-circuit; on a\n   * cold index (`no such table: spaces`) or any other index failure it falls\n   * back to the canonical KV read.\n   *\n   * This is a best-effort optimization. ANY failure of the check path (missing\n   * table, KV error, missing record, thrown exception) resolves to `false` so\n   * the caller falls through to hosting — per the directive, \"if it fails in any\n   * way then create the space\".\n   */\n  private async isOwnedSpaceRegistered(spaceId: string): Promise<boolean> {\n    // Best-effort fast path: the SQLite index. Only trust a positive hit; treat\n    // misses/empties/errors/throws (e.g. a cold `no such table: spaces`) as\n    // inconclusive and fall through to the canonical KV read.\n    try {\n      const indexed = await this.account.index.spaces.list();\n      if (indexed.ok && indexed.data.some((space) => space.spaceId === spaceId)) {\n        return true;\n      }\n    } catch {\n      // Cache miss/error — fall back to canonical below.\n    }\n\n    // Canonical: the `account/spaces/{space_id}` KV record. This is the registry\n    // source of truth and is recap-readable. Any failure here (missing record,\n    // KV error, throw) resolves to \"not registered\" so the caller hosts.\n    try {\n      const record = await this.account.spaces.get(spaceId);\n      return record.ok;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Restore a previously established session from stored delegation data.\n   *\n   * This is used by the CLI to restore a session that was created via the\n   * browser-based delegation flow (OpenKey `/delegate` page). Instead of\n   * signing in with a private key, it injects the delegation data directly.\n   *\n   * @param sessionData - The stored delegation data from the browser flow\n   */\n  async restoreSession(sessionData: {\n    delegationHeader: { Authorization: string };\n    delegationCid: string;\n    spaceId: string;\n    /** Additional capability spaces persisted with the primary session. */\n    spaces?: Record<string, string>;\n    jwk: object;\n    verificationMethod: string;\n    address?: string;\n    chainId?: number;\n    /**\n     * The SIWE message that authorized this session. Required for\n     * downstream operations that need the session's expiry (e.g.\n     * {@link grantRuntimePermissions}). When omitted the SDK can still\n     * invoke services with the existing delegation, but anything that\n     * reads `auth.tinyCloudSession.siwe` will treat the session as\n     * expired-at-epoch-zero.\n     */\n    siwe?: string;\n    /**\n     * The wallet/OpenKey signature over `siwe`. When any signed-session\n     * metadata is restored, this is required and verified in WASM before\n     * local ReCap or expiry authority is installed.\n     */\n    signature?: string;\n    /**\n     * Persisted policy expiry. Required when an otherwise valid SIWE omits\n     * `Expiration Time`; restore never invents a new renewable lifetime.\n     */\n    expiresAt?: string;\n    /**\n     * The TinyCloud hosts this session was created against (from\n     * {@link PersistedSessionData.tinycloudHosts}). When present they are\n     * adopted so the restored session targets the same node as the\n     * original sign-in — without this, service calls fall back to the\n     * default host and the auth layer throws \"TinyCloud hosts have not\n     * been resolved\". When absent (old persisted session) hosts resolve\n     * lazily via the registry/fallback on the first host-needing call.\n     */\n    tinycloudHosts?: string[];\n  }): Promise<void> {\n    // Ensure WASM is ready (critical for browser where WASM loads asynchronously)\n    await this.wasmBindings.ensureInitialized?.();\n\n    // Build every part of the restored state against a disposable manager.\n    // Nothing live is touched until the commit below.\n    const restoredJwk = clonePersistedSessionJwk(sessionData.jwk);\n    if (\n      sessionData.chainId !== undefined &&\n      (!Number.isSafeInteger(sessionData.chainId) || sessionData.chainId <= 0)\n    ) {\n      throw new Error(\"Persisted session chain ID must be a positive safe integer.\");\n    }\n    const stagedManager = this.wasmBindings.createSessionManager();\n    const stagedReplace = stagedManager.replaceSessionKey;\n    const liveKeys = this.sessionManager.listSessionKeys;\n    const stagedKeys = stagedManager.listSessionKeys;\n    if (\n      typeof stagedReplace !== \"function\" ||\n      typeof liveKeys !== \"function\" ||\n      typeof stagedKeys !== \"function\"\n    ) {\n      throw new UnsupportedSessionRestoreError();\n    }\n    let stagedKeyId: string;\n    let stagedJwk: object;\n    let canonicalVerificationMethod: string;\n    try {\n      // Replacing a primary signer without a complete key inventory silently\n      // loses receive/share keys. Require the capability rather than guessing.\n      const keyIds = liveKeys.call(this.sessionManager);\n      if (!Array.isArray(keyIds) || !keyIds.every((keyId) => typeof keyId === \"string\")) {\n        throw new UnsupportedSessionRestoreError(\"it cannot reliably enumerate every live session signer\");\n      }\n      for (const keyId of keyIds) {\n        if (keyId === this.sessionKeyId) continue;\n        const jwk = this.sessionManager.jwk(keyId);\n        if (!jwk) throw new Error(\"missing live session key\");\n        stagedReplace.call(stagedManager, clonePersistedSessionJwk(JSON.parse(jwk)), keyId);\n      }\n      stagedKeyId = stagedReplace.call(stagedManager, restoredJwk, this.sessionKeyId);\n      const stagedJwkJson = stagedManager.jwk(stagedKeyId);\n      if (!stagedJwkJson) throw new Error(\"missing restored session key\");\n      stagedJwk = clonePersistedSessionJwk(JSON.parse(stagedJwkJson));\n      canonicalVerificationMethod = stagedManager.getDID(stagedKeyId);\n    } catch (error) {\n      if (error instanceof UnsupportedSessionRestoreError) throw error;\n      throw new Error(\"Persisted session has an invalid private Ed25519 session key.\");\n    }\n    const restoredVerificationMethod = canonicalRestoredVerificationMethod(\n      canonicalVerificationMethod,\n      sessionData.verificationMethod,\n    );\n    if (!restoredVerificationMethod) {\n      throw new Error(\n        \"Persisted session verification method does not match its private Ed25519 session key.\",\n      );\n    }\n    const proofValues = [\n      sessionData.siwe,\n      sessionData.signature,\n      sessionData.address,\n      sessionData.chainId,\n    ];\n    const hasPersistedProof = proofValues.every((value) => value !== undefined);\n    if (!hasPersistedProof && (proofValues.some((value) => value !== undefined) || sessionData.expiresAt !== undefined)) {\n      throw new Error(\"Persisted session authority metadata is incomplete.\");\n    }\n\n    const restoredAddress = hasPersistedProof\n      ? canonicalizeAddress(sessionData.address!)\n      : undefined;\n    let stagedSessionExpiry = new Date(0);\n    let stagedRecap: WasmRecapEntry[] = [];\n    if (hasPersistedProof) {\n      if (typeof this.wasmBindings.validatePersistedSession !== \"function\") {\n        throw new UnsupportedSessionRestoreError(\"it cannot verify persisted SIWE authority\");\n      }\n      const verified = this.wasmBindings.validatePersistedSession({\n        delegationHeader: sessionData.delegationHeader,\n        delegationCid: sessionData.delegationCid,\n        spaceId: sessionData.spaceId,\n        jwk: stagedJwk,\n        address: restoredAddress!,\n        chainId: sessionData.chainId!,\n        siwe: sessionData.siwe!,\n        signature: sessionData.signature!,\n      });\n      const exactRecap = verified.verifiedRecap;\n      if (!Array.isArray(exactRecap) || !exactRecap.every((entry) =>\n        entry !== null && typeof entry === \"object\" &&\n        typeof entry.service === \"string\" &&\n        typeof entry.space === \"string\" &&\n        typeof entry.path === \"string\" &&\n        Array.isArray(entry.actions) && entry.actions.every((action) => typeof action === \"string\") &&\n        Array.isArray(entry.caveats) && entry.caveats.every((caveat) =>\n          caveat !== null && typeof caveat === \"object\" && !Array.isArray(caveat)\n        )\n      )) {\n        throw new UnsupportedSessionRestoreError(\n          \"it cannot reconstruct caveat-preserving persisted ReCap authority\",\n        );\n      }\n      stagedRecap = exactRecap.map((entry) => ({\n        service: entry.service,\n        space: entry.space,\n        path: entry.path,\n        actions: [...entry.actions],\n        caveats: cloneRecapCaveats(entry.caveats),\n      }));\n      const signedExpiry = verified.expiresAt === undefined\n        ? undefined\n        : persistedExpiry(verified.expiresAt);\n      const persistedPolicyExpiry = sessionData.expiresAt === undefined\n        ? undefined\n        : persistedExpiry(sessionData.expiresAt);\n      if (signedExpiry && persistedPolicyExpiry && !sameInstant(signedExpiry, persistedPolicyExpiry)) {\n        throw new Error(\"Persisted session expiry does not match its signed SIWE authority.\");\n      }\n      stagedSessionExpiry = signedExpiry ?? persistedPolicyExpiry ?? persistedExpiry(undefined);\n    }\n    const resolvedHost = await this.resolveRestoredHost(\n      sessionData.tinycloudHosts,\n      restoredAddress,\n      sessionData.chainId,\n    );\n    const stagedHost = resolvedHost ?? this.config.host!;\n    // Never blend a metadata-light restore with the prior wallet identity.\n    const stagedAddress = restoredAddress;\n    const stagedChainId = sessionData.chainId ?? 1;\n    const stagedNodeDid = stagedAddress\n      ? pkhDid(stagedAddress, stagedChainId)\n      : canonicalVerificationMethod;\n    const serviceSession: ServiceSession = {\n      delegationHeader: sessionData.delegationHeader,\n      delegationCid: sessionData.delegationCid,\n      spaceId: sessionData.spaceId,\n      verificationMethod: restoredVerificationMethod,\n      jwk: stagedJwk,\n    };\n    const stagedTcSession: TinyCloudSession | undefined =\n      hasPersistedProof ? {\n        address: restoredAddress!,\n        chainId: sessionData.chainId!,\n        sessionKey: JSON.stringify(stagedJwk),\n        spaceId: sessionData.spaceId,\n        spaces: sessionData.spaces,\n        delegationCid: sessionData.delegationCid,\n        delegationHeader: sessionData.delegationHeader,\n        verificationMethod: restoredVerificationMethod,\n        jwk: stagedJwk as { [k: string]: unknown },\n        siwe: sessionData.siwe!,\n        signature: sessionData.signature!,\n      } : undefined;\n    const stagedPrimary = this.stagePrimarySessionState(\n      stagedTcSession,\n      stagedNodeDid,\n      stagedHost,\n      stagedSessionExpiry,\n      stagedRecap,\n    );\n    const stagedGraph = this.stageRestoredServiceGraph({\n      host: stagedHost,\n      manager: stagedManager,\n      serviceSession,\n      verificationMethod: canonicalVerificationMethod,\n      nodeDid: stagedNodeDid,\n      address: stagedAddress,\n      chainId: stagedChainId,\n      tinyCloudSession: stagedTcSession,\n      sessionExpiry: stagedSessionExpiry,\n      recap: stagedRecap,\n    });\n\n    // Every operation below is a non-throwing pointer/value swap.\n    const oldGraph = this._serviceGraph;\n    const oldCore = this.tc;\n    this.sessionManager = stagedManager;\n    this.sessionKeyId = stagedKeyId;\n    this.sessionKeyJwk = stagedJwk;\n    if (resolvedHost) this.config.host = resolvedHost;\n    this._address = stagedAddress;\n    this._chainId = stagedChainId;\n    this._serviceContext = stagedGraph.serviceContext;\n    this._kv = stagedGraph.kv;\n    this._sql = stagedGraph.sql;\n    this._duckdb = stagedGraph.duckdb;\n    this._hooks = stagedGraph.hooks;\n    this._vault = stagedGraph.vault;\n    this._encryption = stagedGraph.encryption;\n    this._capabilityRegistry = stagedGraph.capabilityRegistry;\n    this._keyProvider = stagedGraph.keyProvider;\n    this._sharingService = stagedGraph.sharingService;\n    this._delegationManager = stagedGraph.delegationManager;\n    this._spaceService = stagedGraph.spaceService;\n    this._serviceGraph = stagedGraph.graph;\n    this._baseSecrets = new Map();\n    this._secrets = new Map();\n    this._publicKV = undefined;\n    this._account = undefined;\n    this.tc = stagedGraph.core;\n    this._recapOperationsCache = stagedPrimary.cache;\n    this.runtimePermissionGrants = stagedPrimary.grants;\n    if (this.auth) {\n      this.auth.installRestoredSession(stagedManager, stagedTcSession, [stagedHost]);\n      this._restoredTcSession = undefined;\n    } else {\n      this._restoredTcSession = stagedTcSession;\n    }\n    oldGraph.retire();\n    (oldCore as { retireServices?: () => void } | null)?.retireServices?.();\n  }\n\n  private stagePrimarySessionState(\n    session: TinyCloudSession | undefined,\n    verificationMethod: string,\n    host: string,\n    sessionExpiry: Date,\n    recap: WasmRecapEntry[],\n  ): { cache: { siwe: string; operations: RuntimePermissionOperation[] } | undefined; grants: RuntimePermissionGrant[] } {\n    if (!session?.siwe) return { cache: undefined, grants: [] };\n    let operations: RuntimePermissionOperation[] = [];\n    operations = recap.flatMap((entry) => {\n      const service = this.invocationServiceName(entry.service);\n      return entry.actions.map((action) => ({\n        ...(this.isEncryptionNetworkOperation(service, entry.path) ? { resource: entry.path } : { spaceId: entry.space }),\n        service,\n        path: entry.path,\n        action,\n        caveats: cloneRecapCaveats(entry.caveats),\n      }));\n    });\n    const cache = { siwe: session.siwe, operations };\n    // Restored authority has no host-activation result yet. Importing a skip\n    // list from an unrelated prior session would erase valid restored grants.\n    if (operations.length === 0) return { cache, grants: [] };\n    const expiresAt = sessionExpiry;\n    return {\n      cache,\n      grants: [{\n        session: {\n          delegationHeader: session.delegationHeader,\n          delegationCid: session.delegationCid,\n          spaceId: session.spaceId,\n          verificationMethod: session.verificationMethod,\n          jwk: session.jwk,\n        },\n        delegation: {\n          cid: session.delegationCid,\n          delegationHeader: session.delegationHeader,\n          delegateDID: session.verificationMethod,\n          delegatorDID: verificationMethod,\n          spaceId: session.spaceId,\n          path: \"\",\n          actions: [...new Set(operations.map((operation) => operation.action))],\n          expiry: expiresAt,\n          allowSubDelegation: true,\n          ownerAddress: session.address,\n          chainId: session.chainId,\n          host,\n        },\n        operations,\n        expiresAt,\n        provenance: \"primary\",\n      }],\n    };\n  }\n\n  private stageRestoredServiceGraph(input: {\n    host: string;\n    manager: ISessionManager;\n    serviceSession: ServiceSession;\n    verificationMethod: string;\n    nodeDid: string;\n    address: string | undefined;\n    chainId: number;\n    tinyCloudSession: TinyCloudSession | undefined;\n    sessionExpiry: Date;\n    recap: WasmRecapEntry[];\n  }): {\n    core: TinyCloud | null;\n    graph: ServiceGraphLifetime;\n    serviceContext: ServiceContext;\n    kv: KVService;\n    sql: SQLService;\n    duckdb: DuckDbService;\n    hooks: HooksService;\n    vault: DataVaultService;\n    encryption: EncryptionService;\n    capabilityRegistry: CapabilityKeyRegistry;\n    keyProvider: WasmKeyProvider;\n    sharingService: SharingService;\n    delegationManager: DelegationManager;\n    spaceService: SpaceService;\n  } {\n    // TinyCloud owns the public-KV service graph. Stage a replacement core\n    // context alongside the node graph so repeated cross-host restores cannot\n    // leave publicKV pointed at a stale or uninitialized context.\n    const graph = this.createServiceGraphLifetime();\n    const core = this.auth\n      ? new TinyCloud(this.auth, {\n        invokeAny: graph.invokeAny,\n        telemetry: this.config.telemetry,\n      })\n      : null;\n    if (core) {\n      core.initializeServices(graph.invoke, [input.host], graph.fetch);\n      const coreContext = graph.track(core.serviceContext as ServiceContext);\n      coreContext.setSession(input.serviceSession);\n    }\n    const serviceContext = graph.track(new ServiceContext({\n      invoke: graph.invoke,\n      invokeAny: graph.invokeAny,\n      fetch: graph.fetch,\n      hosts: [input.host],\n      telemetry: this.config.telemetry,\n    }));\n    const kv = new KVService({});\n    kv.initialize(serviceContext);\n    serviceContext.registerService('kv', kv);\n    const sql = new SQLService({});\n    sql.initialize(serviceContext);\n    serviceContext.registerService('sql', sql);\n    const duckdb = new DuckDbService({});\n    duckdb.initialize(serviceContext);\n    serviceContext.registerService('duckdb', duckdb);\n    const hooks = new HooksService({});\n    hooks.initialize(serviceContext);\n    serviceContext.registerService('hooks', hooks);\n    serviceContext.setSession(input.serviceSession);\n    const encryption = this.createEncryptionService({\n      graph,\n      host: input.host,\n      session: input.serviceSession,\n      did: input.nodeDid,\n      address: input.address,\n      chainId: input.chainId,\n    });\n    encryption.initialize(serviceContext);\n    serviceContext.registerService('encryption', encryption);\n    const vault = this.createVaultService(input.serviceSession.spaceId, kv, encryption, {\n      host: input.host,\n      did: input.nodeDid,\n      address: input.address,\n      chainId: input.chainId,\n      serviceGraph: graph,\n    });\n    vault.initialize(serviceContext);\n    serviceContext.registerService('vault', vault);\n\n    const capabilityRegistry = new CapabilityKeyRegistry();\n    if (input.tinyCloudSession) {\n      const session = input.tinyCloudSession;\n      // ReCap entries are returned by the verifier that authenticated this\n      // SIWE. Persisted space metadata is only a routing hint and cannot add\n      // an unsigned space, path, or action to the registry.\n      const delegations: Delegation[] = input.recap.map((entry) => ({\n          cid: session.delegationCid,\n          delegateDID: session.verificationMethod,\n          spaceId: entry.space,\n          path: entry.path,\n          actions: [...entry.actions],\n          caveats: cloneRecapCaveats(entry.caveats),\n          expiry: input.sessionExpiry,\n          isRevoked: false,\n          allowSubDelegation: true,\n        }));\n      if (delegations.length > 0) {\n        capabilityRegistry.registerKey({\n          id: session.sessionKey,\n          did: session.verificationMethod,\n          type: \"session\",\n          jwk: session.jwk as JWK,\n          priority: 0,\n        }, delegations);\n      }\n    }\n    const delegationManager = new DelegationManager({\n      hosts: [input.host],\n      session: input.serviceSession,\n      invoke: graph.invoke,\n      invokeAny: graph.invokeAny,\n      fetch: graph.fetch,\n    });\n    const keyProvider = new WasmKeyProvider({ sessionManager: input.manager });\n    const sharingService = new SharingService({\n      hosts: [input.host],\n      invoke: graph.invoke,\n      fetch: graph.fetch,\n      assertActive: () => graph.assertActive(),\n      keyProvider,\n      registry: capabilityRegistry,\n      createDelegationWasm: (params) => this.createDelegationWrapper(params),\n      computeCid: (data, codec) => {\n        if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n        return this.wasmBindings.computeCid(data, codec);\n      },\n      createKVService: (config) => {\n        const service = new KVService({ prefix: config.pathPrefix?.replace(/\\/$/, '') });\n        const context = graph.track(new ServiceContext({\n          invoke: config.invoke,\n          fetch: config.fetch ?? globalThis.fetch.bind(globalThis),\n          hosts: config.hosts,\n          telemetry: this.config.telemetry,\n        }));\n        context.setSession(config.session);\n        service.initialize(context);\n        return service;\n      },\n    });\n    sharingService.updateConfig({\n      session: input.serviceSession,\n      delegationManager,\n      sessionExpiry: input.sessionExpiry,\n      createDelegationWasm: (params) => {\n        graph.assertActive();\n        return this.createDelegationWrapper(params);\n      },\n      onRootDelegationNeeded: this.signer ? async (params) => {\n        graph.assertActive();\n        const delegation = await this.createRootDelegationForSharing(\n          params,\n          () => graph.assertActive(),\n        );\n        graph.assertActive();\n        return delegation;\n      } : undefined,\n    });\n    const spaceService = new SpaceService({\n      hosts: [input.host],\n      session: input.serviceSession,\n      invoke: graph.invoke,\n      fetch: graph.fetch,\n      capabilityRegistry,\n      userDid: input.nodeDid,\n      createKVService: (spaceId) => {\n        graph.assertActive();\n        const scopedKv = new KVService({});\n        const context = graph.track(new ServiceContext({\n          invoke: graph.invoke,\n          invokeAny: graph.invokeAny,\n          fetch: graph.fetch,\n          hosts: [input.host],\n          telemetry: this.config.telemetry,\n        }));\n        context.setSession({ ...input.serviceSession, spaceId });\n        scopedKv.initialize(context);\n        return scopedKv;\n      },\n      createVaultService: (spaceId) => {\n        graph.assertActive();\n        const scopedKv = new KVService({});\n        const context = graph.track(new ServiceContext({\n          invoke: graph.invoke,\n          invokeAny: graph.invokeAny,\n          fetch: graph.fetch,\n          hosts: [input.host],\n          telemetry: this.config.telemetry,\n        }));\n        context.setSession({ ...input.serviceSession, spaceId });\n        scopedKv.initialize(context);\n        const scopedVault = this.createVaultService(spaceId, scopedKv, encryption, {\n          host: input.host,\n          did: input.nodeDid,\n          address: input.address,\n          chainId: input.chainId,\n          serviceGraph: graph,\n        });\n        scopedVault.initialize(context);\n        return scopedVault;\n      },\n      createSecretsService: (spaceId) => {\n        graph.assertActive();\n        return this.secretsForSpace(spaceId);\n      },\n      createDelegation: async (params) => {\n        graph.assertActive();\n        try {\n          const portableDelegation = await this.createDelegation({\n            delegateDID: params.delegateDID,\n            path: params.path,\n            actions: params.actions,\n            disableSubDelegation: params.disableSubDelegation,\n            expiryMs: params.expiry ? params.expiry.getTime() - Date.now() : undefined,\n          });\n          return { ok: true as const, data: {\n            cid: portableDelegation.cid,\n            delegateDID: portableDelegation.delegateDID,\n            delegatorDID: this.did,\n            spaceId: portableDelegation.spaceId,\n            path: portableDelegation.path,\n            actions: portableDelegation.actions,\n            expiry: portableDelegation.expiry,\n            isRevoked: false,\n            allowSubDelegation: !portableDelegation.disableSubDelegation,\n            createdAt: new Date(),\n            authHeader: portableDelegation.delegationHeader.Authorization,\n          }};\n        } catch (error) {\n          return { ok: false as const, error: {\n            code: \"CREATION_FAILED\",\n            message: error instanceof Error ? error.message : String(error),\n            service: \"delegation\",\n          }};\n        }\n      },\n      onSpaceRegistered: async (space) => {\n        graph.assertActive();\n        await this.account.spaces.register(space);\n      },\n    });\n    spaceService.updateConfig({ sharingService });\n    return { core, graph, serviceContext, kv, sql, duckdb, hooks, vault, encryption, capabilityRegistry, keyProvider, sharingService, delegationManager, spaceService };\n  }\n\n  /**\n   * Resolve the host a restored session should target.\n   *\n   * Mirrors fresh sign-in host resolution but for the restore path:\n   * an explicit/pinned host always wins, then the hosts the session was\n   * persisted with, then a lazy registry/fallback resolution for sessions\n   * that predate the persisted `tinycloudHosts` field. Returns `undefined`\n   * only when there's nothing to resolve from (no explicit host, no\n   * persisted hosts, and no address/chainId) — in which case the existing\n   * `config.host` (default) is left in place.\n   *\n   * Resolution failures are surfaced, not swallowed: a genuinely broken\n   * registry lookup throws rather than silently falling back to a wrong host.\n   */\n  private async resolveRestoredHost(\n    persistedHosts: string[] | undefined,\n    address: string | undefined,\n    chainId: number | undefined,\n  ): Promise<string | undefined> {\n    if (this.explicitHost) {\n      return this.explicitHost;\n    }\n    if (persistedHosts && persistedHosts.length > 0) {\n      return persistedHosts[0];\n    }\n    if (address === undefined || chainId === undefined) {\n      return undefined;\n    }\n    const resolved = await resolveTinyCloudHosts(pkhDid(address, chainId), {\n      registryUrl: this.config.tinycloudRegistryUrl,\n      fallbackHosts: this.config.tinycloudFallbackHosts,\n      autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n      localNodeUrl: this.config.localNodeUrl,\n      localLinkName: this.config.localLinkName,\n      expectedNodeDid: this.config.expectedNodeDid,\n      localNodeIdentityStore: this.config.localNodeIdentityStore,\n    });\n    return resolved.hosts[0];\n  }\n\n  /**\n   * Resolve the currently-active TinyCloudSession, preferring the auth\n   * layer's value (wallet mode) and falling back to the node-level\n   * rehydration set by {@link restoreSession} (session-only mode).\n   */\n  private currentTinyCloudSession(): TinyCloudSession | undefined {\n    return this.auth?.tinyCloudSession ?? this._restoredTcSession;\n  }\n\n  /**\n   * Connect a wallet to upgrade from session-only mode to wallet mode.\n   *\n   * This allows a user who started in session-only mode to later connect\n   * a wallet and gain the ability to create their own space.\n   *\n   * Note: This does NOT automatically sign in. Call signIn() after connecting\n   * the wallet to create your space.\n   *\n   * @param privateKey - The Ethereum private key (hex string, no 0x prefix)\n   * @param options - Optional configuration\n   * @param options.prefix - Space name prefix (defaults to \"default\")\n   *\n   * @example\n   * ```typescript\n   * // Start in session-only mode\n   * const node = new TinyCloudNode({ host: \"https://node.tinycloud.xyz\" });\n   * console.log(node.did); // did:key:z6Mk... (session key)\n   *\n   * // Later, connect a wallet\n   * node.connectWallet(privateKey);\n   * await node.signIn();\n   * console.log(node.did); // did:pkh:eip155:1:0x... (PKH)\n   * ```\n   */\n  connectWallet(privateKey: string, options?: { prefix?: string; sessionStorage?: ISessionStorage }): void {\n    if (this.signer) {\n      throw new Error(\"Wallet already connected. Cannot connect another wallet.\");\n    }\n\n    const prefix = options?.prefix ?? \"default\";\n\n    // Create signer from private key\n    if (!TinyCloudNode.nodeDefaults) {\n      throw new Error(\n        \"connectWallet() requires PrivateKeySigner. Use connectSigner() instead, \" +\n        \"or import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults.\"\n      );\n    }\n    this.signer = TinyCloudNode.nodeDefaults.createSigner(privateKey);\n\n    // Create authorization handler\n    const authConfig = { ...this.config, prefix };\n    const useBootstrapSignInRequest = this.shouldUseBootstrapSignInRequest(authConfig);\n    this.auth = new NodeUserAuthorization({\n      signer: this.signer,\n      signStrategy: this.config.signStrategy ?? { type: \"auto-sign\" },\n      wasmBindings: this.wasmBindings,\n      sessionManager: this.sessionManager,\n      sessionStorage: options?.sessionStorage ?? this.config.sessionStorage ?? new MemorySessionStorage(),\n      domain: this.siweDomain,\n      spacePrefix: prefix,\n      sessionExpirationMs: this.config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS,\n      tinycloudHosts: this.explicitHost ? [this.explicitHost] : undefined,\n      tinycloudRegistryUrl: this.config.tinycloudRegistryUrl,\n      tinycloudFallbackHosts: this.config.tinycloudFallbackHosts,\n      autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n      localNodeUrl: this.config.localNodeUrl,\n      localLinkName: this.config.localLinkName,\n      expectedNodeDid: this.config.expectedNodeDid,\n      localNodeIdentityStore: this.config.localNodeIdentityStore,\n      autoCreateSpace: useBootstrapSignInRequest ? false : this.config.autoCreateSpace,\n      enablePublicSpace: this.config.enablePublicSpace ?? true,\n      spaceCreationHandler: useBootstrapSignInRequest\n        ? undefined\n        : this.config.spaceCreationHandler,\n      nonce: this.config.nonce,\n      siweConfig: this.config.siweConfig,\n      manifest: useBootstrapSignInRequest ? undefined : this.config.manifest,\n      capabilityRequest: useBootstrapSignInRequest\n        ? BOOTSTRAP_SESSION_REQUESTS.default\n        : this.config.capabilityRequest,\n      includeAccountRegistryPermissions: useBootstrapSignInRequest\n        ? false\n        : this.config.includeAccountRegistryPermissions,\n    });\n\n    // Create TinyCloud instance\n    this.tc = new TinyCloud(this.auth, {\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      telemetry: this.config.telemetry,\n    });\n\n    // Update config with prefix\n    this.config.prefix = prefix;\n  }\n\n  /**\n   * Connect any ISigner to upgrade from session-only mode to wallet mode.\n   *\n   * Same as connectWallet() but accepts any ISigner implementation instead\n   * of a raw private key string. Use this for browser wallets, hardware wallets,\n   * or custom signing backends.\n   *\n   * Note: This does NOT automatically sign in. Call signIn() after connecting.\n   *\n   * @param signer - Any ISigner implementation\n   * @param options - Optional configuration\n   * @param options.prefix - Space name prefix (defaults to \"default\")\n   */\n  connectSigner(signer: ISigner, options?: { prefix?: string; sessionStorage?: ISessionStorage }): void {\n    if (this.signer) {\n      throw new Error(\"Signer already connected. Cannot connect another signer.\");\n    }\n\n    const prefix = options?.prefix ?? \"default\";\n\n    this.signer = signer;\n\n    const authConfig = { ...this.config, prefix };\n    const useBootstrapSignInRequest = this.shouldUseBootstrapSignInRequest(authConfig);\n    this.auth = new NodeUserAuthorization({\n      signer: this.signer,\n      signStrategy: this.config.signStrategy ?? { type: \"auto-sign\" },\n      wasmBindings: this.wasmBindings,\n      sessionManager: this.sessionManager,\n      sessionStorage: options?.sessionStorage ?? this.config.sessionStorage ?? new MemorySessionStorage(),\n      domain: this.siweDomain,\n      spacePrefix: prefix,\n      sessionExpirationMs: this.config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS,\n      tinycloudHosts: this.explicitHost ? [this.explicitHost] : undefined,\n      tinycloudRegistryUrl: this.config.tinycloudRegistryUrl,\n      tinycloudFallbackHosts: this.config.tinycloudFallbackHosts,\n      autoDiscoverLocalNode: this.config.autoDiscoverLocalNode,\n      localNodeUrl: this.config.localNodeUrl,\n      localLinkName: this.config.localLinkName,\n      expectedNodeDid: this.config.expectedNodeDid,\n      localNodeIdentityStore: this.config.localNodeIdentityStore,\n      autoCreateSpace: useBootstrapSignInRequest ? false : this.config.autoCreateSpace,\n      enablePublicSpace: this.config.enablePublicSpace ?? true,\n      spaceCreationHandler: useBootstrapSignInRequest\n        ? undefined\n        : this.config.spaceCreationHandler,\n      nonce: this.config.nonce,\n      siweConfig: this.config.siweConfig,\n      manifest: useBootstrapSignInRequest ? undefined : this.config.manifest,\n      capabilityRequest: useBootstrapSignInRequest\n        ? BOOTSTRAP_SESSION_REQUESTS.default\n        : this.config.capabilityRequest,\n      includeAccountRegistryPermissions: useBootstrapSignInRequest\n        ? false\n        : this.config.includeAccountRegistryPermissions,\n    });\n\n    this.tc = new TinyCloud(this.auth, {\n      invokeAny: this.invokeAnyWithRuntimePermissions,\n      telemetry: this.config.telemetry,\n    });\n    this.config.prefix = prefix;\n  }\n\n  /**\n   * Initialize the service context and KV service after sign-in.\n   * @internal\n   */\n  private initializeServices(): void {\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      return;\n    }\n\n    // Initialize TinyCloud core services (needed for publicKV, ensurePublicSpace)\n    this.tc!.initializeServices(\n      this._serviceGraph.invoke,\n      [this.config.host!],\n      this._serviceGraph.fetch,\n    );\n    this._serviceGraph.track(this.tc!.serviceContext as ServiceContext);\n\n    // Create service context\n    this._serviceContext = this._serviceGraph.track(new ServiceContext({\n      invoke: this._serviceGraph.invoke,\n      invokeAny: this._serviceGraph.invokeAny,\n      fetch: this._serviceGraph.fetch,\n      hosts: [this.config.host!],\n      telemetry: this.config.telemetry,\n    }));\n\n    // Create and register KV service\n    this._kv = new KVService({});\n    this._kv.initialize(this._serviceContext);\n    this._serviceContext.registerService('kv', this._kv);\n\n    // Create and register SQL service (if supported)\n    const features = this.nodeFeatures;\n    if (features.length === 0 || features.includes(\"sql\")) {\n      this._sql = new SQLService({});\n      this._sql.initialize(this._serviceContext);\n      this._serviceContext.registerService('sql', this._sql);\n    }\n\n    // Create and register DuckDB service (if supported)\n    if (features.length === 0 || features.includes(\"duckdb\")) {\n      this._duckdb = new DuckDbService({});\n      this._duckdb.initialize(this._serviceContext);\n      this._serviceContext.registerService('duckdb', this._duckdb);\n    }\n\n    this._hooks = new HooksService({});\n    this._hooks.initialize(this._serviceContext);\n    this._serviceContext.registerService('hooks', this._hooks);\n\n    // Set session on context\n    const serviceSession: ServiceSession = {\n      delegationHeader: session.delegationHeader,\n      delegationCid: session.delegationCid,\n      spaceId: session.spaceId,\n      verificationMethod: session.verificationMethod,\n      jwk: session.jwk,\n    };\n    this._serviceContext.setSession(serviceSession);\n    (this.tc!.serviceContext as ServiceContext).setSession(serviceSession);\n\n    // Create and register Vault service\n    this._vault = this.createVaultService(session.spaceId, this._kv!);\n    this._vault.initialize(this._serviceContext);\n    this._serviceContext.registerService('vault', this._vault);\n\n    // Initialize v2 services\n    this.initializeV2Services(serviceSession);\n  }\n\n  private createSpaceScopedKVService(spaceId: string): KVService {\n    const kvService = new KVService({});\n    if (this._serviceContext) {\n      const spaceScopedContext = this._serviceGraph.track(new ServiceContext({\n        invoke: this._serviceContext.invoke,\n        fetch: this._serviceContext.fetch,\n        hosts: this._serviceContext.hosts,\n        telemetry: this.config.telemetry,\n      }));\n      const session = this._serviceContext.session;\n      if (session) {\n        spaceScopedContext.setSession({ ...session, spaceId });\n      }\n      kvService.initialize(spaceScopedContext);\n    }\n    return kvService;\n  }\n\n  getDefaultEncryptionNetworkId(name = DEFAULT_ENCRYPTION_NETWORK_NAME): string {\n    return `urn:tinycloud:encryption:${this.did}:${name}`;\n  }\n\n  getEncryptionNetworkIdForSpace(\n    spaceId: string,\n    name = DEFAULT_ENCRYPTION_NETWORK_NAME,\n  ): string {\n    const ownerDid = this.ownerDidFromSpaceId(spaceId) ?? this.did;\n    return `urn:tinycloud:encryption:${ownerDid}:${name}`;\n  }\n\n  private ownerDidFromSpaceId(spaceId: string): string | undefined {\n    if (!spaceId.startsWith(\"tinycloud:\")) return undefined;\n    const body = spaceId.slice(\"tinycloud:\".length);\n    const lastSeparator = body.lastIndexOf(\":\");\n    if (lastSeparator <= 0) return undefined;\n    const owner = body.slice(0, lastSeparator);\n    if (owner.startsWith(\"did:\")) return owner;\n    if (!owner.includes(\":\")) return undefined;\n    return `did:${owner}`;\n  }\n\n  private requireServiceSession(): ServiceSession {\n    const session = this._serviceContext?.session;\n    if (!session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return session;\n  }\n\n  /**\n   * Runtime-permission helpers can be used from an authenticated Node session\n   * before its public ServiceContext is initialized. They still need the\n   * current signed session, never an optional or stale authority object.\n   */\n  private requireEncryptionSession(): ServiceSession {\n    const session = this._serviceContext?.session ?? this.auth?.tinyCloudSession;\n    if (!session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return session;\n  }\n\n  private createEncryptionCrypto(): EncryptionCrypto {\n    const wasm = this.wasmBindings;\n    const columnEncrypt = (key: Uint8Array, plaintext: Uint8Array): Uint8Array => {\n      const encrypted = wasm.vault_encrypt(key, plaintext);\n      const out = new Uint8Array(1 + encrypted.length);\n      out[0] = 0x01;\n      out.set(encrypted, 1);\n      return out;\n    };\n    const columnDecrypt = (key: Uint8Array, blob: Uint8Array): Uint8Array => {\n      if (blob[0] !== 0x01) {\n        return blob;\n      }\n      return wasm.vault_decrypt(key, blob.slice(1));\n    };\n    return {\n      sha256: (data) => wasm.vault_sha256(data),\n      randomBytes: (length) => wasm.vault_random_bytes(length),\n      x25519FromSeed: (seed) => wasm.vault_x25519_from_seed(seed),\n      x25519Dh: (privateKey, publicKey) =>\n        wasm.vault_x25519_dh(privateKey, publicKey),\n      authEncrypt: (key, plaintext) => wasm.vault_encrypt(key, plaintext),\n      authDecrypt: (key, ciphertext) => wasm.vault_decrypt(key, ciphertext),\n      sealToNetworkKey: (networkPublicKey, symmetricKey) => {\n        const seed = wasm.vault_random_bytes(32);\n        const ephemeral = wasm.vault_x25519_from_seed(seed);\n        const shared = wasm.vault_x25519_dh(\n          ephemeral.privateKey,\n          networkPublicKey,\n        );\n        const encrypted = columnEncrypt(shared, symmetricKey);\n        const out = new Uint8Array(ephemeral.publicKey.length + encrypted.length);\n        out.set(ephemeral.publicKey, 0);\n        out.set(encrypted, ephemeral.publicKey.length);\n        return out;\n      },\n      openWithReceiverKey: (receiverPrivateKey, wrappedKey) => {\n        const peerPublic = wrappedKey.slice(0, 32);\n        const ciphertext = wrappedKey.slice(32);\n        const shared = wasm.vault_x25519_dh(receiverPrivateKey, peerPublic);\n        return columnDecrypt(shared, ciphertext);\n      },\n      verifyNodeSignature: (nodeId, message, signature) =>\n        verifyDidKeyEd25519Signature(nodeId, message, signature),\n    };\n  }\n\n  private async fetchNodeId(): Promise<string> {\n    const response = await fetch(`${this.config.host}/info`);\n    if (!response.ok) {\n      throw new Error(`Failed to fetch node info: HTTP ${response.status}`);\n    }\n    const info = (await response.json()) as { nodeId?: unknown };\n    if (typeof info.nodeId !== \"string\" || info.nodeId.length === 0) {\n      throw new Error(\"Node /info response did not include nodeId\");\n    }\n    return info.nodeId;\n  }\n\n  private async signRawNetworkAuthorization(input: {\n    targetNode: string;\n    networkId: string;\n    action: string;\n    facts: NetworkInvocationFact;\n  }, binding?: {\n    graph: ServiceGraphLifetime;\n    session: ServiceSession;\n  }): Promise<{ authorization: string; invocationCid: string }> {\n    binding?.graph.assertActive();\n    if (!this.wasmBindings.invokeAny) {\n      throw new Error(\"WASM binding does not support raw-resource invokeAny\");\n    }\n    if (!this.wasmBindings.computeCid) {\n      throw new Error(\"WASM binding does not support invocation CID computation\");\n    }\n    const session = binding?.session ?? this.requireEncryptionSession();\n    const headers = this.invokeAnyWithRuntimePermissions(\n      session,\n      [\n        {\n          resource: input.networkId,\n          service: \"encryption\",\n          path: input.networkId,\n          action: input.action,\n        },\n      ],\n      [input.facts as Record<string, unknown>],\n    );\n    const authorization = authorizationHeader(headers);\n    const audienceBound = await rewriteInvocationAudience(\n      authorization,\n      input.targetNode,\n      session.jwk,\n    );\n    binding?.graph.assertActive();\n    return {\n      authorization: audienceBound,\n      invocationCid: this.wasmBindings.computeCid(\n        new TextEncoder().encode(audienceBound),\n        0x55n,\n      ),\n    };\n  }\n\n  private async fetchEncryptionNetworkAt(\n    host: string,\n    networkId: string,\n    fetchFn: FetchFunction,\n  ): Promise<NetworkDescriptor | null> {\n    const response = await fetchFn(\n      `${host}/encryption/networks/${encodeURIComponent(networkId)}`,\n    );\n    if (response.status === 404) return null;\n    if (!response.ok) {\n      throw new Error(\n        `Failed to fetch encryption network ${networkId}: HTTP ${response.status} ${await response.text()}`,\n      );\n    }\n    const body = (await response.json()) as {\n      descriptor?: NetworkDescriptor;\n    } | NetworkDescriptor;\n    return \"descriptor\" in body && body.descriptor ? body.descriptor : body as NetworkDescriptor;\n  }\n\n  private createEncryptionService(binding?: {\n    graph: ServiceGraphLifetime;\n    host: string;\n    session: ServiceSession;\n    did: string;\n    address: string | undefined;\n    chainId: number;\n  }): EncryptionService {\n    const graph = binding?.graph ?? this._serviceGraph;\n    const host = binding?.host ?? this.config.host!;\n    // The public service path always has a ServiceContext. Keep the auth-session\n    // fallback for the internal runtime-permission helpers, which construct an\n    // encryption service before a ServiceContext is installed. Both paths bind\n    // the resulting service to this graph, so a later graph replacement still\n    // retires the captured service permanently.\n    const session = binding?.session ?? this.requireEncryptionSession();\n    const did = binding?.did ?? this.did;\n    const address = binding?.address ?? this._address;\n    const chainId = binding?.chainId ?? this._chainId;\n    const crypto = this.createEncryptionCrypto();\n    const transport: DecryptTransport = {\n      postDecrypt: async ({ networkId, authorization, canonicalBody, signal }) => {\n        graph.assertActive();\n        const response = await graph.fetch(\n          `${host}/encryption/networks/${encodeURIComponent(networkId)}/decrypt`,\n          {\n            method: \"POST\",\n            headers: {\n              Authorization: authorization,\n              \"Content-Type\": \"application/json\",\n            },\n            body: canonicalBody,\n            signal,\n          },\n        );\n        graph.assertActive();\n        if (!response.ok) {\n          let permissionHint: PermissionHint | undefined;\n          if (response.status === 401 || response.status === 403) {\n            try {\n              const body: unknown = await response.json();\n              const record = typeof body === \"object\" && body !== null\n                ? body as Record<string, unknown>\n                : undefined;\n              const nested = typeof record?.error === \"object\" && record.error !== null\n                ? record.error as Record<string, unknown>\n                : undefined;\n              permissionHint = parsePermissionHint(record?.permissionHint) ??\n                parsePermissionHint(nested?.permissionHint);\n            } catch {\n              // A denied response without the SDK-owned structured field is\n              // classified safely below and cannot become a grant hint.\n            }\n          }\n          throw new DecryptTransportResponseError(response.status, permissionHint);\n        }\n        return (await response.json()) as DecryptResponseBody;\n      },\n    };\n    return new EncryptionService({\n      crypto,\n      signer: {\n        signDecryptInvocation: async (\n          input: BuildDecryptInvocationInput,\n        ): Promise<BuiltDecryptInvocation> => {\n          graph.assertActive();\n          const signed = await this.signRawNetworkAuthorization({\n            targetNode: input.targetNode,\n            networkId: input.networkId,\n            action: DECRYPT_ACTION,\n            facts: input.facts,\n          }, { graph, session });\n          graph.assertActive();\n          return {\n            ...signed,\n            canonicalBody: canonicalizeEncryptionJson(\n              input.body as unknown as CanonicalizableEncryptionJson,\n            ),\n          };\n        },\n      },\n      transport,\n      node: {\n        fetchByNetworkId: async (networkId) => {\n          graph.assertActive();\n          const descriptor = await this.fetchEncryptionNetworkAt(host, networkId, graph.fetch);\n          graph.assertActive();\n          return descriptor;\n        },\n      },\n      wellKnown: {\n        fetchWellKnown: async (principal, discoveryKey) => {\n          graph.assertActive();\n          if (!address || !didPrincipalMatches(principal, did)) {\n            return null;\n          }\n          const publicSpaceId = makePublicSpaceId(address, chainId);\n          const encodedKey = discoveryKey.split(\"/\").map(encodeURIComponent).join(\"/\");\n          const response = await graph.fetch(\n            `${host}/public/${encodeURIComponent(publicSpaceId)}/kv/${encodedKey}`,\n            { method: \"GET\" },\n          );\n          graph.assertActive();\n          if (!response.ok) {\n            return null;\n          }\n          const body = await response.json() as\n            | NetworkDescriptor\n            | { descriptor?: NetworkDescriptor };\n          graph.assertActive();\n          return \"descriptor\" in body && body.descriptor\n            ? body.descriptor\n            : (body as NetworkDescriptor);\n        },\n      },\n      assertActive: () => graph.assertActive(),\n    });\n  }\n\n  private getEncryptionService(): EncryptionService {\n    if (!this._serviceContext) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    if (!this._encryption) {\n      this._encryption = this.createEncryptionService();\n      this._encryption.initialize(this._serviceContext);\n      this._serviceContext.registerService(\"encryption\", this._encryption);\n    }\n    return this._encryption;\n  }\n\n  private createVaultService(\n    spaceId: string,\n    kv: IKVService,\n    encryptionService = this.getEncryptionService(),\n    nodeContext?: {\n      host: string;\n      did: string;\n      address: string | undefined;\n      chainId: number;\n      serviceGraph?: ServiceGraphLifetime;\n    },\n  ): DataVaultService {\n    const wasm = this.wasmBindings;\n    const serviceGraph = nodeContext?.serviceGraph ?? this._serviceGraph;\n    const vaultCrypto = createVaultCrypto({\n      vault_encrypt: wasm.vault_encrypt, vault_decrypt: wasm.vault_decrypt, vault_derive_key: wasm.vault_derive_key,\n      vault_x25519_from_seed: wasm.vault_x25519_from_seed, vault_x25519_dh: wasm.vault_x25519_dh,\n      vault_random_bytes: wasm.vault_random_bytes, vault_sha256: wasm.vault_sha256,\n    });\n    const self = this;\n    const did = nodeContext?.did ?? this.did;\n    const address = nodeContext?.address ?? this._address;\n    const chainId = nodeContext?.chainId ?? this._chainId;\n    const host = nodeContext?.host ?? this.config.host!;\n    const ownerDid = this.ownerDidFromSpaceId(spaceId) ?? did;\n    return new DataVaultService({\n      spaceId,\n      crypto: vaultCrypto,\n      encryption: {\n        networkId: `urn:tinycloud:encryption:${ownerDid}:${DEFAULT_ENCRYPTION_NETWORK_NAME}`,\n        service: encryptionService,\n        decryptCapabilityProof: () => ({\n          proofs: [this.requireServiceSession().delegationCid],\n        }),\n      },\n      tc: {\n        kv,\n        ensurePublicSpace: async () => {\n          try {\n            serviceGraph.assertActive();\n            await self.ensurePublicSpace();\n            return { ok: true as const, data: undefined };\n          } catch (error) {\n            return { ok: false as const, error: { code: \"STORAGE_ERROR\", message: error instanceof Error ? error.message : String(error), service: \"vault\" } };\n          }\n        },\n        get publicKV() {\n          serviceGraph.assertActive();\n          return self._publicKV ?? self.tc!.publicKV;\n        },\n        readPublicSpace: <T>(host: string, targetSpaceId: string, key: string) =>\n          TinyCloud.readPublicSpace<T>(host, targetSpaceId, key),\n        makePublicSpaceId: TinyCloud.makePublicSpaceId,\n        did,\n        address: address ?? \"\",\n        chainId,\n        hosts: [host],\n      },\n    });\n  }\n\n  /**\n   * Initialize the v2 delegation system services.\n   * @internal\n   */\n  private initializeV2Services(serviceSession: ServiceSession): void {\n    const graph = this._serviceGraph;\n\n    // Initialize CapabilityKeyRegistry\n    this._capabilityRegistry = new CapabilityKeyRegistry();\n\n    const tcSession = this.auth?.tinyCloudSession;\n    // Register the session key with its capabilities\n    if (tcSession && this._address) {\n      const sessionKey: KeyInfo = {\n        id: tcSession.sessionKey,\n        did: tcSession.verificationMethod,\n        type: \"session\",\n        // Cast jwk from generic object to JWK - we know it has the required structure\n        jwk: tcSession.jwk as JWK,\n        priority: 0, // Session keys have highest priority\n      };\n\n      // Create root delegation for the session\n      const rootDelegation: Delegation = {\n        cid: tcSession.delegationCid,\n        delegateDID: tcSession.verificationMethod,\n        spaceId: tcSession.spaceId,\n        path: \"\", // Root access\n        actions: [...ROOT_DELEGATION_ACTIONS],\n        expiry: this.getSessionExpiry(),\n        isRevoked: false,\n        allowSubDelegation: true,\n      };\n\n      // Register root delegations\n      const delegations = [rootDelegation];\n\n      // If session includes additional spaces (e.g., public), register delegations for those too\n      if (tcSession.spaces) {\n        for (const [spaceName, spaceId] of Object.entries(tcSession.spaces)) {\n          delegations.push({\n            cid: tcSession.delegationCid,\n            delegateDID: tcSession.verificationMethod,\n            spaceId,\n            path: \"\",\n            actions: [...ROOT_DELEGATION_ACTIONS],\n            expiry: this.getSessionExpiry(),\n            isRevoked: false,\n            allowSubDelegation: true,\n          });\n        }\n      }\n\n      this._capabilityRegistry.registerKey(sessionKey, delegations);\n    }\n\n    // Initialize DelegationManager\n    this._delegationManager = new DelegationManager({\n      hosts: [this.config.host!],\n      accountSpaceId: this.accountSpaceId,\n      session: serviceSession,\n      invoke: graph.invoke,\n      invokeAny: graph.invokeAny,\n      fetch: graph.fetch,\n    });\n\n    // Initialize SpaceService\n    this._spaceService = new SpaceService({\n      hosts: [this.config.host!],\n      session: serviceSession,\n      invoke: graph.invoke,\n      fetch: graph.fetch,\n      capabilityRegistry: this._capabilityRegistry,\n      userDid: this.did,\n      createKVService: (spaceId: string) => {\n        graph.assertActive();\n        return this.createSpaceScopedKVService(spaceId);\n      },\n      createVaultService: (spaceId: string) => {\n        graph.assertActive();\n        const kvService = this.createSpaceScopedKVService(spaceId);\n        const vaultService = this.createVaultService(spaceId, kvService);\n        if (this._serviceContext) {\n          vaultService.initialize(this._serviceContext);\n        }\n        return vaultService;\n      },\n      createSecretsService: (spaceId: string) => {\n        graph.assertActive();\n        return this.secretsForSpace(spaceId);\n      },\n      // Enable space.delegations.create() via SIWE-based delegation\n      createDelegation: async (params) => {\n        try {\n          graph.assertActive();\n          // Use the existing createDelegation method which calls /delegate with SIWE\n          const portableDelegation = await this.createDelegation({\n            delegateDID: params.delegateDID,\n            path: params.path,\n            actions: params.actions,\n            disableSubDelegation: params.disableSubDelegation,\n            expiryMs: params.expiry\n              ? params.expiry.getTime() - Date.now()\n              : undefined,\n          });\n\n          // Convert PortableDelegation to Delegation type for Space API\n          const delegation: Delegation = {\n            cid: portableDelegation.cid,\n            delegateDID: portableDelegation.delegateDID,\n            delegatorDID: this.did,\n            spaceId: portableDelegation.spaceId,\n            path: portableDelegation.path,\n            actions: portableDelegation.actions,\n            expiry: portableDelegation.expiry,\n            isRevoked: false,\n            allowSubDelegation: !portableDelegation.disableSubDelegation,\n            createdAt: new Date(),\n            authHeader: portableDelegation.delegationHeader.Authorization,\n          };\n\n          return { ok: true, data: delegation };\n        } catch (error) {\n          return {\n            ok: false,\n            error: {\n              code: \"CREATION_FAILED\",\n              message: error instanceof Error ? error.message : String(error),\n              service: \"delegation\",\n            },\n          };\n        }\n      },\n      onSpaceRegistered: async (space) => {\n        graph.assertActive();\n        await this.account.spaces.register(space);\n      },\n    });\n\n    // A SharingService retains its invoke/fetch functions and lifetime guard.\n    // Recreate it for this graph instead of updating the receive-only instance\n    // from the graph that was just retired during a subsequent sign-in.\n    this._sharingService = new SharingService({\n      hosts: [this.config.host!],\n      session: serviceSession,\n      invoke: graph.invoke,\n      fetch: graph.fetch,\n      assertActive: () => graph.assertActive(),\n      keyProvider: this._keyProvider,\n      registry: this._capabilityRegistry,\n      delegationManager: this._delegationManager,\n      sessionExpiry: this.getSessionExpiry(),\n      createDelegationWasm: (params) => {\n        graph.assertActive();\n        return this.createDelegationWrapper(params);\n      },\n      computeCid: (data, codec) => {\n        if (!this.wasmBindings.computeCid) throw new Error(\"computeCid is unavailable\");\n        return this.wasmBindings.computeCid(data, codec);\n      },\n      createKVService: (config) => {\n        graph.assertActive();\n        const service = new KVService({ prefix: config.pathPrefix?.replace(/\\/$/, \"\") });\n        const context = graph.track(new ServiceContext({\n          invoke: config.invoke,\n          fetch: config.fetch ?? graph.fetch,\n          hosts: config.hosts,\n          telemetry: this.config.telemetry,\n        }));\n        context.setSession(config.session);\n        service.initialize(context);\n        return service;\n      },\n      onRootDelegationNeeded: this.signer\n        ? async (params) => {\n          graph.assertActive();\n          const delegation = await this.createRootDelegationForSharing(\n            params,\n            () => graph.assertActive(),\n          );\n          graph.assertActive();\n          return delegation;\n        }\n        : undefined,\n    });\n\n    // Wire up SharingService to SpaceService for space.sharing.generate()\n    this._spaceService.updateConfig({\n      sharingService: this._sharingService,\n    });\n  }\n\n  /**\n   * Get the session expiry time.\n   * @internal\n   */\n  private getSessionExpiry(): Date {\n    // Default to 1 hour from now if not explicitly set\n    const expirationMs = this.config.sessionExpirationMs ?? DEFAULT_SESSION_EXPIRATION_MS;\n    return new Date(Date.now() + expirationMs);\n  }\n\n  /**\n   * Wrapper for the WASM createDelegation function.\n   *\n   * The WASM call now takes a multi-resource `abilities` map\n   * (matching `prepareSession`'s shape) and emits ONE UCAN that\n   * covers every `(service, path, actions)` entry. We mirror the raw\n   * result back through `CreateDelegationWasmResult`, converting the\n   * seconds-since-epoch `expiry` to a Date and normalizing the\n   * `delegateDid` → `delegateDID` case.\n   *\n   * Both SharingService (single-entry) and\n   * {@link TinyCloudNode.delegateTo} (multi-entry) drive this through\n   * the same code path so there's exactly one place that touches the\n   * WASM boundary.\n   *\n   * @internal\n   */\n  private createDelegationWrapper(params: CreateDelegationWasmParams): CreateDelegationWasmResult {\n    // Convert ServiceSession to the format WASM expects\n    const wasmSession = {\n      delegationHeader: params.session.delegationHeader,\n      delegationCid: params.session.delegationCid,\n      jwk: params.session.jwk,\n      spaceId: params.session.spaceId,\n      // Session storage carries the verification method as a DID URL\n      // (`did:key:...#key-id`). The Rust UCAN builder expects the principal\n      // DID here and rejects the fragment as an invalid audience DID.\n      verificationMethod: params.session.verificationMethod.split(\"#\", 1)[0],\n    };\n\n    const result = this.wasmBindings.createDelegation(\n      wasmSession,\n      params.delegateDID,\n      params.spaceId,\n      params.abilities,\n      params.expirationSecs,\n      params.notBeforeSecs\n    );\n\n    return {\n      delegation: result.delegation,\n      cid: result.cid,\n      // Rust serde `rename_all = \"camelCase\"` emits `delegateDid`\n      // (lowercase d); the TypeScript interface uses `delegateDID`\n      // (historical, matches Delegation.delegateDID). Normalize here.\n      delegateDID: result.delegateDid ?? result.delegateDID,\n      expiry: new Date(result.expiry * 1000),\n      resources: result.resources,\n    };\n  }\n\n  /**\n   * Create a direct root delegation from the wallet to a share key.\n   * This bypasses the session delegation chain, allowing share links\n   * with expiry longer than the current session.\n   * @internal\n   */\n  async createOwnerDelegation(\n    params: CreateOwnerDelegationParams,\n    assertActive?: () => void,\n  ): Promise<OwnerDelegationReceipt> {\n    const assertOwnerGraphActive = assertActive ?? this._serviceGraph.assertActive.bind(this._serviceGraph);\n    assertOwnerGraphActive();\n    if (!params.delegateDid.startsWith(\"did:key:\") || params.actions.length === 0 || params.path.length === 0) {\n      throw new Error(\"Owner delegation requires an external did:key audience and bounded capabilities\");\n    }\n    const now = new Date();\n    if (params.expiresAt.getTime() <= now.getTime() || params.expiresAt.getTime() - now.getTime() > EXPIRY.MAX_MS) {\n      throw new Error(\"Owner delegation expiry must be explicit, future, and within EXPIRY.MAX_MS\");\n    }\n    if (!this.signer) throw new Error(\"Owner wallet signer is required\");\n    const session = this.currentTinyCloudSession();\n    if (!session) throw new Error(\"Owner session is required\");\n    const abilities = sharingActionsToAbilities(params.path, [...params.actions]);\n    if (!abilities) throw new Error(\"Owner delegation capabilities are unsupported\");\n\n    const host = this.config.host!;\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(session.address),\n      chainId: session.chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: params.expiresAt.toISOString(),\n      spaceId: params.spaceId,\n      delegateUri: params.delegateDid,\n    });\n    const signature = await this.signer.signMessage(prepared.siwe);\n    assertOwnerGraphActive();\n    const delegationSession = this.wasmBindings.completeSessionSetup({ ...prepared, signature });\n    const activation = await activateSessionWithHost(host, delegationSession.delegationHeader);\n    assertOwnerGraphActive();\n    if (!activation.success) {\n      throw new Error(`Owner delegation import failed: ${activation.status} ${activation.error ?? \"\"}`.trim());\n    }\n    const delegation: Delegation = {\n      cid: delegationSession.delegationCid,\n      delegateDID: params.delegateDid,\n      delegatorDID: pkhDid(session.address, session.chainId),\n      spaceId: params.spaceId,\n      path: params.path,\n      actions: [...params.actions],\n      expiry: params.expiresAt,\n      isRevoked: false,\n      allowSubDelegation: true,\n      createdAt: now,\n      authHeader: delegationSession.delegationHeader.Authorization,\n    };\n    return {\n      delegation,\n      signedDagCbor: decodeAuthorizationBytes(delegationSession.delegationHeader.Authorization),\n      delegationCid: delegationSession.delegationCid,\n      nodeReceipt: {\n        commitEventCid: (activation as typeof activation & { commitEventCid?: string }).commitEventCid,\n        activated: activation.activated ?? [],\n        skipped: activation.skipped ?? [],\n      },\n    };\n  }\n\n  private async createRootDelegationForSharing(params: {\n    shareKeyDID: string;\n    spaceId: string;\n    path: string;\n    actions: string[];\n    requestedExpiry: Date;\n  }, assertActive?: () => void): Promise<Delegation | undefined> {\n    try {\n      return (await this.createOwnerDelegation({\n        delegateDid: params.shareKeyDID,\n        spaceId: params.spaceId,\n        path: params.path,\n        actions: params.actions,\n        expiresAt: params.requestedExpiry,\n      }, assertActive)).delegation;\n    } catch {\n      assertActive?.();\n      return undefined;\n    }\n  }\n\n  /**\n   * Track a received delegation in the capability registry.\n   * @internal\n   */\n  private trackReceivedDelegation(delegation: PortableDelegation, jwk: JWK): void {\n    if (!this._capabilityRegistry) {\n      return;\n    }\n\n    const keyInfo: KeyInfo = {\n      id: `received:${delegation.cid}`,\n      did: this.sessionDid,\n      type: \"ingested\",\n      jwk,\n      priority: 2,\n    };\n\n    // Convert PortableDelegation to Delegation type\n    const delegationRecord: Delegation = {\n      cid: delegation.cid,\n      delegateDID: delegation.delegateDID,\n      spaceId: delegation.spaceId,\n      path: delegation.path,\n      actions: delegation.actions,\n      expiry: delegation.expiry,\n      isRevoked: false,\n      allowSubDelegation: !delegation.disableSubDelegation,\n    };\n\n    this._capabilityRegistry.ingestKey(keyInfo, delegationRecord);\n  }\n\n  /**\n   * Key-value storage operations on this user's space.\n   */\n  get kv(): IKVService {\n    if (!this._kv) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._kv;\n  }\n\n  /**\n   * SQL database operations on this user's space.\n   */\n  get sql(): ISQLService {\n    if (!this._sql) {\n      const features = this.nodeFeatures;\n      if (features.length > 0 && !features.includes(\"sql\")) {\n        throw new UnsupportedFeatureError(\"sql\", this.config.host!, features);\n      }\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._sql;\n  }\n\n  /**\n   * Get an SQL service scoped to a specific space.\n   *\n   * Mirrors {@link SpaceService}'s per-space KV factory: clones the active\n   * service context and overrides its session's spaceId so that subsequent\n   * `sql/<dbName>/<action>` invocations route to that space. Useful when\n   * the caller already holds a delegation covering the target space (e.g.\n   * via {@link grantRuntimePermissions} or {@link useRuntimeDelegation})\n   * but the SDK's per-space SQL surface isn't otherwise exposed.\n   *\n   * Does NOT auto-create the space.\n   *\n   * @param spaceId - Full space URI (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`).\n   */\n  sqlForSpace(spaceId: string): ISQLService {\n    if (!this._serviceContext || !this._serviceContext.session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const sql = new SQLService({});\n    const spaceScopedContext = this._serviceGraph.track(new ServiceContext({\n      invoke: this._serviceContext.invoke,\n      invokeAny: this._serviceContext.invokeAny,\n      fetch: this._serviceContext.fetch,\n      hosts: this._serviceContext.hosts,\n      telemetry: this.config.telemetry,\n    }));\n    spaceScopedContext.setSession({ ...this._serviceContext.session, spaceId });\n    sql.initialize(spaceScopedContext);\n    return sql;\n  }\n\n  /**\n   * Get a KV service scoped to a specific space.\n   *\n   * The KV counterpart to {@link sqlForSpace}: clones the active service\n   * context and overrides its session's spaceId so that subsequent\n   * `kv/<action>` invocations route to that space. Useful for reading data\n   * that a manifest app stores outside the primary space (e.g. transcripts a\n   * `defaults: true` app keeps under the owner's `applications` space), when\n   * the caller already holds a delegation covering the target space.\n   *\n   * Does NOT auto-create the space.\n   *\n   * @param spaceId - Full space URI (`tinycloud:pkh:eip155:<chain>:<addr>:<name>`).\n   */\n  kvForSpace(spaceId: string): IKVService {\n    if (!this._serviceContext || !this._serviceContext.session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const kv = new KVService({});\n    const spaceScopedContext = this._serviceGraph.track(new ServiceContext({\n      invoke: this._serviceContext.invoke,\n      invokeAny: this._serviceContext.invokeAny,\n      fetch: this._serviceContext.fetch,\n      hosts: this._serviceContext.hosts,\n    }));\n    spaceScopedContext.setSession({ ...this._serviceContext.session, spaceId });\n    kv.initialize(spaceScopedContext);\n    return kv;\n  }\n\n  /**\n   * DuckDB database operations on this user's space.\n   */\n  get duckdb(): IDuckDbService {\n    if (!this._duckdb) {\n      const features = this.nodeFeatures;\n      if (features.length > 0 && !features.includes(\"duckdb\")) {\n        throw new UnsupportedFeatureError(\"duckdb\", this.config.host!, features);\n      }\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._duckdb;\n  }\n\n  /**\n   * Data Vault operations - client-side encrypted KV storage.\n   * Call `vault.unlock(signer)` after signIn() to derive encryption keys.\n   */\n  get vault(): IDataVaultService {\n    if (!this._vault) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._vault;\n  }\n\n  /**\n   * Network-scoped encryption/decrypt service.\n   */\n  get encryption(): IEncryptionService {\n    return this.getEncryptionService();\n  }\n\n  async getEncryptionNetwork(\n    nameOrNetworkId = this.getDefaultEncryptionNetworkId(),\n  ): Promise<NetworkDescriptor | null> {\n    const networkId = nameOrNetworkId.startsWith(\"urn:tinycloud:encryption:\")\n      ? nameOrNetworkId\n      : this.getDefaultEncryptionNetworkId(nameOrNetworkId);\n    return this.fetchEncryptionNetworkAt(\n      this.config.host!,\n      networkId,\n      globalThis.fetch.bind(globalThis),\n    );\n  }\n\n  async createEncryptionNetwork(\n    name = DEFAULT_ENCRYPTION_NETWORK_NAME,\n  ): Promise<NetworkDescriptor> {\n    const targetNode = await this.fetchNodeId();\n    const ownerDid = this.did;\n    const networkId = this.getDefaultEncryptionNetworkId(name);\n    const body = {\n      name,\n      ownerDid,\n      threshold: { n: 1, t: 1 },\n    };\n    const crypto = this.createEncryptionCrypto();\n    const facts = {\n      type: NETWORK_ADMIN_TYPE,\n      targetNode,\n      networkId,\n      bodyHash: canonicalHashHex(\n        crypto.sha256,\n        body as unknown as CanonicalizableEncryptionJson,\n      ),\n      action: NETWORK_CREATE_ACTION,\n    };\n    const signed = await this.signRawNetworkAuthorization({\n      targetNode,\n      networkId,\n      action: NETWORK_CREATE_ACTION,\n      facts,\n    });\n    const response = await fetch(`${this.config.host}/encryption/networks`, {\n      method: \"POST\",\n      headers: {\n        Authorization: signed.authorization,\n        \"Content-Type\": \"application/json\",\n      },\n      body: canonicalizeEncryptionJson(\n        body as unknown as CanonicalizableEncryptionJson,\n      ),\n    });\n    if (!response.ok) {\n      throw new Error(\n        `Failed to create encryption network ${networkId}: HTTP ${response.status} ${await response.text()}`,\n      );\n    }\n    const created = (await response.json()) as { descriptor: NetworkDescriptor };\n    return created.descriptor;\n  }\n\n  async ensureEncryptionNetwork(\n    nameOrNetworkId = DEFAULT_ENCRYPTION_NETWORK_NAME,\n  ): Promise<NetworkDescriptor> {\n    const networkId = nameOrNetworkId.startsWith(\"urn:tinycloud:encryption:\")\n      ? nameOrNetworkId\n      : this.getDefaultEncryptionNetworkId(nameOrNetworkId);\n    const existing = await this.getEncryptionNetwork(networkId);\n    if (existing) {\n      return existing;\n    }\n    const parsed = parseNetworkId(networkId);\n    if (!didPrincipalMatches(parsed.ownerDid, this.did)) {\n      throw new Error(\n        `Cannot create encryption network ${networkId}: owner ${parsed.ownerDid} does not match signed-in DID ${this.did}`,\n      );\n    }\n    return this.createEncryptionNetwork(parsed.name);\n  }\n\n  /**\n   * App-facing secrets API backed by the `secrets` space vault.\n   */\n  get secrets(): ISecretsService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this.secretsForSpace(\"secrets\");\n  }\n\n  /**\n   * App-facing secrets API backed by the requested space's vault.\n   */\n  secretsForSpace(spaceId: string): ISecretsService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n      ? spaceId\n      : this.ownedSpaceId(spaceId);\n    let secrets = this._secrets.get(resolvedSpace);\n    if (!secrets) {\n      secrets = new NodeSecretsService({\n        getService: () => this.getBaseSecrets(resolvedSpace),\n        space: resolvedSpace,\n        getManifest: () => this.manifest,\n        hasPermissions: (permissions) => this.hasRuntimePermissions(permissions),\n        grantPermissions: (additional) => this.grantRuntimePermissions(additional),\n        canEscalate: () => this.signer !== undefined && this.tc !== undefined,\n        getEncryptionNetworkId: () => this.getEncryptionNetworkIdForSpace(resolvedSpace),\n        resolveSpace: (space) => space.startsWith(\"tinycloud:\") ? space : this.ownedSpaceId(space),\n        getUnlockSigner: () => this.signer ?? undefined,\n      });\n      this._secrets.set(resolvedSpace, secrets);\n    }\n    return secrets;\n  }\n\n  /**\n   * Read a secret from an explicit target space without requesting or\n   * auto-signing authority. Active runtime delegations are selected by the\n   * normal KV and encryption invocation paths.\n   */\n  async readSecret(input: SecretReadInput): Promise<SecretReadResult> {\n    const resolved = resolveSecretPath(input.name, { scope: input.scope });\n    const targetSpace = input.space.startsWith(\"tinycloud:\")\n      ? input.space\n      : this.ownedSpaceId(input.space);\n    const result = await this.getBaseVault(targetSpace).readNetworkEncrypted<unknown>(\n      resolved.vaultKey,\n    );\n\n    if (result.status !== \"ok\") {\n      if (result.status === \"permission_required\") {\n        const hint = parsePermissionHint(result.hint);\n        if (hint === undefined) return { status: \"read_failed\" };\n        return {\n          status: \"permission_required\",\n          hint: {\n            service: hint.service,\n            ...(hint.space === undefined ? {} : { space: hint.space }),\n            path: hint.path,\n            actions: [...hint.actions],\n          },\n        };\n      }\n      return { status: result.status };\n    }\n    if (!isSecretPayload(result.entry.value)) {\n      return { status: \"invalid_payload\" };\n    }\n    return { status: \"ok\", value: result.entry.value.value };\n  }\n\n  private getBaseSecrets(spaceId: string): ISecretsService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n      ? spaceId\n      : this.ownedSpaceId(spaceId);\n    let secrets = this._baseSecrets.get(resolvedSpace);\n    if (!secrets) {\n      secrets = new SecretsService(() => this.getBaseVault(resolvedSpace));\n      this._baseSecrets.set(resolvedSpace, secrets);\n    }\n    return secrets;\n  }\n\n  private getBaseVault(spaceId: string): DataVaultService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    const resolvedSpace = spaceId.startsWith(\"tinycloud:\")\n      ? spaceId\n      : this.ownedSpaceId(spaceId);\n    let vault = this._baseVaults.get(resolvedSpace);\n    if (!vault) {\n      vault = this.createVaultService(\n        resolvedSpace,\n        this.createSpaceScopedKVService(resolvedSpace),\n      );\n      if (this._serviceContext) {\n        vault.initialize(this._serviceContext);\n      }\n      this._baseVaults.set(resolvedSpace, vault);\n    }\n    return vault;\n  }\n\n  /**\n   * Hooks write stream subscription API.\n   */\n  get hooks(): IHooksService {\n    if (!this._hooks) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._hooks;\n  }\n\n  // ===========================================================================\n  // v2 Service Accessors\n  // ===========================================================================\n\n  /**\n   * Get the CapabilityKeyRegistry for managing keys and their capabilities.\n   *\n   * The registry tracks keys (session, main, ingested) and their associated\n   * delegations, enabling automatic key selection for operations.\n   *\n   * @example\n   * ```typescript\n   * const registry = alice.capabilityRegistry;\n   *\n   * // Get the best key for an operation\n   * const key = registry.getKeyForCapability(\n   *   \"tinycloud://my-space/kv/data\",\n   *   \"tinycloud.kv/get\"\n   * );\n   *\n   * // List all capabilities\n   * const capabilities = registry.getAllCapabilities();\n   * ```\n   */\n  get capabilityRegistry(): ICapabilityKeyRegistry {\n    if (!this._capabilityRegistry) {\n      throw new Error(\"CapabilityKeyRegistry not initialized.\");\n    }\n    return this._capabilityRegistry;\n  }\n\n  /**\n   * Access received delegations (recipient view).\n   *\n   * Use this to see what delegations have been received via useDelegation().\n   *\n   * @example\n   * ```typescript\n   * // List all received delegations\n   * const received = bob.delegations.list();\n   * console.log(\"I have access to:\", received.length, \"spaces\");\n   *\n   * // Get a specific delegation by CID\n   * const delegation = bob.delegations.get(cid);\n   * ```\n   */\n  get delegations(): {\n    /** List all received delegations */\n    list: () => Delegation[];\n    /** Get a delegation by CID */\n    get: (cid: string) => Delegation | undefined;\n  } {\n    const registry = this._capabilityRegistry;\n    if (!registry) {\n      return {\n        list: () => [],\n        get: () => undefined,\n      };\n    }\n\n    return {\n      list: () => registry.getAllCapabilities().map((entry) => entry.delegation),\n      get: (cid: string) => {\n        const capabilities = registry.getAllCapabilities();\n        const entry = capabilities.find((e) => e.delegation.cid === cid);\n        return entry?.delegation;\n      },\n    };\n  }\n\n  /**\n   * Check whether the current session or an approved runtime delegation covers\n   * every requested permission.\n   */\n  hasRuntimePermissions(permissions: PermissionEntry[]): boolean {\n    const session = this.currentTinyCloudSession();\n    if (!session || !Array.isArray(permissions) || permissions.length === 0) {\n      return false;\n    }\n\n    const expanded = this.expandPermissionEntries(permissions);\n    if (this.sessionCoversPermissionEntries(session, expanded)) {\n      return true;\n    }\n\n    return this.findRuntimeGrantsForPermissionEntries(expanded, session).length > 0;\n  }\n\n  /**\n   * Return installed runtime permission delegations. When `permissions` is\n   * provided, only delegations currently covering those permissions are\n   * returned. Base-session manifest permissions are not represented here.\n   */\n  getRuntimePermissionDelegations(\n    permissions?: PermissionEntry[],\n  ): PortableDelegation[] {\n    this.pruneExpiredRuntimePermissionGrants();\n    if (permissions === undefined) {\n      // Exclude the synthetic primary grant: it represents the base session's\n      // own recap, not an installed runtime delegation. Per this method's\n      // contract, base-session manifest permissions are not represented here.\n      return this.runtimePermissionGrants\n        .filter((grant) => grant.provenance !== \"primary\")\n        .map((grant) => grant.delegation);\n    }\n\n    const session = this.currentTinyCloudSession();\n    if (!session || !Array.isArray(permissions) || permissions.length === 0) {\n      return [];\n    }\n    const expanded = this.expandPermissionEntries(permissions);\n    return this.findRuntimeGrantsForPermissionEntries(expanded, session).map(\n      (grant) => grant.delegation,\n    );\n  }\n\n  /**\n   * Return the effective capabilities of installed runtime grants.\n   *\n   * The result is projected from the SDK's activated, expiry-pruned grant\n   * operations rather than from PortableDelegation transport metadata. Base\n   * session authority is intentionally omitted; callers that need the full\n   * live authority must combine this with {@link getVerifiedSessionCapabilities}.\n   */\n  getEffectiveRuntimePermissionEntries(): PermissionEntry[] {\n    const session = this.currentTinyCloudSession();\n    if (!session) return [];\n\n    this.pruneExpiredRuntimePermissionGrants();\n    const grouped = new Map<string, PermissionEntry>();\n    for (const grant of this.runtimePermissionGrants) {\n      if (grant.provenance === \"primary\") continue;\n      for (const operation of grant.operations) {\n        const service = SERVICE_SHORT_TO_LONG[operation.service];\n        if (service === undefined || typeof operation.path !== \"string\" ||\n          typeof operation.action !== \"string\") {\n          continue;\n        }\n\n        let space: string | undefined;\n        if (service !== \"tinycloud.encryption\") {\n          if (typeof operation.spaceId !== \"string\") continue;\n          try {\n            space = this.resolvePermissionSpace(operation.spaceId, session);\n          } catch {\n            continue;\n          }\n        }\n\n        const caveats = operation.caveats === undefined || operation.caveats.length === 0\n          ? undefined\n          : cloneRecapCaveats(operation.caveats);\n        const identity = JSON.stringify({\n          service,\n          ...(space === undefined ? {} : { space }),\n          path: operation.path,\n          caveats: canonicalizeRecapCaveats(caveats),\n        });\n        const existing = grouped.get(identity);\n        if (existing === undefined) {\n          grouped.set(identity, {\n            service,\n            ...(space === undefined ? {} : { space }),\n            path: operation.path,\n            actions: [operation.action],\n            ...(caveats === undefined ? {} : { caveats }),\n          });\n          continue;\n        }\n        if (!existing.actions.includes(operation.action)) {\n          existing.actions.push(operation.action);\n          existing.actions.sort();\n        }\n      }\n    }\n\n    return [...grouped.values()].sort((left, right) =>\n      left.service.localeCompare(right.service) ||\n      (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n      left.path.localeCompare(right.path) ||\n      left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")),\n    );\n  }\n\n  /**\n   * Install a portable runtime permission delegation into this SDK instance so\n   * matching service calls and downstream `delegateTo()` calls can use it.\n   */\n  async useRuntimeDelegation(delegation: PortableDelegation): Promise<void> {\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      throw new SessionExpiredError(new Date(0));\n    }\n    if (delegation.expiry.getTime() <= Date.now()) {\n      throw new SessionExpiredError(delegation.expiry);\n    }\n\n    const expectedDids = [session.verificationMethod, this.sessionDid];\n    if (!expectedDids.some((did) => didPrincipalMatches(delegation.delegateDID, did))) {\n      throw new Error(\n        `Runtime delegation targets ${delegation.delegateDID} but this session key is ${session.verificationMethod}.`,\n      );\n    }\n\n    const targetHost = delegation.host ?? this.config.host!;\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      delegation.delegationHeader,\n    );\n    if (!activateResult.success) {\n      throw new Error(\n        `Failed to activate runtime permission delegation: ${activateResult.error}`,\n      );\n    }\n\n    this.runtimePermissionGrants = this.runtimePermissionGrants.filter(\n      (grant) => grant.delegation.cid !== delegation.cid,\n    );\n    this.runtimePermissionGrants.push(\n      this.runtimeGrantFromDelegation(delegation, session),\n    );\n  }\n\n  /**\n   * Store additional permissions as narrow delegations to the current session\n   * key. Future service invocations automatically use a stored delegation when\n   * its `(space, service, path, action)` covers the request.\n   */\n  async grantRuntimePermissions(\n    permissions: PermissionEntry[],\n    options?: RuntimePermissionGrantOptions,\n  ): Promise<PortableDelegation[]> {\n    if (!Array.isArray(permissions) || permissions.length === 0) {\n      throw new Error(\"grantRuntimePermissions requires a non-empty permissions array\");\n    }\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      throw new SessionExpiredError(new Date(0));\n    }\n\n    const sessionExpiry = extractSiweExpiration(session.siwe);\n    if (sessionExpiry !== undefined) {\n      const marginMs = TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS;\n      if (sessionExpiry.getTime() <= Date.now() + marginMs) {\n        throw new SessionExpiredError(sessionExpiry);\n      }\n    }\n\n    const expanded = this.expandPermissionEntries(permissions);\n    if (this.sessionCoversPermissionEntries(session, expanded)) {\n      return [];\n    }\n\n    const existingGrants = this.findRuntimeGrantsForPermissionEntries(expanded, session);\n    if (existingGrants.length > 0) {\n      return existingGrants.map((grant) => grant.delegation);\n    }\n    if (!this.signer) {\n      throw new Error(\n        \"grantRuntimePermissions requires wallet mode with a signer or privateKey.\",\n      );\n    }\n    this.assertDelegationCaveatsPreservable(expanded);\n\n    const rawEntries = expanded.filter((entry) =>\n      this.isEncryptionPermissionEntry(entry)\n    );\n    const spaceEntries = expanded.filter((entry) =>\n      !this.isEncryptionPermissionEntry(entry)\n    );\n\n    const bySpace = new Map<string, PermissionEntry[]>();\n    for (const entry of spaceEntries) {\n      const spaceId = this.resolvePermissionSpace(entry.space, session);\n      const current = bySpace.get(spaceId) ?? [];\n      current.push(entry);\n      bySpace.set(spaceId, current);\n    }\n    if (bySpace.size === 0 && rawEntries.length > 0) {\n      bySpace.set(session.spaceId, []);\n    }\n\n    const now = new Date();\n    const requestedExpiryMs = resolveExpiryMs(options?.expiry);\n    let expiresAt = new Date(now.getTime() + requestedExpiryMs);\n    if (sessionExpiry !== undefined && sessionExpiry < expiresAt) {\n      expiresAt = sessionExpiry;\n    }\n\n    const delegations: PortableDelegation[] = [];\n    let rawEntriesAttached = false;\n    for (const [spaceId, entries] of bySpace) {\n      const rawForDelegation = !rawEntriesAttached ? rawEntries : [];\n      if (rawForDelegation.length > 0) {\n        rawEntriesAttached = true;\n      }\n      const delegatedEntries = [...entries, ...rawForDelegation];\n      const abilities = this.permissionsToAbilities(entries);\n      const prepared = this.wasmBindings.prepareSession({\n        abilities,\n        ...(rawForDelegation.length > 0\n          ? { rawAbilities: this.permissionsToRawAbilities(rawForDelegation) }\n          : {}),\n        address: this.wasmBindings.ensureEip55(session.address),\n        chainId: session.chainId,\n        domain: this.siweDomain,\n        issuedAt: now.toISOString(),\n        expirationTime: expiresAt.toISOString(),\n        spaceId,\n        jwk: session.jwk,\n      });\n\n      const signature = await this.signer.signMessage(prepared.siwe);\n      const delegatedSession = this.wasmBindings.completeSessionSetup({\n        ...prepared,\n        signature,\n      });\n\n      const activateResult = await activateSessionWithHost(\n        this.config.host!,\n        delegatedSession.delegationHeader,\n      );\n      if (!activateResult.success) {\n        throw new Error(\n          `Failed to activate runtime permission delegation: ${activateResult.error}`,\n        );\n      }\n\n      const delegation = this.runtimeDelegationFromSession(\n        delegatedSession,\n        delegatedEntries,\n        spaceId,\n        session,\n        expiresAt,\n      );\n      this.runtimePermissionGrants.push({\n        session: {\n          delegationHeader: delegatedSession.delegationHeader,\n          delegationCid: delegatedSession.delegationCid,\n          spaceId,\n          verificationMethod: session.verificationMethod,\n          jwk: session.jwk,\n        },\n        delegation,\n        operations: this.permissionOperations(delegatedEntries, spaceId),\n        expiresAt,\n        provenance: \"runtime\",\n      });\n      delegations.push(delegation);\n    }\n\n    return delegations;\n  }\n\n  /**\n   * Get the DelegationManager for delegation CRUD operations.\n   *\n   * This is the v2 delegation service providing a cleaner API than\n   * the legacy createDelegation/useDelegation methods.\n   *\n   * @example\n   * ```typescript\n   * const delegations = alice.delegationManager;\n   *\n   * // Create a delegation\n   * const result = await delegations.create({\n   *   delegateDID: bob.did,\n   *   path: \"shared/\",\n   *   actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\"],\n   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours\n   * });\n   *\n   * // List delegations\n   * const listResult = await delegations.list();\n   *\n   * // Revoke a delegation\n   * await delegations.revoke(delegationCid);\n   * ```\n   */\n  get delegationManager(): DelegationManager {\n    if (!this._delegationManager) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._delegationManager;\n  }\n\n  /**\n   * Get the SpaceService for managing spaces.\n   *\n   * The SpaceService provides access to owned and delegated spaces,\n   * including space creation, listing, and scoped operations.\n   *\n   * @example\n   * ```typescript\n   * const spaces = alice.spaces;\n   *\n   * // List all accessible spaces\n   * const result = await spaces.list();\n   *\n   * // Create a new space\n   * const createResult = await spaces.create('photos');\n   *\n   * // Get a space object for operations\n   * const mySpace = spaces.get('default');\n   * await mySpace.kv.put('key', 'value');\n   *\n   * // Check if a space exists\n   * const exists = await spaces.exists('photos');\n   * ```\n   */\n  get spaces(): ISpaceService {\n    if (!this._spaceService) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this._spaceService;\n  }\n\n  /**\n   * Alias for `spaces` - get the SpaceService.\n   * @see spaces\n   */\n  get spaceService(): ISpaceService {\n    return this.spaces;\n  }\n\n  /**\n   * Get a Space object by short name or full URI.\n   */\n  space(nameOrUri: string): ISpace {\n    return this.spaces.get(nameOrUri);\n  }\n\n  /**\n   * Get the SharingService for creating and receiving v2 sharing links.\n   *\n   * The SharingService creates sharing links with embedded private keys,\n   * allowing recipients to exercise delegations without prior session setup.\n   *\n   * @example\n   * ```typescript\n   * const sharing = alice.sharing;\n   *\n   * // Generate a sharing link\n   * const result = await sharing.generate({\n   *   path: \"/kv/documents/report.pdf\",\n   *   actions: [\"tinycloud.kv/get\"],\n   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),\n   * });\n   *\n   * if (result.ok) {\n   *   console.log(\"Share URL:\", result.data.url);\n   *   // Send the URL to the recipient\n   * }\n   *\n   * // Receive a sharing link\n   * const receiveResult = await sharing.receive(shareUrl);\n   * if (receiveResult.ok) {\n   *   // Use the pre-configured KV service\n   *   const data = await receiveResult.data.kv.get(\"report.pdf\");\n   * }\n   * ```\n   */\n  get sharing(): ISharingService {\n    // SharingService is initialized in constructor for receive-only access\n    // Full capabilities (generate) are added after signIn()\n    return this._sharingService;\n  }\n\n  /**\n   * Alias for `sharing` - get the SharingService.\n   * @see sharing\n   */\n  get sharingService(): ISharingService {\n    return this.sharing;\n  }\n\n  // ===========================================================================\n  // Public Space Methods\n  // ===========================================================================\n\n  /**\n   * Ensure the user's public space exists and is accessible.\n   * Creates the space and activates a session delegation for it.\n   * This is the trigger for lazy public space creation — call it\n   * before writing to spaces.get('public').kv.\n   */\n  async ensurePublicSpace() {\n    if (!this.auth || !this.session || !this.signer) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    const publicSpaceId = this.session.spaces?.public;\n    if (!publicSpaceId) {\n      throw new Error(\"Public space not enabled. Set enablePublicSpace: true in config.\");\n    }\n\n    // Create the public space on the server (host SIWE)\n    await (this.auth as NodeUserAuthorization).hostPublicSpace(publicSpaceId);\n\n    // Create a session delegation for the public space using the session key JWK.\n    // This mirrors the primary session flow (prepareSession with jwk), ensuring\n    // the delegation targets the session key — not the PKH DID — so that\n    // invoke() requests signed by the session key are properly authorized.\n    const kvActions = [KV.PUT, KV.GET, KV.DEL, KV.LIST, KV.METADATA];\n    const abilities = { kv: { \"\": kvActions } };\n    const now = new Date();\n    // EPHEMERAL tier — this sub-delegation is auto-derived from the\n    // session and re-issued whenever the SDK touches the public space,\n    // so a short lifetime bounds replay without forcing user re-prompts.\n    const expiryMs = EXPIRY.EPHEMERAL_MS;\n    const expirationTime = new Date(now.getTime() + expiryMs);\n\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(this.session.address),\n      chainId: this.session.chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: publicSpaceId,\n      jwk: this.session.jwk,\n      parents: [this.session.delegationCid],\n    });\n\n    const signature = await this.signer.signMessage(prepared.siwe);\n\n    const delegationSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    const activateResult = await activateSessionWithHost(\n      this.config.host!,\n      delegationSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate public space delegation: ${activateResult.error}`);\n    }\n\n    // Register the delegation in the capability registry so\n    // spaces.get('public').kv operations are authorized\n    if (this._capabilityRegistry && this.session) {\n      const sessionKey: KeyInfo = {\n        id: this.session.sessionKey,\n        did: this.session.verificationMethod,\n        type: \"session\",\n        jwk: this.session.jwk as JWK,\n        priority: 0,\n      };\n      this._capabilityRegistry.registerKey(sessionKey, [{\n        cid: delegationSession.delegationCid,\n        delegateDID: this.session.verificationMethod,\n        spaceId: publicSpaceId,\n        path: \"\",\n        actions: kvActions,\n        expiry: expirationTime,\n        isRevoked: false,\n        allowSubDelegation: true,\n      }]);\n    }\n\n    // Cache a properly authorized public KV service using the new delegation\n    if (this._serviceContext) {\n      const publicKV = new KVService({ prefix: \"\" });\n      const publicContext = this._serviceGraph.track(new ServiceContext({\n        invoke: this._serviceGraph.invoke,\n        fetch: this._serviceGraph.fetch,\n        hosts: this._serviceContext.hosts,\n        telemetry: this.config.telemetry,\n      }));\n      publicContext.setSession({\n        delegationHeader: delegationSession.delegationHeader,\n        delegationCid: delegationSession.delegationCid,\n        spaceId: publicSpaceId,\n        verificationMethod: this.session.verificationMethod,\n        jwk: this.session.jwk,\n      });\n      publicKV.initialize(publicContext);\n      this._publicKV = publicKV;\n    }\n  }\n\n  /**\n   * Get a KVService scoped to the user's own public space.\n   * Writes require authentication (owner/delegate).\n   */\n  get publicKV(): IKVService {\n    if (this._publicKV) {\n      return this._publicKV;\n    }\n    if (!this.tc) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n    return this.tc.publicKV;\n  }\n\n  // ===========================================================================\n  // v2 Delegation Convenience Methods\n  // ===========================================================================\n\n  /**\n   * Create a delegation using the v2 DelegationManager.\n   *\n   * This is a convenience method that wraps DelegationManager.create().\n   * For more control, use `this.delegationManager` directly.\n   *\n   * @param params - Delegation parameters\n   * @returns Result containing the created Delegation\n   *\n   * @example\n   * ```typescript\n   * const result = await alice.delegate({\n   *   delegateDID: bob.did,\n   *   path: \"shared/\",\n   *   actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\"],\n   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),\n   * });\n   *\n   * if (result.ok) {\n   *   console.log(\"Delegation created:\", result.data.cid);\n   * }\n   * ```\n   */\n  async delegate(params: CreateDelegationParams): Promise<DelegationResult<Delegation>> {\n    return this.delegationManager.create(params);\n  }\n\n  /**\n   * Revoke a delegation using the v2 DelegationManager.\n   *\n   * @param cid - The CID of the delegation to revoke\n   * @returns Result indicating success or failure\n   */\n  async revokeDelegation(cid: string): Promise<DelegationResult<DelegationRevocationReceipt>> {\n    return this.delegationManager.revoke(cid);\n  }\n\n  /** Read node-confirmed lifecycle state for one delegation. */\n  async getDelegationStatus(cid: string): Promise<DelegationResult<DelegationStatus>> {\n    return this.delegationManager.status(cid);\n  }\n\n  /** Compute the canonical CID of a compact UCAN or DAG-CBOR delegation authorization. */\n  computeDelegationCid(authorization: string): string {\n    if (!authorization || !this.wasmBindings.computeCid) {\n      throw new Error(\"Delegation CID computation is unavailable\");\n    }\n    const compact = authorization.replace(/^Bearer /i, \"\");\n    return this.wasmBindings.computeCid(\n      compact.includes(\".\")\n        ? new TextEncoder().encode(compact)\n        : decodeAuthorizationBytes(authorization),\n      0x55n,\n    );\n  }\n\n  /**\n   * List all delegations for the current session's space.\n   *\n   * @returns Result containing an array of Delegations\n   */\n  async listDelegations(): Promise<DelegationResult<Delegation[]>> {\n    return this.delegationManager.list();\n  }\n\n  /**\n   * Check if the current session has permission for a path and action.\n   *\n   * @param path - The resource path to check\n   * @param action - The action to check (e.g., \"tinycloud.kv/get\")\n   * @returns Result containing boolean permission status\n   */\n  async checkPermission(path: string, action: string): Promise<DelegationResult<boolean>> {\n    return this.delegationManager.checkPermission(path, action);\n  }\n\n  // ===========================================================================\n  // Capability-chain delegation (spec: .claude/specs/capability-chain.md)\n  // ===========================================================================\n\n  /**\n   * Safety margin before the session's own expiry at which {@link delegateTo}\n   * will refuse to issue a derived delegation. Prevents issuing sub-delegations\n   * that would be invalid by the time the recipient used them. Spec: 60 seconds.\n   *\n   * @internal\n   */\n  private static readonly SESSION_EXPIRY_SAFETY_MARGIN_MS = 60_000;\n\n  /**\n   * Issue a delegation using the capability-chain flow.\n   *\n   * When every requested permission is a subset of the current\n   * session's recap, or of one installed runtime permission delegation,\n   * the delegation is signed by the session key via WASM — no wallet\n   * prompt. When at least one is NOT derivable, a\n   * {@link PermissionNotInManifestError} is raised (carrying the\n   * missing entries) so the caller can trigger an escalation flow\n   * (e.g. `TinyCloudWeb.requestPermissions`). Passing\n   * `forceWalletSign: true` bypasses the derivability check and\n   * always uses the wallet-signed SIWE path — used by the legacy\n   * `createDelegation` fallback and by callers that want explicit\n   * wallet confirmation.\n   *\n   * Multi-entry delegations are now emitted as **one** signed UCAN:\n   * the underlying WASM `createDelegation` takes a full\n   * `HashMap<Service, HashMap<Path, Vec<Ability>>>` abilities map\n   * and produces a single attenuation carrying every\n   * `(service, path, actions)` entry. The returned\n   * {@link DelegateToResult.delegation} is that single blob, and\n   * apps can POST it to their backend exactly like a single-entry\n   * delegation (the server verifies all granted resources from one\n   * UCAN).\n   *\n   * For single-entry requests the `PortableDelegation.path` and\n   * `.actions` fields mirror the one granted entry. For\n   * multi-entry requests they mirror the **first** entry (stable\n   * lexicographic order from the Rust side); consumers that need\n   * the full picture read `PortableDelegation.resources`.\n   *\n   * @throws {@link SessionExpiredError} when there is no session or\n   *   the current session has expired (or will within the 60s\n   *   safety margin).\n   * @throws {@link PermissionNotInManifestError} when any requested\n   *   entry is not a subset of the granted session capabilities and\n   *   `forceWalletSign` is not set.\n   */\n  async delegateTo(\n    did: string,\n    permissions: PermissionEntry[],\n    options?: DelegateToOptions,\n  ): Promise<DelegateToResult> {\n    // 1. Session validity check — fail fast with a clear error class so\n    //    callers can catch and trigger a fresh sign-in.\n    const session = this.currentTinyCloudSession();\n    if (!session) {\n      throw new SessionExpiredError(new Date(0));\n    }\n    const sessionExpiry = extractSiweExpiration(session.siwe);\n    if (sessionExpiry !== undefined) {\n      const now = Date.now();\n      const marginMs = TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS;\n      if (sessionExpiry.getTime() <= now + marginMs) {\n        throw new SessionExpiredError(sessionExpiry);\n      }\n    }\n\n    // 2. Input validation. Empty arrays and non-arrays both fail here so\n    //    downstream code can safely assume at least one entry.\n    if (!Array.isArray(permissions) || permissions.length === 0) {\n      throw new Error(\n        \"delegateTo requires a non-empty permissions array\",\n      );\n    }\n\n    // 3. Defensively expand any short-form action names into full URNs\n    //    for every entry so the subset check and downstream WASM call\n    //    both see canonical form. This also deep-copies the entries so\n    //    we don't mutate caller-owned data.\n    const expandedEntries = this.expandPermissionEntries(permissions);\n\n    // 4. Compute expiration. `options.expiry` overrides the default 1h.\n    //    ms-format (\"7d\") or raw millisecond count both accepted. Cap\n    //    at the session's own expiry so we never emit a UCAN whose\n    //    validity exceeds the parent chain.\n    const now = new Date();\n    const expiryMs = resolveExpiryMs(options?.expiry);\n    const expirationTime = new Date(now.getTime() + expiryMs);\n    let effectiveExpiration = expirationTime;\n    if (sessionExpiry !== undefined && sessionExpiry < expirationTime) {\n      effectiveExpiration = sessionExpiry;\n    }\n\n    // 5. forceWalletSign short-circuit → always legacy path. The\n    //    legacy wallet path currently handles one `(space, path)` at\n    //    a time, so we only support single-entry when forced. Callers\n    //    that need multi-entry wallet-signed delegations should issue\n    //    them via the legacy `createDelegation` which loops internally\n    //    (or just not pass `forceWalletSign: true`).\n    if (options?.forceWalletSign) {\n      if (expandedEntries.length > 1) {\n        throw new Error(\n          \"delegateTo with forceWalletSign=true supports at most one \" +\n            \"PermissionEntry. Multi-entry requests must go through the \" +\n            \"session-key UCAN path (drop forceWalletSign) or the legacy \" +\n            \"createDelegation method.\",\n        );\n      }\n      this.assertDelegationCaveatsPreservable(expandedEntries);\n      const delegation = await this.createDelegationLegacyWalletPath(\n        did,\n        expandedEntries[0],\n        effectiveExpiration,\n      );\n      return { delegation, prompted: true };\n    }\n\n    // 6. Derivability check across ALL entries. If any entry is not a\n    //    subset of the granted session capabilities, the whole call\n    //    fails with a typed error carrying the missing entries — we do\n    //    NOT partially issue and drop the failing ones, because that\n    //    would produce a delegation the caller didn't ask for.\n    //\n    //    `parseRecapCapabilities` is a thin wrapper around the\n    //    injected WASM binding; the binding is required because\n    //    `IWasmBindings` declares `parseRecapFromSiwe` as mandatory.\n    //    If the runtime binding hasn't been updated, this call will\n    //    surface a clear TypeError rather than silently falling\n    //    through.\n    const granted = parseRecapCapabilities(\n      (siwe: string) => this.parseRecapWithCaveats(siwe),\n      session.siwe,\n    );\n    const { subset, missing } = isCapabilitySubset(expandedEntries, granted);\n\n    if (!subset) {\n      // This branch only runs when the session recap is NOT a superset of the\n      // requested entries. The synthetic primary grant is built from that same\n      // recap, so it should never cover an entry the recap itself doesn't —\n      // but `operationCovers` is strictly more permissive than\n      // `isCapabilitySubset` (action `/*` and path `/*`/`/**` wildcards), so a\n      // wildcard-bearing recap could slip through and mint a delegation with\n      // the primary session's spaceId (the wrong-space class). Exclude the\n      // primary explicitly; failure then degrades to\n      // PermissionNotInManifestError instead of a wrong-space delegation.\n      const runtimeOperations = this.permissionEntriesToOperations(expandedEntries, session);\n      const runtimeGrant = this.findGrantForOperations(\n        runtimeOperations,\n        { excludePrimary: true },\n      );\n      if (runtimeGrant) {\n        const marginMs = TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS;\n        if (runtimeGrant.expiresAt.getTime() <= Date.now() + marginMs) {\n          throw new SessionExpiredError(runtimeGrant.expiresAt);\n        }\n        const runtimeExpiration =\n          runtimeGrant.expiresAt < effectiveExpiration\n            ? runtimeGrant.expiresAt\n            : effectiveExpiration;\n        const delegation = await this.createDelegationViaRuntimeGrant(\n          did,\n          expandedEntries,\n          runtimeExpiration,\n          runtimeGrant,\n          runtimeOperations,\n        );\n        return { delegation, prompted: false };\n      }\n      throw new PermissionNotInManifestError(missing, granted);\n    }\n\n    // 7. Subset path — sign ONE sub-delegation with the session key\n    //    via WASM that carries every requested entry. No wallet\n    //    prompt. `createDelegationViaWasmPath` builds the\n    //    multi-resource abilities map and returns a single\n    //    PortableDelegation whose `.resources` field lists every\n    //    granted entry.\n    const delegation = await this.createDelegationViaWasmPath(\n      did,\n      expandedEntries,\n      effectiveExpiration,\n      session,\n    );\n    return { delegation, prompted: false };\n  }\n\n  /**\n   * Materialize one manifest-declared delegation using the current session key.\n   * Delivery is intentionally out of band; callers decide how to transmit the\n   * returned UCAN to the delegate.\n   */\n  async materializeDelegation(\n    did: string,\n    request: ComposedManifestRequest | undefined = this.capabilityRequest,\n  ): Promise<DelegateToResult & { target: ResolvedDelegate }> {\n    if (!request) {\n      throw new Error(\n        \"materializeDelegation requires a composed manifest request\",\n      );\n    }\n    const target = request.delegationTargets.find((entry) =>\n      didPrincipalMatches(entry.did, did),\n    );\n    if (!target) {\n      throw new Error(`No manifest delegation target found for DID ${did}`);\n    }\n    const result = await this.delegateTo(target.did, target.permissions, {\n      expiry: target.expiryMs,\n    });\n    return { ...result, target };\n  }\n\n  /**\n   * Materialize every delegation target declared by the composed manifest\n   * request. This does not deliver the delegations anywhere.\n   */\n  async materializeDelegations(\n    request: ComposedManifestRequest | undefined = this.capabilityRequest,\n  ): Promise<Array<DelegateToResult & { target: ResolvedDelegate }>> {\n    if (!request) {\n      throw new Error(\n        \"materializeDelegations requires a composed manifest request\",\n      );\n    }\n    const out: Array<DelegateToResult & { target: ResolvedDelegate }> = [];\n    for (const target of request.delegationTargets) {\n      out.push(await this.materializeDelegation(target.did, request));\n    }\n    return out;\n  }\n\n  /**\n   * Issue a delegation via the session-key UCAN WASM path.\n   *\n   * The caller has already verified every entry is derivable from\n   * the current session; we build one multi-resource abilities map\n   * and emit one signed UCAN covering them all.\n   *\n   * Non-encryption entries must share the same target space. Encryption\n   * entries are raw network URNs and do not participate in space grouping.\n   *\n   * @internal\n   */\n  private async createDelegationViaWasmPath(\n    did: string,\n    entries: PermissionEntry[],\n    expirationTime: Date,\n    session: TinyCloudSession,\n  ): Promise<PortableDelegation> {\n    if (entries.length === 0) {\n      throw new Error(\n        \"createDelegationViaWasmPath requires a non-empty entries array\",\n      );\n    }\n    this.assertDelegationCaveatsPreservable(entries);\n\n    // Translate non-raw manifest `space` fields into the server-side\n    // spaceId. Encryption entries target raw network URNs, not spaces.\n    const resolvedSpaces = new Set<string>();\n    for (const entry of entries) {\n      if (this.isEncryptionPermissionEntry(entry)) {\n        continue;\n      }\n      const spaceId = this.resolvePermissionSpace(entry.space, session);\n      resolvedSpaces.add(spaceId);\n    }\n    if (resolvedSpaces.size > 1) {\n      throw new Error(\n        `delegateTo: all permission entries must target the same space, got ${resolvedSpaces.size}: ${JSON.stringify([...resolvedSpaces])}`,\n      );\n    }\n    const spaceId = resolvedSpaces.size === 1\n      ? [...resolvedSpaces][0]\n      : session.spaceId;\n\n    // Convert entries to the WASM abilities shape. Each entry's\n    // `service` is the long form (e.g. \"tinycloud.kv\") which we\n    // translate to the short form keyed by the abilities map. Raw\n    // encryption network entries stay in this map because the Rust\n    // create_delegation boundary special-cases network URNs into raw\n    // resources while preserving the legacy spaceId parameter.\n    // Multiple entries on the same (service, path) merge and dedupe\n    // their action lists — unusual in practice (the subset check\n    // should have pruned dupes already) but cheap and safe.\n    const abilities: AbilitiesMap = {};\n    for (const entry of entries) {\n      const shortService = SERVICE_LONG_TO_SHORT[entry.service];\n      if (shortService === undefined) {\n        throw new Error(\n          `delegateTo: unknown service '${entry.service}' — no short-form mapping`,\n        );\n      }\n      if (abilities[shortService] === undefined) {\n        abilities[shortService] = {};\n      }\n      const pathsMap = abilities[shortService];\n      const existing = pathsMap[entry.path];\n      if (existing === undefined) {\n        pathsMap[entry.path] = [...entry.actions];\n      } else {\n        const seen = new Set(existing);\n        for (const action of entry.actions) {\n          if (!seen.has(action)) {\n            existing.push(action);\n            seen.add(action);\n          }\n        }\n      }\n    }\n\n    // Build ServiceSession from TinyCloudSession. This mirrors how\n    // SharingService hands sessions to createDelegationWrapper.\n    const serviceSession: ServiceSession = {\n      delegationHeader: session.delegationHeader,\n      delegationCid: session.delegationCid,\n      jwk: session.jwk,\n      spaceId,\n      verificationMethod: session.verificationMethod,\n    };\n\n    const expirationSecs = Math.floor(expirationTime.getTime() / 1000);\n    const result = this.createDelegationWrapper({\n      session: serviceSession,\n      delegateDID: did,\n      spaceId,\n      abilities,\n      expirationSecs,\n    });\n\n    // Translate the WASM result into a PortableDelegation. We don't\n    // have a structured delegation header from the WASM path, so we\n    // synthesize one from the serialized delegation (the recipient\n    // decodes it via `deserializeDelegation`).\n    //\n    // The flat `.path` and `.actions` fields mirror the first\n    // resource — stable because the Rust side sorts by\n    // (service, path) before signing. Consumers that need the full\n    // multi-resource picture read `.resources`.\n    const primary = result.resources[0];\n    // Use the raw JWT without a \"Bearer \" prefix. The host's HeaderEncode\n    // decoder passes the header value directly to Ucan::decode(), which\n    // expects a bare JWT string. The wallet-signed CACAO path also uses\n    // raw base64 without any prefix. Adding \"Bearer \" causes a parse\n    // failure that surfaces as a 401 from the host.\n    const delegationHeader = { Authorization: result.delegation };\n\n    // Activate the delegation with the host so downstream consumers (e.g.\n    // a backend calling useDelegation) can find it by CID when building\n    // their invoker SIWE. The host validates the UCAN's parent chain\n    // (session key → wallet SIWE) to confirm authority.\n    const activateResult = await activateSessionWithHost(\n      this.config.host!,\n      delegationHeader,\n    );\n    if (!activateResult.success) {\n      throw new Error(\n        `Failed to activate delegation with host: ${activateResult.error}`,\n      );\n    }\n\n    return {\n      cid: result.cid,\n      delegationHeader,\n      spaceId,\n      path: primary.path,\n      actions: primary.actions,\n      resources: result.resources,\n      disableSubDelegation: false,\n      expiry: result.expiry,\n      delegateDID: did,\n      ownerAddress: session.address,\n      chainId: session.chainId,\n      host: this.config.host,\n    };\n  }\n\n  private async createDelegationViaRuntimeGrant(\n    did: string,\n    entries: PermissionEntry[],\n    expirationTime: Date,\n    grant: RuntimePermissionGrant,\n    requestedOperations: RuntimePermissionOperation[],\n  ): Promise<PortableDelegation> {\n    this.assertRuntimeGrantCaveatsPreservable(entries, requestedOperations, grant);\n    this.assertDelegationCaveatsPreservable(entries);\n    const result = this.createDelegationWrapper({\n      session: grant.session,\n      delegateDID: did,\n      spaceId: grant.session.spaceId,\n      abilities: this.permissionsToAbilities(entries),\n      expirationSecs: Math.floor(expirationTime.getTime() / 1000),\n    });\n\n    const primary = result.resources[0];\n    const delegationHeader = { Authorization: result.delegation };\n    const targetHost = grant.delegation.host ?? this.config.host!;\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      delegationHeader,\n    );\n    if (!activateResult.success) {\n      throw new Error(\n        `Failed to activate delegation with host: ${activateResult.error}`,\n      );\n    }\n\n    return {\n      cid: result.cid,\n      delegationHeader,\n      spaceId: grant.session.spaceId,\n      path: primary.path,\n      actions: primary.actions,\n      resources: result.resources,\n      disableSubDelegation: false,\n      expiry: result.expiry,\n      delegateDID: did,\n      ownerAddress: grant.delegation.ownerAddress,\n      chainId: grant.delegation.chainId,\n      host: targetHost,\n    };\n  }\n\n  private resolvePermissionSpace(\n    space: string | undefined,\n    session: TinyCloudSession,\n  ): string {\n    if (space === undefined) {\n      return this.wasmBindings.makeSpaceId(\n        session.address,\n        session.chainId,\n        \"applications\",\n      );\n    }\n    if (space === \"default\") {\n      return session.spaceId;\n    }\n    if (space.startsWith(\"tinycloud:\")) {\n      return space;\n    }\n    return this.wasmBindings.makeSpaceId(session.address, session.chainId, space);\n  }\n\n  private expandPermissionEntries(\n    permissions: PermissionEntry[],\n  ): PermissionEntry[] {\n    return expandPermissionEntriesCore(permissions);\n  }\n\n  /**\n   * The current WASM child-delegation APIs accept action-only maps. Refuse any\n   * constrained branch rather than signing a broader action-only child UCAN.\n   */\n  private assertDelegationCaveatsPreservable(entries: PermissionEntry[]): void {\n    const caveated = entries.filter((entry) =>\n      !recapCaveatsEqual(entry.caveats, undefined)\n    );\n    if (caveated.length > 0) {\n      throw new CaveatedDelegationUnsupportedError(caveated);\n    }\n  }\n\n  /**\n   * Runtime grant selection intentionally allows an uncaveated operation to\n   * select a caveated grant so invocation can restore the signed caveat before\n   * crossing the caveat-aware WASM boundary. Child delegation cannot do that:\n   * it only accepts action maps, so reject the selected constrained branch.\n   */\n  private assertRuntimeGrantCaveatsPreservable(\n    entries: PermissionEntry[],\n    requestedOperations: RuntimePermissionOperation[],\n    grant: RuntimePermissionGrant,\n  ): void {\n    let operationIndex = 0;\n    const caveated: PermissionEntry[] = [];\n    for (const entry of entries) {\n      for (const action of entry.actions) {\n        const requested = requestedOperations[operationIndex++];\n        if (!requested) continue;\n        const constrained = grant.operations.find((granted) =>\n          this.operationCovers(granted, requested) &&\n          !recapCaveatsEqual(granted.caveats, undefined),\n        );\n        if (constrained) {\n          caveated.push({\n            ...entry,\n            actions: [action],\n            caveats: cloneRecapCaveats(constrained.caveats),\n          });\n        }\n      }\n    }\n    if (caveated.length > 0) {\n      throw new CaveatedDelegationUnsupportedError(caveated);\n    }\n  }\n\n  /** Reject caveated parent branches before action-only child signing. */\n  private assertPortableDelegationCaveatsPreservable(\n    delegation: PortableDelegation,\n  ): void {\n    const entries: PermissionEntry[] = [];\n    const add = (\n      service: string,\n      space: string,\n      path: string,\n      actions: string[],\n      caveats: readonly Record<string, unknown>[] | undefined,\n    ): void => {\n      if (recapCaveatsEqual(caveats, undefined)) return;\n      entries.push({\n        service: service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`,\n        space,\n        path,\n        actions: [...actions],\n        caveats: cloneRecapCaveats(caveats),\n      });\n    };\n\n    add(\n      delegation.actions[0]?.split(\"/\", 1)[0] ?? \"tinycloud.unknown\",\n      delegation.spaceId,\n      delegation.path,\n      delegation.actions,\n      delegation.caveats,\n    );\n    for (const resource of delegation.resources ?? []) {\n      add(resource.service, resource.space, resource.path, resource.actions, resource.caveats);\n    }\n    if (entries.length > 0) {\n      throw new CaveatedDelegationUnsupportedError(entries);\n    }\n  }\n\n  private shortServiceName(service: string): string {\n    const short = SERVICE_LONG_TO_SHORT[service];\n    if (short === undefined) {\n      throw new Error(\n        `unknown service '${service}' — no short-form mapping`,\n      );\n    }\n    return short;\n  }\n\n  private permissionsToAbilities(entries: PermissionEntry[]): AbilitiesMap {\n    const abilities: AbilitiesMap = {};\n    for (const entry of entries) {\n      const service = this.shortServiceName(entry.service);\n      abilities[service] ??= {};\n      const existing = abilities[service][entry.path] ?? [];\n      const seen = new Set(existing);\n      for (const action of entry.actions) {\n        if (!seen.has(action)) {\n          existing.push(action);\n          seen.add(action);\n        }\n      }\n      abilities[service][entry.path] = existing;\n    }\n    return abilities;\n  }\n\n  private isEncryptionPermissionEntry(entry: PermissionEntry): boolean {\n    return entry.service === ENCRYPTION_PERMISSION_SERVICE &&\n      entry.path.startsWith(\"urn:tinycloud:encryption:\");\n  }\n\n  private permissionsToRawAbilities(\n    entries: PermissionEntry[],\n  ): Record<string, string[]> {\n    const rawAbilities: Record<string, string[]> = {};\n    for (const entry of entries) {\n      if (!this.isEncryptionPermissionEntry(entry)) {\n        continue;\n      }\n      const existing = rawAbilities[entry.path] ?? [];\n      const seen = new Set(existing);\n      for (const action of entry.actions) {\n        if (!seen.has(action)) {\n          existing.push(action);\n          seen.add(action);\n        }\n      }\n      rawAbilities[entry.path] = existing;\n    }\n    return rawAbilities;\n  }\n\n  private permissionOperations(\n    entries: PermissionEntry[],\n    spaceId: string,\n  ): RuntimePermissionOperation[] {\n    return entries.flatMap((entry) => {\n      const service = this.shortServiceName(entry.service);\n      return entry.actions.map((action) => ({\n        ...(this.isEncryptionNetworkOperation(service, entry.path)\n          ? { resource: entry.path }\n          : { spaceId }),\n        service,\n        path: entry.path,\n        action,\n        ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n      }));\n    });\n  }\n\n  private sessionCoversPermissionEntries(\n    session: TinyCloudSession,\n    entries: PermissionEntry[],\n  ): boolean {\n    try {\n      const granted = parseRecapCapabilities(\n        (siwe: string) => this.parseRecapWithCaveats(siwe),\n        session.siwe,\n      );\n      return isCapabilitySubset(entries, granted).subset;\n    } catch {\n      return false;\n    }\n  }\n\n  private permissionEntriesToOperations(\n    entries: PermissionEntry[],\n    session: TinyCloudSession,\n  ): RuntimePermissionOperation[] {\n    return entries.flatMap((entry) => {\n      const spaceId = this.resolvePermissionSpace(entry.space, session);\n      const service = this.shortServiceName(entry.service);\n      return entry.actions.map((action) => ({\n        ...(this.isEncryptionNetworkOperation(service, entry.path)\n          ? { resource: entry.path }\n          : { spaceId }),\n        service,\n        path: entry.path,\n        action,\n        ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n      }));\n    });\n  }\n\n  private findRuntimeGrantsForPermissionEntries(\n    entries: PermissionEntry[],\n    session: TinyCloudSession,\n  ): RuntimePermissionGrant[] {\n    const grants: RuntimePermissionGrant[] = [];\n    const operations = this.permissionEntriesToOperations(entries, session);\n    if (operations.length === 0) {\n      return grants;\n    }\n\n    for (const operation of operations) {\n      // Public surface: never surface the synthetic primary grant. It exists\n      // only to win runtime invocation selection; the base session's own recap\n      // is not an installed runtime delegation, so excluding it keeps the\n      // `getRuntimePermissionDelegations` contract (base-session manifest\n      // permissions are not represented here) airtight.\n      const grant = this.findGrantForOperation(operation, { excludePrimary: true });\n      if (!grant) {\n        return [];\n      }\n      if (!grants.includes(grant)) {\n        grants.push(grant);\n      }\n    }\n    return grants;\n  }\n\n  private runtimeDelegationFromSession(\n    delegatedSession: {\n      delegationHeader: { Authorization: string };\n      delegationCid: string;\n    },\n    entries: PermissionEntry[],\n    spaceId: string,\n    session: TinyCloudSession,\n    expiresAt: Date,\n  ): PortableDelegation {\n    const resources = this.delegatedResourcesForEntries(entries, spaceId);\n    const primary = resources[0];\n    return {\n      cid: delegatedSession.delegationCid,\n      delegationHeader: delegatedSession.delegationHeader,\n      spaceId,\n      path: primary.path,\n      actions: primary.actions,\n      resources,\n      disableSubDelegation: false,\n      expiry: expiresAt,\n      delegateDID: session.verificationMethod,\n      ownerAddress: session.address,\n      chainId: session.chainId,\n      host: this.config.host,\n    };\n  }\n\n  private runtimeGrantFromDelegation(\n    delegation: PortableDelegation,\n    session: TinyCloudSession,\n  ): RuntimePermissionGrant {\n    const operations = this.operationsFromDelegation(delegation);\n    return {\n      session: {\n        delegationHeader: delegation.delegationHeader,\n        delegationCid: delegation.cid,\n        spaceId: delegation.spaceId,\n        verificationMethod: session.verificationMethod,\n        jwk: session.jwk,\n      },\n      delegation,\n      operations,\n      expiresAt: delegation.expiry,\n      provenance: \"delegated\",\n    };\n  }\n\n  private installRuntimeGrantFromServiceSession(\n    delegation: PortableDelegation,\n    session: ServiceSession,\n    expiresAt: Date,\n  ): void {\n    const operations = this.operationsFromDelegation(delegation);\n    if (operations.length === 0) {\n      return;\n    }\n    this.runtimePermissionGrants = this.runtimePermissionGrants.filter(\n      (grant) =>\n        grant.delegation.cid !== delegation.cid &&\n        grant.session.delegationCid !== session.delegationCid,\n    );\n    this.runtimePermissionGrants.push({\n      session,\n      delegation,\n      operations,\n      expiresAt,\n      provenance: \"delegated\",\n    });\n  }\n\n  private delegatedResourcesForEntries(\n    entries: PermissionEntry[],\n    spaceId: string,\n  ): DelegatedResource[] {\n    return entries.map((entry) => ({\n      service: this.shortServiceName(entry.service),\n      space: this.isEncryptionPermissionEntry(entry) ? \"encryption\" : spaceId,\n      path: entry.path,\n      actions: [...entry.actions],\n      ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n    }));\n  }\n\n  private operationsFromDelegation(\n    delegation: PortableDelegation,\n  ): RuntimePermissionOperation[] {\n    const resources =\n      delegation.resources !== undefined && delegation.resources.length > 0\n        ? delegation.resources\n        : this.flatDelegationResources(delegation);\n\n    return resources.flatMap((resource) => {\n      const service = this.invocationServiceName(resource.service);\n      return resource.actions.map((action) => ({\n        ...(this.isEncryptionNetworkOperation(service, resource.path)\n          ? { resource: resource.path }\n          : { spaceId: resource.space }),\n        service,\n        path: resource.path,\n        action,\n        caveats: cloneRecapCaveats(resource.caveats),\n      }));\n    });\n  }\n\n  private flatDelegationResources(\n    delegation: PortableDelegation,\n  ): DelegatedResource[] {\n    const byService = new Map<string, string[]>();\n    for (const action of delegation.actions) {\n      const service = this.shortServiceName(action.split(\"/\")[0]);\n      const actions = byService.get(service) ?? [];\n      actions.push(action);\n      byService.set(service, actions);\n    }\n    return [...byService.entries()].map(([service, actions]) => ({\n      service,\n      space: delegation.spaceId,\n      path: delegation.path,\n      actions,\n      ...(delegation.caveats === undefined ? {} : { caveats: cloneRecapCaveats(delegation.caveats) }),\n    }));\n  }\n\n  /**\n   * Build the abilities/rawAbilities maps for a wallet-mode activation\n   * sub-delegation from the FULL resource set of a received delegation.\n   *\n   * Each entry in `delegation.resources[]` is one `(service, space, path,\n   * actions)` grant; the flat top-level `path`/`actions` mirror only the\n   * first resource. We must reconstruct every grant so the activated\n   * session carries all of them (e.g. both `tinycloud.kv/get` and\n   * `tinycloud.encryption/decrypt`) — not just the primary one.\n   *\n   * Encryption resources are raw network URNs (space-independent) and go\n   * into `rawAbilities`. All other resources are space-scoped and go into\n   * `abilities` keyed by short service name. The activation `prepareSession`\n   * call uses a single `spaceId` (`delegation.spaceId`), so every\n   * non-encryption resource must target that same space — which is exactly\n   * what the multi-resource issuance path enforces. A resource targeting a\n   * different space cannot be activated in one call, so we fail loudly\n   * rather than silently dropping it.\n   *\n   * @internal\n   */\n  private buildActivationAbilities(delegation: PortableDelegation): {\n    abilities: Record<string, Record<string, string[]>>;\n    rawAbilities: Record<string, string[]>;\n  } {\n    const resources =\n      delegation.resources !== undefined && delegation.resources.length > 0\n        ? delegation.resources\n        : this.flatDelegationResources(delegation);\n\n    const abilities: Record<string, Record<string, string[]>> = {};\n    const rawAbilities: Record<string, string[]> = {};\n\n    const addActions = (target: string[], actions: string[]): void => {\n      const seen = new Set(target);\n      for (const action of actions) {\n        if (!seen.has(action)) {\n          target.push(action);\n          seen.add(action);\n        }\n      }\n    };\n\n    for (const resource of resources) {\n      const service = this.invocationServiceName(resource.service);\n      if (this.isEncryptionNetworkOperation(service, resource.path)) {\n        rawAbilities[resource.path] ??= [];\n        addActions(rawAbilities[resource.path], resource.actions);\n        continue;\n      }\n\n      if (resource.space !== delegation.spaceId) {\n        throw new Error(\n          `useDelegation: resource targets space '${resource.space}' but the ` +\n            `delegation activates space '${delegation.spaceId}'. Multi-space ` +\n            `delegations cannot be activated in a single useDelegation call.`,\n        );\n      }\n\n      abilities[service] ??= {};\n      abilities[service][resource.path] ??= [];\n      addActions(abilities[service][resource.path], resource.actions);\n    }\n\n    return { abilities, rawAbilities };\n  }\n\n  private selectInvocationSession(\n    fallback: ServiceSession,\n    service: string,\n    path: string,\n    action: string,\n  ): ServiceSession {\n    const grant = this.findGrantForOperation({\n      spaceId: fallback.spaceId,\n      service: this.invocationServiceName(service),\n      path,\n      action,\n    });\n    if (!grant) {\n      return fallback;\n    }\n    // \"Primary wins\" means the caller's own session already authorizes the op:\n    // use the PASSED session, not the stored primary `ServiceSession`. The stored\n    // primary carries the primary space's `spaceId`, but a multi-space recap can\n    // cover scoped ops on OTHER spaces whose fallback session carries the correct\n    // target `spaceId`. Returning `grant.session` there would mint the invocation\n    // against the wrong space (TC-111 follow-up). Non-primary grants keep their\n    // own session.\n    return grant.provenance === \"primary\" ? fallback : grant.session;\n  }\n\n  private findGrantForOperations(\n    operations: RuntimePermissionOperation[],\n    options?: { excludePrimary?: boolean },\n  ): RuntimePermissionGrant | undefined {\n    if (operations.length === 0) {\n      return undefined;\n    }\n    this.pruneExpiredRuntimePermissionGrants();\n    const covering = this.runtimePermissionGrants.filter((grant) => {\n      if (options?.excludePrimary && grant.provenance === \"primary\") {\n        return false;\n      }\n      return operations.every((operation) =>\n        grant.operations.some((granted) =>\n          this.operationCovers(granted, operation),\n        ),\n      );\n    });\n    if (covering.length === 0) {\n      return undefined;\n    }\n    // Provenance ranking: the synthetic primary grant (the base session's own\n    // recap) always wins when it covers every op, so a broad bootstrap or\n    // delegated grant can never hijack an operation the primary session itself\n    // authorizes (TC-111). Otherwise fall back to insertion order — the same\n    // semantics as the previous `.find`.\n    return covering.find((grant) => grant.provenance === \"primary\") ?? covering[0];\n  }\n\n  private findGrantForOperation(\n    operation: RuntimePermissionOperation,\n    options?: { excludePrimary?: boolean },\n  ): RuntimePermissionGrant | undefined {\n    return this.findGrantForOperations([operation], options);\n  }\n\n  private pruneExpiredRuntimePermissionGrants(): void {\n    const now = Date.now();\n    this.runtimePermissionGrants = this.runtimePermissionGrants.filter(\n      (grant) => grant.expiresAt.getTime() > now,\n    );\n  }\n\n  private operationCovers(\n    granted: RuntimePermissionOperation,\n    requested: RuntimePermissionOperation,\n  ): boolean {\n    if (granted.service !== requested.service ||\n      !this.actionContains(granted.action, requested.action)\n    ) {\n      return false;\n    }\n\n    // A caller that already carries a caveat can only be covered by the exact\n    // same signed attenuation.  An uncaveated request is decorated with the\n    // grant's caveat immediately before WASM signs it.\n    if (requested.caveats !== undefined &&\n      !recapCaveatsEqual(granted.caveats, requested.caveats)\n    ) {\n      return false;\n    }\n\n    if (granted.resource !== undefined || requested.resource !== undefined) {\n      return granted.resource !== undefined &&\n        requested.resource !== undefined &&\n        granted.resource === requested.resource &&\n        this.pathContains(granted.path, requested.path);\n    }\n\n    return granted.spaceId !== undefined &&\n      requested.spaceId !== undefined &&\n      this.spaceIdsEqual(granted.spaceId, requested.spaceId) &&\n      this.pathContains(granted.path, requested.path);\n  }\n\n  // Space IDs are `tinycloud:pkh:eip155:<chain>:<0xADDR>:<name>`. The embedded\n  // EIP-155 address is case-insensitive, but the CLI canonicalizes it to\n  // lowercase when building a space URI while stored runtime delegations keep\n  // the EIP-55 checksummed form — so a byte-for-byte compare spuriously rejects\n  // an otherwise-valid grant. Lowercase ONLY the `eip155:<chain>:0x<addr>`\n  // segment and leave everything else (crucially the case-sensitive space NAME)\n  // byte-exact. Mirrors the CLI's `normalizeSpaceForCompare` (OPENKEY_SCOPE_MISMATCH fix).\n  private spaceIdsEqual(a: string, b: string): boolean {\n    return this.normalizeSpaceAddress(a) === this.normalizeSpaceAddress(b);\n  }\n\n  private normalizeSpaceAddress(space: string): string {\n    return space.replace(\n      /(eip155:\\d+:)(0x[0-9a-fA-F]{40})/,\n      (_match, prefix: string, addr: string) => prefix + addr.toLowerCase(),\n    );\n  }\n\n  private actionContains(grantedAction: string, requestedAction: string): boolean {\n    if (grantedAction === requestedAction) {\n      return true;\n    }\n    if (grantedAction.endsWith(\"/*\")) {\n      const prefix = grantedAction.slice(0, -2);\n      return requestedAction.startsWith(`${prefix}/`);\n    }\n    return false;\n  }\n\n  private invocationServiceName(service: string): string {\n    return service.startsWith(\"tinycloud.\")\n      ? this.shortServiceName(service)\n      : service;\n  }\n\n  /** Prefer the v2 caveat-preserving parser while retaining old custom WASM. */\n  private parseRecapWithCaveats(siwe: string): WasmRecapEntry[] {\n    return this.wasmBindings.parseVerifiedRecapFromSiwe?.(siwe)\n      ?? this.wasmBindings.parseRecapFromSiwe(siwe);\n  }\n\n  private isEncryptionNetworkOperation(service: string, path: string): boolean {\n    return service === \"encryption\" &&\n      path.startsWith(\"urn:tinycloud:encryption:\");\n  }\n\n  private operationFromInvokeAnyEntry(entry: {\n    spaceId?: string;\n    resource?: string;\n    service: string;\n    path: string;\n    action: string;\n    caveats?: Record<string, unknown>[];\n  }): RuntimePermissionOperation | undefined {\n    const service = this.invocationServiceName(entry.service);\n    if (typeof entry.resource === \"string\") {\n      return {\n        resource: entry.resource,\n        service,\n        path: entry.path,\n        action: entry.action,\n        ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n      };\n    }\n    if (this.isEncryptionNetworkOperation(service, entry.path)) {\n      return {\n        resource: entry.path,\n        service,\n        path: entry.path,\n        action: entry.action,\n        ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n      };\n    }\n    if (typeof entry.spaceId === \"string\") {\n      return {\n        spaceId: entry.spaceId,\n        service,\n        path: entry.path,\n        action: entry.action,\n        ...(entry.caveats === undefined ? {} : { caveats: cloneRecapCaveats(entry.caveats) }),\n      };\n    }\n    return undefined;\n  }\n\n  private pathContains(grantedPath: string, requestedPath: string): boolean {\n    if (grantedPath === \"\" || grantedPath === \"/\") {\n      return true;\n    }\n    if (grantedPath.endsWith(\"/**\")) {\n      return requestedPath.startsWith(grantedPath.slice(0, -3));\n    }\n    if (grantedPath.endsWith(\"/*\")) {\n      const prefix = grantedPath.slice(0, -2);\n      if (!requestedPath.startsWith(prefix)) {\n        return false;\n      }\n      const remainder = requestedPath.slice(prefix.length);\n      return !remainder.includes(\"/\") || remainder === \"/\";\n    }\n    if (grantedPath.endsWith(\"/\")) {\n      return requestedPath.startsWith(grantedPath);\n    }\n    return grantedPath === requestedPath;\n  }\n\n  /**\n   * Issue a delegation via the legacy wallet-signed SIWE path for a single\n   * {@link PermissionEntry}. Shares the implementation with the public\n   * `createDelegation` method via {@link createDelegationWalletPath} so\n   * both entry points hit exactly the same SIWE / signer / public-space\n   * logic without mutual recursion.\n   *\n   * @internal\n   */\n  private async createDelegationLegacyWalletPath(\n    delegateDID: string,\n    entry: PermissionEntry,\n    expirationTime: Date,\n  ): Promise<PortableDelegation> {\n    const session = this.auth?.tinyCloudSession;\n    const spaceIdOverride =\n      session === undefined || entry.space === \"default\"\n        ? undefined\n        : this.resolvePermissionSpace(entry.space, session);\n    return this.createDelegationWalletPath({\n      path: entry.path,\n      actions: entry.actions,\n      delegateDID,\n      includePublicSpace: true,\n      expiryMs: Math.max(0, expirationTime.getTime() - Date.now()),\n      spaceIdOverride,\n    });\n  }\n\n  /**\n   * Create a delegation from this user to another user.\n   *\n   * The delegation grants the recipient access to a specific path and actions\n   * within this user's space.\n   *\n   * @param params - Delegation parameters\n   * @returns A portable delegation that can be sent to the recipient\n   */\n  async createDelegation(params: {\n    /** Path within the space to delegate access to */\n    path: string;\n    /** Actions to allow (e.g., [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]) */\n    actions: string[];\n    /** DID of the recipient (from their TinyCloudNode.did) */\n    delegateDID: string;\n    /** Whether to prevent the recipient from creating sub-delegations (default: false) */\n    disableSubDelegation?: boolean;\n    /** Expiration time in milliseconds from now (default: 1 hour) */\n    expiryMs?: number;\n    /** Override space ID (for creating delegations to non-primary spaces like public) */\n    spaceIdOverride?: string;\n    /** Include a companion delegation for the user's public space (default: true) */\n    includePublicSpace?: boolean;\n  }): Promise<PortableDelegation> {\n    // Legacy compatibility shim.\n    //\n    // Route through delegateTo so that callers whose requested capabilities\n    // are a subset of their current session get the session-key UCAN path\n    // (no wallet prompt). Fall back to the legacy wallet-sign path on\n    // PermissionNotInManifestError, preserving today's behaviour for\n    // callers that request scope outside their session.\n    //\n    // SessionExpiredError propagates — an expired session can't be fixed\n    // by re-signing the SIWE, the caller needs to run signIn() again.\n    if (!this.signer) {\n      throw new Error(\"Cannot createDelegation() in session-only mode. Requires wallet mode.\");\n    }\n    if (!this.auth?.tinyCloudSession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Resolve ENS names to PKH DIDs up front so both paths see the resolved\n    // DID. The wallet path mutates params further below; we do it here so\n    // the fast path (delegateTo) also picks up the resolved DID.\n    let resolvedDelegateDID = params.delegateDID;\n    if (resolvedDelegateDID.endsWith('.eth') && this.config.ensResolver) {\n      const address = await this.config.ensResolver.resolveAddress(resolvedDelegateDID);\n      if (!address) throw new Error(`Could not resolve ENS name: ${resolvedDelegateDID}`);\n      resolvedDelegateDID = pkhDid(address, 1);\n    }\n\n    // Legacy params lump multiple services' actions under one path. We\n    // now emit ONE multi-resource UCAN for any number of entries via\n    // the fast path, so there's no longer a \"single-entry only\" gate\n    // here — the fast path handles N entries and returns a single\n    // PortableDelegation whose `.resources` describes the full set.\n    //\n    // Fall back to the wallet path when the capabilities aren't\n    // derivable from the current session (PermissionNotInManifestError)\n    // so legacy callers requesting scope outside their session continue\n    // to see a wallet prompt, matching today's behaviour.\n    const entries = legacyParamsToPermissionEntries(\n      params.actions,\n      params.path,\n      params.spaceIdOverride,\n    );\n    try {\n      const result = await this.delegateTo(\n        resolvedDelegateDID,\n        entries,\n        params.expiryMs !== undefined ? { expiry: params.expiryMs } : undefined,\n      );\n      return result.delegation;\n    } catch (err) {\n      if (err instanceof PermissionNotInManifestError) {\n        // Expected — fall through to the wallet path below. Legacy\n        // callers that request scope outside their current session\n        // continue to see a wallet prompt, matching today's behaviour.\n      } else {\n        // SessionExpiredError and any other error class must propagate.\n        // An expired session can't be rescued by re-signing the SIWE\n        // here — the caller needs to run signIn() again.\n        throw err;\n      }\n    }\n\n    // Legacy wallet-signed SIWE path — same implementation as before the\n    // delegateTo refactor. Callers that request scope outside their\n    // current session land here and see the familiar wallet prompt.\n    return this.createDelegationWalletPath({\n      ...params,\n      delegateDID: resolvedDelegateDID,\n    });\n  }\n\n  /**\n   * Legacy wallet-signed SIWE delegation path. Lifted from the original\n   * `createDelegation` body verbatim so both the legacy public method and\n   * `delegateTo({ forceWalletSign: true })` hit the same code.\n   *\n   * @internal\n   */\n  private async createDelegationWalletPath(params: {\n    path: string;\n    actions: string[];\n    delegateDID: string;\n    disableSubDelegation?: boolean;\n    expiryMs?: number;\n    spaceIdOverride?: string;\n    includePublicSpace?: boolean;\n  }): Promise<PortableDelegation> {\n    if (!this.signer) {\n      throw new Error(\"Cannot createDelegation() in session-only mode. Requires wallet mode.\");\n    }\n    const session = this.auth?.tinyCloudSession;\n    if (!session) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Build abilities for the delegation\n    const abilities: Record<string, Record<string, string[]>> = {};\n    const kvActions = params.actions.filter(a => a.startsWith(\"tinycloud.kv/\"));\n    const sqlActions = params.actions.filter(a => a.startsWith(\"tinycloud.sql/\"));\n    const duckdbActions = params.actions.filter(a => a.startsWith(\"tinycloud.duckdb/\"));\n    if (kvActions.length > 0) {\n      abilities.kv = { [params.path]: kvActions };\n    }\n    if (sqlActions.length > 0) {\n      abilities.sql = { [params.path]: sqlActions };\n    }\n    if (duckdbActions.length > 0) {\n      abilities.duckdb = { [params.path]: duckdbActions };\n    }\n\n    const now = new Date();\n    const expiryMs = params.expiryMs ?? 60 * 60 * 1000; // Default 1 hour\n    const expirationTime = new Date(now.getTime() + expiryMs);\n\n    // Prepare the delegation session with:\n    // - delegateUri: target the recipient's DID directly (for user-to-user delegation)\n    // - parents: reference our session CID for chain validation\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(session.address),\n      chainId: session.chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: params.spaceIdOverride ?? session.spaceId,\n      delegateUri: params.delegateDID,\n      parents: [session.delegationCid],\n    });\n\n    // Sign the SIWE message with this user's signer\n    const signature = await this.signer.signMessage(prepared.siwe);\n\n    // Complete the session setup\n    const delegationSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Activate the delegation with the server\n    const activateResult = await activateSessionWithHost(\n      this.config.host!,\n      delegationSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate delegation: ${activateResult.error}`);\n    }\n\n    const result: PortableDelegation = {\n      cid: delegationSession.delegationCid,\n      delegationHeader: delegationSession.delegationHeader,\n      spaceId: params.spaceIdOverride ?? session.spaceId,\n      path: params.path,\n      actions: params.actions,\n      disableSubDelegation: params.disableSubDelegation ?? false,\n      expiry: expirationTime,\n      delegateDID: params.delegateDID,\n      ownerAddress: session.address,\n      chainId: session.chainId,\n      host: this.config.host,\n    };\n\n    // Auto-create public-space delegation for vault key publishing\n    const hasKvActions = params.actions.some(a => a.startsWith(\"tinycloud.kv/\"));\n    if (hasKvActions && params.includePublicSpace !== false) {\n      const publicSpaceId = makePublicSpaceId(\n        this.wasmBindings.ensureEip55(session.address), session.chainId\n      );\n      const publicAbilities: Record<string, Record<string, string[]>> = {\n        kv: { \"\": [KV.GET, KV.PUT, KV.METADATA] },\n      };\n      const publicPrepared = this.wasmBindings.prepareSession({\n        abilities: publicAbilities,\n        address: this.wasmBindings.ensureEip55(session.address),\n        chainId: session.chainId,\n        domain: this.siweDomain,\n        issuedAt: now.toISOString(),\n        expirationTime: expirationTime.toISOString(),\n        spaceId: publicSpaceId,\n        delegateUri: params.delegateDID,\n        parents: [session.delegationCid],\n      });\n      const publicSignature = await this.signer.signMessage(publicPrepared.siwe);\n      const publicSession = this.wasmBindings.completeSessionSetup({\n        ...publicPrepared,\n        signature: publicSignature,\n      });\n\n      const publicActivateResult = await activateSessionWithHost(\n        this.config.host!,\n        publicSession.delegationHeader\n      );\n\n      if (publicActivateResult.success) {\n        result.publicDelegation = {\n          cid: publicSession.delegationCid,\n          delegationHeader: publicSession.delegationHeader,\n          spaceId: publicSpaceId,\n          path: \"\",\n          actions: [KV.GET, KV.PUT, KV.METADATA],\n          disableSubDelegation: params.disableSubDelegation ?? false,\n          expiry: expirationTime,\n          delegateDID: params.delegateDID,\n          ownerAddress: session.address,\n          chainId: session.chainId,\n          host: this.config.host,\n        };\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * Use a delegation received from another user.\n   *\n   * This creates a new session key for this user that chains from the\n   * received delegation, allowing operations on the delegator's space.\n   *\n   * Works in both modes:\n   * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key\n   * - **Session-only mode**: Uses the delegation directly (must target session key DID)\n   *\n   * @param delegation - The PortableDelegation to use (from createDelegation or transport)\n   * @returns A DelegatedAccess instance for performing operations\n   */\n  async useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess> {\n    const delegationHeader = delegation.delegationHeader;\n\n    // Use the host from the delegation if provided, otherwise fall back to config\n    const targetHost = delegation.host ?? this.config.host!;\n\n    // Session-only mode: use the delegation directly\n    // The delegation must target this user's session key DID\n    if (this.isSessionOnly) {\n      // Verify the delegation targets our session key DID\n      const myDid = this.did; // In session-only mode, this is the session key DID\n      if (!didPrincipalMatches(delegation.delegateDID, myDid)) {\n        throw new Error(\n          `Delegation targets ${delegation.delegateDID} but this user's DID is ${myDid}. ` +\n          `The delegation must target this user's DID.`\n        );\n      }\n\n      // Create a session using the delegation directly\n      // In session-only mode, we use the received delegation as-is\n      const session: TinyCloudSession = {\n        address: delegation.ownerAddress,\n        chainId: delegation.chainId,\n        sessionKey: JSON.stringify(this.sessionKeyJwk),\n        spaceId: delegation.spaceId,\n        delegationCid: delegation.cid,\n        delegationHeader,\n        verificationMethod: this.sessionDid,\n        jwk: this.sessionKeyJwk as unknown as JWK,\n        siwe: \"\", // Not used in session-only mode\n        signature: \"\", // Not used in session-only mode\n      };\n\n      // Track received delegation in registry\n      this.trackReceivedDelegation(delegation, this.sessionKeyJwk as unknown as JWK);\n      this.installRuntimeGrantFromServiceSession(\n        delegation,\n        {\n          delegationHeader: session.delegationHeader,\n          delegationCid: session.delegationCid,\n          spaceId: session.spaceId,\n          verificationMethod: session.verificationMethod,\n          jwk: session.jwk,\n        },\n        delegation.expiry,\n      );\n\n      return new DelegatedAccess(\n        session,\n        delegation,\n        targetHost,\n        this.wasmBindings.invoke,\n        this.wasmBindings.invokeAny,\n        this.config.telemetry,\n      );\n    }\n\n    // Wallet mode: create a SIWE sub-delegation\n    const mySession = this.auth?.tinyCloudSession;\n    if (!mySession) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Use our existing session key - the delegation targets our DID from signIn\n    // We must use the same key that the delegation was created for\n    const jwk = mySession.jwk;\n\n    // Build the activation abilities from the FULL resource set, not just\n    // the flat top-level path/actions. A multi-resource delegation (e.g.\n    // [{kv get vault/secrets/X}, {encryption decrypt <networkId>}]) carries\n    // every grant in `delegation.resources[]`; the flat `path`/`actions`\n    // mirror only the first resource. Building from the flat fields alone\n    // silently drops every other resource from the activated session.\n    const { abilities, rawAbilities } = this.buildActivationAbilities(delegation);\n\n    const now = new Date();\n    // Use delegation expiry or 1 hour, whichever is sooner\n    const maxExpiry = new Date(now.getTime() + 60 * 60 * 1000);\n    const expirationTime = delegation.expiry < maxExpiry ? delegation.expiry : maxExpiry;\n\n    // Prepare the session with:\n    // - THIS user's address (we are the invoker)\n    // - The delegation owner's space (where we're accessing data)\n    // - Our existing session key (must match the DID the delegation targets)\n    // - Parent reference to the received delegation\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(mySession.address),\n      chainId: mySession.chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: expirationTime.toISOString(),\n      spaceId: delegation.spaceId,\n      jwk,\n      parents: [delegation.cid],\n      ...(Object.keys(rawAbilities).length > 0 ? { rawAbilities } : {}),\n    });\n\n    // Sign with THIS user's signer\n    const signature = await this.signer!.signMessage(prepared.siwe);\n\n    // Complete the session setup\n    const invokerSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Activate with server\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      invokerSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate delegated session: ${activateResult.error}`);\n    }\n\n    // Create TinyCloudSession for the delegated access\n    const session: TinyCloudSession = {\n      address: mySession.address,\n      chainId: mySession.chainId,\n      sessionKey: mySession.sessionKey,\n      spaceId: delegation.spaceId,\n      delegationCid: invokerSession.delegationCid,\n      delegationHeader: invokerSession.delegationHeader,\n      verificationMethod: mySession.verificationMethod,\n      jwk,\n      siwe: prepared.siwe,\n      signature,\n    };\n\n    // Track received delegation in registry\n    this.trackReceivedDelegation(delegation, jwk as unknown as JWK);\n    this.installRuntimeGrantFromServiceSession(\n      delegation,\n      {\n        delegationHeader: session.delegationHeader,\n        delegationCid: session.delegationCid,\n        spaceId: session.spaceId,\n        verificationMethod: session.verificationMethod,\n        jwk: session.jwk,\n      },\n      expirationTime,\n    );\n\n    return new DelegatedAccess(\n      session,\n      delegation,\n      targetHost,\n      this.wasmBindings.invoke,\n      this.wasmBindings.invokeAny,\n      this.config.telemetry,\n    );\n  }\n\n  /**\n   * Create a sub-delegation from a received delegation.\n   *\n   * This allows further delegating access that was received from another user,\n   * if the original delegation allows sub-delegation.\n   *\n   * @param parentDelegation - The delegation received from another user\n   * @param params - Sub-delegation parameters (must be within parent's scope)\n   * @returns A portable delegation for the sub-delegate\n   */\n  async createSubDelegation(\n    parentDelegation: PortableDelegation,\n    params: {\n      /** Path within the delegated path to sub-delegate */\n      path: string;\n      /** Actions to allow (must be subset of parent's actions) */\n      actions: string[];\n      /** DID of the recipient */\n      delegateDID: string;\n      /** Whether to prevent the recipient from creating further sub-delegations */\n      disableSubDelegation?: boolean;\n      /** Expiration time in milliseconds from now (must be before parent's expiry) */\n      expiryMs?: number;\n    }\n  ): Promise<PortableDelegation> {\n    this.assertPortableDelegationCaveatsPreservable(parentDelegation);\n\n    if (!this.signer) {\n      throw new Error(\"Cannot createSubDelegation() in session-only mode. Requires wallet mode.\");\n    }\n    if (!this._address) {\n      throw new Error(\"Not signed in. Call signIn() first.\");\n    }\n\n    // Validate sub-delegation is allowed\n    if (parentDelegation.disableSubDelegation) {\n      throw new Error(\"Parent delegation does not allow sub-delegation\");\n    }\n\n    // Validate path is within parent's path\n    if (!params.path.startsWith(parentDelegation.path)) {\n      throw new Error(\n        `Sub-delegation path \"${params.path}\" must be within parent path \"${parentDelegation.path}\"`\n      );\n    }\n\n    // Validate actions are subset of parent's actions\n    const parentActions = new Set(parentDelegation.actions);\n    for (const action of params.actions) {\n      if (!parentActions.has(action)) {\n        throw new Error(\n          `Sub-delegation action \"${action}\" is not in parent's actions: ${parentDelegation.actions.join(\", \")}`\n        );\n      }\n    }\n\n    // Calculate expiry - cap at parent's expiry\n    const now = new Date();\n    const expiryMs = params.expiryMs ?? 60 * 60 * 1000;\n    const requestedExpiry = new Date(now.getTime() + expiryMs);\n    // Sub-delegation cannot outlive parent, so cap at parent's expiry\n    const actualExpiry =\n      requestedExpiry > parentDelegation.expiry ? parentDelegation.expiry : requestedExpiry;\n\n    // Build abilities for the sub-delegation\n    const abilities: Record<string, Record<string, string[]>> = {};\n    const kvActions = params.actions.filter(a => a.startsWith(\"tinycloud.kv/\"));\n    const sqlActions = params.actions.filter(a => a.startsWith(\"tinycloud.sql/\"));\n    const duckdbActions = params.actions.filter(a => a.startsWith(\"tinycloud.duckdb/\"));\n    if (kvActions.length > 0) {\n      abilities.kv = { [params.path]: kvActions };\n    }\n    if (sqlActions.length > 0) {\n      abilities.sql = { [params.path]: sqlActions };\n    }\n    if (duckdbActions.length > 0) {\n      abilities.duckdb = { [params.path]: duckdbActions };\n    }\n\n    // Use parent's host or fall back to config\n    const targetHost = parentDelegation.host ?? this.config.host!;\n\n    // Prepare the sub-delegation session\n    // Uses THIS user's address (who received the delegation and is now sub-delegating)\n    // Targets the recipient's PKH DID (delegateUri)\n    // References the parent delegation as the chain\n    const prepared = this.wasmBindings.prepareSession({\n      abilities,\n      address: this.wasmBindings.ensureEip55(this._address),\n      chainId: this._chainId,\n      domain: this.siweDomain,\n      issuedAt: now.toISOString(),\n      expirationTime: actualExpiry.toISOString(),\n      spaceId: parentDelegation.spaceId,\n      delegateUri: params.delegateDID,\n      parents: [parentDelegation.cid],\n    });\n\n    // Sign with THIS user's signer\n    const signature = await this.signer.signMessage(prepared.siwe);\n\n    // Complete the session setup\n    const subDelegationSession = this.wasmBindings.completeSessionSetup({\n      ...prepared,\n      signature,\n    });\n\n    // Activate the sub-delegation with the server\n    const activateResult = await activateSessionWithHost(\n      targetHost,\n      subDelegationSession.delegationHeader\n    );\n\n    if (!activateResult.success) {\n      throw new Error(`Failed to activate sub-delegation: ${activateResult.error}`);\n    }\n\n    // Return the portable sub-delegation\n    return {\n      cid: subDelegationSession.delegationCid,\n      delegationHeader: subDelegationSession.delegationHeader,\n      spaceId: parentDelegation.spaceId,\n      path: params.path,\n      actions: params.actions,\n      disableSubDelegation: params.disableSubDelegation ?? false,\n      expiry: actualExpiry,\n      delegateDID: params.delegateDID,\n      ownerAddress: parentDelegation.ownerAddress!,\n      chainId: parentDelegation.chainId!,\n      host: targetHost,\n    };\n  }\n}\n","export { AccountService } from \"@tinycloud/sdk-core\";\nexport type {\n  AccountApplication,\n  AccountApplicationListOptions,\n  AccountDelegation,\n  AccountDelegationListOptions,\n  AccountDelegationRevokeOptions,\n  AccountIndexEnsureResult,\n  AccountIndexRebuildResult,\n  AccountIndexStatus,\n  AccountIndexedReadOptions,\n  AccountServiceConfig,\n  AccountSpace,\n  AccountSpaceListOptions,\n  AccountStatus,\n} from \"@tinycloud/sdk-core\";\n","import {\n  TinyCloudSession,\n  KVService,\n  IKVService,\n  HooksService,\n  IHooksService,\n  SQLService,\n  ISQLService,\n  DuckDbService,\n  IDuckDbService,\n  ServiceSession,\n  ServiceContext,\n  type TelemetryConfig,\n} from \"@tinycloud/sdk-core\";\nimport type { InvokeFunction, InvokeAnyFunction } from \"@tinycloud/sdk-services\";\nimport { PortableDelegation } from \"./delegation\";\n\n/**\n * The handles needed to rehydrate this delegation activation in a fresh\n * `TinyCloudNode` via `TinyCloudNode.restoreSession(...)` in another process\n * or after a restart.\n *\n * In wallet mode, `delegationHeader` and `delegationCid` are bound to the\n * session key that ran `useDelegation`. They are NOT intrinsic to the\n * portable delegation — they expire with the server-side session (typically\n * ~1h). To keep a restored node alive longer, re-run `useDelegation` with\n * the original portable delegation and call `restoreSession` again with the\n * fresh `RestorableSession`.\n */\nexport interface RestorableSession {\n  delegationHeader: { Authorization: string };\n  delegationCid: string;\n  spaceId: string;\n  jwk: object;\n  verificationMethod: string;\n  address: string;\n  chainId: number;\n}\n\n/**\n * Provides access to a space via a received delegation.\n *\n * This is returned by TinyCloudNode.useDelegation() and provides\n * KV operations on the delegated space.\n */\nexport class DelegatedAccess {\n  private session: TinyCloudSession;\n  private _delegation: PortableDelegation;\n  private host: string;\n  private _serviceContext: ServiceContext;\n  private _kv: KVService;\n  private _sql: SQLService;\n  private _duckdb: DuckDbService;\n  private _hooks: HooksService;\n\n  constructor(\n    session: TinyCloudSession,\n    delegation: PortableDelegation,\n    host: string,\n    invoke: InvokeFunction,\n    invokeAny?: InvokeAnyFunction,\n    telemetry?: TelemetryConfig,\n  ) {\n    this.session = session;\n    this._delegation = delegation;\n    this.host = host;\n\n    // Create service context. invokeAny is required for SQL operations whose\n    // statements span multiple actions in a single invocation (e.g. the\n    // migration runner batches a CREATE TABLE (ddl) with the tracking-row\n    // INSERT (write)); without it those calls throw \"multi-resource\n    // invocations\" not supported.\n    this._serviceContext = new ServiceContext({\n      invoke,\n      invokeAny,\n      fetch: globalThis.fetch.bind(globalThis),\n      hosts: [host],\n      telemetry,\n    });\n\n    // Create and initialize KV service with path prefix from delegation\n    // Strip trailing slash to avoid double-slash in paths\n    const prefix = this._delegation.path.replace(/\\/$/, '');\n    this._kv = new KVService({ prefix });\n    this._kv.initialize(this._serviceContext);\n    this._serviceContext.registerService('kv', this._kv);\n\n    // Create and initialize SQL service with same delegation context\n    this._sql = new SQLService({});\n    this._sql.initialize(this._serviceContext);\n    this._serviceContext.registerService('sql', this._sql);\n\n    // Create and initialize DuckDB service with same delegation context\n    this._duckdb = new DuckDbService({});\n    this._duckdb.initialize(this._serviceContext);\n    this._serviceContext.registerService('duckdb', this._duckdb);\n\n    // Create and initialize Hooks service with same delegation context\n    this._hooks = new HooksService({});\n    this._hooks.initialize(this._serviceContext);\n    this._serviceContext.registerService('hooks', this._hooks);\n\n    // Set session on context\n    const serviceSession: ServiceSession = {\n      delegationHeader: session.delegationHeader,\n      delegationCid: session.delegationCid,\n      spaceId: session.spaceId,\n      verificationMethod: session.verificationMethod,\n      jwk: session.jwk,\n    };\n    this._serviceContext.setSession(serviceSession);\n  }\n\n  /**\n   * Get the delegation this access was created from.\n   */\n  get delegation(): PortableDelegation {\n    return this._delegation;\n  }\n\n  /**\n   * The space ID this access is for.\n   */\n  get spaceId(): string {\n    return this._delegation.spaceId;\n  }\n\n  /**\n   * The path this access is scoped to.\n   */\n  get path(): string {\n    return this._delegation.path;\n  }\n\n  /**\n   * KV operations on the delegated space.\n   */\n  get kv(): IKVService {\n    return this._kv;\n  }\n\n  /**\n   * SQL operations on the delegated space.\n   */\n  get sql(): ISQLService {\n    return this._sql;\n  }\n\n  /**\n   * DuckDB operations on the delegated space.\n   */\n  get duckdb(): IDuckDbService {\n    return this._duckdb;\n  }\n\n  /**\n   * Hooks write-stream subscriptions on the delegated space.\n   */\n  get hooks(): IHooksService {\n    return this._hooks;\n  }\n\n  /**\n   * Export the handles needed to rehydrate this activated delegation via\n   * `TinyCloudNode.restoreSession(...)` in another process or after a\n   * restart.\n   *\n   * See `RestorableSession` for lifetime caveats.\n   */\n  get restorable(): RestorableSession {\n    return {\n      delegationHeader: this.session.delegationHeader,\n      delegationCid: this.session.delegationCid,\n      spaceId: this.session.spaceId,\n      jwk: this.session.jwk,\n      verificationMethod: this.session.verificationMethod,\n      address: this.session.address,\n      chainId: this.session.chainId,\n    };\n  }\n}\n","/**\n * WasmKeyProvider - KeyProvider implementation using WASM session manager.\n *\n * This provider wraps the SessionManager from node-sdk-wasm to provide\n * cryptographic key operations required by the SharingService.\n *\n * @packageDocumentation\n */\n\nimport type { KeyProvider, JWK, ISessionManager } from \"@tinycloud/sdk-core\";\n\n/**\n * Extended session manager with optional key listing support.\n * The base ISessionManager doesn't include listSessionKeys(),\n * but concrete implementations (e.g., TCWSessionManager) may provide it.\n */\ninterface SessionManagerWithListing extends ISessionManager {\n  listSessionKeys?(): string[];\n}\n\n/**\n * Configuration for WasmKeyProvider.\n */\nexport interface WasmKeyProviderConfig {\n  /**\n   * The WASM session manager instance.\n   * Must be created before constructing the KeyProvider.\n   */\n  sessionManager: SessionManagerWithListing;\n}\n\n/**\n * KeyProvider implementation that wraps the WASM session manager.\n *\n * This allows the SharingService to create new session keys for sharing links\n * using the same cryptographic operations as the main session management.\n *\n * @example\n * ```typescript\n * // sessionManager from wasmBindings.createSessionManager()\n * import { WasmKeyProvider } from \"@tinycloud/node-sdk\";\n *\n * const sessionManager = new SessionManager();\n * const keyProvider = new WasmKeyProvider({ sessionManager });\n *\n * // Create a session key for a sharing link\n * const keyId = await keyProvider.createSessionKey(\"share:abc123\");\n * const jwk = keyProvider.getJWK(keyId);\n * const did = await keyProvider.getDID(keyId);\n * ```\n */\nexport class WasmKeyProvider implements KeyProvider {\n  private sessionManager: SessionManagerWithListing;\n\n  /**\n   * Create a new WasmKeyProvider.\n   *\n   * @param config - Configuration with the WASM session manager\n   */\n  constructor(config: WasmKeyProviderConfig) {\n    this.sessionManager = config.sessionManager;\n  }\n\n  /**\n   * Generate a new session key with the given name.\n   *\n   * This creates a new Ed25519 key pair in the WASM session manager.\n   * The key can then be used for signing delegations in sharing links.\n   *\n   * @param name - A unique name/ID for the key (e.g., \"share:timestamp:random\")\n   * @returns The key ID (same as the name provided)\n   */\n  async createSessionKey(name: string): Promise<string> {\n    // The WASM session manager's createSessionKey returns the key_id\n    // and stores the key internally\n    return this.sessionManager.createSessionKey(name);\n  }\n\n  /**\n   * Get the JWK (JSON Web Key) for a key.\n   *\n   * Returns the full JWK including the private key (d parameter),\n   * which is required for signing and for embedding in sharing links.\n   *\n   * @param keyId - The key ID to retrieve\n   * @returns The JWK object with public and private key components\n   * @throws Error if the key is not found\n   */\n  getJWK(keyId: string): JWK {\n    // The WASM session manager returns the JWK as a JSON string\n    const jwkJson = this.sessionManager.jwk(keyId);\n    if (!jwkJson) {\n      throw new Error(`Key not found: ${keyId}`);\n    }\n    // Parse the JSON string to get the JWK object\n    return JSON.parse(jwkJson) as JWK;\n  }\n\n  /**\n   * Get the DID (Decentralized Identifier) for a key.\n   *\n   * Returns the did:key format DID derived from the key's public key.\n   * This DID can be used as the delegatee in delegations.\n   *\n   * @param keyId - The key ID to retrieve\n   * @returns The DID in did:key format (e.g., \"did:key:z6Mk...\")\n   */\n  async getDID(keyId: string): Promise<string> {\n    // The WASM session manager has a synchronous getDID method\n    return this.sessionManager.getDID(keyId);\n  }\n\n  /**\n   * List all session keys currently held by the provider.\n   *\n   * @returns Array of key IDs\n   */\n  listKeys(): string[] {\n    const keys = this.sessionManager.listSessionKeys?.();\n    return Array.isArray(keys) ? keys : [];\n  }\n\n  /**\n   * Check if a key exists in the provider.\n   *\n   * @param keyId - The key ID to check\n   * @returns True if the key exists\n   */\n  hasKey(keyId: string): boolean {\n    const jwk = this.sessionManager.jwk(keyId);\n    return jwk !== undefined;\n  }\n}\n\n/**\n * Create a new WasmKeyProvider instance.\n *\n * @param sessionManager - The WASM session manager\n * @returns A new WasmKeyProvider instance\n */\nexport function createWasmKeyProvider(sessionManager: SessionManagerWithListing): WasmKeyProvider {\n  return new WasmKeyProvider({ sessionManager });\n}\n","/**\n * Internal helpers for TinyCloudNode.delegateTo and the legacy\n * createDelegation compatibility shim. Exported from their own module so\n * they are easy to unit-test without spinning up a full TinyCloudNode.\n *\n * None of these are part of the public API — the module path is not\n * re-exported from `@tinycloud/node-sdk` or `@tinycloud/node-sdk/core`.\n *\n * @packageDocumentation\n */\n\nimport {\n  type PermissionEntry,\n  parseExpiry,\n  SiweMessage,\n  EXPIRY,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * Convert legacy `createDelegation` params into one {@link PermissionEntry}\n * per service. Groups action URNs by their `tinycloud.<service>` prefix and\n * emits one entry per group. Actions whose prefix is not `tinycloud.*` are\n * dropped (preserving the wallet-path behaviour, which also ignores\n * unrecognised URN prefixes).\n *\n * Used by the legacy compatibility shim in `createDelegation` to hand off\n * to `delegateTo` on the fast (subset) path.\n */\nexport function legacyParamsToPermissionEntries(\n  actions: readonly string[],\n  path: string,\n  spaceIdOverride: string | undefined,\n): PermissionEntry[] {\n  const byService = new Map<string, string[]>();\n  for (const a of actions) {\n    // Action URNs look like `tinycloud.kv/get`, `tinycloud.sql/read`, etc.\n    // Split on the first `/` to get the service namespace.\n    const slashIdx = a.indexOf(\"/\");\n    if (slashIdx === -1) {\n      continue;\n    }\n    const service = a.slice(0, slashIdx);\n    if (!service.startsWith(\"tinycloud.\")) {\n      continue;\n    }\n    const list = byService.get(service);\n    if (list === undefined) {\n      byService.set(service, [a]);\n    } else {\n      list.push(a);\n    }\n  }\n  const space = spaceIdOverride ?? \"default\";\n  const entries: PermissionEntry[] = [];\n  for (const [service, actionList] of byService) {\n    entries.push({\n      service,\n      space,\n      path,\n      actions: actionList,\n    });\n  }\n  return entries;\n}\n\n/**\n * Default lifetime for a delegation when no explicit expiry is provided.\n * Sourced from the SESSION tier — runtime grants are always capped at the\n * parent session's expiry, so they can't usefully be longer than SESSION\n * even if a caller asks. See `@tinycloud/sdk-core/expiry.ts`.\n */\nexport const DEFAULT_DELEGATION_EXPIRY_MS = EXPIRY.SESSION_MS;\n\n/**\n * Resolve the `expiry` option of {@link DelegateToOptions} into a concrete\n * millisecond duration from now. Default is {@link DEFAULT_DELEGATION_EXPIRY_MS}\n * (7 days).\n *\n * Accepts:\n *  - `undefined` → {@link DEFAULT_DELEGATION_EXPIRY_MS}\n *  - `number` → raw milliseconds (must be positive + finite)\n *  - `string` → parsed via {@link parseExpiry} (ms-format, e.g. `\"7d\"`)\n */\nexport function resolveExpiryMs(expiry: string | number | undefined): number {\n  if (expiry === undefined) {\n    return DEFAULT_DELEGATION_EXPIRY_MS;\n  }\n  if (typeof expiry === \"number\") {\n    if (!Number.isFinite(expiry) || expiry <= 0) {\n      throw new Error(\n        `delegateTo expiry must be a positive finite number (got ${expiry})`,\n      );\n    }\n    return expiry;\n  }\n  // string — parseExpiry throws ManifestValidationError on bad input.\n  return parseExpiry(expiry);\n}\n\n/**\n * Extract the `expirationTime` field of a signed SIWE message as a `Date`.\n *\n * Returns `undefined` only when the SIWE genuinely has no `Expiration Time`\n * line (RFC-4501 permits it). Propagates parse errors — the SDK always\n * produces signed SIWEs during sign-in, so an unparseable `session.siwe`\n * means something is actively wrong and we do not want to silently skip\n * the expiry check.\n */\nexport function extractSiweExpiration(siwe: string): Date | undefined {\n  const parsed = new SiweMessage(siwe);\n  if (parsed.expirationTime === undefined || parsed.expirationTime === null) {\n    return undefined;\n  }\n  const d = new Date(parsed.expirationTime);\n  if (Number.isNaN(d.getTime())) {\n    throw new Error(\n      `Session SIWE has unparseable expirationTime: ${parsed.expirationTime}`,\n    );\n  }\n  return d;\n}\n","import {\n  ErrorCodes,\n  resolveSecretListPrefix,\n  resolveSecretPath,\n  expandPermissionEntries,\n  resolveManifest,\n  type IDataVaultService,\n  type ISecretsService,\n  type Manifest,\n  type PermissionEntry,\n  type Result,\n  type SecretScopeOptions,\n  type ServiceError,\n  type VaultError,\n} from \"@tinycloud/sdk-core\";\n\nconst SECRETS_SPACE = \"secrets\";\ntype SecretAction = \"get\" | \"put\" | \"del\" | \"list\";\n\nfunction ok(): Result<void, ServiceError> {\n  return { ok: true, data: undefined };\n}\n\nfunction secretsError(\n  code: string,\n  message: string,\n  cause?: Error,\n): Result<never, ServiceError> {\n  return {\n    ok: false,\n    error: {\n      code,\n      service: \"secrets\",\n      message,\n      ...(cause ? { cause } : {}),\n    },\n  };\n}\n\nfunction displayActionUrn(action: SecretAction): string {\n  switch (action) {\n    case \"get\":\n      return \"tinycloud.kv/get\";\n    case \"put\":\n      return \"tinycloud.kv/put\";\n    case \"del\":\n      return \"tinycloud.kv/del\";\n    case \"list\":\n      return \"tinycloud.kv/list\";\n  }\n}\n\nfunction secretActionName(action: SecretAction): \"get\" | \"put\" | \"del\" | \"list\" {\n  return action;\n}\n\nfunction secretPermissionEntries(\n  name: string,\n  options: SecretScopeOptions | undefined,\n  action: SecretAction,\n  space: string,\n  encryptionNetworkId?: string,\n): PermissionEntry[] {\n  const entries: PermissionEntry[] = [];\n  const path =\n    action === \"list\"\n      ? resolveSecretListPrefix(options)\n      : resolveSecretPath(name, options).permissionPaths.vault;\n\n  entries.push({\n    service: \"tinycloud.kv\",\n    space,\n    path,\n    actions: [secretActionName(action)],\n    skipPrefix: true,\n  });\n\n  if (action === \"get\" && encryptionNetworkId !== undefined) {\n    entries.push({\n      service: \"tinycloud.encryption\",\n      path: encryptionNetworkId,\n      actions: [\"decrypt\"],\n      skipPrefix: true,\n    });\n  }\n\n  return entries;\n}\n\nfunction normalizeSpace(space: string | undefined, resolveSpace?: (space: string) => string): string | undefined {\n  if (!space) return undefined;\n  if (space.startsWith(\"tinycloud:\")) return space;\n  return resolveSpace?.(space) ?? space;\n}\n\nfunction spaceMatches(\n  granted: string | undefined,\n  requested: string | undefined,\n  resolveSpace?: (space: string) => string,\n): boolean {\n  if (!granted || !requested) return false;\n  return normalizeSpace(granted, resolveSpace) === normalizeSpace(requested, resolveSpace);\n}\n\nexport interface NodeSecretsServiceConfig {\n  getService: () => ISecretsService;\n  space?: string;\n  getManifest: () => Manifest | Manifest[] | undefined;\n  hasPermissions?: (permissions: PermissionEntry[]) => boolean;\n  grantPermissions: (additional: PermissionEntry[]) => Promise<unknown>;\n  canEscalate: () => boolean;\n  getEncryptionNetworkId?: () => string;\n  resolveSpace?: (space: string) => string;\n  getUnlockSigner?: () => unknown;\n}\n\nexport class NodeSecretsService implements ISecretsService {\n  private unlockSigner?: unknown;\n  private shouldRestoreUnlock = false;\n\n  constructor(private readonly config: NodeSecretsServiceConfig) {}\n\n  private get space(): string {\n    return this.config.space ?? SECRETS_SPACE;\n  }\n\n  get vault(): IDataVaultService {\n    return this.service.vault;\n  }\n\n  get isUnlocked(): boolean {\n    return this.service.isUnlocked;\n  }\n\n  async unlock(signer?: unknown): Promise<Result<void, VaultError>> {\n    const effectiveSigner = signer ?? this.config.getUnlockSigner?.();\n    if (effectiveSigner !== undefined) {\n      this.unlockSigner = effectiveSigner;\n    }\n    const result = await this.service.unlock(effectiveSigner);\n    if (result.ok) {\n      this.shouldRestoreUnlock = true;\n    }\n    return result;\n  }\n\n  lock(): void {\n    this.shouldRestoreUnlock = false;\n    this.service.lock();\n  }\n\n  async get(name: string, options?: SecretScopeOptions): ReturnType<ISecretsService[\"get\"]> {\n    const permission = await this.ensurePermission(name, options, \"get\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.get(name)\n      : this.service.get(name, options);\n  }\n\n  async put(\n    name: string,\n    value: string,\n    options?: SecretScopeOptions,\n  ): ReturnType<ISecretsService[\"put\"]> {\n    const permission = await this.ensurePermission(name, options, \"put\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.put(name, value)\n      : this.service.put(name, value, options);\n  }\n\n  async delete(\n    name: string,\n    options?: SecretScopeOptions,\n  ): ReturnType<ISecretsService[\"delete\"]> {\n    const permission = await this.ensurePermission(name, options, \"del\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.delete(name)\n      : this.service.delete(name, options);\n  }\n\n  async list(options?: SecretScopeOptions): ReturnType<ISecretsService[\"list\"]> {\n    const permission = await this.ensurePermission(\"\", options, \"list\");\n    if (!permission.ok) return permission;\n    return options === undefined\n      ? this.service.list()\n      : this.service.list(options);\n  }\n\n  private get service(): ISecretsService {\n    return this.config.getService();\n  }\n\n  private async ensurePermission(\n    name: string,\n    options: SecretScopeOptions | undefined,\n    action: SecretAction,\n  ): Promise<Result<void, ServiceError | VaultError>> {\n    const target = name || \"secrets\";\n    let permissionEntries: PermissionEntry[];\n    try {\n      permissionEntries = secretPermissionEntries(\n        name,\n        options,\n        action,\n        this.space,\n        action === \"get\" ? this.config.getEncryptionNetworkId?.() : undefined,\n      );\n    } catch (error) {\n      return secretsError(\n        ErrorCodes.INVALID_INPUT,\n        error instanceof Error ? error.message : String(error),\n        error instanceof Error ? error : undefined,\n      );\n    }\n\n    if (this.hasPermission(permissionEntries)) {\n      return ok();\n    }\n\n    if (!this.config.canEscalate()) {\n      return secretsError(\n        ErrorCodes.PERMISSION_DENIED,\n        `Cannot autosign ${displayActionUrn(action)} for ${target}; TinyCloudNode needs wallet mode with a signer or privateKey.`,\n      );\n    }\n\n    try {\n      await this.config.grantPermissions(permissionEntries);\n      return this.restoreUnlockAfterEscalation();\n    } catch (error) {\n      return secretsError(\n        ErrorCodes.PERMISSION_DENIED,\n        error instanceof Error\n          ? error.message\n          : `Autosign escalation for ${displayActionUrn(action)} on ${target} failed.`,\n        error instanceof Error ? error : undefined,\n      );\n    }\n  }\n\n  private async restoreUnlockAfterEscalation(): Promise<\n    Result<void, ServiceError | VaultError>\n  > {\n    if (!this.shouldRestoreUnlock) {\n      return ok();\n    }\n    return this.service.unlock(this.unlockSigner);\n  }\n\n  private hasPermission(\n    permissionEntries: PermissionEntry[],\n  ): boolean {\n    if (this.config.hasPermissions?.(permissionEntries)) {\n      return true;\n    }\n\n    const manifest = this.config.getManifest();\n    if (manifest === undefined) {\n      return false;\n    }\n\n    const manifests = Array.isArray(manifest) ? manifest : [manifest];\n    const requestedEntries = expandPermissionEntries(permissionEntries);\n    return requestedEntries.every((entry) =>\n      manifests.some((candidate) => {\n        const resolved = resolveManifest(candidate);\n        return resolved.resources.some(\n          (resource) =>\n            resource.service === entry.service &&\n            spaceMatches(resource.space, entry.space, this.config.resolveSpace) &&\n            resource.path === entry.path &&\n            entry.actions.every((action) => resource.actions.includes(action)),\n        );\n      }),\n    );\n  }\n\n}\n","import {\n  canonicalizeRecapCaveats,\n  Delegation,\n  DelegatedResource,\n  PermissionEntry,\n  principalDidEquals,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * A portable delegation that can be transported between users.\n * Extends the base Delegation type with fields required for transport.\n *\n * @remarks\n * PortableDelegation adds transport fields to Delegation:\n * - `delegationHeader`: Structured authorization header for API calls\n * - `ownerAddress`: Space owner's address for session creation\n * - `chainId`: Chain ID for session creation\n * - `host`: Optional server URL\n * - `resources`: Multi-resource grant breakdown (present when the\n *   delegation was issued via the multi-resource WASM path, i.e. one\n *   UCAN covering multiple `(service, path, actions)` entries). The\n *   flat `path` + `actions` fields mirror the first entry for\n *   single-resource callers; consumers that need the full picture\n *   read `resources`.\n */\nexport interface PortableDelegation extends Omit<Delegation, \"isRevoked\"> {\n  /** The authorization header for this delegation (structured format) */\n  delegationHeader: { Authorization: string };\n\n  /** The address of the space owner */\n  ownerAddress: string;\n\n  /** The chain ID */\n  chainId: number;\n\n  /** TinyCloud server URL where this delegation was created */\n  host?: string;\n\n  /** Whether the recipient is prevented from creating sub-delegations */\n  disableSubDelegation?: boolean;\n\n  /** Companion delegation for the user's public space (auto-created when includePublicSpace is true) */\n  publicDelegation?: PortableDelegation;\n\n  /**\n   * Full multi-resource grant breakdown. Present when the delegation\n   * was issued via the multi-resource WASM path; each entry describes\n   * one `(service, space, path, actions)` grant carried by the single\n   * underlying UCAN. When absent, only the flat `path` + `actions`\n   * fields are authoritative (legacy single-resource shape).\n   */\n  resources?: DelegatedResource[];\n}\n\n/**\n * The transport shape `tc auth request --emit` produces and that an owner\n * grants to its requester. Only the fields the grant logic needs are declared;\n * the CLI artifact carries more (posture, captured command, ...) and remains a\n * structural superset of this interface.\n */\nexport interface AuthRequestArtifact {\n  kind: \"tinycloud.auth.request\";\n  version: 1;\n  requestId: string;\n  /** The requester's session DID — the audience the grant is issued to. */\n  sessionDid: string;\n  /** The capabilities the requester is asking the owner to delegate. */\n  requested: PermissionEntry[];\n  /** Optional lifetime override carried from the request. */\n  requestedExpiry?: string | number;\n}\n\n/**\n * The transport shape returned by {@link grantAuthRequest} (and written by\n * `tc auth grant`). `tc auth import` accepts this artifact directly.\n */\nexport interface AuthDelegationArtifact {\n  kind: \"tinycloud.auth.delegation\";\n  version: 1;\n  requestId: string;\n  delegationCid: string;\n  delegation: PortableDelegation;\n  permissions: PermissionEntry[];\n  expiry: string;\n  /** Whether issuing the delegation triggered a wallet prompt. */\n  prompted: boolean;\n}\n\n/**\n * Minimal owner-side capability {@link grantAuthRequest} needs: the signed\n * `delegateTo` primitive. `TinyCloudNode` satisfies this directly; web/SDK\n * contexts can supply any object that exposes the same method.\n */\nexport interface DelegationAuthority {\n  delegateTo(\n    did: string,\n    permissions: PermissionEntry[],\n    options?: { expiry?: string | number; forceWalletSign?: boolean },\n  ): Promise<{ delegation: PortableDelegation; prompted: boolean }>;\n}\n\n/**\n * Authority that the validated runtime-delegation activation helper needs.\n * `TinyCloudNode` implements this surface directly; keeping it structural\n * makes the helper usable by a compatible Node wrapper without exposing node\n * internals.\n */\nexport interface RuntimeDelegationActivator {\n  readonly sessionDid: string;\n  readonly did?: string;\n  readonly isSessionOnly?: boolean;\n  computeDelegationCid(authorization: string): string;\n  useRuntimeDelegation(delegation: PortableDelegation): Promise<void>;\n  useDelegation?(delegation: PortableDelegation): Promise<unknown>;\n  getRuntimePermissionDelegations(): PortableDelegation[];\n}\n\n/** The installed authority returned by {@link activateValidatedRuntimeDelegation}. */\nexport interface ValidatedRuntimeDelegation {\n  /** CID recomputed from the signed authorization bytes. */\n  readonly cid: string;\n  /** The authority object installed by the node runtime. */\n  readonly delegation: PortableDelegation;\n  /** Capabilities read from the signed compact UCAN attenuation. */\n  readonly effectivePermissions: readonly PermissionEntry[];\n  /** Expiry read from the signed compact UCAN payload. */\n  readonly expiry: Date;\n  /** Audience read from the signed compact UCAN payload. */\n  readonly audience: string;\n  /** Host selected for, and used by, the runtime activation. */\n  readonly host: string;\n}\n\ninterface SignedRuntimeAuthority {\n  readonly audience: string;\n  readonly expiry: Date;\n  readonly permissions: readonly PermissionEntry[];\n  readonly resources: readonly DelegatedResource[];\n}\n\nconst SERVICE_BY_SHORT_NAME: Record<string, string> = {\n  kv: \"tinycloud.kv\",\n  sql: \"tinycloud.sql\",\n  duckdb: \"tinycloud.duckdb\",\n  hooks: \"tinycloud.hooks\",\n};\n\nfunction authorizationWithoutBearer(authorization: string): string {\n  return authorization.replace(/^Bearer /i, \"\");\n}\n\nfunction normalizedHost(host: string): string {\n  if (typeof host !== \"string\" || host.length === 0) {\n    throw new Error(\"Validated runtime delegation requires a non-empty host.\");\n  }\n  return host.replace(/\\/+$/, \"\");\n}\n\nfunction didPrincipalsMatch(left: string, right: string): boolean {\n  try {\n    return principalDidEquals(left, right);\n  } catch {\n    return left === right;\n  }\n}\n\nfunction compactUcanPayload(authorization: string): Record<string, unknown> {\n  const compact = authorizationWithoutBearer(authorization);\n  const parts = compact.split(\".\");\n  if (parts.length !== 3 || parts.some((part) => part.length === 0)) {\n    throw new Error(\n      \"Validated runtime delegation requires a compact UCAN authorization so its signed authority can be derived.\",\n    );\n  }\n  try {\n    const payload = JSON.parse(\n      Buffer.from(parts[1]!, \"base64url\").toString(\"utf8\"),\n    ) as unknown;\n    if (payload === null || typeof payload !== \"object\" || Array.isArray(payload)) {\n      throw new Error(\"payload is not an object\");\n    }\n    return payload as Record<string, unknown>;\n  } catch {\n    throw new Error(\n      \"Validated runtime delegation authorization has an invalid compact UCAN payload.\",\n    );\n  }\n}\n\nfunction canonicalPermissionEntries(\n  permissions: PermissionEntry[],\n): PermissionEntry[] {\n  return permissions\n    .map((permission) => ({\n      ...permission,\n      actions: [...permission.actions].sort(),\n    }))\n    .sort((left, right) =>\n      left.service.localeCompare(right.service) ||\n      (left.space ?? \"\").localeCompare(right.space ?? \"\") ||\n      left.path.localeCompare(right.path) ||\n      left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")) ||\n      canonicalizeRecapCaveats(left.caveats).localeCompare(canonicalizeRecapCaveats(right.caveats)),\n    );\n}\n\nfunction signedCaveats(value: unknown): Record<string, unknown>[] | undefined {\n  if (!Array.isArray(value) || value.some((caveat) =>\n    caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n  )) {\n    throw new Error(\"Validated runtime delegation has malformed signed ReCap caveats.\");\n  }\n  const cloned = JSON.parse(JSON.stringify(value)) as Record<string, unknown>[];\n  return canonicalizeRecapCaveats(cloned) === canonicalizeRecapCaveats(undefined)\n    ? undefined\n    : cloned;\n}\n\nfunction groupedSignedEntries(\n  service: string,\n  space: string | undefined,\n  path: string,\n  abilities: Record<string, unknown>,\n): PermissionEntry[] {\n  const groups = new Map<string, { actions: string[]; caveats?: Record<string, unknown>[] }>();\n  for (const [action, rawCaveats] of Object.entries(abilities)) {\n    const caveats = signedCaveats(rawCaveats);\n    const identity = canonicalizeRecapCaveats(caveats);\n    const group = groups.get(identity) ?? { actions: [], caveats };\n    group.actions.push(action);\n    groups.set(identity, group);\n  }\n  return [...groups.values()].map((group) => ({\n    service,\n    ...(space === undefined ? {} : { space }),\n    path,\n    actions: group.actions.sort(),\n    ...(group.caveats === undefined ? {} : { caveats: group.caveats }),\n  }));\n}\n\nfunction signedAuthorityFromCompactUcan(\n  authorization: string,\n): SignedRuntimeAuthority {\n  const payload = compactUcanPayload(authorization);\n  if (typeof payload.aud !== \"string\" || payload.aud.length === 0) {\n    throw new Error(\"Validated runtime delegation is missing a signed audience.\");\n  }\n  if (typeof payload.exp !== \"number\" || !Number.isFinite(payload.exp)) {\n    throw new Error(\"Validated runtime delegation is missing a signed expiry.\");\n  }\n  const expiry = new Date(payload.exp * 1000);\n  if (Number.isNaN(expiry.getTime())) {\n    throw new Error(\"Validated runtime delegation has an invalid signed expiry.\");\n  }\n  if (payload.att === null || typeof payload.att !== \"object\" || Array.isArray(payload.att)) {\n    throw new Error(\"Validated runtime delegation is missing a signed attenuation.\");\n  }\n\n  const permissions: PermissionEntry[] = [];\n  for (const [resource, abilities] of Object.entries(payload.att)) {\n    if (abilities === null || typeof abilities !== \"object\" || Array.isArray(abilities)) {\n      throw new Error(\"Validated runtime delegation has an invalid signed attenuation.\");\n    }\n    const abilityEntries = Object.entries(abilities as Record<string, unknown>);\n    if (abilityEntries.length === 0) {\n      throw new Error(\"Validated runtime delegation has an empty signed capability.\");\n    }\n\n    if (resource.startsWith(\"urn:tinycloud:encryption:\")) {\n      permissions.push(...groupedSignedEntries(\n        \"tinycloud.encryption\",\n        undefined,\n        resource,\n        abilities as Record<string, unknown>,\n      ));\n      continue;\n    }\n\n    const match = /^(tinycloud:[^/]+)\\/(kv|sql|duckdb|hooks)\\/(.*)$/.exec(resource);\n    if (!match) {\n      throw new Error(\n        `Validated runtime delegation has an unsupported signed resource '${resource}'.`,\n      );\n    }\n    const [, space, shortService, path] = match;\n    const service = SERVICE_BY_SHORT_NAME[shortService!];\n    if (service === undefined) {\n      throw new Error(\n        `Validated runtime delegation has an unsupported signed service '${shortService}'.`,\n      );\n    }\n    permissions.push(...groupedSignedEntries(\n      service,\n      space!,\n      path!,\n      abilities as Record<string, unknown>,\n    ));\n  }\n\n  if (permissions.length === 0) {\n    throw new Error(\"Validated runtime delegation has no signed capabilities.\");\n  }\n  const canonicalPermissions = canonicalPermissionEntries(permissions);\n  const canonicalResources = canonicalPermissions.map((permission) => ({\n    service:\n      permission.service === \"tinycloud.encryption\"\n        ? \"encryption\"\n        : permission.service.slice(\"tinycloud.\".length),\n    space:\n      permission.service === \"tinycloud.encryption\"\n        ? \"encryption\"\n        : permission.space!,\n    path: permission.path,\n    actions: [...permission.actions],\n    ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n  }));\n  return {\n    audience: payload.aud,\n    expiry,\n    permissions: canonicalPermissions,\n    resources: canonicalResources,\n  };\n}\n\nfunction canonicalResourcesFromPortableDelegation(\n  delegation: PortableDelegation,\n): DelegatedResource[] {\n  if (delegation.resources !== undefined && delegation.resources.length > 0) {\n    return delegation.resources\n      .map((resource) => ({ ...resource, actions: [...resource.actions].sort() }))\n      .sort((left, right) =>\n        left.service.localeCompare(right.service) ||\n        left.space.localeCompare(right.space) ||\n        left.path.localeCompare(right.path) ||\n        left.actions.join(\"\\u0000\").localeCompare(right.actions.join(\"\\u0000\")) ||\n        canonicalizeRecapCaveats(left.caveats).localeCompare(canonicalizeRecapCaveats(right.caveats)),\n      );\n  }\n  const byService = new Map<string, string[]>();\n  for (const action of delegation.actions) {\n    const [service] = action.split(\"/\", 1);\n    const shortService = service!.replace(/^tinycloud\\./, \"\");\n    const values = byService.get(shortService) ?? [];\n    values.push(action);\n    byService.set(shortService, values);\n  }\n  return [...byService.entries()]\n    .map(([service, actions]) => ({\n      service,\n      space: service === \"encryption\" ? \"encryption\" : delegation.spaceId,\n      path: delegation.path,\n      actions: [...new Set(actions)].sort(),\n      ...(delegation.caveats === undefined ? {} : { caveats: delegation.caveats }),\n    }))\n    .sort((left, right) =>\n      left.service.localeCompare(right.service) ||\n      left.space.localeCompare(right.space) ||\n      left.path.localeCompare(right.path),\n    );\n}\n\nfunction resourcesMatch(\n  actual: readonly DelegatedResource[],\n  expected: readonly DelegatedResource[],\n): boolean {\n  const comparable = (resource: DelegatedResource) => ({\n    ...resource,\n    caveats: canonicalizeRecapCaveats(resource.caveats),\n  });\n  return JSON.stringify(actual.map(comparable)) === JSON.stringify(expected.map(comparable));\n}\n\n/**\n * CID-bind and activate one compact runtime delegation.\n *\n * The helper derives audience, expiry, and effective permissions from the\n * compact UCAN's signed payload, verifies the transport fields agree, then\n * invokes {@link TinyCloudNode.useRuntimeDelegation}. The node activation call\n * remains the authority and delegation-chain validation boundary.\n */\nexport async function activateValidatedRuntimeDelegation(\n  node: RuntimeDelegationActivator,\n  delegation: PortableDelegation,\n  options: { host: string },\n): Promise<ValidatedRuntimeDelegation> {\n  const host = normalizedHost(options.host);\n  if (delegation.host !== undefined && normalizedHost(delegation.host) !== host) {\n    throw new Error(\n      `Runtime delegation host '${delegation.host}' does not match expected host '${options.host}'.`,\n    );\n  }\n  if (!(delegation.expiry instanceof Date) || Number.isNaN(delegation.expiry.getTime())) {\n    throw new Error(\"Runtime delegation has an invalid expiry.\");\n  }\n  if (delegation.expiry.getTime() <= Date.now()) {\n    throw new Error(\"Runtime delegation is expired.\");\n  }\n\n  const authorization = delegation.delegationHeader?.Authorization;\n  if (typeof authorization !== \"string\" || authorization.length === 0) {\n    throw new Error(\"Runtime delegation is missing authorization bytes.\");\n  }\n  const cid = node.computeDelegationCid(authorization);\n  if (cid !== delegation.cid) {\n    throw new Error(\"Runtime delegation CID does not match authorization bytes.\");\n  }\n\n  const signed = signedAuthorityFromCompactUcan(authorization);\n  if (signed.expiry.getTime() <= Date.now()) {\n    throw new Error(\"Runtime delegation is expired.\");\n  }\n  if (delegation.expiry.getTime() !== signed.expiry.getTime()) {\n    throw new Error(\"Runtime delegation expiry does not match signed authority.\");\n  }\n  if (!didPrincipalsMatch(signed.audience, node.sessionDid)) {\n    throw new Error(\n      `Runtime delegation targets ${signed.audience} but this session is ${node.sessionDid}.`,\n    );\n  }\n  if (!didPrincipalsMatch(delegation.delegateDID, signed.audience)) {\n    throw new Error(\"Runtime delegation audience does not match signed authority.\");\n  }\n\n  const declaredResources = canonicalResourcesFromPortableDelegation(delegation);\n  if (!resourcesMatch(declaredResources, signed.resources)) {\n    throw new Error(\"Runtime delegation resources do not match signed authority.\");\n  }\n  const previouslyInstalled = node\n    .getRuntimePermissionDelegations()\n    .find((candidate) => candidate.cid === cid);\n  if (\n    previouslyInstalled !== undefined &&\n    previouslyInstalled.delegationHeader.Authorization !== authorization\n  ) {\n    throw new Error(\n      \"A different authorization is already installed for this runtime delegation CID.\",\n    );\n  }\n  const primary = signed.resources[0]!;\n  const signedSpace = signed.permissions.find(\n    (permission) => permission.service !== \"tinycloud.encryption\",\n  )?.space;\n  const installedCandidate: PortableDelegation = {\n    cid,\n    delegationHeader: { Authorization: authorization },\n    ownerAddress: delegation.ownerAddress,\n    chainId: delegation.chainId,\n    spaceId: signedSpace ?? delegation.spaceId,\n    path: primary.path,\n    actions: [...primary.actions],\n    ...(primary.caveats === undefined ? {} : { caveats: primary.caveats }),\n    resources: signed.resources.map((resource) => ({\n      ...resource,\n      actions: [...resource.actions],\n    })),\n    expiry: new Date(signed.expiry),\n    delegateDID: signed.audience,\n    host,\n  };\n\n  if (\n    node.isSessionOnly === true &&\n    typeof node.did === \"string\" &&\n    principalDidEquals(node.did, node.sessionDid) &&\n    typeof node.useDelegation === \"function\"\n  ) {\n    await node.useDelegation(installedCandidate);\n  } else {\n    await node.useRuntimeDelegation(installedCandidate);\n  }\n  const installed = node\n    .getRuntimePermissionDelegations()\n    .find((candidate) => candidate.cid === cid);\n  if (!installed) {\n    throw new Error(\"Runtime delegation activation did not install the validated authority.\");\n  }\n  if (\n    installed.delegationHeader.Authorization !== authorization ||\n    !didPrincipalsMatch(installed.delegateDID, signed.audience) ||\n    installed.expiry.getTime() !== signed.expiry.getTime() ||\n    !resourcesMatch(\n      canonicalResourcesFromPortableDelegation(installed),\n      signed.resources,\n    ) ||\n    normalizedHost(installed.host ?? \"\") !== host\n  ) {\n    throw new Error(\n      \"Runtime delegation activation installed authority that differs from the validated authority.\",\n    );\n  }\n\n  return {\n    cid,\n    delegation: installed,\n    effectivePermissions: signed.permissions,\n    expiry: new Date(signed.expiry),\n    audience: signed.audience,\n    host: normalizedHost(installed.host ?? host),\n  };\n}\n\n/**\n * Turn a delegation REQUEST into a signed GRANT.\n *\n * Lifts the body of `tc auth grant` into the SDK so the request→grant\n * handshake is callable programmatically (future SDK/web owner tooling and the\n * KV delegation inbox), with the CLI verb reduced to a thin wrapper. The owner\n * `authority` (a `TinyCloudNode`) signs a delegation scoped to exactly the\n * requested caps, audienced to the requester's `sessionDid`, honoring the\n * request's expiry. The returned artifact round-trips through `tc auth import`.\n *\n * Authorization is enforced cryptographically by `delegateTo`: caps that are\n * not derivable from the owner's own session capability chain are rejected\n * (it throws), so this never widens authority the owner doesn't hold.\n */\nexport async function grantAuthRequest(\n  authority: DelegationAuthority,\n  request: AuthRequestArtifact,\n  options?: { expiry?: string | number },\n): Promise<AuthDelegationArtifact> {\n  if (request.kind !== \"tinycloud.auth.request\") {\n    throw new Error(\n      `grantAuthRequest expects a tinycloud.auth.request artifact, got \"${request.kind}\".`,\n    );\n  }\n  if (!Array.isArray(request.requested) || request.requested.length === 0) {\n    throw new Error(\"grantAuthRequest request has no requested capabilities.\");\n  }\n\n  const expiry = options?.expiry ?? request.requestedExpiry;\n  const result = await authority.delegateTo(\n    request.sessionDid,\n    request.requested,\n    expiry !== undefined ? { expiry } : undefined,\n  );\n\n  return {\n    kind: \"tinycloud.auth.delegation\",\n    version: 1,\n    requestId: request.requestId,\n    delegationCid: result.delegation.cid,\n    delegation: result.delegation,\n    permissions: request.requested,\n    expiry: result.delegation.expiry.toISOString(),\n    prompted: result.prompted,\n  };\n}\n\n/**\n * Serialize a PortableDelegation for transport (e.g., over network).\n */\nexport function serializeDelegation(delegation: PortableDelegation): string {\n  return JSON.stringify({\n    ...delegation,\n    expiry: delegation.expiry.toISOString(),\n  });\n}\n\n/**\n * Deserialize a PortableDelegation from transport.\n */\nexport function deserializeDelegation(data: string): PortableDelegation {\n  const parsed = JSON.parse(data);\n  return {\n    ...parsed,\n    cid: parsed.cid,\n    expiry: new Date(parsed.expiry),\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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kB,qBAAqB;AAAA,MACvC,SAAS,iBAAiB;AAAA,MAC1B,MAAM,OAAO;AAAA,MACb,SAAS,OAAO;AAAA,MAChB,sBAAsB,OAAO,wBAAwB;AAAA,MACrD,QAAQ;AAAA,MACR,aAAa,OAAO;AAAA,MACpB,cAAc,iBAAiB;AAAA,MAC/B,SAAS,iBAAiB;AAAA,MAC1B,MAAM;AAAA,IACR;AAAA,EACF;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA/+Ka,eAu5Ha,kCAAkC;AAv5HrD,IAAM,gBAAN;;;ALpnBP,IAAAC,oBA+BO;;;AW5KP,IAAAC,mBAMO;AAkiBA,SAAS,oBAAoB,YAAwC;AAC1E,SAAO,KAAK,UAAU;AAAA,IACpB,GAAG;AAAA,IACH,QAAQ,WAAW,OAAO,YAAY;AAAA,EACxC,CAAC;AACH;AAKO,SAAS,sBAAsB,MAAkC;AACtE,QAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,SAAO;AAAA,IACL,GAAG;AAAA,IACH,KAAK,OAAO;AAAA,IACZ,QAAQ,IAAI,KAAK,OAAO,MAAM;AAAA,EAChC;AACF;;;AXrYA,IAAAC,oBAIO;AAaP,IAAAA,oBAAsD;AAmBtD,IAAAA,oBAIO;AAwBP,IAAAA,oBAUO;AAuBP,IAAAA,oBAKO;AAoCP,IAAAA,oBAIO;AAUP,IAAAA,oBAQO;AAcP,IAAAA,oBAKO;AAGP,IAAAA,oBAA+B;","names":["import_sdk_core","import_sdk_core","import_sdk_core","primarySpaceId","import_sdk_core","import_sdk_core","import_sdk_core","import_sdk_core","import_sdk_core","NETWORK_CREATE_ACTION","DECRYPT_ACTION","didPrincipalMatches","config","actions","host","now","delegation","spaceId","expandPermissionEntriesCore","session","import_sdk_core","import_sdk_core","import_sdk_core"]}