@namera-ai/cli 0.1.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +91 -221
  2. package/dist/index.js +1660 -0
  3. package/dist/index.js.map +1 -0
  4. package/package.json +57 -50
  5. package/LICENSE +0 -201
  6. package/dist/commands/index.mjs +0 -21
  7. package/dist/commands/index.mjs.map +0 -1
  8. package/dist/commands/keystore/create.mjs +0 -74
  9. package/dist/commands/keystore/create.mjs.map +0 -1
  10. package/dist/commands/keystore/decrypt.mjs +0 -71
  11. package/dist/commands/keystore/decrypt.mjs.map +0 -1
  12. package/dist/commands/keystore/import.mjs +0 -84
  13. package/dist/commands/keystore/import.mjs.map +0 -1
  14. package/dist/commands/keystore/index.mjs +0 -28
  15. package/dist/commands/keystore/index.mjs.map +0 -1
  16. package/dist/commands/keystore/info.mjs +0 -62
  17. package/dist/commands/keystore/info.mjs.map +0 -1
  18. package/dist/commands/keystore/list.mjs +0 -46
  19. package/dist/commands/keystore/list.mjs.map +0 -1
  20. package/dist/commands/keystore/remove.mjs +0 -51
  21. package/dist/commands/keystore/remove.mjs.map +0 -1
  22. package/dist/commands/mcp/index.mjs +0 -13
  23. package/dist/commands/mcp/index.mjs.map +0 -1
  24. package/dist/commands/mcp/start.mjs +0 -82
  25. package/dist/commands/mcp/start.mjs.map +0 -1
  26. package/dist/commands/schema/index.mjs +0 -53
  27. package/dist/commands/schema/index.mjs.map +0 -1
  28. package/dist/commands/session-key/create/index.mjs +0 -87
  29. package/dist/commands/session-key/create/index.mjs.map +0 -1
  30. package/dist/commands/session-key/create/prompts/base.mjs +0 -52
  31. package/dist/commands/session-key/create/prompts/base.mjs.map +0 -1
  32. package/dist/commands/session-key/create/prompts/call.mjs +0 -85
  33. package/dist/commands/session-key/create/prompts/call.mjs.map +0 -1
  34. package/dist/commands/session-key/create/prompts/common.mjs +0 -27
  35. package/dist/commands/session-key/create/prompts/common.mjs.map +0 -1
  36. package/dist/commands/session-key/create/prompts/gas.mjs +0 -19
  37. package/dist/commands/session-key/create/prompts/gas.mjs.map +0 -1
  38. package/dist/commands/session-key/create/prompts/index.mjs +0 -44
  39. package/dist/commands/session-key/create/prompts/index.mjs.map +0 -1
  40. package/dist/commands/session-key/create/prompts/rate-limit.mjs +0 -40
  41. package/dist/commands/session-key/create/prompts/rate-limit.mjs.map +0 -1
  42. package/dist/commands/session-key/create/prompts/signature-caller.mjs +0 -26
  43. package/dist/commands/session-key/create/prompts/signature-caller.mjs.map +0 -1
  44. package/dist/commands/session-key/create/prompts/timestamp.mjs +0 -32
  45. package/dist/commands/session-key/create/prompts/timestamp.mjs.map +0 -1
  46. package/dist/commands/session-key/index.mjs +0 -26
  47. package/dist/commands/session-key/index.mjs.map +0 -1
  48. package/dist/commands/session-key/info.mjs +0 -64
  49. package/dist/commands/session-key/info.mjs.map +0 -1
  50. package/dist/commands/session-key/list.mjs +0 -54
  51. package/dist/commands/session-key/list.mjs.map +0 -1
  52. package/dist/commands/session-key/remove.mjs +0 -51
  53. package/dist/commands/session-key/remove.mjs.map +0 -1
  54. package/dist/commands/session-key/status.mjs +0 -64
  55. package/dist/commands/session-key/status.mjs.map +0 -1
  56. package/dist/commands/smart-account/create.mjs +0 -94
  57. package/dist/commands/smart-account/create.mjs.map +0 -1
  58. package/dist/commands/smart-account/import.mjs +0 -45
  59. package/dist/commands/smart-account/import.mjs.map +0 -1
  60. package/dist/commands/smart-account/index.mjs +0 -30
  61. package/dist/commands/smart-account/index.mjs.map +0 -1
  62. package/dist/commands/smart-account/info.mjs +0 -66
  63. package/dist/commands/smart-account/info.mjs.map +0 -1
  64. package/dist/commands/smart-account/list.mjs +0 -48
  65. package/dist/commands/smart-account/list.mjs.map +0 -1
  66. package/dist/commands/smart-account/remove.mjs +0 -54
  67. package/dist/commands/smart-account/remove.mjs.map +0 -1
  68. package/dist/commands/smart-account/status.mjs +0 -63
  69. package/dist/commands/smart-account/status.mjs.map +0 -1
  70. package/dist/dto/index.mjs +0 -6
  71. package/dist/dto/keystore.mjs +0 -44
  72. package/dist/dto/keystore.mjs.map +0 -1
  73. package/dist/dto/mcp.mjs +0 -13
  74. package/dist/dto/mcp.mjs.map +0 -1
  75. package/dist/dto/session-key.mjs +0 -54
  76. package/dist/dto/session-key.mjs.map +0 -1
  77. package/dist/dto/smart-account.mjs +0 -45
  78. package/dist/dto/smart-account.mjs.map +0 -1
  79. package/dist/flags/global.mjs +0 -29
  80. package/dist/flags/global.mjs.map +0 -1
  81. package/dist/flags/shared.mjs +0 -11
  82. package/dist/flags/shared.mjs.map +0 -1
  83. package/dist/helpers/humanize.mjs +0 -153
  84. package/dist/helpers/humanize.mjs.map +0 -1
  85. package/dist/helpers/paths.mjs +0 -31
  86. package/dist/helpers/paths.mjs.map +0 -1
  87. package/dist/helpers/policy.mjs +0 -89
  88. package/dist/helpers/policy.mjs.map +0 -1
  89. package/dist/helpers/pretty.mjs +0 -71
  90. package/dist/helpers/pretty.mjs.map +0 -1
  91. package/dist/index.d.mts +0 -2
  92. package/dist/index.mjs +0 -36
  93. package/dist/index.mjs.map +0 -1
  94. package/dist/layers/config.mjs +0 -124
  95. package/dist/layers/config.mjs.map +0 -1
  96. package/dist/layers/index.mjs +0 -11
  97. package/dist/layers/keystore.mjs +0 -225
  98. package/dist/layers/keystore.mjs.map +0 -1
  99. package/dist/layers/mcp-context.mjs +0 -8
  100. package/dist/layers/mcp-context.mjs.map +0 -1
  101. package/dist/layers/mcp.mjs +0 -31
  102. package/dist/layers/mcp.mjs.map +0 -1
  103. package/dist/layers/output.mjs +0 -21
  104. package/dist/layers/output.mjs.map +0 -1
  105. package/dist/layers/prompt.mjs +0 -78
  106. package/dist/layers/prompt.mjs.map +0 -1
  107. package/dist/layers/session-key.mjs +0 -218
  108. package/dist/layers/session-key.mjs.map +0 -1
  109. package/dist/layers/smart-account.mjs +0 -175
  110. package/dist/layers/smart-account.mjs.map +0 -1
  111. package/dist/layers/web3.mjs +0 -83
  112. package/dist/layers/web3.mjs.map +0 -1
  113. package/dist/mcp/helpers/common.mjs +0 -9
  114. package/dist/mcp/helpers/common.mjs.map +0 -1
  115. package/dist/mcp/helpers/index.mjs +0 -4
  116. package/dist/mcp/helpers/session-key.mjs +0 -129
  117. package/dist/mcp/helpers/session-key.mjs.map +0 -1
  118. package/dist/mcp/index.mjs +0 -43
  119. package/dist/mcp/index.mjs.map +0 -1
  120. package/dist/mcp/mcp.mjs +0 -15
  121. package/dist/mcp/mcp.mjs.map +0 -1
  122. package/dist/mcp/tools/account/address.mjs +0 -20
  123. package/dist/mcp/tools/account/address.mjs.map +0 -1
  124. package/dist/mcp/tools/account/get-balance.mjs +0 -54
  125. package/dist/mcp/tools/account/get-balance.mjs.map +0 -1
  126. package/dist/mcp/tools/account/index.mjs +0 -15
  127. package/dist/mcp/tools/account/index.mjs.map +0 -1
  128. package/dist/mcp/tools/read/index.mjs +0 -11
  129. package/dist/mcp/tools/read/index.mjs.map +0 -1
  130. package/dist/mcp/tools/read/read-contract.mjs +0 -49
  131. package/dist/mcp/tools/read/read-contract.mjs.map +0 -1
  132. package/dist/mcp/tools/transaction/execute-transaction.mjs +0 -38
  133. package/dist/mcp/tools/transaction/execute-transaction.mjs.map +0 -1
  134. package/dist/mcp/tools/transaction/index.mjs +0 -15
  135. package/dist/mcp/tools/transaction/index.mjs.map +0 -1
  136. package/dist/mcp/tools/transaction/native-transfer.mjs +0 -59
  137. package/dist/mcp/tools/transaction/native-transfer.mjs.map +0 -1
  138. package/dist/schema/chain.mjs +0 -124
  139. package/dist/schema/chain.mjs.map +0 -1
  140. package/dist/schema/common.mjs +0 -29
  141. package/dist/schema/common.mjs.map +0 -1
  142. package/dist/schema/index.mjs +0 -5
  143. package/dist/schema/policy.mjs +0 -114
  144. package/dist/schema/policy.mjs.map +0 -1
  145. package/dist/schema/tx.mjs +0 -19
  146. package/dist/schema/tx.mjs.map +0 -1
  147. package/dist/types/index.mjs +0 -11
  148. package/dist/types/index.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["entry","metadata.version","status","list","list","get","SignRequest"],"sources":["../src/commands/common.ts","../src/services/config.ts","../src/services/credentials.ts","../src/services/oauth.ts","../src/services/session-keystore/resolver.ts","../src/services/session-keystore/storage.ts","../src/services/session-keystore/index.ts","../src/services/client.ts","../src/commands/root.ts","../src/services/output.ts","../src/services/output/document.ts","../src/services/output/auth.ts","../src/commands/auth/status.ts","../package.json","../src/version.ts","../src/commands/auth/login.ts","../src/commands/auth/logout.ts","../src/commands/auth/index.ts","../src/services/output/execution.ts","../src/services/prompts.ts","../src/commands/execution/index.ts","../src/services/mcp/oauth-contracts.ts","../src/services/mcp/api-client.ts","../src/services/mcp/credential-store.ts","../src/services/mcp/callback.ts","../src/services/mcp/oauth-upstream.ts","../src/services/mcp/session.ts","../src/services/mcp/tool-errors.ts","../src/services/mcp/tools.ts","../src/services/mcp/stdio.ts","../src/services/mcp/transport-security.ts","../src/commands/mcp/index.ts","../src/services/output/session-key.ts","../src/commands/session-key/import.ts","../src/commands/session-key/index.ts","../src/commands/sign.ts","../src/commands/verify-signature.ts","../src/services/output/wallet.ts","../src/commands/wallet/index.ts","../src/index.ts"],"sourcesContent":["import { Option, Schema, type Effect } from \"effect\";\nimport { Flag } from \"effect/unstable/cli\";\n\nexport const profileFlag = Flag.string(\"profile\").pipe(\n Flag.withDescription(\"CLI profile name\"),\n Flag.withDefault(\"personal\"),\n);\n\nexport const paramsFlag = Flag.string(\"params\").pipe(\n Flag.withDescription(\"Inline JSON command payload\"),\n Flag.optional,\n);\n\nexport const resolveParams = <S extends Schema.Top, E, R>(\n params: Option.Option<string>,\n schema: S,\n prompt: Effect.Effect<S[\"Type\"], E, R>,\n) =>\n Option.match(params, {\n onNone: () => prompt,\n onSome: (value) => Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(value),\n });\n","import { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport interface CliProfile {\n readonly baseUrl: string;\n readonly authorizationId?: string;\n readonly organizationId?: string;\n readonly organizationName?: string;\n}\n\nexport interface CliConfig {\n readonly activeProfile: string;\n readonly profiles: Readonly<Record<string, CliProfile>>;\n}\n\nconst configDirectory = () => {\n if (process.env.XDG_CONFIG_HOME) return join(process.env.XDG_CONFIG_HOME, \"namera\");\n if (process.platform === \"darwin\")\n return join(homedir(), \"Library\", \"Application Support\", \"namera\");\n if (process.platform === \"win32\") {\n return join(process.env.APPDATA ?? join(homedir(), \"AppData\", \"Roaming\"), \"Namera\");\n }\n return join(homedir(), \".config\", \"namera\");\n};\n\nexport const cliConfigPath = join(configDirectory(), \"config.json\");\nexport const cliLockPath = (profile: string) => join(configDirectory(), `${profile}.refresh.lock`);\n\nexport const readCliConfig = async (): Promise<CliConfig> => {\n try {\n return JSON.parse(await readFile(cliConfigPath, \"utf8\")) as CliConfig;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n return { activeProfile: \"personal\", profiles: {} };\n }\n};\n\nexport const writeCliConfig = async (config: CliConfig) => {\n await mkdir(dirname(cliConfigPath), { recursive: true, mode: 0o700 });\n const temporaryPath = `${cliConfigPath}.${process.pid}.tmp`;\n await writeFile(temporaryPath, `${JSON.stringify(config, null, 2)}\\n`, { mode: 0o600 });\n await rename(temporaryPath, cliConfigPath);\n};\n\nexport const getProfile = async (name?: string) => {\n const config = await readCliConfig();\n const profileName = name ?? config.activeProfile;\n const profile = config.profiles[profileName];\n if (profile === undefined) throw new Error(`Profile \"${profileName}\" is not logged in.`);\n return { config, profile, profileName };\n};\n\nexport const saveProfile = async (name: string, profile: CliProfile) => {\n const config = await readCliConfig();\n await writeCliConfig({\n activeProfile: name,\n profiles: { ...config.profiles, [name]: profile },\n });\n};\n\nexport const removeProfile = async (name: string) => {\n const config = await readCliConfig();\n const profiles = { ...config.profiles };\n delete profiles[name];\n await writeCliConfig({\n activeProfile:\n config.activeProfile === name\n ? (Object.keys(profiles)[0] ?? \"personal\")\n : config.activeProfile,\n profiles,\n });\n};\n","import { Entry } from \"@napi-rs/keyring\";\n\nexport interface CredentialBundle {\n readonly accessToken: string;\n readonly refreshToken: string | null;\n readonly expiresAt: number;\n readonly scopes: ReadonlyArray<string>;\n}\n\nconst entry = (profile: string) => new Entry(\"namera-cli\", profile);\n\nexport const readCredentials = (profile: string): CredentialBundle | undefined => {\n const value = entry(profile).getPassword();\n return value === null ? undefined : (JSON.parse(value) as CredentialBundle);\n};\n\nexport const writeCredentials = (profile: string, credentials: CredentialBundle) => {\n entry(profile).setPassword(JSON.stringify(credentials));\n};\n\nexport const deleteCredentials = (profile: string) => {\n try {\n entry(profile).deletePassword();\n } catch {\n // Keyring backends report a missing credential as an error; logout remains idempotent.\n }\n};\n","import { open, unlink } from \"node:fs/promises\";\n\nimport { cliLockPath } from \"./config.js\";\nimport { readCredentials, writeCredentials, type CredentialBundle } from \"./credentials.js\";\n\nconst clientId = \"namera-cli\";\nconst resourceScopes = [\n \"wallet:read\",\n \"session-key:read\",\n \"execution:read\",\n \"execution:execute\",\n \"signature:create\",\n \"offline_access\",\n] as const;\n\ninterface DeviceAuthorizationResponse {\n readonly device_code: string;\n readonly user_code: string;\n readonly verification_uri: string;\n readonly verification_uri_complete: string;\n readonly expires_in: number;\n readonly interval: number;\n}\n\ninterface TokenResponse {\n readonly access_token: string;\n readonly refresh_token?: string;\n readonly expires_in: number;\n readonly scope: string;\n}\n\nexport class OAuthRequestError extends Error {\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nconst postForm = async <A>(url: string, body: URLSearchParams): Promise<A> => {\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n const data = (await response.json()) as Record<string, unknown>;\n if (!response.ok) {\n throw new OAuthRequestError(\n typeof data.error === \"string\" ? data.error : \"oauth_error\",\n typeof data.error_description === \"string\" ? data.error_description : \"OAuth request failed\",\n );\n }\n return data as A;\n};\n\nexport const startDeviceAuthorization = (\n baseUrl: string,\n metadata: { readonly deviceName: string; readonly cliVersion: string; readonly platform: string },\n) =>\n postForm<DeviceAuthorizationResponse>(\n `${baseUrl}/oauth/device/authorize`,\n new URLSearchParams({\n client_id: clientId,\n scope: resourceScopes.join(\" \"),\n resource: new URL(baseUrl).origin,\n device_name: metadata.deviceName,\n cli_version: metadata.cliVersion,\n platform: metadata.platform,\n }),\n );\n\nconst toCredentials = (token: TokenResponse): CredentialBundle => ({\n accessToken: token.access_token,\n refreshToken: token.refresh_token ?? null,\n expiresAt: Date.now() + token.expires_in * 1_000,\n scopes: token.scope.split(/\\s+/).filter(Boolean),\n});\n\nexport const pollDeviceToken = async (baseUrl: string, deviceCode: string) => {\n const token = await postForm<TokenResponse>(\n `${baseUrl}/oauth/token`,\n new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n device_code: deviceCode,\n client_id: clientId,\n resource: new URL(baseUrl).origin,\n }),\n );\n return toCredentials(token);\n};\n\nconst acquireRefreshLock = async (profile: string) => {\n const path = cliLockPath(profile);\n for (let attempt = 0; attempt < 40; attempt += 1) {\n try {\n // Lock acquisition must be sequential so concurrent CLI processes cannot rotate one token.\n // oxlint-disable-next-line no-await-in-loop\n const handle = await open(path, \"wx\", 0o600);\n return async () => {\n await handle.close();\n await unlink(path).catch(() => undefined);\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n // oxlint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n throw new Error(\"Timed out waiting for another Namera command to refresh credentials.\");\n};\n\nexport const getValidAccessToken = async (profile: string, baseUrl: string) => {\n const release = await acquireRefreshLock(profile);\n try {\n const credentials = readCredentials(profile);\n if (credentials === undefined) throw new Error(`Profile \"${profile}\" is not logged in.`);\n if (credentials.expiresAt > Date.now() + 30_000) return credentials.accessToken;\n if (credentials.refreshToken === null)\n throw new Error(\"The CLI session expired. Run namera login.\");\n\n const token = await postForm<TokenResponse>(\n `${baseUrl}/oauth/token`,\n new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: credentials.refreshToken,\n client_id: clientId,\n resource: new URL(baseUrl).origin,\n }),\n );\n const refreshed = toCredentials(token);\n writeCredentials(profile, refreshed);\n return refreshed.accessToken;\n } finally {\n await release();\n }\n};\n","import { Redacted } from \"effect\";\n\nimport type { ResolveSessionSigner } from \"@namera-ai/sdk\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nimport type { createSessionKeystore } from \"./storage.js\";\n\nexport const makeSessionSignerResolver =\n (\n store: Pick<ReturnType<typeof createSessionKeystore>, \"readKey\">,\n apiOrigin: string,\n maxGasCostWei?: bigint,\n ): ResolveSessionSigner =>\n async (request) => {\n const material = await store.readKey(apiOrigin, request.sessionKeyId);\n const binding = material.bindings.find(\n (installation) =>\n installation.chainId === request.chainId && installation.walletId === request.walletId,\n );\n if (binding === undefined)\n throw new Error(\"No local installation for the selected wallet and chain.\");\n const account = privateKeyToAccount(Redacted.value(material.privateKey));\n return {\n binding,\n ...(maxGasCostWei === undefined ? {} : { maxGasCostWei }),\n signMessage: (message) => account.signMessage({ message }),\n signTypedData: (typedData) => account.signTypedData(typedData),\n };\n };\n","import { createHash, randomBytes, randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { chmod, link, lstat, mkdir, open, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { Redacted, Schema } from \"effect\";\n\nimport { SessionKeyId } from \"@namera-ai/protocol\";\nimport { EncryptedLocalSessionKey, type LocalSessionKeyMaterial } from \"@namera-ai/protocol/local\";\nimport { openLocalSessionKey, sealLocalSessionKey } from \"@namera-ai/sdk\";\n\nexport interface SessionKeyring {\n readonly get: (id: string) => string | null;\n readonly set: (id: string, secret: string) => void;\n readonly delete: (id: string) => void;\n}\n\nconst StoredSession = Schema.Struct({\n version: Schema.Literal(1),\n keyringId: Schema.String.check(Schema.isPattern(/^[0-9a-f-]{36}$/)),\n encrypted: EncryptedLocalSessionKey,\n});\n\nexport class SessionKeystoreError extends Schema.TaggedError<SessionKeystoreError>()(\n \"SessionKeystoreError\",\n {\n code: Schema.Literals([\n \"IMPORT_FAILED\",\n \"ORIGIN_MISMATCH\",\n \"READ_FAILED\",\n \"UNLOCK_UNAVAILABLE\",\n ]),\n },\n) {}\n\nexport const createSessionKeystore = (directory: string, keyring: SessionKeyring) => {\n const pathFor = (apiOrigin: string, sessionKeyId: SessionKeyId) => {\n const id = Schema.decodeUnknownSync(SessionKeyId)(sessionKeyId);\n const host = createHash(\"sha256\").update(apiOrigin).digest(\"hex\");\n return join(directory, `${host}-${id}.json`);\n };\n\n const importKey = async (\n input: unknown,\n password: Redacted.Redacted<string>,\n apiOrigin: string,\n ) => {\n const material = await openLocalSessionKey(input, password);\n if (material.apiOrigin !== apiOrigin)\n throw new SessionKeystoreError({ code: \"ORIGIN_MISMATCH\" });\n const binding = material.bindings[0];\n if (binding === undefined) throw new SessionKeystoreError({ code: \"IMPORT_FAILED\" });\n const keyringId = randomUUID();\n const unlockSecret = randomBytes(32).toString(\"base64url\");\n const encrypted = await sealLocalSessionKey(material, Redacted.make(unlockSecret));\n const temporaryPath = join(directory, `.${randomUUID()}.tmp`);\n let savedSecret = false;\n let temporaryCreated = false;\n let installed = false;\n let failed = false;\n try {\n await mkdir(directory, { recursive: true, mode: 0o700 });\n const directoryStat = await lstat(directory);\n if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink())\n throw new Error(\"Unsafe directory\");\n if (process.platform !== \"win32\") await chmod(directory, 0o700);\n keyring.set(keyringId, unlockSecret);\n savedSecret = true;\n const handle = await open(temporaryPath, \"wx\", 0o600);\n temporaryCreated = true;\n try {\n await handle.writeFile(JSON.stringify({ version: 1, keyringId, encrypted }));\n await handle.sync();\n } finally {\n await handle.close();\n }\n // Hard-link installation is atomic and refuses to overwrite an existing key.\n // The random keyring ID prevents a failed import from deleting its secret.\n await link(temporaryPath, pathFor(apiOrigin, binding.sessionKeyId));\n installed = true;\n } catch {\n failed = true;\n }\n\n // Attempt both cleanup steps even if one fails. Decide the result afterward,\n // rather than replacing a return or exception from inside a finally block.\n try {\n if (temporaryCreated) await unlink(temporaryPath);\n } catch {\n failed = true;\n }\n try {\n if (!installed && savedSecret) keyring.delete(keyringId);\n } catch {\n failed = true;\n }\n if (failed) throw new SessionKeystoreError({ code: \"IMPORT_FAILED\" });\n return {\n sessionKeyId: binding.sessionKeyId,\n walletId: binding.walletId,\n chains: material.bindings.map((entry) => entry.chainId),\n };\n };\n\n const readKey = async (\n apiOrigin: string,\n sessionKeyId: SessionKeyId,\n ): Promise<LocalSessionKeyMaterial> => {\n let record: typeof StoredSession.Type;\n try {\n const handle = await open(\n pathFor(apiOrigin, sessionKeyId),\n constants.O_RDONLY | constants.O_NOFOLLOW,\n );\n try {\n const stat = await handle.stat();\n if (\n !stat.isFile() ||\n stat.size > 128 * 1024 ||\n (process.platform !== \"win32\" && (stat.mode & 0o077) !== 0)\n )\n throw new Error(\"Unsafe keystore file\");\n record = Schema.decodeUnknownSync(StoredSession)(JSON.parse(await handle.readFile(\"utf8\")));\n } finally {\n await handle.close();\n }\n } catch {\n throw new SessionKeystoreError({ code: \"READ_FAILED\" });\n }\n let password: string | null;\n try {\n password = keyring.get(record.keyringId);\n } catch {\n throw new SessionKeystoreError({ code: \"UNLOCK_UNAVAILABLE\" });\n }\n if (password === null) throw new SessionKeystoreError({ code: \"UNLOCK_UNAVAILABLE\" });\n const material = await openLocalSessionKey(record.encrypted, Redacted.make(password));\n if (\n material.apiOrigin !== apiOrigin ||\n material.bindings.some((binding) => binding.sessionKeyId !== sessionKeyId)\n )\n throw new SessionKeystoreError({ code: \"ORIGIN_MISMATCH\" });\n return material;\n };\n\n return { importKey, readKey };\n};\n","import { dirname, join } from \"node:path\";\n\nimport type { ResolveSessionSigner } from \"@namera-ai/sdk\";\nimport { Entry } from \"@napi-rs/keyring\";\n\nimport { cliConfigPath } from \"../config.js\";\nimport { makeSessionSignerResolver } from \"./resolver.js\";\nimport { createSessionKeystore } from \"./storage.js\";\n\nconst entry = (id: string) => new Entry(\"namera-session-keystore\", id);\n\nexport const sessionKeystore = createSessionKeystore(join(dirname(cliConfigPath), \"session-keys\"), {\n get: (id) => entry(id).getPassword(),\n set: (id, secret) => entry(id).setPassword(secret),\n delete: (id) => entry(id).deletePassword(),\n});\n\nexport const resolveCliSessionSigner = (\n apiOrigin: string,\n maxGasCostWei?: bigint,\n): ResolveSessionSigner => makeSessionSignerResolver(sessionKeystore, apiOrigin, maxGasCostWei);\n","import { NAMERA_API_ORIGIN, NameraClient } from \"@namera-ai/sdk\";\n\nimport { getProfile } from \"./config.js\";\nimport { getValidAccessToken } from \"./oauth.js\";\nimport { resolveCliSessionSigner } from \"./session-keystore/index.js\";\n\nexport const makeCliClient = async (profile?: string, maxGasCostWei?: bigint) => {\n const apiKey = process.env.NAMERA_API_KEY;\n if (apiKey !== undefined) {\n const baseUrl = process.env.NAMERA_API_URL ?? NAMERA_API_ORIGIN;\n return {\n config: { activeProfile: \"automation\", profiles: {} },\n profile: { baseUrl },\n profileName: \"automation\",\n client: new NameraClient({\n apiKey,\n baseUrl,\n resolveSessionSigner: resolveCliSessionSigner(new URL(baseUrl).origin, maxGasCostWei),\n }),\n };\n }\n\n const resolved = await getProfile(profile);\n return {\n ...resolved,\n client: new NameraClient({\n baseUrl: resolved.profile.baseUrl,\n getAccessToken: () => getValidAccessToken(resolved.profileName, resolved.profile.baseUrl),\n resolveSessionSigner: resolveCliSessionSigner(\n new URL(resolved.profile.baseUrl).origin,\n maxGasCostWei,\n ),\n }),\n };\n};\n","import { Command, Flag } from \"effect/unstable/cli\";\n\nexport const outputFlag = Flag.choice(\"output\", [\"pretty\", \"json\", \"ndjson\"]).pipe(\n Flag.withAlias(\"o\"),\n Flag.withDescription(\"Output format\"),\n Flag.withDefault(\"pretty\"),\n);\n\nexport const quietFlag = Flag.boolean(\"quiet\").pipe(\n Flag.withAlias(\"q\"),\n Flag.withDescription(\"Suppress command output\"),\n);\n\nexport const nameraCommand = Command.make(\"namera\").pipe(\n Command.withSharedFlags({ output: outputFlag, quiet: quietFlag }),\n Command.withDescription(\"Manage Namera wallets through delegated session-key grants\"),\n);\n","import { Console, DateTime, Effect, Predicate } from \"effect\";\n\nimport type { NameraResult } from \"@namera-ai/sdk\";\n\nimport { nameraCommand } from \"#/commands/root\";\n\nimport type { PrettyPrinter } from \"./output/document.js\";\n\nexport type OutputFormat = \"pretty\" | \"json\" | \"ndjson\";\n\nconst replacer = (_: string, item: unknown) => (typeof item === \"bigint\" ? item.toString() : item);\n\nconst color = (code: number, value: string, enabled: boolean) =>\n enabled ? `\\u001B[${code}m${value}\\u001B[0m` : value;\n\nconst prettyScalar = (value: unknown, colors: boolean): string => {\n if (value === null) return color(90, \"null\", colors);\n if (value === undefined) return color(90, \"undefined\", colors);\n if (Predicate.isString(value)) return color(32, value, colors);\n if (Predicate.isNumber(value) || Predicate.isBigInt(value)) {\n return color(33, String(value), colors);\n }\n if (Predicate.isBoolean(value)) return color(35, String(value), colors);\n if (Predicate.isDate(value)) return color(32, value.toISOString(), colors);\n if (DateTime.isDateTime(value)) return color(32, DateTime.formatIso(value), colors);\n return color(32, String(value), colors);\n};\n\nconst prettyValue = (value: unknown, colors: boolean, depth = 0): string => {\n const indentation = \" \".repeat(depth);\n if (Array.isArray(value)) {\n if (value.length === 0) return `${indentation}${color(90, \"(none)\", colors)}`;\n return value\n .map(\n (item, index) =>\n `${indentation}${color(1, `${index + 1}.`, colors)}\\n${prettyValue(item, colors, depth + 1)}`,\n )\n .join(\"\\n\");\n }\n if (Predicate.isObject(value) && !Predicate.isDate(value) && !DateTime.isDateTime(value)) {\n const entries = Object.entries(value);\n if (entries.length === 0) return `${indentation}${color(90, \"(empty)\", colors)}`;\n return entries\n .map(([key, item]) => {\n const label = `${indentation}${color(36, key, colors)}:`;\n return Array.isArray(item) || Predicate.isObject(item)\n ? `${label}\\n${prettyValue(item, colors, depth + 1)}`\n : `${label} ${prettyScalar(item, colors)}`;\n })\n .join(\"\\n\");\n }\n return `${indentation}${prettyScalar(value, colors)}`;\n};\n\nexport const formatValue = <A>(\n value: A,\n output: OutputFormat,\n options: { readonly colors?: boolean; readonly pretty?: PrettyPrinter<A> } = {},\n): ReadonlyArray<string> => {\n if (output === \"pretty\")\n return [\n options.pretty\n ? options.pretty(value, options.colors ?? false)\n : prettyValue(value, options.colors ?? false),\n ];\n if (output === \"json\") return [JSON.stringify(value, replacer)];\n if (Array.isArray(value)) return value.map((item) => JSON.stringify(item, replacer));\n return [JSON.stringify(value, replacer)];\n};\n\nexport const printValue = Effect.fn(\"cli.output.printValue\")(function* <A>(\n value: A,\n pretty?: PrettyPrinter<A>,\n) {\n const { output, quiet } = yield* nameraCommand;\n if (quiet) return;\n const colors = output === \"pretty\" && process.stdout.isTTY && process.env.NO_COLOR === undefined;\n for (const line of formatValue(value, output, { colors, ...(pretty ? { pretty } : {}) }))\n yield* Console.log(line);\n});\n\nexport const printLine = Effect.fn(\"cli.output.printLine\")(function* (value: string) {\n const { quiet } = yield* nameraCommand;\n if (!quiet) yield* Console.log(value);\n});\n\nexport const unwrapResult = <A, E>(result: NameraResult<A, E>): Effect.Effect<A, Error> =>\n result.success\n ? Effect.succeed(result.data)\n : Effect.fail(\n new Error(\n result.error.kind === \"api\"\n ? result.error.code === undefined\n ? result.error.message\n : `${result.error.code}: ${result.error.message}`\n : result.error.message,\n ),\n );\n\nexport const runPromise = <A, E>(promise: Promise<NameraResult<A, E>>) =>\n Effect.tryPromise(() => promise).pipe(Effect.flatMap(unwrapResult));\n","import { stripVTControlCharacters } from \"node:util\";\n\nimport { DateTime, Predicate } from \"effect\";\n\nimport {\n arbitrum,\n arbitrumSepolia,\n base,\n baseSepolia,\n mainnet,\n optimism,\n optimismSepolia,\n sepolia,\n} from \"viem/chains\";\n\nexport type PrettyPrinter<A> = (value: A, colors: boolean) => string;\nexport type Field = readonly [label: string, value: unknown];\n\nconst networks = [\n arbitrum,\n arbitrumSepolia,\n base,\n baseSepolia,\n mainnet,\n optimism,\n optimismSepolia,\n sepolia,\n];\nexport const network = (chainId: string): string => {\n const chain = networks.find((entry) => `eip155:${entry.id}` === chainId);\n return chain ? `${chain.name} (${chainId})` : chainId;\n};\n\n// API metadata must not be able to clear the terminal or inject OSC hyperlinks.\nexport const terminalText = (value: string): string =>\n stripVTControlCharacters(value).replace(\n // oxlint-disable-next-line no-control-regex -- Neutralize terminal control characters in API metadata.\n /[\\u0000-\\u001f\\u007f-\\u009f\\u202a-\\u202e\\u2066-\\u2069]/g,\n \" \",\n );\n\nexport const heading = (value: string, colors: boolean): string =>\n colors ? `\\u001b[1m${terminalText(value)}\\u001b[0m` : terminalText(value);\n\nexport const humanize = (value: string): string => {\n const words = value.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/[-_]/g, \" \");\n return (words.charAt(0).toUpperCase() + words.slice(1))\n .replace(/\\bId\\b/g, \"ID\")\n .replace(/\\bApi\\b/g, \"API\");\n};\n\nexport const date = (value: DateTime.DateTime): string =>\n `${DateTime.format(value, {\n dateStyle: \"medium\",\n timeStyle: \"medium\",\n timeZone: \"UTC\",\n locale: \"en-GB\",\n })} UTC`;\n\nexport const timestamp = (seconds: number): string => date(DateTime.makeUnsafe(seconds * 1000));\n\nconst scalar = (value: unknown): string => {\n if (value === null || value === undefined) return \"None\";\n if (DateTime.isDateTime(value)) return date(value);\n if (Predicate.isDate(value)) return date(DateTime.makeUnsafe(value));\n if (typeof value === \"boolean\") return value ? \"Yes\" : \"No\";\n return terminalText(String(value));\n};\n\nconst nested = (value: unknown): boolean =>\n Predicate.isObject(value) && !DateTime.isDateTime(value) && !Predicate.isDate(value);\n\nexport const fields = (entries: readonly Field[], colors: boolean, indent = 2): string =>\n entries\n .filter(([, value]) => value !== undefined)\n .map(([label, value]) => {\n const prefix = \" \".repeat(indent) + heading(label + \":\", colors);\n if (Array.isArray(value)) {\n if (!value.length) return `${prefix} None`;\n if (value.every((entry) => !nested(entry)))\n return `${prefix} ${value.map(scalar).join(\", \")}`;\n return `${prefix}\\n${value\n .map((entry, index) => fields([[String(index + 1), entry]], colors, indent + 2))\n .join(\"\\n\")}`;\n }\n if (nested(value))\n return `${prefix}\\n${fields(\n Object.entries(value as object).map(([key, entry]) => [humanize(key), entry]),\n colors,\n indent + 2,\n )}`;\n return `${prefix} ${scalar(value)}`;\n })\n .join(\"\\n\");\n\nexport const section = (title: string, entries: readonly Field[], colors: boolean): string =>\n `${heading(title, colors)}\\n${fields(entries, colors)}`;\n\nexport const collection = <A>(\n values: readonly A[],\n singular: string,\n plural: string,\n render: PrettyPrinter<A>,\n colors: boolean,\n): string =>\n values.length === 0\n ? `No ${plural} found.`\n : `${heading(`Found ${values.length} ${values.length === 1 ? singular : plural}:`, colors)}\\n\\n${values.map((value) => render(value, colors)).join(\"\\n\\n\")}`;\n\nexport const named = (metadata: {\n readonly name: string;\n readonly logo?: { readonly type: string; readonly value: string } | null;\n}): string =>\n metadata.logo?.type === \"emoji\" ? `${metadata.logo.value} ${metadata.name}` : metadata.name;\n\nexport const recordView =\n (title: string): PrettyPrinter<object> =>\n (value, colors) =>\n section(\n title,\n Object.entries(value).map(([key, entry]) => [humanize(key), entry]),\n colors,\n );\n","import type { CurrentActorResponse } from \"@namera-ai/protocol/dto\";\n\nimport { humanize, section, type PrettyPrinter } from \"./document.js\";\n\nexport const authView: PrettyPrinter<{\n readonly profile: string;\n readonly actor: CurrentActorResponse;\n}> = ({ profile, actor }, colors) =>\n section(\n \"CLI authorization\",\n [\n [\"Profile\", profile],\n [\"Authenticated via\", actor.type === \"api-key\" ? \"API key\" : actor.type.toUpperCase()],\n [\n \"Organization ID\",\n actor.type === \"user\" ? actor.data.organization.id : actor.data.organizationId,\n ],\n ...(\"authorization\" in actor.data\n ? ([\n [\"Authorization ID\", actor.data.authorization.id],\n [\"Scopes\", actor.data.authorization.scopes],\n [\"Expires\", actor.data.authorization.expiresAt],\n ] as const)\n : []),\n ...(\"grants\" in actor.data\n ? ([\n [\n \"Granted session keys\",\n actor.data.grants.map(({ sessionKey }) => ({\n name: sessionKey.metadata.name,\n sessionKeyId: sessionKey.id,\n walletId: sessionKey.walletId,\n status: humanize(sessionKey.status),\n })),\n ],\n ] as const)\n : []),\n ],\n colors,\n );\n","import { Effect } from \"effect\";\nimport { Command } from \"effect/unstable/cli\";\n\nimport { profileFlag } from \"#/commands/common\";\nimport { makeCliClient } from \"#/services/client\";\nimport { printValue, runPromise } from \"#/services/output\";\nimport { authView } from \"#/services/output/auth\";\n\nexport const authStatusCommand = Command.make(\n \"status\",\n { profile: profileFlag },\n Effect.fn(function* ({ profile }) {\n const { client, profileName } = yield* Effect.tryPromise(() => makeCliClient(profile));\n const actor = yield* runPromise(client.auth.currentActor());\n yield* printValue({ profile: profileName, actor }, authView);\n }),\n).pipe(Command.withDescription(\"Show the current delegated CLI actor\"));\n","","import metadata from \"../package.json\" with { type: \"json\" };\n\nexport const version = metadata.version;\n","import { spawn } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\nimport { Effect } from \"effect\";\nimport { Command, Flag } from \"effect/unstable/cli\";\n\nimport { NAMERA_API_ORIGIN, NameraClient } from \"@namera-ai/sdk\";\n\nimport { profileFlag } from \"#/commands/common\";\nimport { saveProfile } from \"#/services/config\";\nimport { writeCredentials } from \"#/services/credentials\";\nimport { OAuthRequestError, pollDeviceToken, startDeviceAuthorization } from \"#/services/oauth\";\nimport { printLine, runPromise } from \"#/services/output\";\nimport { version } from \"#/version\";\n\nconst openBrowser = (url: string) => {\n const command =\n process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"cmd\" : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n spawn(command, args, { detached: true, stdio: \"ignore\" }).unref();\n};\n\nconst waitForToken = async (\n baseUrl: string,\n deviceCode: string,\n expiresIn: number,\n initialInterval: number,\n) => {\n const deadline = Date.now() + expiresIn * 1_000;\n let interval = initialInterval;\n while (Date.now() < deadline) {\n // RFC 8628 polling is deliberately sequential and observes the server-provided interval.\n // oxlint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setTimeout(resolve, interval * 1_000));\n try {\n // oxlint-disable-next-line no-await-in-loop\n return await pollDeviceToken(baseUrl, deviceCode);\n } catch (error) {\n if (!(error instanceof OAuthRequestError)) throw error;\n if (error.code === \"authorization_pending\") continue;\n if (error.code === \"slow_down\") {\n interval += 5;\n continue;\n }\n throw error;\n }\n }\n throw new Error(\"The device authorization expired. Run namera login again.\");\n};\n\nexport const loginCommand = Command.make(\n \"login\",\n {\n profile: profileFlag,\n host: Flag.string(\"host\").pipe(\n Flag.withDescription(\"Namera API origin\"),\n Flag.withDefault(NAMERA_API_ORIGIN),\n ),\n deviceName: Flag.string(\"device-name\").pipe(\n Flag.withDescription(\"Friendly name shown on the consent screen\"),\n Flag.withDefault(`Namera CLI on ${platform()}`),\n ),\n },\n Effect.fn(function* ({ profile, host, deviceName }) {\n const baseUrl = new URL(host).origin;\n const request = yield* Effect.tryPromise(() =>\n startDeviceAuthorization(baseUrl, {\n deviceName,\n cliVersion: version,\n platform: platform(),\n }),\n );\n\n yield* printLine(`Open ${request.verification_uri}`);\n yield* printLine(`Confirm code: ${request.user_code}`);\n yield* Effect.sync(() => openBrowser(request.verification_uri_complete));\n\n const credentials = yield* Effect.tryPromise(() =>\n waitForToken(baseUrl, request.device_code, request.expires_in, request.interval),\n );\n writeCredentials(profile, credentials);\n\n const actor = yield* runPromise(\n new NameraClient({ accessToken: credentials.accessToken, baseUrl }).auth.currentActor(),\n );\n if (actor.type !== \"cli\") return yield* Effect.fail(new Error(\"Expected a CLI actor token.\"));\n\n yield* Effect.tryPromise(() =>\n saveProfile(profile, {\n baseUrl,\n authorizationId: actor.data.authorization.id,\n organizationId: actor.data.organizationId,\n }),\n );\n yield* printLine(`Logged in as profile \"${profile}\".`);\n }),\n).pipe(Command.withDescription(\"Authorize this CLI using the browser device flow\"));\n","import { Effect } from \"effect\";\nimport { Command } from \"effect/unstable/cli\";\n\nimport { profileFlag } from \"#/commands/common\";\nimport { removeProfile } from \"#/services/config\";\nimport { deleteCredentials } from \"#/services/credentials\";\nimport { printLine } from \"#/services/output\";\n\nexport const logoutCommand = Command.make(\n \"logout\",\n { profile: profileFlag },\n Effect.fn(function* ({ profile }) {\n yield* Effect.sync(() => deleteCredentials(profile));\n yield* Effect.tryPromise(() => removeProfile(profile));\n yield* printLine(`Logged out profile \"${profile}\".`);\n }),\n).pipe(Command.withDescription(\"Remove a CLI profile and its stored credentials\"));\n","import { Command } from \"effect/unstable/cli\";\n\nimport { authStatusCommand } from \"./status.js\";\n\nexport const authCommand = Command.make(\"auth\").pipe(\n Command.withDescription(\"Inspect CLI authentication\"),\n Command.withSubcommands([authStatusCommand]),\n);\n\nexport * from \"./login.js\";\nexport * from \"./logout.js\";\n","import type {\n CompleteExecutionResponse,\n GetExecutionSubmissionResponse,\n ListExecutionsResponse,\n SimulateExecutionResponse,\n SignResponse,\n VerifySignatureResponse,\n} from \"@namera-ai/protocol/dto\";\n\nimport { collection, humanize, network, section, type PrettyPrinter } from \"./document.js\";\n\nexport const executionStatusView: PrettyPrinter<\n GetExecutionSubmissionResponse | CompleteExecutionResponse\n> = (result, colors) =>\n [\n section(\n `Execution ${humanize(result.status).toLowerCase()}`,\n [\n [\"Status\", humanize(result.status)],\n [\"Submission ID\", result.submissionId],\n [\n \"User operation\",\n \"userOperationHash\" in result ? (result.userOperationHash ?? undefined) : undefined,\n ],\n ...(result.status === \"confirmed\" && \"execution\" in result\n ? ([\n [\"Execution ID\", result.execution.id],\n [\"Network\", network(result.execution.data.chainId)],\n [\"Transaction\", result.execution.data.transactionHash],\n [\"Created\", result.execution.createdAt],\n ] as const)\n : []),\n ],\n colors,\n ),\n ...([\"reserved\", \"prepared\", \"submitted\"].includes(result.status)\n ? [`Not confirmed yet. Check again with:\\n namera execution status ${result.submissionId}`]\n : []),\n ].join(\"\\n\\n\");\n\nexport const executionsView: PrettyPrinter<ListExecutionsResponse> = (result, colors) =>\n [\n collection(\n result.items,\n \"confirmed execution\",\n \"confirmed executions\",\n (item, useColors) =>\n section(\n item.wallet.metadata.name,\n [\n [\"Execution ID\", item.details.id],\n [\"Network\", network(item.details.chainId)],\n [\"Transaction\", item.details.transactionHash],\n [\"Session key\", item.sessionKey.metadata.name],\n [\"Created\", item.details.createdAt],\n ],\n useColors,\n ),\n colors,\n ),\n ...(result.nextCursor\n ? [`Next page:\\n namera execution list --cursor ${result.nextCursor}`]\n : []),\n ].join(\"\\n\\n\");\n\nexport const simulationView: PrettyPrinter<SimulateExecutionResponse> = (result, colors) =>\n [\n section(\n \"Execution simulation\",\n [\n [\"Policy decision\", result.allowed ? \"Allowed\" : \"Denied\"],\n [\"Calls\", result.callsSucceeded ? \"Succeeded\" : \"Failed\"],\n [\"Wallet ID\", result.walletId],\n [\"Account\", result.account],\n [\"Network\", network(result.chainId)],\n [\"Session key ID\", result.allowed ? result.sessionKeyId : undefined],\n [\"Denials\", result.allowed ? undefined : result.denials],\n ],\n colors,\n ),\n section(\n \"Simulation details\",\n [\n [\"Gas estimate\", result.simulation.userOperation],\n [\"Calls\", result.simulation.calls],\n ],\n colors,\n ),\n \"Simulation only. No transaction was submitted.\",\n ].join(\"\\n\\n\");\n\nexport const signatureView: PrettyPrinter<SignResponse> = (result, colors) =>\n section(\n \"Signature created\",\n [\n [\"Type\", result.type === \"typed-data\" ? \"Typed data (EIP-712)\" : \"Message\"],\n [\"Account\", result.account],\n [\"Wallet ID\", result.walletId],\n [\"Network\", network(result.chainId)],\n [\"Signature\", result.signature],\n ],\n colors,\n );\n\nexport const verificationView: PrettyPrinter<VerifySignatureResponse> = (result, colors) =>\n section(\n result.valid ? \"Signature valid\" : \"Signature invalid\",\n [\n [\"Valid\", result.valid],\n [\"Account\", result.account],\n [\"Wallet ID\", result.walletId],\n [\"Network\", network(result.chainId)],\n [\"Type\", humanize(result.type)],\n ],\n colors,\n );\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport { Prompt } from \"effect/unstable/cli\";\n\nimport {\n EthereumAddress,\n EvmTypedData,\n Hex,\n SessionKeyId,\n SupportedEvmChainId,\n WalletId,\n} from \"@namera-ai/protocol\";\n\nconst schemaText = (message: string, schema: Schema.Decoder<unknown>, defaultValue?: string) =>\n Prompt.text({\n message,\n ...(defaultValue === undefined ? {} : { default: defaultValue }),\n validate: (value) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.as(value),\n Effect.mapError((error) => error.message),\n ),\n });\n\nconst makePrompts = () => ({\n namespace: Prompt.run(\n Prompt.select({\n message: \"Namespace\",\n choices: [\n { title: \"EVM\", description: \"Ethereum and EVM-compatible networks\", value: \"eip155\" },\n ],\n }),\n ),\n walletId: (message = \"Wallet ID\") =>\n Prompt.run(schemaText(message, WalletId)).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(WalletId)),\n ),\n chainId: (message = \"Chain\") =>\n Prompt.run(schemaText(message, SupportedEvmChainId, \"eip155:11155111\")).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(SupportedEvmChainId)),\n ),\n sessionKeyId: (message = \"Session key ID\") =>\n Prompt.run(schemaText(message, SessionKeyId)).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(SessionKeyId)),\n ),\n ethereumAddress: (message: string) =>\n Prompt.run(schemaText(message, EthereumAddress)).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(EthereumAddress)),\n ),\n ethereumValue: (message = \"Native value (wei)\") =>\n Prompt.run(\n schemaText(\n message,\n Schema.BigIntFromString.check(Schema.isGreaterThanOrEqualToBigInt(0n)),\n \"0\",\n ),\n ).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.BigIntFromString))),\n hex: (message: string, defaultValue = \"0x\") =>\n Prompt.run(schemaText(message, Hex, defaultValue)).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Hex)),\n ),\n integer: (message: string, options?: { readonly min?: number; readonly default?: number }) =>\n Prompt.run(Prompt.integer({ message, ...options })),\n confirm: (message: string, initial = false) => Prompt.run(Prompt.confirm({ message, initial })),\n signatureType: Prompt.run(\n Prompt.select({\n message: \"Signature type\",\n choices: [\n { title: \"Message\", description: \"Sign or verify a UTF-8 message\", value: \"message\" },\n {\n title: \"Typed data\",\n description: \"Sign or verify an EIP-712 typed-data object\",\n value: \"typed-data\",\n },\n ],\n }),\n ),\n message: (message = \"Message\") => Prompt.run(Prompt.text({ message })),\n typedData: Prompt.run(\n Prompt.text({\n message: \"EIP-712 typed data (JSON)\",\n validate: (value) =>\n Schema.decodeUnknownEffect(Schema.fromJsonString(EvmTypedData))(value).pipe(\n Effect.as(value),\n Effect.mapError((error) => error.message),\n ),\n }),\n ).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(EvmTypedData)))),\n date: (message: string) => Prompt.run(Prompt.date({ message })),\n});\n\nexport type CliPromptsService = ReturnType<typeof makePrompts>;\n\nexport class CliPrompts extends Context.Service<CliPrompts, CliPromptsService>()(\n \"@namera-ai/cli/CliPrompts\",\n) {\n static readonly layer = Layer.succeed(CliPrompts, CliPrompts.of(makePrompts()));\n}\n","import { Effect, Option, Schema } from \"effect\";\nimport { Argument, Command, Flag } from \"effect/unstable/cli\";\n\nimport { ExecutionId, ExecutionSubmissionId } from \"@namera-ai/protocol\";\nimport {\n ExecuteRequest,\n type ExecuteRequest as ExecuteRequestType,\n SimulateExecutionRequest,\n type SimulateExecutionRequest as SimulateExecutionRequestType,\n} from \"@namera-ai/protocol/dto\";\n\nimport { paramsFlag, profileFlag, resolveParams } from \"#/commands/common\";\nimport { makeCliClient } from \"#/services/client\";\nimport { printValue, runPromise } from \"#/services/output\";\nimport { executionStatusView, executionsView, simulationView } from \"#/services/output/execution\";\nimport { CliPrompts } from \"#/services/prompts\";\n\nconst promptTransactionRequest = Effect.fn(\"cli.execution.promptTransactionRequest\")(function* () {\n const prompts = yield* CliPrompts;\n const namespace = yield* prompts.namespace;\n const walletId = yield* prompts.walletId();\n const sessionKeyId = yield* prompts.sessionKeyId();\n const chainId = yield* prompts.chainId();\n const callCount = yield* prompts.integer(\"Number of calls\", { min: 1, default: 1 });\n const calls = yield* Effect.forEach(\n Array.from({ length: callCount }, (_, index) => index),\n (index) =>\n Effect.gen(function* () {\n const number = callCount === 1 ? \"\" : ` ${index + 1}`;\n return {\n to: yield* prompts.ethereumAddress(`Recipient${number}`),\n value: yield* prompts.ethereumValue(`Native value${number} (wei)`),\n data: yield* prompts.hex(`Calldata${number}`),\n };\n }),\n );\n\n return {\n namespace,\n walletId,\n sessionKeyId,\n chainId,\n calls,\n } satisfies SimulateExecutionRequestType;\n});\n\nconst promptExecutionRequest = Effect.fn(\"cli.execution.promptExecutionRequest\")(function* () {\n const prompts = yield* CliPrompts;\n const request = yield* promptTransactionRequest();\n const sponsor = yield* prompts.confirm(\"Sponsor gas with Namera?\", true);\n\n return { ...request, sponsor } satisfies ExecuteRequestType;\n});\n\nconst execute = Command.make(\n \"execute\",\n {\n params: paramsFlag,\n profile: profileFlag,\n maxGasCost: Flag.string(\"max-gas-cost-wei\").pipe(\n Flag.withDescription(\"Local fee ceiling for self-funded operations, in wei\"),\n Flag.optional,\n ),\n },\n Effect.fn(function* ({ params, profile, maxGasCost }) {\n const request = yield* resolveParams(params, ExecuteRequest, promptExecutionRequest());\n let maxGasCostWei: bigint | undefined;\n if (Option.isSome(maxGasCost)) {\n maxGasCostWei = yield* Schema.decodeUnknownEffect(\n Schema.BigIntFromString.check(Schema.isGreaterThanOrEqualToBigInt(0n)),\n )(maxGasCost.value);\n } else if (request.sponsor === false && Option.isNone(params)) {\n const prompts = yield* CliPrompts;\n maxGasCostWei = yield* prompts.ethereumValue(\"Maximum total gas cost (wei)\");\n }\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile, maxGasCostWei));\n yield* printValue(yield* runPromise(client.executions.execute(request)), executionStatusView);\n }),\n).pipe(Command.withDescription(\"Execute EVM calls after validating an inline or prompted request\"));\n\nconst simulate = Command.make(\n \"simulate\",\n { params: paramsFlag, profile: profileFlag },\n Effect.fn(function* ({ params, profile }) {\n const request = yield* resolveParams(\n params,\n SimulateExecutionRequest,\n promptTransactionRequest(),\n );\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(yield* runPromise(client.executions.simulate(request)), simulationView);\n }),\n).pipe(\n Command.withDescription(\n \"Simulate calls and evaluate session-key policies without signing or submitting\",\n ),\n);\n\nconst status = Command.make(\n \"status\",\n { submissionId: Argument.string(\"submission-id\"), profile: profileFlag },\n Effect.fn(function* ({ submissionId, profile }) {\n const id = yield* Schema.decodeUnknownEffect(ExecutionSubmissionId)(submissionId);\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(yield* runPromise(client.executions.getStatus(id)), executionStatusView);\n }),\n);\n\nconst list = Command.make(\n \"list\",\n {\n cursor: Flag.string(\"cursor\").pipe(Flag.optional),\n profile: profileFlag,\n },\n Effect.fn(function* ({ cursor, profile }) {\n const decodedCursor = Option.isSome(cursor)\n ? yield* Schema.decodeUnknownEffect(ExecutionId)(cursor.value)\n : undefined;\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(\n yield* runPromise(\n client.executions.list(decodedCursor === undefined ? {} : { cursor: decodedCursor }),\n ),\n executionsView,\n );\n }),\n);\n\nexport const executionCommand = Command.make(\"execution\").pipe(\n Command.withDescription(\"Execute and inspect onchain operations\"),\n Command.withSubcommands([execute, simulate, status, list]),\n);\n","import { Context, Schema } from \"effect\";\nimport type { Effect, Redacted } from \"effect\";\n\nexport class LocalOAuthError extends Schema.TaggedError<LocalOAuthError>()(\"LocalOAuthError\", {\n code: Schema.Literals([\"invalid_grant\", \"invalid_token\", \"temporarily_unavailable\"]),\n}) {}\n\nexport interface UpstreamCredentials {\n readonly accessToken: Redacted.Redacted<string>;\n readonly refreshToken?: Redacted.Redacted<string>;\n readonly expiresAt: number;\n readonly scopes: readonly string[];\n}\n\nexport class McpOAuthUpstream extends Context.Service<\n McpOAuthUpstream,\n {\n readonly register: (name: string) => Effect.Effect<string, LocalOAuthError>;\n readonly exchange: (input: {\n readonly clientId: string;\n readonly code: string;\n readonly verifier: Redacted.Redacted<string>;\n }) => Effect.Effect<UpstreamCredentials, LocalOAuthError>;\n readonly refresh: (input: {\n readonly clientId: string;\n readonly refreshToken: Redacted.Redacted<string>;\n readonly scopes: readonly string[];\n }) => Effect.Effect<UpstreamCredentials, LocalOAuthError>;\n readonly revoke: (\n clientId: string,\n token: Redacted.Redacted<string>,\n ) => Effect.Effect<void, LocalOAuthError>;\n }\n>()(\"@namera-ai/cli/McpOAuthUpstream\") {}\n","import { Context, Effect, Redacted } from \"effect\";\n\nimport type { McpActor } from \"@namera-ai/protocol/dto\";\nimport { NameraClient, type NameraFetch, type ResolveSessionSigner } from \"@namera-ai/sdk\";\n\nimport { LocalOAuthError } from \"./oauth-contracts.js\";\n\nexport interface LocalMcpPrincipal {\n readonly client: NameraClient;\n readonly actor: McpActor;\n readonly scopes: readonly string[];\n}\n\nexport class McpAuthentication extends Context.Service<\n McpAuthentication,\n {\n readonly principal: Effect.Effect<LocalMcpPrincipal, unknown>;\n }\n>()(\"@namera-ai/cli/McpAuthentication\") {}\n\nexport const makeMcpApiClient = Effect.fn(\"LocalMcpApi.authenticate\")(function* (\n config: {\n readonly apiOrigin: string;\n readonly fetch?: NameraFetch;\n readonly resolveSessionSigner?: ResolveSessionSigner;\n },\n authorization: {\n readonly accessToken: Redacted.Redacted<string>;\n readonly clientId: string;\n readonly scopes: readonly string[];\n },\n) {\n const resolveSigner = config.resolveSessionSigner;\n const client = new NameraClient({\n baseUrl: config.apiOrigin,\n accessToken: Redacted.value(authorization.accessToken),\n fetch: (input, init) => {\n const timeout = AbortSignal.timeout(30_000);\n return (config.fetch ?? globalThis.fetch)(input, {\n ...init,\n redirect: \"error\",\n signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout,\n });\n },\n ...(resolveSigner === undefined\n ? {}\n : {\n resolveSessionSigner: async (request) => {\n // Resolve no key material until the API has confirmed this exact grant.\n const permitted = actor.data.grants.some(\n ({ sessionKey }) =>\n sessionKey.id === request.sessionKeyId &&\n sessionKey.walletId === request.walletId &&\n sessionKey.namespace === request.namespace &&\n sessionKey.status === \"active\",\n );\n if (!permitted) throw new Error(\"The selected session is not authorized.\");\n return resolveSigner(request);\n },\n }),\n });\n const result = yield* Effect.tryPromise({\n try: () => client.auth.currentActor(),\n catch: () => new LocalOAuthError({ code: \"temporarily_unavailable\" }),\n });\n if (!result.success)\n return yield* new LocalOAuthError({\n code:\n result.error.status === 401 ||\n result.error.status === 403 ||\n (result.error.kind === \"api\" &&\n (result.error.tag === \"Unauthorized\" || result.error.tag === \"Forbidden\"))\n ? \"invalid_token\"\n : \"temporarily_unavailable\",\n });\n if (result.data.type !== \"mcp\") return yield* new LocalOAuthError({ code: \"invalid_token\" });\n const actor = result.data;\n // The actor contains the database client UUID, not OAuth's public client_id.\n // The API authenticates the bearer token and returns its bound authorization.\n const scopes = authorization.scopes.filter((scope) =>\n actor.data.authorization.scopes.some((allowed) => allowed === scope),\n );\n if (!scopes.includes(\"mcp:read\")) return yield* new LocalOAuthError({ code: \"invalid_token\" });\n return {\n client,\n actor,\n scopes,\n } satisfies LocalMcpPrincipal;\n});\n","import { createHash } from \"node:crypto\";\nimport { chmod, mkdir } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\n\nimport { Schema } from \"effect\";\n\nimport { Entry } from \"@napi-rs/keyring\";\n\nimport { cliConfigPath } from \"../config.js\";\n\nexport const McpProfile = Schema.String.check(Schema.isPattern(/^[a-zA-Z0-9_-]{1,64}$/));\nexport const McpCredential = Schema.Struct({\n version: Schema.Literal(1),\n generation: Schema.String,\n phase: Schema.Literals([\"ready\", \"refreshing\", \"authorizing\", \"signed-out\"]),\n clientId: Schema.String,\n accessToken: Schema.String,\n refreshToken: Schema.NullOr(Schema.String),\n expiresAt: Schema.Number,\n scopes: Schema.Array(Schema.Literals([\"mcp:read\", \"mcp:execute\", \"offline_access\"])),\n});\nexport type McpCredential = typeof McpCredential.Type;\n\nexport interface McpCredentialStore {\n readonly read: () => McpCredential | undefined;\n readonly write: (credentials: McpCredential) => void;\n readonly lock: <A>(run: () => Promise<A>) => Promise<A>;\n}\n\n// Refresh tokens rotate once. Every process must reread them under this lock.\nexport const withCredentialLock = async <A>(path: string, run: () => Promise<A>): Promise<A> => {\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n // SQLite's OS lock is released on process death. This database holds no\n // credentials or application rows, only a cross-process transaction lock.\n const database = new DatabaseSync(path);\n try {\n if (process.platform !== \"win32\") await chmod(path, 0o600);\n database.exec(\"PRAGMA busy_timeout = 0\");\n for (let attempt = 0; attempt < 200; attempt += 1) {\n try {\n database.exec(\"BEGIN IMMEDIATE\");\n } catch (error) {\n if ((error as { errcode?: number }).errcode !== 5) throw error;\n // oxlint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setTimeout(resolve, 100));\n continue;\n }\n try {\n // oxlint-disable-next-line no-await-in-loop\n return await run();\n } finally {\n database.exec(\"ROLLBACK\");\n }\n }\n throw new Error(\"Another Namera process is updating MCP credentials. Try again.\");\n } finally {\n database.close();\n }\n};\n\nexport const mcpCredentialStore = (apiOrigin: string, profile: string): McpCredentialStore => {\n Schema.decodeUnknownSync(McpProfile)(profile);\n const key = createHash(\"sha256\").update(`${apiOrigin}\\n${profile}`).digest(\"hex\");\n const entry = () => new Entry(\"namera-mcp\", key);\n return {\n read: () => {\n try {\n const raw = entry().getPassword();\n return raw === null\n ? undefined\n : Schema.decodeUnknownSync(Schema.fromJsonString(McpCredential))(raw);\n } catch {\n throw new Error(\"MCP credentials could not be read from the OS keyring.\");\n }\n },\n write: (credentials) => {\n try {\n entry().setPassword(JSON.stringify(credentials));\n } catch {\n throw new Error(\"MCP credentials could not be saved to the OS keyring.\");\n }\n },\n lock: (run) =>\n withCredentialLock(join(dirname(cliConfigPath), \"mcp\", `${key}.lock.sqlite`), run),\n };\n};\n","import { spawn } from \"node:child_process\";\nimport { timingSafeEqual } from \"node:crypto\";\nimport { createServer } from \"node:http\";\n\nexport const openAuthorizationBrowser = (url: string): Promise<void> =>\n new Promise((resolve, reject) => {\n const command =\n process.platform === \"darwin\"\n ? \"open\"\n : process.platform === \"win32\"\n ? \"rundll32\"\n : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"url.dll,FileProtocolHandler\", url] : [url];\n const child = spawn(command, args, { stdio: \"ignore\", timeout: 10_000 });\n child.once(\"error\", () => reject(new Error(\"Open the authorization URL in your browser.\")));\n child.once(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(\"Open the authorization URL in your browser.\"));\n });\n });\n\nexport const listenForAuthorization = async (state: string, signal: AbortSignal) => {\n let accept!: (code: string) => void;\n let deny!: (error: Error) => void;\n let consumed = false;\n const code = new Promise<string>((resolve, reject) => {\n accept = resolve;\n deny = reject;\n });\n // A cancellation can happen before the caller starts awaiting the callback.\n void code.catch(() => undefined);\n let authority = \"\";\n const server = createServer(\n { headersTimeout: 10_000, requestTimeout: 10_000 },\n (request, response) => {\n response.setHeader(\"Cache-Control\", \"no-store\");\n response.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n response.setHeader(\"Referrer-Policy\", \"no-referrer\");\n response.setHeader(\"Content-Security-Policy\", \"default-src 'none'; frame-ancestors 'none'\");\n const url = URL.parse(request.url ?? \"/\", `http://${authority}`);\n if (!url) {\n response.writeHead(400).end(\"Invalid authorization callback.\");\n return;\n }\n const received = url.searchParams.get(\"state\") ?? \"\";\n const params = [...url.searchParams.keys()];\n const receivedBytes = Buffer.from(received);\n const expectedBytes = Buffer.from(state);\n const validState =\n receivedBytes.length === expectedBytes.length &&\n timingSafeEqual(receivedBytes, expectedBytes);\n if (\n request.method !== \"GET\" ||\n request.headers.host !== authority ||\n url.origin !== `http://${authority}` ||\n request.headers.origin !== undefined ||\n (request.url?.length ?? 0) > 8192 ||\n url.pathname !== \"/oauth/callback\" ||\n consumed ||\n params.length !== new Set(params).size ||\n !validState ||\n url.searchParams.has(\"code\") === url.searchParams.has(\"error\")\n ) {\n response.writeHead(400).end(\"Invalid authorization callback.\");\n return;\n }\n consumed = true;\n const value = url.searchParams.get(\"code\");\n if (!value || value.length > 2048) {\n deny(new Error(\"Authorization was denied. Run namera mcp login to try again.\"));\n response.writeHead(400).end(\"Authorization was not completed. Return to Namera.\");\n } else {\n accept(value);\n response.end(\"Authorization received. You can close this tab and return to your agent.\");\n }\n },\n );\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", resolve);\n });\n const address = server.address();\n if (!address || typeof address === \"string\") throw new Error(\"Could not open OAuth callback.\");\n authority = `127.0.0.1:${address.port}`;\n const abort = () => {\n deny(new Error(\"Authorization cancelled.\"));\n server.closeAllConnections();\n server.close();\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) abort();\n return {\n callback: `http://${authority}/oauth/callback`,\n code,\n close: () => {\n signal.removeEventListener(\"abort\", abort);\n server.closeAllConnections();\n server.close();\n },\n };\n};\n","import { Clock, Effect, FileSystem, Layer, Redacted, Schema } from \"effect\";\nimport {\n FetchHttpClient,\n HttpClient,\n HttpClientRequest,\n HttpIncomingMessage,\n} from \"effect/unstable/http\";\n\nimport {\n OAuthDynamicClientRegistrationResponse,\n OAuthTokenResponse,\n} from \"@namera-ai/protocol/dto\";\n\nimport { LocalOAuthError, McpOAuthUpstream, type UpstreamCredentials } from \"./oauth-contracts.js\";\n\nexport const mcpOAuthUpstreamLayer = (config: {\n readonly callback: string;\n readonly apiOrigin: string;\n}) =>\n Layer.effect(\n McpOAuthUpstream,\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n const requestJson = Effect.fn(\"McpOAuthUpstream.request\")(\n function* (request: HttpClientRequest.HttpClientRequest) {\n const response = yield* client\n .execute(request)\n .pipe(Effect.mapError(() => new LocalOAuthError({ code: \"temporarily_unavailable\" })));\n if (response.status < 200 || response.status >= 300) {\n return yield* new LocalOAuthError({\n code:\n response.status >= 500 || response.status === 429\n ? \"temporarily_unavailable\"\n : \"invalid_grant\",\n });\n }\n return yield* response.json.pipe(\n Effect.mapError(() => new LocalOAuthError({ code: \"temporarily_unavailable\" })),\n );\n },\n Effect.provideService(FetchHttpClient.RequestInit, { redirect: \"error\" }),\n Effect.provideService(HttpIncomingMessage.MaxBodySize, FileSystem.KiB(32)),\n Effect.timeout(\"15 seconds\"),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(new LocalOAuthError({ code: \"temporarily_unavailable\" })),\n ),\n Effect.scoped,\n );\n\n const tokenRequest = Effect.fn(\"McpOAuthUpstream.token\")(function* (\n body: Record<string, string>,\n ) {\n const json = yield* requestJson(\n HttpClientRequest.post(`${config.apiOrigin}/oauth/token`).pipe(\n HttpClientRequest.bodyUrlParams({ ...body, resource: config.apiOrigin }),\n ),\n );\n const token = yield* Schema.decodeUnknownEffect(OAuthTokenResponse)(json).pipe(\n Effect.mapError(() => new LocalOAuthError({ code: \"temporarily_unavailable\" })),\n );\n const now = yield* Clock.currentTimeMillis;\n return {\n accessToken: Redacted.make(token.access_token),\n ...(token.refresh_token === undefined\n ? {}\n : { refreshToken: Redacted.make(token.refresh_token) }),\n expiresAt: now + token.expires_in * 1000,\n scopes: token.scope.split(/\\s+/).filter(Boolean),\n } satisfies UpstreamCredentials;\n });\n\n return McpOAuthUpstream.of({\n register: Effect.fn(\"McpOAuthUpstream.register\")(function* (name) {\n const json = yield* requestJson(\n HttpClientRequest.post(`${config.apiOrigin}/oauth/register`).pipe(\n HttpClientRequest.bodyJsonUnsafe({\n client_name: `Namera local MCP: ${name}`.slice(0, 128),\n redirect_uris: [config.callback],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n application_type: \"native\",\n }),\n ),\n );\n const registered = yield* Schema.decodeUnknownEffect(\n OAuthDynamicClientRegistrationResponse,\n )(json).pipe(\n Effect.mapError(() => new LocalOAuthError({ code: \"temporarily_unavailable\" })),\n );\n if (\n registered.redirect_uris.length !== 1 ||\n registered.redirect_uris[0] !== config.callback ||\n registered.token_endpoint_auth_method !== \"none\"\n ) {\n return yield* new LocalOAuthError({ code: \"temporarily_unavailable\" });\n }\n return registered.client_id;\n }),\n exchange: ({ clientId, code, verifier }) =>\n tokenRequest({\n grant_type: \"authorization_code\",\n client_id: clientId,\n redirect_uri: config.callback,\n code,\n code_verifier: Redacted.value(verifier),\n }),\n refresh: ({ clientId, refreshToken, scopes }) =>\n tokenRequest({\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: Redacted.value(refreshToken),\n scope: scopes.join(\" \"),\n }),\n revoke: Effect.fn(\"McpOAuthUpstream.revoke\")(\n function* (clientId, token) {\n // The revocation response is empty; do not attempt JSON decoding.\n const response = yield* client\n .execute(\n HttpClientRequest.post(`${config.apiOrigin}/oauth/revoke`).pipe(\n HttpClientRequest.bodyUrlParams({\n client_id: clientId,\n token: Redacted.value(token),\n }),\n ),\n )\n .pipe(\n Effect.mapError(() => new LocalOAuthError({ code: \"temporarily_unavailable\" })),\n );\n if (response.status < 200 || response.status >= 300)\n return yield* new LocalOAuthError({ code: \"temporarily_unavailable\" });\n },\n Effect.provideService(FetchHttpClient.RequestInit, { redirect: \"error\" }),\n Effect.timeout(\"15 seconds\"),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(new LocalOAuthError({ code: \"temporarily_unavailable\" })),\n ),\n Effect.scoped,\n ),\n });\n }),\n );\n","import { randomBytes, createHash, randomUUID } from \"node:crypto\";\n\nimport { Effect, Layer, Redacted, Schema } from \"effect\";\nimport { FetchHttpClient } from \"effect/unstable/http\";\n\nimport { listenForAuthorization, openAuthorizationBrowser } from \"./callback.js\";\nimport { type McpCredential, type McpCredentialStore } from \"./credential-store.js\";\nimport {\n type LocalOAuthError,\n McpOAuthUpstream,\n type UpstreamCredentials,\n} from \"./oauth-contracts.js\";\nimport { mcpOAuthUpstreamLayer } from \"./oauth-upstream.js\";\n\nexport interface McpOAuthProvider {\n register: (name: string) => Promise<string>;\n exchange: (clientId: string, code: string, verifier: string) => Promise<UpstreamCredentials>;\n refresh: (saved: McpCredential) => Promise<UpstreamCredentials>;\n revoke: (saved: McpCredential) => Promise<void>;\n}\n\nexport const mcpOAuthProvider = (apiOrigin: string, callback: string): McpOAuthProvider => {\n const layer = mcpOAuthUpstreamLayer({ apiOrigin, callback }).pipe(\n Layer.provide(FetchHttpClient.layer),\n );\n const run = <A>(\n call: (provider: McpOAuthUpstream[\"Service\"]) => Effect.Effect<A, LocalOAuthError>,\n ) => Effect.runPromise(Effect.flatMap(McpOAuthUpstream, call).pipe(Effect.provide(layer)));\n return {\n register: (name) => run((provider) => provider.register(name)),\n exchange: (clientId, code, verifier) =>\n run((provider) => provider.exchange({ clientId, code, verifier: Redacted.make(verifier) })),\n refresh: (saved) =>\n run((provider) =>\n provider.refresh({\n clientId: saved.clientId,\n refreshToken: Redacted.make(saved.refreshToken ?? \"\"),\n scopes: saved.scopes,\n }),\n ),\n revoke: (saved) =>\n run((provider) =>\n provider.revoke(saved.clientId, Redacted.make(saved.refreshToken ?? saved.accessToken)),\n ),\n };\n};\n\nconst scopeSchema = Schema.Array(Schema.Literals([\"mcp:read\", \"mcp:execute\", \"offline_access\"]));\nconst ready = (generation: string, clientId: string, token: UpstreamCredentials): McpCredential => {\n const scopes = Schema.decodeUnknownSync(scopeSchema)(token.scopes);\n if (!scopes.includes(\"mcp:read\")) throw new Error(\"MCP read permission was not granted.\");\n return {\n version: 1,\n generation,\n phase: \"ready\",\n clientId,\n accessToken: Redacted.value(token.accessToken),\n refreshToken: token.refreshToken ? Redacted.value(token.refreshToken) : null,\n expiresAt: token.expiresAt,\n scopes,\n };\n};\nconst signedOut = (): McpCredential => ({\n version: 1,\n generation: randomUUID(),\n phase: \"signed-out\",\n clientId: \"\",\n accessToken: \"\",\n refreshToken: null,\n expiresAt: 0,\n scopes: [],\n});\n\nexport const createMcpSession = (config: {\n apiOrigin: string;\n profile: string;\n store: McpCredentialStore;\n provider?: (callback: string) => McpOAuthProvider;\n openBrowser?: (url: string) => Promise<void>;\n notify?: (message: string) => void;\n now?: () => number;\n}) => {\n const { store } = config;\n const provider = config.provider ?? ((callback) => mcpOAuthProvider(config.apiOrigin, callback));\n const now = config.now ?? Date.now;\n const notify = config.notify ?? ((message) => process.stderr.write(`${message}\\n`));\n let attempted = false;\n let pending: Promise<void> | undefined;\n const lifetime = new AbortController();\n\n const login = async () => {\n const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(5 * 60_000)]);\n const state = randomBytes(32).toString(\"base64url\");\n const verifier = randomBytes(32).toString(\"base64url\");\n const generation = randomUUID();\n await store.lock(async () => {\n const previous = store.read();\n if (previous?.accessToken) await provider(\"\").revoke(previous);\n store.write({ ...signedOut(), generation, phase: \"authorizing\" });\n });\n const callback = await listenForAuthorization(state, signal);\n try {\n const oauth = provider(callback.callback);\n const clientId = await oauth.register(config.profile);\n const url = new URL(\"/oauth/authorize\", config.apiOrigin);\n url.search = new URLSearchParams({\n client_id: clientId,\n redirect_uri: callback.callback,\n resource: config.apiOrigin,\n response_type: \"code\",\n code_challenge_method: \"S256\",\n code_challenge: createHash(\"sha256\").update(verifier).digest(\"base64url\"),\n scope: \"mcp:read mcp:execute offline_access\",\n state,\n }).toString();\n notify(`Authorize Namera (${config.profile}): ${url}`);\n try {\n await (config.openBrowser ?? openAuthorizationBrowser)(url.toString());\n } catch {\n notify(\"Could not open your browser. Open the URL above manually.\");\n }\n const code = await callback.code;\n signal.throwIfAborted();\n const token = await oauth.exchange(clientId, code, verifier);\n const saved = ready(generation, clientId, token);\n try {\n await store.lock(async () => {\n if (signal.aborted || store.read()?.generation !== generation) {\n throw new Error(\"Authorization was cancelled or replaced.\");\n }\n store.write(saved);\n });\n } catch (error) {\n await oauth.revoke(saved);\n throw error;\n }\n notify(`Namera MCP profile \"${config.profile}\" is connected.`);\n } finally {\n callback.close();\n }\n };\n\n const startLogin = () => {\n if (!pending) {\n attempted = true;\n pending = login().finally(() => {\n pending = undefined;\n });\n }\n return pending;\n };\n\n const credentials = () =>\n store.lock(async () => {\n const saved = store.read();\n if (saved?.phase !== \"ready\") return undefined;\n if (saved.expiresAt > now() + 30_000) return saved;\n if (!saved.refreshToken) return undefined;\n // Persist before consuming a rotating token. A crash or ambiguous failure\n // requires fresh consent instead of replaying the old refresh token.\n store.write({ ...saved, phase: \"refreshing\" });\n const token = await provider(\"\").refresh(saved);\n if (\n token.scopes.some((scope) => !saved.scopes.includes(scope as (typeof saved.scopes)[number]))\n )\n throw new Error(\"Refreshed MCP permissions expanded unexpectedly.\");\n const refreshed = ready(saved.generation, saved.clientId, token);\n store.write(refreshed);\n return refreshed;\n });\n\n return {\n login: startLogin,\n credentials,\n requestLogin: () => {\n if (!attempted)\n void startLogin().catch(() =>\n notify(\n `MCP login did not finish. Run namera mcp login --profile ${config.profile} --host ${config.apiOrigin}`,\n ),\n );\n },\n status: () => {\n const saved = store.read();\n return {\n profile: config.profile,\n apiOrigin: config.apiOrigin,\n status:\n saved?.phase === \"ready\"\n ? saved.expiresAt > now()\n ? \"connected\"\n : saved.refreshToken\n ? \"refresh-required\"\n : \"login-required\"\n : \"login-required\",\n scopes: saved?.phase === \"ready\" ? saved.scopes : [],\n };\n },\n logout: () =>\n store.lock(async () => {\n const saved = store.read();\n // Discard local authority even if remote revocation fails; retain no token\n // that another MCP process could continue to use after logout.\n store.write(signedOut());\n if (saved?.accessToken) await provider(\"\").revoke(saved);\n }),\n close: () => lifetime.abort(),\n };\n};\n","import { Effect, Predicate, Schema } from \"effect\";\nimport { McpSchema } from \"effect/unstable/ai\";\n\nimport { McpToolError, McpToolErrorCode } from \"@namera-ai/protocol/dto\";\nimport type { NameraResult } from \"@namera-ai/sdk\";\n\nconst messages: Readonly<Record<McpToolErrorCode, string>> = {\n NETWORK_PAUSED: \"New operations on this network are paused. Do not retry until it is re-enabled.\",\n INVALID_ARGUMENT: \"Invalid tool input. Use returned IDs and the documented field formats.\",\n UNAUTHORIZED: \"The authorization expired or was revoked. Reconnect Namera.\",\n INSUFFICIENT_SCOPE: \"Reauthorize Namera with permission to execute and sign.\",\n WALLET_NOT_FOUND: \"Wallet not delegated or not found. Use a walletId from list_wallets.\",\n SESSION_KEY_NOT_FOUND: \"Session not delegated or not found. Use list_session_keys.\",\n EXECUTION_SUBMISSION_NOT_FOUND: \"Use the submissionId returned by execute_transaction.\",\n NO_AUTHORIZED_SESSION_KEY: \"The selected session does not authorize this wallet operation.\",\n POLICY_DENIED:\n \"The selected session's policy denied the operation. Inspect policyCode and simulate again.\",\n IDEMPOTENCY_CONFLICT: \"The operation conflicts with an earlier request.\",\n EXECUTION_FAILED: \"The execution failed. Inspect its status before submitting another operation.\",\n EXECUTION_UNAVAILABLE:\n \"Execution is unavailable. Check submission status before retrying a transfer.\",\n SIGNING_FAILED: \"The signature could not be created.\",\n SIGNATURE_UNAVAILABLE: \"Signature creation is unavailable.\",\n VERIFICATION_FAILED: \"Signature verification could not be completed on this chain.\",\n LIMIT_EXCEEDED: \"The workspace has reached its plan limit.\",\n RATE_LIMITED: \"Too many requests. Wait before retrying.\",\n INTERNAL_ERROR: \"Namera could not complete the operation.\",\n UPSTREAM_UNAVAILABLE:\n \"The API is unavailable. Check transaction status before repeating a transfer.\",\n LOCAL_SIGNER_REQUIRED: \"Configure a local signer before executing or signing.\",\n LOCAL_SIGNER_UNAVAILABLE:\n \"The authorized session's local key is unavailable. Import it with namera session-key import.\",\n PREPARED_EXECUTION_INVALID:\n \"The preparation does not match local session authorization or fee consent. Do not sign it.\",\n PREPARED_SIGNATURE_INVALID:\n \"The challenge does not match the original payload or local signature consent. Do not sign it.\",\n LOCAL_SIGNATURE_INVALID: \"Local signature verification failed. Check the imported session key.\",\n};\n\nexport const localToolError = (code: McpToolErrorCode): McpToolError => ({\n code,\n message: messages[code],\n retryable: false,\n});\n\nexport const unwrapMcpSdk = Effect.fn(\"LocalMcp.unwrapSdk\")(function* <A, E>(\n call: () => Promise<NameraResult<A, E>>,\n) {\n const result = yield* Effect.tryPromise({\n try: call,\n catch: () => localToolError(\"INTERNAL_ERROR\"),\n });\n if (result.success) return result.data;\n const error = result.error;\n const code =\n error.kind === \"contract\"\n ? \"INVALID_ARGUMENT\"\n : error.kind === \"network\"\n ? \"UPSTREAM_UNAVAILABLE\"\n : error.status === 401 || (error.kind === \"api\" && error.tag === \"Unauthorized\")\n ? \"UNAUTHORIZED\"\n : error.status === 403 || (error.kind === \"api\" && error.tag === \"Forbidden\")\n ? \"INSUFFICIENT_SCOPE\"\n : \"code\" in error && Schema.is(McpToolErrorCode)(error.code)\n ? error.code\n : error.status === 429\n ? \"RATE_LIMITED\"\n : \"INTERNAL_ERROR\";\n const cause = error.cause;\n const base = localToolError(code);\n // Only schema-validated policy diagnostics can leave the local process.\n const diagnostic = Predicate.isObject(cause)\n ? {\n ...base,\n ...(Reflect.get(cause, \"policyId\") === undefined\n ? {}\n : { policyId: Reflect.get(cause, \"policyId\") }),\n ...(Reflect.get(cause, \"policyCode\") === undefined\n ? {}\n : { policyCode: Reflect.get(cause, \"policyCode\") }),\n }\n : base;\n return yield* Effect.fail(Schema.is(McpToolError)(diagnostic) ? diagnostic : base);\n});\n\nexport const toolErrorResult = (failure: unknown) => {\n const error = Schema.is(McpToolError)(failure)\n ? failure\n : localToolError(Schema.isSchemaError(failure) ? \"INVALID_ARGUMENT\" : \"INTERNAL_ERROR\");\n return new McpSchema.CallToolResult({\n isError: true,\n structuredContent: { error },\n content: [{ type: \"text\", text: JSON.stringify({ error }) }],\n });\n};\n","import { Context, Effect, Schema } from \"effect\";\nimport { McpSchema, McpServer, Tool } from \"effect/unstable/ai\";\n\nimport {\n CompleteExecutionResponse,\n GetExecutionSubmissionResponse,\n GetSessionKeyResponse,\n GetWalletResponse,\n ListExecutionsResponse,\n ListSessionKeysForOrganizationResponse,\n ListWalletsResponse,\n McpExecuteTransactionRequest,\n McpGetExecutionsRequest,\n McpGetSessionKeyRequest,\n McpGetTransactionStatusRequest,\n McpGetWalletRequest,\n McpListSessionKeysRequest,\n McpSignRequest,\n McpSimulateTransactionRequest,\n McpVerifySignatureRequest,\n SignResponse,\n SimulateExecutionResponse,\n VerifySignatureResponse,\n} from \"@namera-ai/protocol/dto\";\nimport type { NameraClient } from \"@namera-ai/sdk\";\n\nimport { McpAuthentication } from \"./api-client.js\";\nimport { localToolError, toolErrorResult, unwrapMcpSdk } from \"./tool-errors.js\";\n\nconst rootObject = (schema: ReturnType<typeof Tool.getJsonSchema>) => {\n const ref = Reflect.get(schema, \"$ref\");\n const defs = Reflect.get(schema, \"$defs\");\n if (\n typeof ref !== \"string\" ||\n !ref.startsWith(\"#/$defs/\") ||\n typeof defs !== \"object\" ||\n defs === null\n )\n return schema;\n const root = Reflect.get(defs, ref.slice(8));\n return typeof root === \"object\" && root !== null ? { ...root, $defs: defs } : schema;\n};\n\nconst register = Effect.fn(\"LocalMcp.registerTool\")(function* <T extends Tool.Any, E>(\n tool: T,\n scope: \"mcp:read\" | \"mcp:execute\",\n destructive: boolean,\n handle: (input: Tool.Parameters<T>, client: NameraClient) => Effect.Effect<Tool.Success<T>, E>,\n) {\n const authentication = yield* McpAuthentication;\n yield* (yield* McpServer.McpServer).addTool({\n tool: new McpSchema.Tool({\n name: tool.name,\n description: tool.description,\n inputSchema: rootObject(Tool.getJsonSchema(tool)),\n outputSchema: rootObject(Tool.getJsonSchemaFromSchema(tool.successSchema)),\n annotations: {\n readOnlyHint: scope === \"mcp:read\" || tool.name === \"simulate_transaction\",\n destructiveHint: destructive,\n idempotentHint: tool.name !== \"execute_transaction\" && tool.name !== \"sign\",\n openWorldHint: true,\n },\n }),\n annotations: Context.empty(),\n handle: (payload) =>\n Effect.gen(function* () {\n const principal = yield* authentication.principal;\n if (!principal.scopes.includes(scope))\n return toolErrorResult(localToolError(\"INSUFFICIENT_SCOPE\"));\n const input = yield* Schema.decodeUnknownEffect(\n tool.parametersSchema as Schema.Codec<Tool.Parameters<T>, unknown, never, never>,\n )(payload);\n const value = yield* handle(input, principal.client);\n const encoded = yield* Schema.encodeUnknownEffect(\n tool.successSchema as Schema.Codec<Tool.Success<T>, unknown, never, never>,\n )(value);\n return new McpSchema.CallToolResult({\n structuredContent: encoded,\n content: [{ type: \"text\", text: JSON.stringify(encoded) }],\n });\n }).pipe(\n Effect.catch((error) => Effect.succeed(toolErrorResult(error))),\n Effect.withSpan(\"cli.mcp.tool\", { attributes: { tool: tool.name } }),\n ),\n });\n});\n\nexport const localMcpTools = Effect.gen(function* () {\n yield* register(\n Tool.make(\"list_wallets\", {\n description:\n \"List delegated wallets. Use a returned wallet id as walletId, never an address or session-key ID.\",\n success: Schema.Struct({ wallets: ListWalletsResponse }),\n }),\n \"mcp:read\",\n false,\n (_, client) =>\n unwrapMcpSdk(() => client.wallets.list()).pipe(Effect.map((wallets) => ({ wallets }))),\n );\n yield* register(\n Tool.make(\"get_wallet\", {\n description: \"Get one delegated wallet by walletId from list_wallets.\",\n parameters: McpGetWalletRequest,\n success: Schema.Struct({ wallet: GetWalletResponse }),\n }),\n \"mcp:read\",\n false,\n ({ walletId }, client) =>\n unwrapMcpSdk(() => client.wallets.get(walletId)).pipe(Effect.map((wallet) => ({ wallet }))),\n );\n yield* register(\n Tool.make(\"list_session_keys\", {\n description:\n \"List delegated session keys and their wallet IDs. Execute and sign require both walletId and sessionKeyId; do not interchange them. The local key must also be imported on this machine.\",\n parameters: McpListSessionKeysRequest,\n success: Schema.Struct({ sessionKeys: ListSessionKeysForOrganizationResponse }),\n }),\n \"mcp:read\",\n false,\n (input, client) =>\n unwrapMcpSdk(() => client.sessionKeys.list(input)).pipe(\n Effect.map((sessionKeys) => ({ sessionKeys })),\n ),\n );\n yield* register(\n Tool.make(\"get_session_key\", {\n description: \"Get one delegated session key and its policies by sessionKeyId.\",\n parameters: McpGetSessionKeyRequest,\n success: Schema.Struct({ sessionKey: GetSessionKeyResponse }),\n }),\n \"mcp:read\",\n false,\n ({ sessionKeyId }, client) =>\n unwrapMcpSdk(() => client.sessionKeys.get(sessionKeyId)).pipe(\n Effect.map((sessionKey) => ({ sessionKey })),\n ),\n );\n yield* register(\n Tool.make(\"simulate_transaction\", {\n description:\n \"Simulate the exact session and calls without signing or consuming operation usage. Execute only when allowed and callsSucceeded are true.\",\n parameters: McpSimulateTransactionRequest,\n success: Schema.Struct({ simulation: SimulateExecutionResponse }),\n }),\n \"mcp:execute\",\n false,\n (input, client) =>\n unwrapMcpSdk(() => client.executions.simulate(input)).pipe(\n Effect.map((simulation) => ({ simulation })),\n ),\n );\n yield* register(\n Tool.make(\"execute_transaction\", {\n description:\n \"Execute exact calls using walletId and sessionKeyId from discovery tools. Simulate first. Signs locally using an imported session key. Gas is sponsored by default; sponsor:false requires a fee cap configured by the user when starting local MCP. Prepared means queued, not confirmed: poll get_transaction_status. Repeating this tool can transfer assets twice.\",\n parameters: McpExecuteTransactionRequest,\n success: Schema.Struct({ execution: CompleteExecutionResponse }),\n }),\n \"mcp:execute\",\n true,\n (input, client) =>\n unwrapMcpSdk(() => client.executions.execute(input)).pipe(\n Effect.map((execution) => ({ execution })),\n ),\n );\n yield* register(\n Tool.make(\"get_transaction_status\", {\n description:\n \"Poll the submissionId returned by execute_transaction until confirmed or failed. Prepared and submitted are still pending.\",\n parameters: McpGetTransactionStatusRequest,\n success: Schema.Struct({ submission: GetExecutionSubmissionResponse }),\n }),\n \"mcp:read\",\n false,\n ({ submissionId }, client) =>\n unwrapMcpSdk(() => client.executions.getStatus(submissionId)).pipe(\n Effect.map((submission) => ({ submission })),\n ),\n );\n yield* register(\n Tool.make(\"get_executions\", {\n description:\n \"Read confirmed execution history for this authorization. Pass nextCursor to fetch the next page. Pending submissions use get_transaction_status.\",\n parameters: McpGetExecutionsRequest,\n success: ListExecutionsResponse,\n }),\n \"mcp:read\",\n false,\n (input, client) => unwrapMcpSdk(() => client.executions.list(input)),\n );\n yield* register(\n Tool.make(\"sign\", {\n description:\n \"Sign an exact UTF-8 message or EIP-712 object locally, using an explicit walletId and sessionKeyId. Requires imported signature consent and installed onchain signature permission plus passing API policies. Does not submit a transaction.\",\n parameters: McpSignRequest,\n success: Schema.Struct({ signature: SignResponse }),\n }),\n \"mcp:execute\",\n false,\n ({ request }, client) =>\n unwrapMcpSdk(() => client.sign(request)).pipe(Effect.map((signature) => ({ signature }))),\n );\n yield* register(\n Tool.make(\"verify_signature\", {\n description:\n \"Verify a smart-account signature against the original unmodified payload and walletId. A false validity result is not a tool failure.\",\n parameters: McpVerifySignatureRequest,\n success: Schema.Struct({ verification: VerifySignatureResponse }),\n }),\n \"mcp:read\",\n false,\n ({ request }, client) =>\n unwrapMcpSdk(() => client.verifySignature(request)).pipe(\n Effect.map((verification) => ({ verification })),\n ),\n );\n});\n","import { Layer } from \"effect\";\nimport { McpProtocol, McpServer } from \"effect/unstable/ai\";\n\nimport { version } from \"#/version\";\n\nimport { localMcpTools } from \"./tools.js\";\n\nexport const mcpStdio = Layer.effectDiscard(localMcpTools).pipe(\n Layer.provide(\n McpServer.layerStdio({\n name: \"Namera\",\n version,\n protocols: [McpProtocol.v2025_06_18],\n }),\n ),\n);\n","import { Schema } from \"effect\";\n\nexport const LocalMcpApiOrigin = Schema.NonEmptyString.check(\n Schema.makeFilter(\n (value) => {\n const url = URL.parse(value);\n return (\n url !== null &&\n url.username === \"\" &&\n url.password === \"\" &&\n url.pathname === \"/\" &&\n url.search === \"\" &&\n url.hash === \"\" &&\n (url.protocol === \"https:\" ||\n (url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)))\n );\n },\n {\n message:\n \"Use an HTTPS API origin, or HTTP localhost for development, without credentials, path, query or fragment\",\n },\n ),\n);\n","import {\n Effect,\n Layer,\n Option,\n Redacted,\n Schema,\n Stdio,\n Stream,\n Deferred,\n Logger,\n Fiber,\n} from \"effect\";\nimport { Command, Flag } from \"effect/unstable/cli\";\n\nimport { NAMERA_API_ORIGIN } from \"@namera-ai/sdk\";\n\nimport { makeMcpApiClient, McpAuthentication } from \"#/services/mcp/api-client\";\nimport { mcpCredentialStore, McpProfile } from \"#/services/mcp/credential-store\";\nimport { createMcpSession } from \"#/services/mcp/session\";\nimport { mcpStdio } from \"#/services/mcp/stdio\";\nimport { localToolError } from \"#/services/mcp/tool-errors\";\nimport { LocalMcpApiOrigin } from \"#/services/mcp/transport-security\";\nimport { printValue } from \"#/services/output\";\nimport { recordView } from \"#/services/output/document\";\nimport { resolveCliSessionSigner } from \"#/services/session-keystore/index\";\n\nconst flags = {\n profile: Flag.string(\"profile\").pipe(Flag.withDefault(\"default\")),\n host: Flag.string(\"host\").pipe(\n Flag.withDefault(NAMERA_API_ORIGIN),\n Flag.withDescription(\"Namera API origin\"),\n ),\n};\nconst session = Effect.fn(\"Mcp.session\")(function* (options: { host: string; profile: string }) {\n const apiOrigin = new URL(yield* Schema.decodeUnknownEffect(LocalMcpApiOrigin)(options.host))\n .origin;\n const profile = yield* Schema.decodeUnknownEffect(McpProfile)(options.profile);\n return yield* Effect.acquireRelease(\n Effect.try(() =>\n createMcpSession({ apiOrigin, profile, store: mcpCredentialStore(apiOrigin, profile) }),\n ),\n (value) => Effect.sync(() => value.close()),\n );\n});\n\nconst serve = Command.make(\n \"serve\",\n {\n ...flags,\n maxGasCost: Flag.string(\"max-gas-cost-wei\").pipe(\n Flag.optional,\n Flag.withDescription(\"Fee ceiling for self-funded operations; default is sponsored only\"),\n ),\n },\n Effect.fn(\"Mcp.serve\")(\n function* (options) {\n const connection = yield* session(options);\n const apiOrigin = new URL(options.host).origin;\n const maxGasCostWei = Option.isSome(options.maxGasCost)\n ? yield* Schema.decodeUnknownEffect(\n Schema.BigIntFromString.check(Schema.isGreaterThanOrEqualToBigInt(0n)),\n )(options.maxGasCost.value)\n : undefined;\n const principal = Effect.gen(function* () {\n const credentials = yield* Effect.tryPromise({\n try: connection.credentials,\n catch: () => localToolError(\"UNAUTHORIZED\"),\n });\n if (!credentials) {\n connection.requestLogin();\n return yield* Effect.fail({\n ...localToolError(\"UNAUTHORIZED\"),\n message: `Authorize Namera in your browser, or run namera mcp login --profile ${options.profile} --host ${apiOrigin}. Then retry.`,\n });\n }\n return yield* makeMcpApiClient(\n { apiOrigin, resolveSessionSigner: resolveCliSessionSigner(apiOrigin, maxGasCostWei) },\n {\n accessToken: Redacted.make(credentials.accessToken),\n clientId: credentials.clientId,\n scopes: credentials.scopes,\n },\n ).pipe(\n Effect.mapError((error) =>\n localToolError(\n error.code === \"temporarily_unavailable\" ? \"UPSTREAM_UNAVAILABLE\" : \"UNAUTHORIZED\",\n ),\n ),\n );\n });\n const io = yield* Stdio.Stdio;\n const ended = yield* Deferred.make<void>();\n const transport = Stdio.make({\n ...io,\n stdin: io.stdin.pipe(Stream.ensuring(Deferred.succeed(ended, undefined))),\n });\n // The stdio protocol interrupts its construction fiber on EOF. Isolate\n // that fiber so the command can finish normally after stdin closes.\n yield* Layer.build(\n mcpStdio.pipe(\n Layer.provide(Layer.succeed(McpAuthentication, { principal })),\n Layer.provide(Layer.succeed(Stdio.Stdio, transport)),\n ),\n ).pipe(Effect.forkScoped, Effect.flatMap(Fiber.join));\n yield* Deferred.await(ended);\n },\n Effect.scoped,\n Effect.provide(Logger.layer([Logger.withConsoleError(Logger.formatSimple)])),\n ),\n);\n\nconst login = Command.make(\n \"login\",\n flags,\n Effect.fn(\"Mcp.login\")(function* (options) {\n const connection = yield* session(options);\n yield* Effect.tryPromise({\n try: connection.login,\n catch: () =>\n new Error(\n \"MCP login failed. Check the browser consent and API connection, then try again.\",\n ),\n });\n yield* printValue(connection.status(), recordView(\"MCP connection\"));\n }, Effect.scoped),\n);\nconst status = Command.make(\n \"status\",\n flags,\n Effect.fn(\"Mcp.status\")(function* (options) {\n const connection = yield* session(options);\n yield* printValue(yield* Effect.try(connection.status), recordView(\"MCP connection\"));\n }, Effect.scoped),\n);\nconst logout = Command.make(\n \"logout\",\n flags,\n Effect.fn(\"Mcp.logout\")(function* (options) {\n const connection = yield* session(options);\n yield* Effect.tryPromise({\n try: connection.logout,\n catch: () =>\n new Error(\n \"MCP logout could not be completed. Check your OS keyring and revoke the connection in Namera settings.\",\n ),\n });\n yield* printValue(\n { profile: options.profile, status: \"signed-out\" },\n recordView(\"MCP signed out\"),\n );\n }, Effect.scoped),\n);\n\nexport const mcpCommand = Command.make(\"mcp\").pipe(\n Command.withDescription(\"Local stdio MCP with persistent OAuth authorization\"),\n Command.withSubcommands([serve, login, status, logout]),\n);\n","import type { SessionKeyResponse } from \"@namera-ai/protocol/dto\";\n\nimport {\n collection,\n humanize,\n named,\n network,\n section,\n timestamp,\n type PrettyPrinter,\n} from \"./document.js\";\n\ntype SessionDisplay = Pick<\n SessionKeyResponse,\n | \"metadata\"\n | \"id\"\n | \"status\"\n | \"walletId\"\n | \"createdAt\"\n | \"revokedAt\"\n | \"installations\"\n | \"policies\"\n> & {\n readonly wallet: Pick<SessionKeyResponse[\"wallet\"], \"metadata\">;\n};\n\nexport const sessionKeyView: PrettyPrinter<SessionDisplay> = (key, colors) =>\n [\n section(\n named(key.metadata),\n [\n [\"Status\", humanize(key.status)],\n [\"Session key ID\", key.id],\n [\"Wallet\", key.wallet.metadata.name],\n [\"Wallet ID\", key.walletId],\n [\"Description\", key.metadata.description ?? undefined],\n [\"Created\", key.createdAt],\n [\"Revoked\", key.revokedAt ?? undefined],\n ],\n colors,\n ),\n ...key.installations.map((installation) =>\n section(\n network(installation.chainId),\n [\n [\"Status\", humanize(installation.status)],\n [\"Signer\", installation.authorization.signerAddress],\n [\n \"Starts\",\n installation.authorization.validAfter === 0\n ? \"Immediately after installation\"\n : timestamp(installation.authorization.validAfter),\n ],\n [\"Expires\", timestamp(installation.authorization.validUntil)],\n [\n \"Signatures\",\n installation.authorization.allowSignatures === true ? \"Enabled\" : \"Disabled\",\n ],\n [\n \"Onchain permissions\",\n installation.authorization.permissions.map((permission) => {\n const { type, ...parameters } = permission;\n return {\n policy: type === \"root\" ? \"Unrestricted account access\" : humanize(type),\n ...parameters,\n ...(type === \"native-token-transfer\" ? { unit: \"wei\" } : {}),\n ...(type === \"erc20-token-transfer\" ? { unit: \"token base units\" } : {}),\n ...(type === \"gas-limit\" ? { unit: \"gas units\" } : {}),\n };\n }),\n ],\n ],\n colors,\n ),\n ),\n ...(key.installations.length === 0 ? [\" No network installations.\"] : []),\n section(\n \"Offchain policies\",\n [\n [\n \"Policies\",\n key.policies.map(({ type, ...parameters }) => ({\n policy: humanize(type.replace(/^evm\\./, \"\")),\n ...parameters,\n })),\n ],\n ],\n colors,\n ),\n ].join(\"\\n\\n\");\n\nexport const sessionKeysView: PrettyPrinter<readonly SessionDisplay[]> = (keys, colors) =>\n collection(\n keys,\n \"session key\",\n \"session keys\",\n (key, useColors) =>\n section(\n named(key.metadata),\n [\n [\"Status\", humanize(key.status)],\n [\"Session key ID\", key.id],\n [\"Wallet\", key.wallet.metadata.name],\n [\"Wallet ID\", key.walletId],\n [\n \"Networks\",\n key.installations.map(\n (installation) =>\n `${network(installation.chainId)}: ${humanize(installation.status)}`,\n ),\n ],\n [\"Created\", key.createdAt],\n ],\n useColors,\n ),\n colors,\n );\n","import { Effect, Schema } from \"effect\";\nimport { Argument, Command, Prompt } from \"effect/unstable/cli\";\n\nimport { EncryptedLocalSessionKey } from \"@namera-ai/protocol/local\";\n\nimport { profileFlag } from \"#/commands/common\";\nimport { makeCliClient } from \"#/services/client\";\nimport { printValue } from \"#/services/output\";\nimport { recordView } from \"#/services/output/document\";\nimport { sessionKeystore } from \"#/services/session-keystore/index\";\nimport { SessionKeystoreError } from \"#/services/session-keystore/storage\";\n\nexport const importSessionKeyCommand = Command.make(\n \"import\",\n {\n encryptedExport: Argument.string(\"encrypted-export\"),\n profile: profileFlag,\n },\n Effect.fn(\"cli.sessionKey.import\")(function* ({ encryptedExport, profile }) {\n const envelope = yield* Effect.try({\n try: () => {\n if (encryptedExport.length > 128 * 1024 || !/^[A-Za-z0-9_-]+$/.test(encryptedExport))\n throw new Error(\"Invalid export\");\n return Schema.decodeUnknownSync(Schema.fromJsonString(EncryptedLocalSessionKey))(\n Buffer.from(encryptedExport, \"base64url\").toString(\"utf8\"),\n );\n },\n catch: () => new SessionKeystoreError({ code: \"IMPORT_FAILED\" }),\n });\n const { profile: activeProfile } = yield* Effect.tryPromise(() => makeCliClient(profile));\n const password = yield* Prompt.password({ message: \"Export passphrase\" });\n const result = yield* Effect.tryPromise({\n try: () =>\n sessionKeystore.importKey(envelope, password, new URL(activeProfile.baseUrl).origin),\n catch: () => new SessionKeystoreError({ code: \"IMPORT_FAILED\" }),\n });\n yield* printValue({ status: \"imported\", ...result }, recordView(\"Session key imported\"));\n }),\n).pipe(\n Command.withDescription(\n \"Import an encrypted dashboard session export; passphrase is entered securely\",\n ),\n);\n","import { Effect, Option, Schema } from \"effect\";\nimport { Argument, Command, Flag } from \"effect/unstable/cli\";\n\nimport { SessionKeyId, WalletId } from \"@namera-ai/protocol\";\n\nimport { profileFlag } from \"#/commands/common\";\nimport { makeCliClient } from \"#/services/client\";\nimport { printValue, runPromise } from \"#/services/output\";\nimport { sessionKeyView, sessionKeysView } from \"#/services/output/session-key\";\n\nimport { importSessionKeyCommand } from \"./import.js\";\n\nconst list = Command.make(\n \"list\",\n {\n wallet: Flag.string(\"wallet\").pipe(\n Flag.withDescription(\"Only list keys for one wallet\"),\n Flag.optional,\n ),\n profile: profileFlag,\n },\n Effect.fn(function* ({ wallet, profile }) {\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n const result = yield* runPromise(\n client.sessionKeys.list(\n Option.isSome(wallet)\n ? { walletId: yield* Schema.decodeUnknownEffect(WalletId)(wallet.value) }\n : {},\n ),\n );\n yield* printValue(result, sessionKeysView);\n }),\n);\n\nconst get = Command.make(\n \"get\",\n { sessionKeyId: Argument.string(\"session-key-id\"), profile: profileFlag },\n Effect.fn(function* ({ sessionKeyId, profile }) {\n const id = yield* Schema.decodeUnknownEffect(SessionKeyId)(sessionKeyId);\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(yield* runPromise(client.sessionKeys.get(id)), sessionKeyView);\n }),\n);\n\nexport const sessionKeyCommand = Command.make(\"session-key\").pipe(\n Command.withDescription(\"Read granted session keys and import local signing material\"),\n Command.withSubcommands([list, get, importSessionKeyCommand]),\n);\n","import { Effect } from \"effect\";\nimport { Command } from \"effect/unstable/cli\";\n\nimport {\n PrepareSignatureRequest as SignRequest,\n type PrepareSignatureRequest as SignRequestType,\n} from \"@namera-ai/protocol/dto\";\n\nimport { paramsFlag, profileFlag, resolveParams } from \"#/commands/common\";\nimport { makeCliClient } from \"#/services/client\";\nimport { printValue, runPromise } from \"#/services/output\";\nimport { signatureView } from \"#/services/output/execution\";\nimport { CliPrompts } from \"#/services/prompts\";\n\nconst promptSignRequest = Effect.fn(\"cli.sign.promptRequest\")(function* () {\n const prompts = yield* CliPrompts;\n const namespace = yield* prompts.namespace;\n const walletId = yield* prompts.walletId();\n const sessionKeyId = yield* prompts.sessionKeyId();\n const chainId = yield* prompts.chainId();\n const type = yield* prompts.signatureType;\n\n return type === \"message\"\n ? ({\n namespace,\n walletId,\n sessionKeyId,\n chainId,\n type,\n message: yield* prompts.message(),\n } satisfies SignRequestType)\n : ({\n namespace,\n walletId,\n sessionKeyId,\n chainId,\n type,\n typedData: yield* prompts.typedData,\n } satisfies SignRequestType);\n});\n\nexport const signCommand = Command.make(\n \"sign\",\n { params: paramsFlag, profile: profileFlag },\n Effect.fn(function* ({ params, profile }) {\n const request = yield* resolveParams(params, SignRequest, promptSignRequest());\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(yield* runPromise(client.sign(request)), signatureView);\n }),\n).pipe(Command.withDescription(\"Sign an EVM message or typed-data request\"));\n","import { Effect } from \"effect\";\nimport { Command } from \"effect/unstable/cli\";\n\nimport {\n VerifySignatureRequest,\n type VerifySignatureRequest as VerifySignatureRequestType,\n} from \"@namera-ai/protocol/dto\";\n\nimport { paramsFlag, profileFlag, resolveParams } from \"#/commands/common\";\nimport { makeCliClient } from \"#/services/client\";\nimport { printValue, runPromise } from \"#/services/output\";\nimport { verificationView } from \"#/services/output/execution\";\nimport { CliPrompts } from \"#/services/prompts\";\n\nconst promptVerifySignatureRequest = Effect.fn(\"cli.verifySignature.promptRequest\")(function* () {\n const prompts = yield* CliPrompts;\n const namespace = yield* prompts.namespace;\n const walletId = yield* prompts.walletId();\n const chainId = yield* prompts.chainId();\n const type = yield* prompts.signatureType;\n const signature = yield* prompts.hex(\"Signature\");\n\n return type === \"message\"\n ? ({\n namespace,\n walletId,\n chainId,\n type,\n signature,\n message: yield* prompts.message(),\n } satisfies VerifySignatureRequestType)\n : ({\n namespace,\n walletId,\n chainId,\n type,\n signature,\n typedData: yield* prompts.typedData,\n } satisfies VerifySignatureRequestType);\n});\n\nexport const verifySignatureCommand = Command.make(\n \"verify-signature\",\n { params: paramsFlag, profile: profileFlag },\n Effect.fn(function* ({ params, profile }) {\n const request = yield* resolveParams(\n params,\n VerifySignatureRequest,\n promptVerifySignatureRequest(),\n );\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(yield* runPromise(client.verifySignature(request)), verificationView);\n }),\n).pipe(Command.withDescription(\"Verify an EVM smart-account signature\"));\n","import type { WalletResponse } from \"@namera-ai/protocol/dto\";\n\nimport { collection, humanize, named, section, type PrettyPrinter } from \"./document.js\";\n\ntype WalletDisplay = Pick<\n WalletResponse,\n \"metadata\" | \"status\" | \"address\" | \"id\" | \"namespace\" | \"owner\" | \"createdAt\"\n>;\n\nexport const walletView: PrettyPrinter<WalletDisplay> = (wallet, colors) =>\n section(\n named(wallet.metadata),\n [\n [\"Status\", humanize(wallet.status)],\n [\"Address\", wallet.address],\n [\"Wallet ID\", wallet.id],\n [\"Network type\", \"EVM\"],\n [\"Key custody\", wallet.owner.custody === \"local\" ? \"Local (user-owned)\" : \"Namera-managed\"],\n [\"Implementation\", \"Alchemy Modular V2\"],\n [\"Description\", wallet.metadata.description ?? undefined],\n [\"Created\", wallet.createdAt],\n ],\n colors,\n );\n\nexport const walletsView: PrettyPrinter<readonly WalletDisplay[]> = (wallets, colors) =>\n collection(wallets, \"delegated wallet\", \"delegated wallets\", walletView, colors);\n","import { Effect, Schema } from \"effect\";\nimport { Argument, Command } from \"effect/unstable/cli\";\n\nimport { WalletId } from \"@namera-ai/protocol\";\n\nimport { profileFlag } from \"#/commands/common\";\nimport { makeCliClient } from \"#/services/client\";\nimport { printValue, runPromise } from \"#/services/output\";\nimport { walletView, walletsView } from \"#/services/output/wallet\";\n\nconst list = Command.make(\n \"list\",\n { profile: profileFlag },\n Effect.fn(function* ({ profile }) {\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(yield* runPromise(client.wallets.list()), walletsView);\n }),\n);\n\nconst get = Command.make(\n \"get\",\n { walletId: Argument.string(\"wallet-id\"), profile: profileFlag },\n Effect.fn(function* ({ walletId, profile }) {\n const id = yield* Schema.decodeUnknownEffect(WalletId)(walletId);\n const { client } = yield* Effect.tryPromise(() => makeCliClient(profile));\n yield* printValue(yield* runPromise(client.wallets.get(id)), walletView);\n }),\n);\n\nexport const walletCommand = Command.make(\"wallet\").pipe(\n Command.withDescription(\"Read wallets granted to this CLI\"),\n Command.withSubcommands([list, get]),\n);\n","#!/usr/bin/env node\nimport { NodeRuntime, NodeServices } from \"@effect/platform-node\";\nimport { Effect } from \"effect\";\nimport { Command } from \"effect/unstable/cli\";\n\nimport { authCommand, loginCommand, logoutCommand } from \"#/commands/auth/index\";\nimport { executionCommand } from \"#/commands/execution/index\";\nimport { mcpCommand } from \"#/commands/mcp/index\";\nimport { nameraCommand } from \"#/commands/root\";\nimport { sessionKeyCommand } from \"#/commands/session-key/index\";\nimport { signCommand } from \"#/commands/sign\";\nimport { verifySignatureCommand } from \"#/commands/verify-signature\";\nimport { walletCommand } from \"#/commands/wallet/index\";\nimport { CliPrompts } from \"#/services/prompts\";\nimport { version } from \"#/version\";\n\nconst namera = nameraCommand.pipe(\n Command.withSubcommands([\n loginCommand,\n logoutCommand,\n authCommand,\n walletCommand,\n sessionKeyCommand,\n executionCommand,\n mcpCommand,\n signCommand,\n verifySignatureCommand,\n ]),\n);\n\nnamera.pipe(\n Command.run({ version }),\n Effect.provide(CliPrompts.layer),\n Effect.provide(NodeServices.layer),\n NodeRuntime.runMain,\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAa,cAAc,KAAK,OAAO,SAAS,CAAC,CAAC,KAChD,KAAK,gBAAgB,kBAAkB,GACvC,KAAK,YAAY,UAAU,CAC7B;AAEA,MAAa,aAAa,KAAK,OAAO,QAAQ,CAAC,CAAC,KAC9C,KAAK,gBAAgB,6BAA6B,GAClD,KAAK,QACP;AAEA,MAAa,iBACX,QACA,QACA,WAEA,OAAO,MAAM,QAAQ;CACnB,cAAc;CACd,SAAS,UAAU,OAAO,oBAAoB,OAAO,eAAe,MAAM,CAAC,CAAC,CAAC,KAAK;AACpF,CAAC;;;;ACLH,MAAM,wBAAwB;CAC5B,IAAI,QAAQ,IAAI,iBAAiB,OAAO,KAAK,QAAQ,IAAI,iBAAiB,QAAQ;CAClF,IAAI,QAAQ,aAAa,UACvB,OAAO,KAAK,QAAQ,GAAG,WAAW,uBAAuB,QAAQ;CACnE,IAAI,QAAQ,aAAa,SACvB,OAAO,KAAK,QAAQ,IAAI,WAAW,KAAK,QAAQ,GAAG,WAAW,SAAS,GAAG,QAAQ;CAEpF,OAAO,KAAK,QAAQ,GAAG,WAAW,QAAQ;AAC5C;AAEA,MAAa,gBAAgB,KAAK,gBAAgB,GAAG,aAAa;AAClE,MAAa,eAAe,YAAoB,KAAK,gBAAgB,GAAG,GAAG,QAAQ,cAAc;AAEjG,MAAa,gBAAgB,YAAgC;CAC3D,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,eAAe,MAAM,CAAC;CACzD,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAA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GAC1D,QAAQ,gBAAgB,CAAC,MAAM,GAAG,CAAC,CACrC;;;;AChBe,cAAc,KAC3B,QAAQ,gBAAgB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAGE,CAAC,CAAC,KACL,QAAQ,IAAI,EAAE,QAAQ,CAAC,GACvB,OAAO,QAAQ,WAAW,KAAK,GAC/B,OAAO,QAAQ,aAAa,KAAK,GACjC,YAAY,OACd"}
package/package.json CHANGED
@@ -1,62 +1,69 @@
1
1
  {
2
- "author": "Vedant Chainani <vedant@namespace.ninja>",
3
- "bin": {
4
- "namera": "dist/index.mjs"
5
- },
6
- "bugs": {
7
- "url": "https://github.com/thenamespace/namera/issues"
8
- },
9
- "dependencies": {
10
- "@effect/platform-node": "4.0.0-beta.60",
11
- "@ethereumjs/wallet": "10.0.0",
12
- "dotenv": "17.4.2",
13
- "effect": "4.0.0-beta.60",
14
- "tslib": "2.8.1",
15
- "viem": "2.48.8",
16
- "@namera-ai/sdk": "0.1.0"
17
- },
18
- "description": "Agent-first smart account interface with session keys and scoped permissions, enabling fully local multichain automation.",
19
- "devDependencies": {
20
- "@types/node": "25.6.0",
21
- "tsdown": "0.21.10",
22
- "typescript": "6.0.3",
23
- "@namera-ai/config": "1.0.0"
24
- },
25
- "files": [
26
- "dist",
27
- "README.md"
28
- ],
29
- "homepage": "https://github.com/thenamespace/namera#readme",
2
+ "name": "@namera-ai/cli",
3
+ "version": "1.0.0",
4
+ "description": "Namera CLI and local stdio MCP server for self-custodial agent wallets.",
30
5
  "keywords": [
6
+ "ai-agents",
7
+ "cli",
8
+ "ethereum",
9
+ "mcp",
31
10
  "namera",
32
- "smart accounts",
33
- "account abstraction",
34
- "session keys",
35
- "wallet automation",
36
- "agent wallets",
37
- "agents",
38
- "multichain",
39
- "web3 cli",
40
- "passkeys",
41
- "scoped permissions",
42
- "local first",
43
- "automation"
11
+ "session-keys",
12
+ "smart-account"
44
13
  ],
45
- "license": "Apache-2.0",
46
- "name": "@namera-ai/cli",
47
- "publishConfig": {
48
- "access": "public"
14
+ "homepage": "https://namera.ai",
15
+ "bugs": {
16
+ "url": "https://github.com/thenamespace/namera-core/issues"
49
17
  },
18
+ "license": "Apache-2.0",
50
19
  "repository": {
51
20
  "type": "git",
52
- "url": "https://github.com/thenamespace/namera"
21
+ "url": "git+https://github.com/thenamespace/namera-core.git",
22
+ "directory": "apps/cli"
23
+ },
24
+ "bin": {
25
+ "namera": "dist/index.js"
53
26
  },
54
- "sideEffects": false,
27
+ "files": [
28
+ "dist"
29
+ ],
55
30
  "type": "module",
56
- "version": "0.1.4",
31
+ "imports": {
32
+ "#/*": "./src/*.ts"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "provenance": true
37
+ },
38
+ "dependencies": {
39
+ "@effect/platform-node": "4.0.0-beta.105",
40
+ "@napi-rs/keyring": "1.3.0",
41
+ "effect": "4.0.0-beta.105",
42
+ "viem": "2.55.11",
43
+ "@namera-ai/protocol": "1.0.0",
44
+ "@namera-ai/sdk": "1.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "26.1.2",
48
+ "klarity": "0.2.0",
49
+ "tsdown": "0.22.14",
50
+ "tsx": "4.23.1",
51
+ "typescript": "6.0.3",
52
+ "vitest": "4.1.10"
53
+ },
54
+ "engines": {
55
+ "node": ">=24.14.0"
56
+ },
57
57
  "scripts": {
58
- "build": "tsdown",
59
- "dev": "tsdown --watch",
60
- "start": "node dist/index.mjs"
58
+ "build": "tsdown --config tsdown.config.ts",
59
+ "dev": "tsx --conditions=namera-source src/index.ts",
60
+ "format": "oxfmt . --write --no-error-on-unmatched-pattern",
61
+ "format:check": "oxfmt . --check --no-error-on-unmatched-pattern",
62
+ "lint": "oxlint . --no-error-on-unmatched-pattern",
63
+ "lint:fix": "oxlint . --fix --no-error-on-unmatched-pattern",
64
+ "start": "node dist/index.js",
65
+ "test": "NODE_OPTIONS=--conditions=namera-source vitest run",
66
+ "typecheck": "tsc -p tsconfig.json --pretty false",
67
+ "typecheck:test": "tsc -p tsconfig.test.json --pretty false"
61
68
  }
62
69
  }