@sol-merrai/cli 0.2.0 → 0.10.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.
package/dist/bin.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.mjs","names":["fs","packageMetadata.version"],"sources":["../src/client.ts","../package.json","../src/config.ts","../src/errors.ts","../src/input.ts","../src/commands/auth.ts","../src/commands/debug.ts","../src/commands/shared.ts","../src/commands/entity.ts","../src/commands/ingest.ts","../src/commands/living-document.ts","../src/commands/memory.ts","../src/commands/system.ts","../src/output.ts","../src/runtime.ts","../src/program.ts","../src/bin.ts"],"sourcesContent":["import { createORPCClient, createSafeClient } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\n\nexport type RpcProcedure<Input = unknown, Output = unknown> = (\n input?: Input\n) => Promise<readonly [unknown, Output, ...unknown[]]>;\n\nexport type ThrowingRpcProcedure<Input = unknown, Output = unknown> = (\n input?: Input\n) => Promise<Output>;\n\nexport type EntityType =\n | \"person\"\n | \"event\"\n | \"action\"\n | \"knowledge\"\n | \"document\";\n\nexport type JsonValue =\n | boolean\n | number\n | string\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport interface AddMemoryInput {\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n}\n\nexport interface AddMemoryOutput {\n queued: boolean;\n workflowId: string;\n}\n\nexport interface AddMemoryRecallInput {\n memory: string;\n observationDate?: string;\n}\n\nexport interface AddMemoryRecallOutput {\n processing: true;\n status: \"enqueued\";\n}\n\nexport interface AddMemoriesInput {\n memories: {\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n }[];\n}\n\nexport interface AddMemoriesOutput {\n failures: { error: string; groupKey: string | null }[];\n queued: number;\n workflowId: string;\n}\n\nexport interface FindMemoryEntitiesInput {\n name: string;\n type?: EntityType;\n limit?: number;\n}\n\nexport interface MemoriesByEntityInput {\n entityId: string;\n limit?: number;\n}\n\nexport interface MemoriesByDateInput {\n start?: string;\n end?: string;\n limit?: number;\n}\n\nexport interface MemoryRecallResult {\n category: string | null;\n content: string;\n id: string;\n lobeKey: string;\n recordedAt: string;\n}\n\nexport interface FindMemoryEntitiesOutput {\n entities: {\n displayName: string;\n id: string;\n memoryCount: number;\n name: string;\n type: EntityType;\n }[];\n suggestedNextAction: {\n entityIds: string[];\n tool: \"search_memories_by_entity\";\n when: string;\n } | null;\n}\n\nexport interface SearchMemoryRecallInput {\n limit?: number;\n query: string;\n}\n\nexport interface SearchMemoryRecallOutput {\n memories: MemoryRecallResult[];\n suggestedNextAction: {\n consentRequired: true;\n tool: \"add_memory\";\n when: string;\n } | null;\n}\n\nexport interface MemoriesByEntityOutput {\n entity: {\n displayName: string;\n id: string;\n type: EntityType;\n };\n memories: MemoryRecallResult[];\n}\n\nexport interface MemoriesByDateOutput {\n memories: MemoryRecallResult[];\n range: {\n end: string | null;\n start: string | null;\n };\n}\n\nexport interface MemoryOverviewOutput {\n account: {\n name: string;\n numberOfAiTools: number | null;\n preferredMessagingChannel: string | null;\n primaryRole: string | null;\n workplace: string | null;\n };\n profile: {\n facts: Omit<MemoryRecallResult, \"id\">[];\n ongoingContext: Omit<MemoryRecallResult, \"id\">[];\n scope: string;\n suggestions: {\n expiresAt: string | null;\n text: string;\n }[];\n updatedAt: string;\n } | null;\n suggestedNextAction: {\n tool: \"search_memory\";\n when: string;\n };\n}\n\nexport interface ListLivingDocumentsInput {\n status?: (\"enabled\" | \"disabled\" | \"archived\")[];\n}\n\nexport type LivingDocumentStatus = \"enabled\" | \"disabled\" | \"archived\";\n\nexport interface LivingDocument {\n autoPublish: boolean;\n createdAt: string;\n currentApprovedVersionId: string | null;\n currentVersionId: string | null;\n description: string | null;\n entities: string[];\n extractionPrompt: string;\n id: string;\n patchFailureCount: number;\n routingSummary: string | null;\n routingSummaryDirty: boolean;\n status: LivingDocumentStatus;\n title: string;\n triggerKeywords: string[];\n updatedAt: string;\n}\n\nexport interface LivingDocumentVersion {\n causedByMemoryIds: string[];\n causedByRunId: string | null;\n contentMd: string;\n contentMdSummary: string | null;\n createdAt: string;\n documentId: string;\n extractorModel: string | null;\n id: string;\n parentVersionId: string | null;\n patch: JsonValue;\n updatedAt: string;\n versionNumber: number;\n}\n\nexport interface LivingDocumentShare {\n createdAt: string;\n documentId: string;\n expiresAt: string | null;\n id: string;\n mode: \"pinned\" | \"live\";\n permissions: \"view\" | \"view+comment\";\n revokedAt: string | null;\n shareToken: string;\n updatedAt: string;\n versionId: string | null;\n}\n\nexport interface ListLivingDocumentsOutput {\n documents: LivingDocument[];\n slots: {\n limit: number;\n plan: string;\n remaining: number;\n used: number;\n };\n}\n\nexport interface ListLivingDocumentsRecallOutput {\n documents: {\n autoPublish: boolean;\n currentVersion: { createdAt: string; number: number } | null;\n id: string;\n status: string;\n summary: string;\n title: string;\n }[];\n}\n\nexport interface ReadLivingDocumentRecallInput {\n documentId: string;\n}\n\nexport interface ReadLivingDocumentRecallOutput {\n document: {\n activeShares: {\n expiresAt: string | null;\n mode: string;\n permissions: string;\n url: string;\n versionId: string | null;\n }[];\n autoPublish: boolean;\n currentVersion: {\n contentMarkdown: string;\n createdAt: string;\n id: string;\n number: number;\n } | null;\n description: string | null;\n entities: string[];\n headings: string[];\n id: string;\n status: string;\n summary: string;\n title: string;\n triggerKeywords: string[];\n };\n}\n\nexport interface GetLivingDocumentOutput {\n currentVersion: LivingDocumentVersion | null;\n document: LivingDocument;\n}\n\nexport interface ListLivingDocumentSharesOutput {\n shares: LivingDocumentShare[];\n}\n\nexport interface GetLivingDocumentInput {\n id: string;\n}\n\nexport interface ListLivingDocumentSharesInput {\n documentId: string;\n}\n\nexport interface AddChatSessionInput {\n memories: {\n memory: string;\n source?: string;\n }[];\n lobeKey?: string;\n source?: string;\n sessionMetadata?: Record<string, unknown>;\n}\n\nexport interface AddChatSessionOutput {\n queued: number;\n workflowId: string;\n}\n\nexport interface AddChatSessionsInput {\n lobeKey?: string;\n source?: string;\n questionMetadata?: Record<string, unknown>;\n /**\n * Override the V3 extractor's prompt profile.\n * - `general` — default chat-ingest extraction.\n * - `agent` — agent-scoped ingests (no user, only agent_id).\n * - `code-personal` — coding-session bias (developer intent over\n * assistant scaffolding, code-specific entities).\n * When omitted, the server resolves a profile from `source`\n * (e.g. `claude-code` → `code-personal`); use this only to override\n * that mapping or for sources the server hasn't pre-mapped.\n */\n extractionProfile?: \"general\" | \"agent\" | \"code-personal\";\n /**\n * Optional idempotency key (1-64 chars, [A-Za-z0-9_-]). When supplied,\n * retries with the same key short-circuit on the server instead of\n * re-running the ingest pipeline. Derive deterministically from\n * (sessionId, turnRange) so retries collide but distinct flushes do not.\n */\n idempotencyKey?: string;\n sessions: {\n sessionId: string;\n metadata?: Record<string, unknown>;\n turns: {\n content: string;\n role: \"user\" | \"assistant\";\n speaker?: string;\n turnIndex: number;\n }[];\n }[];\n}\n\nexport interface AddChatSessionsOutput {\n queuedSessions: number;\n workflowId: string;\n}\n\nexport interface SearchMemoriesInput {\n query: string;\n lobeKey?: string;\n limit?: number;\n threshold?: number;\n mode?: \"fast\" | \"adaptive\" | \"reflective\";\n graph?: {\n enabled?: boolean;\n maxNeighborsPerSeed?: number;\n maxTotalNeighbors?: number;\n };\n}\n\nexport interface SearchMemoryHit {\n category: string | null;\n content: string;\n id: string;\n memoryDate: string;\n score: number;\n summary: string | null;\n}\n\nexport interface MemoryStatusInput {\n lobeKey?: string;\n}\n\nexport interface MemoryStatusOutput {\n count: number;\n}\n\nexport interface ClearLobeInput {\n lobeKey: string;\n}\n\nexport interface ClearLobeOutput {\n deleted: number;\n}\n\nexport interface MemoryListItem {\n category: string | null;\n content: string;\n createdAt: string;\n expiresAt: string | null;\n id: string;\n isCurrent: string;\n lobeKey: string;\n memoryAt: string | null;\n memoryKind: string;\n metadata: JsonValue | null;\n summary: string | null;\n supersededByMemoryId: string | null;\n updatedAt: string;\n}\n\nexport interface AuthSessionOutput {\n session: {\n createdAt: string | null;\n expiresAt: string | null;\n id: string;\n ipAddress: string | null;\n token: string;\n updatedAt: string | null;\n userAgent: string | null;\n userId: string;\n };\n user: {\n createdAt: string | null;\n email: string;\n emailVerified: boolean;\n id: string;\n image: string | null;\n name: string;\n onboardingComplete: boolean;\n updatedAt: string | null;\n };\n}\n\nexport type UsagePlan = \"free\" | \"beta\";\nexport type UsageMeter =\n | \"assistant_messages\"\n | \"automation_executions\"\n | \"llm_tokens\"\n | \"memory_processed\";\n\nexport interface UsageMeterSummary {\n allowed: boolean;\n current: number;\n limit: number | null;\n meter: UsageMeter;\n periodKey: string;\n plan: UsagePlan;\n remaining: number | null;\n userId: string;\n}\n\nexport interface UsageSummaryOutput {\n billing: {\n hasPaidPlan: boolean;\n plan: UsagePlan;\n scheduledDowngradeAt: string | null;\n };\n llm: {\n byModel: {\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n requests: number;\n totalTokens: number;\n }[];\n bySurface: {\n inputTokens: number;\n outputTokens: number;\n requests: number;\n surface: string;\n totalTokens: number;\n }[];\n recentRequests: {\n cachedInputTokens: number;\n createdAt: string;\n id: string;\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n reasoningTokens: number;\n requestId: string | null;\n surface: string;\n totalTokens: number;\n }[];\n totals: {\n cachedInputTokens: number;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number;\n requests: number;\n totalTokens: number;\n };\n };\n meters: {\n automationExecutions: UsageMeterSummary;\n llmTokens: UsageMeterSummary;\n memoryProcessed: UsageMeterSummary;\n };\n periodStart: string;\n plan: UsagePlan;\n plans: {\n automations: number | null;\n id: UsagePlan;\n memories: number | null;\n tokens: number | null;\n }[];\n}\n\nexport interface GetSessionStartContextInput {\n /**\n * Restrict to a single lobe. Plugin callers pass `cc:<repo-slug>` so memory\n * is scoped to the active project. Omit to read across every lobe.\n */\n lobeKey?: string;\n /**\n * Short retrieval hints biased toward what the caller is about to do\n * (e.g. current git branch name, last commit subject, cwd basename).\n * Cap: 5 hints × 200 chars.\n */\n recentHints?: string[];\n /**\n * Caller-side budget. Server hard caps both numbers regardless.\n */\n budget?: {\n /** Default 15, hard cap 30. */\n maxMemories?: number;\n /** Default 2000, hard cap 4000. Char-based estimate (chars / 4). */\n maxTokens?: number;\n };\n}\n\nexport interface GetSessionStartContextOutput {\n /** Markdown block ready to drop into a hook's `additionalContext`. */\n markdown: string;\n /** IDs of every memory referenced in the markdown. */\n memoryIds: string[];\n /** True when the response was truncated by the budget. */\n hasMore: boolean;\n /** Server-side ISO 8601 timestamp the context was generated. */\n generatedAt: string;\n}\n\ninterface MerraiProcedureContract {\n addChatSession: {\n input: AddChatSessionInput;\n output: AddChatSessionOutput;\n };\n addChatSessions: {\n input: AddChatSessionsInput;\n output: AddChatSessionsOutput;\n };\n addMemories: { input: AddMemoriesInput; output: AddMemoriesOutput };\n addMemory: { input: AddMemoryInput; output: AddMemoryOutput };\n clearLobe: { input: ClearLobeInput; output: ClearLobeOutput };\n findMemoryEntities: {\n input: FindMemoryEntitiesInput;\n output: FindMemoryEntitiesOutput;\n };\n getLivingDocument: {\n input: GetLivingDocumentInput;\n output: GetLivingDocumentOutput;\n };\n getSessionStartContext: {\n input: GetSessionStartContextInput;\n output: GetSessionStartContextOutput;\n };\n healthCheck: { input: undefined; output: \"OK\" };\n listLivingDocuments: {\n input: ListLivingDocumentsInput;\n output: ListLivingDocumentsOutput;\n };\n listLivingDocumentShares: {\n input: ListLivingDocumentSharesInput;\n output: ListLivingDocumentSharesOutput;\n };\n memories: { input: undefined; output: MemoryListItem[] };\n memoriesByDate: {\n input: MemoriesByDateInput;\n output: MemoriesByDateOutput;\n };\n memoriesByEntity: {\n input: MemoriesByEntityInput;\n output: MemoriesByEntityOutput;\n };\n memoryOverview: { input: undefined; output: MemoryOverviewOutput };\n memoryStatus: { input: MemoryStatusInput; output: MemoryStatusOutput };\n searchMemories: { input: SearchMemoriesInput; output: SearchMemoryHit[] };\n session: { input: undefined; output: AuthSessionOutput | null };\n usageSummary: { input: undefined; output: UsageSummaryOutput };\n}\n\ninterface MerraiRecallProcedureContract {\n addMemory: {\n input: AddMemoryRecallInput;\n output: AddMemoryRecallOutput;\n };\n listLivingDocuments: {\n input: undefined;\n output: ListLivingDocumentsRecallOutput;\n };\n readLivingDocument: {\n input: ReadLivingDocumentRecallInput;\n output: ReadLivingDocumentRecallOutput;\n };\n searchMemory: {\n input: SearchMemoryRecallInput;\n output: SearchMemoryRecallOutput;\n };\n}\n\ntype SafeProcedureClient<Contract> = {\n [ProcedureName in keyof Contract]: Contract[ProcedureName] extends {\n input: infer Input;\n output: infer Output;\n }\n ? RpcProcedure<Input, Output>\n : never;\n};\n\ntype ThrowingProcedureClient<Contract> = {\n [ProcedureName in keyof Contract]: Contract[ProcedureName] extends {\n input: infer Input;\n output: infer Output;\n }\n ? ThrowingRpcProcedure<Input, Output>\n : never;\n};\n\nexport type MerraiClient = SafeProcedureClient<MerraiProcedureContract> & {\n recall: SafeProcedureClient<MerraiRecallProcedureContract>;\n};\n\nexport type MerraiThrowingClient =\n ThrowingProcedureClient<MerraiProcedureContract> & {\n recall: ThrowingProcedureClient<MerraiRecallProcedureContract>;\n };\n\nexport interface MerraiClientOptions {\n baseURL?: string;\n apiKey?: string;\n cookie?: string;\n fetch?: typeof fetch;\n headers?: HeadersInit;\n}\n\nexport const resolveBaseURL = (baseURL?: string) => {\n const resolved = baseURL?.trim();\n\n if (!resolved) {\n throw new Error(\n \"baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials\"\n );\n }\n\n return resolved.endsWith(\"/\") ? resolved.slice(0, -1) : resolved;\n};\n\nconst resolveHeaders = (\n headers?: HeadersInit,\n apiKey?: string,\n cookie?: string\n): Record<string, string> => {\n const resolvedHeaders = new Headers(headers);\n\n if (apiKey) {\n resolvedHeaders.set(\"x-api-key\", apiKey);\n }\n\n if (cookie) {\n resolvedHeaders.set(\"Cookie\", cookie);\n }\n\n return Object.fromEntries(resolvedHeaders.entries());\n};\n\nexport const createRawMerraiClient = (options: MerraiClientOptions = {}) => {\n const link = new RPCLink({\n fetch: options.fetch,\n headers: () =>\n resolveHeaders(options.headers, options.apiKey, options.cookie),\n url: `${resolveBaseURL(options.baseURL)}/rpc`,\n });\n\n return createORPCClient(link);\n};\n\nexport const createMerraiClient = (options: MerraiClientOptions = {}) =>\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Legacy cast requires typed boundary validation.\n createSafeClient(createRawMerraiClient(options)) as unknown as MerraiClient;\n\nexport const createMerraiThrowingClient = (\n options: MerraiClientOptions = {}\n): MerraiThrowingClient =>\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- oRPC is dynamic without the server contract package; keep the cast at this construction seam.\n createRawMerraiClient(options) as unknown as MerraiThrowingClient;\n","","import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport type { MerraiClientOptions } from \"./client\";\n\nexport const DEFAULT_MERRAI_BASE_URL = \"https://api.merrai.app\";\nconst CREDENTIALS_VERSION = 1;\n\nexport type MerraiCliEnvironment = Readonly<Record<string, string | undefined>>;\n\nexport interface MerraiCliConnectionOverrides {\n apiKey?: string;\n baseURL?: string;\n cookie?: string;\n}\n\nexport interface MerraiCredentials {\n apiKey: string;\n baseURL?: string;\n savedAt: string;\n version: typeof CREDENTIALS_VERSION;\n}\n\nexport interface MerraiConfigPaths {\n credentials: string;\n directory: string;\n legacyClaudeCredentials: string;\n}\n\nconst trimmed = (value: string | undefined): string | undefined => {\n const result = value?.trim();\n return result === undefined || result.length === 0 ? undefined : result;\n};\n\nconst isUnknownRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst resolveHomeDirectory = (env: MerraiCliEnvironment): string =>\n trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? os.homedir();\n\nexport const resolveMerraiConfigPaths = (\n env: MerraiCliEnvironment\n): MerraiConfigPaths => {\n const home = resolveHomeDirectory(env);\n const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);\n const windowsAppData = trimmed(env.APPDATA);\n const directory = xdgConfigHome\n ? path.join(xdgConfigHome, \"merrai\")\n : process.platform === \"win32\" && windowsAppData\n ? path.join(windowsAppData, \"Merrai\")\n : path.join(home, \".config\", \"merrai\");\n\n return {\n credentials: path.join(directory, \"credentials.json\"),\n directory,\n legacyClaudeCredentials: path.join(\n home,\n \".merrai-claude-code\",\n \"credentials.json\"\n ),\n };\n};\n\nconst parseCredentials = (\n raw: string,\n options: { requireVersion: boolean }\n): MerraiCredentials | null => {\n try {\n const value: unknown = JSON.parse(raw);\n if (!isUnknownRecord(value)) {\n return null;\n }\n\n if (options.requireVersion && value.version !== CREDENTIALS_VERSION) {\n return null;\n }\n const apiKey =\n typeof value.apiKey === \"string\" ? trimmed(value.apiKey) : undefined;\n const baseURL =\n typeof value.baseURL === \"string\" ? trimmed(value.baseURL) : undefined;\n if (apiKey === undefined) {\n return null;\n }\n\n return {\n apiKey,\n ...(baseURL === undefined ? {} : { baseURL }),\n savedAt:\n typeof value.savedAt === \"string\"\n ? value.savedAt\n : new Date(0).toISOString(),\n version: CREDENTIALS_VERSION,\n };\n } catch {\n return null;\n }\n};\n\nconst readCredentialsFile = (\n file: string,\n options: { requireVersion: boolean; strict: boolean }\n): MerraiCredentials | null => {\n if (!fs.existsSync(file)) {\n return null;\n }\n try {\n const credentials = parseCredentials(fs.readFileSync(file, \"utf8\"), {\n requireVersion: options.requireVersion,\n });\n if (credentials === null && options.strict) {\n throw new Error(\n `Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`\n );\n }\n return credentials;\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n return null;\n }\n};\n\nexport const loadMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { strict?: boolean } = {}\n): MerraiCredentials | null => {\n const paths = resolveMerraiConfigPaths(env);\n return (\n readCredentialsFile(paths.credentials, {\n requireVersion: true,\n strict: options.strict === true,\n }) ??\n readCredentialsFile(paths.legacyClaudeCredentials, {\n requireVersion: false,\n strict: options.strict === true,\n })\n );\n};\n\nexport const saveMerraiCredentials = (\n env: MerraiCliEnvironment,\n input: { apiKey: string; baseURL?: string }\n): MerraiCredentials => {\n const apiKey = trimmed(input.apiKey);\n if (apiKey === undefined) {\n throw new Error(\"API key cannot be empty\");\n }\n\n const paths = resolveMerraiConfigPaths(env);\n fs.mkdirSync(paths.directory, { mode: 0o700, recursive: true });\n fs.chmodSync(paths.directory, 0o700);\n const credentials: MerraiCredentials = {\n apiKey,\n baseURL: trimmed(input.baseURL) ?? DEFAULT_MERRAI_BASE_URL,\n savedAt: new Date().toISOString(),\n version: CREDENTIALS_VERSION,\n };\n fs.writeFileSync(paths.credentials, JSON.stringify(credentials, null, 2), {\n mode: 0o600,\n });\n fs.chmodSync(paths.credentials, 0o600);\n return credentials;\n};\n\nconst removeFileIfPresent = (file: string): boolean => {\n try {\n fs.unlinkSync(file);\n return true;\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n};\n\nexport const clearMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { includeLegacy?: boolean } = {}\n): boolean => {\n const paths = resolveMerraiConfigPaths(env);\n const removedShared = removeFileIfPresent(paths.credentials);\n const removedLegacy =\n options.includeLegacy === true\n ? removeFileIfPresent(paths.legacyClaudeCredentials)\n : false;\n return removedShared || removedLegacy;\n};\n\nexport const resolveMerraiClientOptions = (\n env: MerraiCliEnvironment,\n overrides: MerraiCliConnectionOverrides,\n options: { strictCredentials?: boolean } = {}\n): MerraiClientOptions => {\n const apiKeyOverride =\n trimmed(overrides.apiKey) ?? trimmed(env.MERRAI_API_KEY);\n const baseURLOverride =\n trimmed(overrides.baseURL) ?? trimmed(env.MERRAI_BASE_URL);\n const credentials =\n apiKeyOverride !== undefined && baseURLOverride !== undefined\n ? null\n : loadMerraiCredentials(env, {\n strict: options.strictCredentials !== false,\n });\n return {\n apiKey: apiKeyOverride ?? credentials?.apiKey,\n baseURL: baseURLOverride ?? credentials?.baseURL ?? DEFAULT_MERRAI_BASE_URL,\n cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE),\n };\n};\n","import { ORPCError } from \"@orpc/client\";\nimport { CommanderError } from \"commander\";\n\nexport const MERRAI_CLI_EXIT_CODES = {\n auth: 3,\n network: 10,\n notFound: 4,\n rateLimit: 5,\n success: 0,\n usage: 2,\n} as const;\n\nexport class MerraiCliUsageError extends Error {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"MerraiCliUsageError\";\n }\n}\n\nexport interface MerraiCliErrorResult {\n exitCode: number;\n message: string;\n shouldRender: boolean;\n}\n\nconst renderJsonError = (\n message: string,\n metadata: Readonly<Record<string, unknown>> = {}\n): string => JSON.stringify({ error: { ...metadata, message } }, null, 2);\n\nconst renderOrpcError = (error: ORPCError<string, unknown>): string =>\n renderJsonError(error.message, {\n code: error.code,\n ...(error.data === undefined ? {} : { data: error.data }),\n status: error.status,\n });\n\nexport const classifyMerraiCliError = (\n error: unknown\n): MerraiCliErrorResult => {\n if (error instanceof CommanderError) {\n const isSuccessfulControlFlow =\n error.code === \"commander.helpDisplayed\" ||\n error.code === \"commander.version\";\n return {\n exitCode: isSuccessfulControlFlow\n ? MERRAI_CLI_EXIT_CODES.success\n : MERRAI_CLI_EXIT_CODES.usage,\n message: error.message,\n shouldRender: false,\n };\n }\n\n if (error instanceof MerraiCliUsageError) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.usage,\n message: renderJsonError(error.message, { code: \"USAGE_ERROR\" }),\n shouldRender: true,\n };\n }\n\n if (error instanceof ORPCError) {\n const code = error.code;\n if (code === \"BAD_REQUEST\" || code === \"UNPROCESSABLE_CONTENT\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.usage,\n message: renderOrpcError(error),\n shouldRender: true,\n };\n }\n if (code === \"UNAUTHORIZED\" || code === \"FORBIDDEN\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.auth,\n message: renderOrpcError(error),\n shouldRender: true,\n };\n }\n if (code === \"NOT_FOUND\" || code === \"CONFLICT\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.notFound,\n message: renderOrpcError(error),\n shouldRender: true,\n };\n }\n if (\n code === \"RATE_LIMITED\" ||\n code === \"TOO_MANY_REQUESTS\" ||\n code === \"PAYLOAD_TOO_LARGE\" ||\n code === \"RESOURCE_EXHAUSTED\" ||\n error.status === 429\n ) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.rateLimit,\n message: renderOrpcError(error),\n shouldRender: true,\n };\n }\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.network,\n message: renderOrpcError(error),\n shouldRender: true,\n };\n }\n\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.network,\n message: renderJsonError(\n error instanceof Error ? error.message : String(error),\n { code: \"NETWORK_ERROR\" }\n ),\n shouldRender: true,\n };\n};\n","import type { Readable, Writable } from \"node:stream\";\n\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\n\nimport { MerraiCliUsageError } from \"./errors\";\n\nconst readStream = async (stream: Readable): Promise<string> => {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readFileOrStdin = async (options: {\n cwd: string;\n file: string;\n stdin: Readable;\n}): Promise<string> => {\n if (options.file === \"-\") {\n return readStream(options.stdin);\n }\n const resolvedPath = path.resolve(options.cwd, options.file);\n try {\n return await fs.readFile(resolvedPath, \"utf8\");\n } catch (error) {\n throw new MerraiCliUsageError(\n `Unable to read ${resolvedPath}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n );\n }\n};\n\nexport const readStructuredInput = async (options: {\n cwd: string;\n file?: string;\n input?: string;\n stdin: Readable;\n}): Promise<unknown> => {\n if (options.file !== undefined && options.input !== undefined) {\n throw new MerraiCliUsageError(\"Use only one of --input or --file\");\n }\n if (options.file === undefined && options.input === undefined) {\n throw new MerraiCliUsageError(\"Provide --input <json> or --file <path|->\");\n }\n\n const source =\n options.input ??\n (await readFileOrStdin({\n cwd: options.cwd,\n file: options.file!,\n stdin: options.stdin,\n }));\n try {\n return JSON.parse(source) as unknown;\n } catch (error) {\n const label = options.file === undefined ? \"--input\" : options.file;\n throw new MerraiCliUsageError(\n `Invalid JSON from ${label}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n );\n }\n};\n\nexport const readTextInput = async (options: {\n cwd: string;\n file?: string;\n option?: string;\n positional?: string;\n stdin: Readable;\n}): Promise<string> => {\n const directValues = [options.positional, options.option].filter(\n (value): value is string => value !== undefined\n );\n if (\n directValues.length > 1 ||\n (options.file !== undefined && directValues.length > 0)\n ) {\n throw new MerraiCliUsageError(\n \"Provide memory text using only one positional value, --memory, or --file\"\n );\n }\n\n const value =\n directValues[0] ??\n (options.file === undefined\n ? undefined\n : await readFileOrStdin({\n cwd: options.cwd,\n file: options.file,\n stdin: options.stdin,\n }));\n if (value === undefined || value.trim().length === 0) {\n throw new MerraiCliUsageError(\"Memory text cannot be empty\");\n }\n return value;\n};\n\nexport const confirmAction = async (options: {\n input: Readable;\n message: string;\n output: Writable;\n}): Promise<boolean> => {\n const terminal = \"isTTY\" in options.input && options.input.isTTY === true;\n if (!terminal) {\n return false;\n }\n const prompt = createInterface({\n input: options.input,\n output: options.output,\n });\n try {\n const answer = await prompt.question(`${options.message} [y/N] `);\n return (\n answer.trim().toLowerCase() === \"y\" ||\n answer.trim().toLowerCase() === \"yes\"\n );\n } finally {\n prompt.close();\n }\n};\n\ninterface RawModeReadable extends Readable {\n isRaw?: boolean;\n isTTY?: boolean;\n setRawMode?: (mode: boolean) => void;\n}\n\nexport const readSecretInput = async (options: {\n input: Readable;\n message: string;\n output: Writable;\n}): Promise<string> => {\n const input = options.input as RawModeReadable;\n if (input.isTTY !== true || input.setRawMode === undefined) {\n throw new MerraiCliUsageError(\n \"Provide the API key as an argument or through MERRAI_API_KEY in noninteractive use\"\n );\n }\n\n options.output.write(options.message);\n const wasRaw = input.isRaw === true;\n input.setRawMode(true);\n\n return new Promise<string>((resolve, reject) => {\n let value = \"\";\n const cleanup = (): void => {\n input.off(\"data\", onData);\n input.off(\"end\", onEnd);\n input.off(\"error\", onError);\n input.setRawMode?.(wasRaw);\n input.pause();\n };\n const rejectInput = (error: Error): void => {\n cleanup();\n reject(error);\n };\n const onEnd = (): void => {\n rejectInput(new MerraiCliUsageError(\"API key entry ended unexpectedly\"));\n };\n const onError = (error: Error): void => {\n rejectInput(\n new MerraiCliUsageError(`Unable to read API key: ${error.message}`, {\n cause: error,\n })\n );\n };\n const onData = (chunk: Buffer | string): void => {\n const text = Buffer.isBuffer(chunk) ? chunk.toString(\"utf8\") : chunk;\n for (const character of text) {\n if (character === \"\\r\" || character === \"\\n\") {\n options.output.write(\"\\n\");\n cleanup();\n resolve(value);\n return;\n }\n if (character === \"\\u0003\" || character === \"\\u0004\") {\n options.output.write(\"\\n\");\n rejectInput(new MerraiCliUsageError(\"API key entry cancelled\"));\n return;\n }\n if (character === \"\\u007f\" || character === \"\\b\") {\n if (value.length > 0) {\n value = value.slice(0, -1);\n options.output.write(\"\\b \\b\");\n }\n continue;\n }\n value += character;\n options.output.write(\"*\");\n }\n };\n input.on(\"data\", onData);\n input.once(\"end\", onEnd);\n input.once(\"error\", onError);\n input.resume();\n });\n};\n","import type { Command } from \"commander\";\n\nimport type { MerraiCommandContext } from \"../runtime\";\n\nimport {\n clearMerraiCredentials,\n loadMerraiCredentials,\n resolveMerraiClientOptions,\n resolveMerraiConfigPaths,\n saveMerraiCredentials,\n} from \"../config\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport { confirmAction, readSecretInput } from \"../input\";\n\ninterface GlobalOptions {\n apiKey?: string;\n baseUrl?: string;\n}\n\ninterface LogoutOptions {\n yes?: boolean;\n}\n\nexport const registerAuthCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const auth = program.command(\"auth\").description(\"Manage CLI credentials\");\n\n auth\n .command(\"set-key\")\n .argument(\"[apiKey]\", \"Merrai API key\")\n .description(\"Validate and save an API key\")\n .action(\n async (\n positional: string | undefined,\n _options: unknown,\n actionCommand: Command\n ) => {\n const globals = actionCommand.optsWithGlobals<GlobalOptions>();\n const apiKey =\n positional?.trim() ||\n globals.apiKey?.trim() ||\n context.runtime.env.MERRAI_API_KEY?.trim() ||\n (await readSecretInput({\n input: context.runtime.stdin,\n message: \"Merrai API key: \",\n output: context.runtime.stderr,\n }));\n if (apiKey.length === 0) {\n throw new MerraiCliUsageError(\"API key cannot be empty\");\n }\n const connection = resolveMerraiClientOptions(\n context.runtime.env,\n {\n apiKey,\n baseURL: globals.baseUrl,\n },\n { strictCredentials: false }\n );\n await context.runtime.createClient(connection).memoryStatus({});\n const credentials = saveMerraiCredentials(context.runtime.env, {\n apiKey,\n baseURL: connection.baseURL,\n });\n context\n .output(actionCommand)\n .data(\n { authenticated: true, baseURL: credentials.baseURL },\n () => `Saved API key for ${credentials.baseURL}.`\n );\n }\n );\n\n auth\n .command(\"status\")\n .description(\"Show credential status without revealing the key\")\n .action(async (_options: unknown, actionCommand: Command) => {\n const credentials = loadMerraiCredentials(context.runtime.env, {\n strict: true,\n });\n const paths = resolveMerraiConfigPaths(context.runtime.env);\n const result = {\n authenticated:\n credentials !== null ||\n (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0,\n baseURL: credentials?.baseURL ?? null,\n configured: credentials !== null,\n credentialsPath: paths.credentials,\n environmentKeySet:\n (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0,\n };\n context\n .output(actionCommand)\n .data(result, () =>\n result.configured\n ? `Authenticated for ${result.baseURL}.`\n : result.environmentKeySet\n ? \"Authenticated through MERRAI_API_KEY.\"\n : \"No saved CLI credentials.\"\n );\n });\n\n auth\n .command(\"logout\")\n .description(\"Remove saved CLI credentials\")\n .option(\"--yes\", \"Skip confirmation\")\n .action(async (options: LogoutOptions, actionCommand: Command) => {\n if (options.yes !== true) {\n const confirmed = await confirmAction({\n input: context.runtime.stdin,\n message: \"Remove saved Merrai CLI credentials?\",\n output: context.runtime.stderr,\n });\n if (!confirmed) {\n throw new MerraiCliUsageError(\n \"Logout cancelled. Use --yes for noninteractive confirmation.\"\n );\n }\n }\n const removed = clearMerraiCredentials(context.runtime.env, {\n includeLegacy: true,\n });\n const output = context.output(actionCommand);\n output.data({ removed }, () =>\n removed ? \"Removed saved credentials.\" : \"No saved credentials found.\"\n );\n if ((context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0) {\n output.diagnostic(\n \"MERRAI_API_KEY is still set; commands will continue using it.\"\n );\n }\n });\n};\n","import type { Command } from \"commander\";\n\nimport type { MerraiCommandContext } from \"../runtime\";\n\nimport { MerraiCliUsageError } from \"../errors\";\nimport { readStructuredInput } from \"../input\";\n\ninterface RpcOptions {\n file?: string;\n input?: string;\n}\n\nconst configureRpcCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"<procedure>\", \"Top-level oRPC procedure\")\n .option(\"--input <json>\", \"Inline JSON input\")\n .option(\"--file <path>\", \"Read JSON input from a file, or - for stdin\")\n .action(\n async (\n procedureName: string,\n options: RpcOptions,\n actionCommand: Command\n ) => {\n const client = context.client(actionCommand);\n const procedure: unknown = Reflect.get(client, procedureName);\n if (typeof procedure !== \"function\") {\n throw new MerraiCliUsageError(`Unknown procedure: ${procedureName}`);\n }\n const hasInput =\n options.input !== undefined || options.file !== undefined;\n const input = hasInput\n ? await readStructuredInput({\n cwd: context.runtime.cwd,\n file: options.file,\n input: options.input,\n stdin: context.runtime.stdin,\n })\n : undefined;\n const result = await procedure(input);\n context.output(actionCommand).data(result);\n }\n );\n};\n\nexport const registerDebugCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const debug = program\n .command(\"debug\")\n .description(\"Unstable debugging commands\");\n configureRpcCommand(\n debug.command(\"rpc\").description(\"Call a top-level oRPC procedure\"),\n context\n );\n configureRpcCommand(\n program\n .command(\"rpc\", { hidden: true })\n .description(\"Legacy raw oRPC command\"),\n context\n );\n};\n","import { MerraiCliUsageError } from \"../errors\";\n\nconst ISO_8601_DATETIME_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/;\n\nexport const resolveLobeKey = (options: {\n lobe?: string;\n lobeKey?: string;\n}): string | undefined => options.lobe ?? options.lobeKey;\n\nexport const parseIntegerOption = (\n value: string | undefined,\n name: string,\n range: { maximum: number; minimum: number }\n): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n const parsed = Number(value);\n if (\n !Number.isInteger(parsed) ||\n parsed < range.minimum ||\n parsed > range.maximum\n ) {\n throw new MerraiCliUsageError(\n `${name} must be an integer from ${range.minimum} to ${range.maximum}`\n );\n }\n return parsed;\n};\n\nexport const parseNumberOption = (\n value: string | undefined,\n name: string,\n range: { maximum: number; minimum: number }\n): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n const parsed = Number(value);\n if (\n !Number.isFinite(parsed) ||\n parsed < range.minimum ||\n parsed > range.maximum\n ) {\n throw new MerraiCliUsageError(\n `${name} must be a number from ${range.minimum} to ${range.maximum}`\n );\n }\n return parsed;\n};\n\nexport const parseDateOption = (\n value: string | undefined,\n name: string\n): string | undefined => {\n if (value === undefined) {\n return undefined;\n }\n if (\n !ISO_8601_DATETIME_PATTERN.test(value) ||\n Number.isNaN(new Date(value).getTime())\n ) {\n throw new MerraiCliUsageError(`${name} must be a valid ISO 8601 datetime`);\n }\n return value;\n};\n\nexport const parseEntityType = (\n value: string | undefined\n): import(\"../client\").EntityType | undefined => {\n if (value === undefined) {\n return undefined;\n }\n switch (value) {\n case \"action\":\n case \"document\":\n case \"event\":\n case \"knowledge\":\n case \"person\":\n return value;\n default:\n throw new MerraiCliUsageError(\n \"--type must be one of: person, event, action, knowledge, document\"\n );\n }\n};\n","import type { Command } from \"commander\";\n\nimport type {\n FindMemoryEntitiesOutput,\n MemoriesByEntityOutput,\n} from \"../client\";\nimport type { MerraiCommandContext } from \"../runtime\";\n\nimport { MerraiCliUsageError } from \"../errors\";\nimport { parseEntityType, parseIntegerOption } from \"./shared\";\n\ninterface FindEntityOptions {\n limit?: string;\n name?: string;\n type?: string;\n}\n\ninterface EntityMemoriesOptions {\n entityId?: string;\n limit?: string;\n}\n\nconst renderEntities = (result: FindMemoryEntitiesOutput): string => {\n if (result.entities.length === 0) {\n return \"No matching entities found.\";\n }\n return result.entities\n .map(\n (entity) =>\n `- ${entity.displayName} (${entity.type}, ${entity.memoryCount} memories) — ${entity.id}`\n )\n .join(\"\\n\");\n};\n\nconst renderEntityMemories = (result: MemoriesByEntityOutput): string => {\n const heading = `# ${result.entity.displayName} (${result.entity.type})`;\n if (result.memories.length === 0) {\n return `${heading}\\nNo linked memories.`;\n }\n return `${heading}\\n${result.memories\n .map((memory) => `- ${memory.recordedAt.slice(0, 10)} — ${memory.content}`)\n .join(\"\\n\")}`;\n};\n\nconst configureFindCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"[name]\", \"Entity name\")\n .option(\"--name <name>\", \"Entity name\")\n .option(\"--type <type>\", \"person, event, action, knowledge, or document\")\n .option(\"--limit <number>\", \"Maximum results\")\n .action(\n async (\n positional: string | undefined,\n options: FindEntityOptions,\n actionCommand: Command\n ) => {\n const name = options.name ?? positional;\n if (name === undefined || name.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide an entity name\");\n }\n const input = {\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 25,\n minimum: 1,\n }),\n name,\n type: parseEntityType(options.type),\n };\n const result = await context\n .client(actionCommand)\n .findMemoryEntities(input);\n context.output(actionCommand).data(result, renderEntities);\n }\n );\n};\n\nconst configureMemoriesCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"[entityId]\", \"Entity id\")\n .option(\"--entity-id <id>\", \"Entity id\")\n .option(\"--limit <number>\", \"Maximum results\")\n .action(\n async (\n positional: string | undefined,\n options: EntityMemoriesOptions,\n actionCommand: Command\n ) => {\n const entityId = options.entityId ?? positional;\n if (entityId === undefined || entityId.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide an entity id\");\n }\n const input = {\n entityId,\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 50,\n minimum: 1,\n }),\n };\n const result = await context\n .client(actionCommand)\n .memoriesByEntity(input);\n context.output(actionCommand).data(result, renderEntityMemories);\n }\n );\n};\n\nexport const registerEntityCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const entity = program.command(\"entity\").description(\"Find memory entities\");\n configureFindCommand(\n entity.command(\"find\").description(\"Find entities by name\"),\n context\n );\n configureFindCommand(\n program\n .command(\"find-entity\", { hidden: true })\n .description(\"Legacy entity find\"),\n context\n );\n configureMemoriesCommand(\n entity\n .command(\"memories\")\n .description(\"Recall memories linked to an entity\"),\n context\n );\n configureMemoriesCommand(\n program\n .command(\"search-memories-by-entity\", { hidden: true })\n .description(\"Legacy entity recall\"),\n context\n );\n};\n","import type { Command } from \"commander\";\n\nimport type {\n AddChatSessionInput,\n AddChatSessionsInput,\n AddMemoriesInput,\n} from \"../client\";\nimport type { MerraiCommandContext } from \"../runtime\";\n\nimport { MerraiCliUsageError } from \"../errors\";\nimport { readStructuredInput } from \"../input\";\n\ninterface StructuredInputOptions {\n file?: string;\n input?: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst parseMemoriesInput = (value: unknown): AddMemoriesInput => {\n if (!Array.isArray(value)) {\n throw new MerraiCliUsageError(\"Memory ingest input must be a JSON array\");\n }\n // The server owns full DTO validation. The CLI only verifies the top-level shape.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The remote schema remains the canonical nested validator.\n return { memories: value as AddMemoriesInput[\"memories\"] };\n};\n\nconst parseChatInput = (value: unknown): AddChatSessionInput => {\n if (!isRecord(value) || !Array.isArray(value.memories)) {\n throw new MerraiCliUsageError(\n \"Chat ingest input must be an object containing a memories array\"\n );\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The remote schema remains the canonical nested validator.\n return value as unknown as AddChatSessionInput;\n};\n\nconst parseChatsInput = (value: unknown): AddChatSessionsInput => {\n if (!isRecord(value) || !Array.isArray(value.sessions)) {\n throw new MerraiCliUsageError(\n \"Multi-chat ingest input must be an object containing a sessions array\"\n );\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The remote schema remains the canonical nested validator.\n return value as unknown as AddChatSessionsInput;\n};\n\nconst configureStructuredCommand = <Input>(\n command: Command,\n context: MerraiCommandContext,\n parse: (value: unknown) => Input,\n submit: (command: Command, input: Input) => Promise<unknown>\n): void => {\n command\n .option(\"--input <json>\", \"Inline JSON input\")\n .option(\"--file <path>\", \"Read JSON from a file, or - for stdin\")\n .action(async (options: StructuredInputOptions, actionCommand: Command) => {\n const value = await readStructuredInput({\n cwd: context.runtime.cwd,\n file: options.file,\n input: options.input,\n stdin: context.runtime.stdin,\n });\n const result = await submit(actionCommand, parse(value));\n context.output(actionCommand).data(result, () => \"Ingest queued.\");\n });\n};\n\nexport const registerIngestCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const ingest = program.command(\"ingest\").description(\"Bulk memory ingestion\");\n\n const registerMemories = (command: Command): void =>\n configureStructuredCommand(\n command,\n context,\n parseMemoriesInput,\n async (actionCommand, input) =>\n context.client(actionCommand).addMemories(input)\n );\n registerMemories(ingest.command(\"memories\").description(\"Ingest memories\"));\n registerMemories(\n program\n .command(\"add-memories\", { hidden: true })\n .description(\"Legacy memory ingest\")\n );\n\n const registerChat = (command: Command): void =>\n configureStructuredCommand(\n command,\n context,\n parseChatInput,\n async (actionCommand, input) =>\n context.client(actionCommand).addChatSession(input)\n );\n registerChat(ingest.command(\"chat\").description(\"Ingest one chat session\"));\n registerChat(\n program\n .command(\"add-chat-session\", { hidden: true })\n .description(\"Legacy chat ingest\")\n );\n\n const registerChats = (command: Command): void =>\n configureStructuredCommand(\n command,\n context,\n parseChatsInput,\n async (actionCommand, input) =>\n context.client(actionCommand).addChatSessions(input)\n );\n registerChats(\n ingest.command(\"chats\").description(\"Ingest multiple chat sessions\")\n );\n registerChats(\n program\n .command(\"add-chat-sessions\", { hidden: true })\n .description(\"Legacy multi-chat ingest\")\n );\n};\n","import type { Command } from \"commander\";\n\nimport type { ListLivingDocumentsRecallOutput } from \"../client\";\nimport type { MerraiCommandContext } from \"../runtime\";\n\nimport { MerraiCliUsageError } from \"../errors\";\n\ninterface DocumentGetOptions {\n documentId?: string;\n}\n\nconst renderDocumentList = (value: ListLivingDocumentsRecallOutput): string => {\n if (value.documents.length === 0) {\n return \"No living documents found.\";\n }\n return value.documents\n .map((document) => `- ${document.title} — ${document.id}`)\n .join(\"\\n\");\n};\n\nconst configureGetCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"[documentId]\", \"Living document id\")\n .option(\"--document-id <id>\", \"Living document id\")\n .action(\n async (\n positional: string | undefined,\n options: DocumentGetOptions,\n actionCommand: Command\n ) => {\n const documentId = options.documentId ?? positional;\n if (documentId === undefined || documentId.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide a living document id\");\n }\n const result = await context\n .client(actionCommand)\n .recall.readLivingDocument({ documentId });\n context\n .output(actionCommand)\n .data(result, (value) => JSON.stringify(value, null, 2));\n }\n );\n};\n\nexport const registerLivingDocumentCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const document = program\n .command(\"document\")\n .description(\"Read living documents\");\n const listAction = async (command: Command): Promise<void> => {\n const result = await context.client(command).recall.listLivingDocuments();\n context.output(command).data(result, renderDocumentList);\n };\n\n document\n .command(\"list\")\n .description(\"List living documents\")\n .action(async (_options: unknown, command: Command) => listAction(command));\n program\n .command(\"list-living-documents\", { hidden: true })\n .description(\"Legacy living document list\")\n .action(async (_options: unknown, command: Command) => listAction(command));\n\n configureGetCommand(\n document\n .command(\"get\")\n .description(\"Read a living document and its shares\"),\n context\n );\n configureGetCommand(\n program\n .command(\"read-living-document\", { hidden: true })\n .description(\"Legacy living document read\"),\n context\n );\n};\n","import type { Command } from \"commander\";\n\nimport type {\n MemoriesByDateOutput,\n MemoryOverviewOutput,\n MemoryStatusOutput,\n SearchMemoryHit,\n} from \"../client\";\nimport type { MerraiCommandContext } from \"../runtime\";\n\nimport { MerraiCliUsageError } from \"../errors\";\nimport { confirmAction, readTextInput } from \"../input\";\nimport {\n parseDateOption,\n parseIntegerOption,\n parseNumberOption,\n resolveLobeKey,\n} from \"./shared\";\n\ninterface AddMemoryOptions {\n file?: string;\n lobe?: string;\n lobeKey?: string;\n memory?: string;\n observationDate?: string;\n source?: string;\n}\n\ninterface SearchOptions {\n graph?: boolean;\n graphMax?: string;\n graphPerSeed?: string;\n limit?: string;\n lobe?: string;\n lobeKey?: string;\n mode?: string;\n query?: string;\n threshold?: string;\n}\n\ninterface DateOptions {\n end?: string;\n limit?: string;\n start?: string;\n}\n\ninterface LobeOptions {\n lobe?: string;\n lobeKey?: string;\n}\n\ninterface ClearOptions extends LobeOptions {\n yes?: boolean;\n}\n\nconst renderSearchHits = (hits: SearchMemoryHit[]): string => {\n if (hits.length === 0) {\n return \"No memories found.\";\n }\n return hits\n .map((hit) => {\n const category = hit.category === null ? \"\" : `[${hit.category}] `;\n return `- ${category}${hit.memoryDate.slice(0, 10)} — ${hit.content}`;\n })\n .join(\"\\n\");\n};\n\nconst renderProfile = (overview: MemoryOverviewOutput): string => {\n const lines = [`# ${overview.account.name}`];\n if (overview.account.primaryRole !== null) {\n lines.push(`Role: ${overview.account.primaryRole}`);\n }\n if (overview.account.workplace !== null) {\n lines.push(`Workplace: ${overview.account.workplace}`);\n }\n if (overview.profile !== null) {\n lines.push(`Scope: ${overview.profile.scope}`);\n for (const fact of overview.profile.facts) {\n lines.push(`- ${fact.content}`);\n }\n }\n return lines.join(\"\\n\");\n};\n\nconst renderDateResults = (result: MemoriesByDateOutput): string => {\n if (result.memories.length === 0) {\n return \"No memories found in the requested date range.\";\n }\n return result.memories\n .map((memory) => `- ${memory.recordedAt.slice(0, 10)} — ${memory.content}`)\n .join(\"\\n\");\n};\n\nconst configureAddCommand = (\n command: Command,\n context: MerraiCommandContext,\n contract: \"legacy\" | \"recall\"\n): void => {\n command\n .argument(\"[text]\", \"Memory text\")\n .option(\"--memory <text>\", \"Memory text\")\n .option(\"--file <path>\", \"Read memory text from a file, or - for stdin\")\n .option(\"--observation-date <datetime>\", \"ISO 8601 observation time\");\n if (contract === \"legacy\") {\n command\n .option(\"--source <source>\", \"Source identifier\")\n .option(\"--lobe <key>\", \"Memory lobe\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\");\n }\n command.action(\n async (\n positional: string | undefined,\n options: AddMemoryOptions,\n actionCommand: Command\n ) => {\n const memory = await readTextInput({\n cwd: context.runtime.cwd,\n file: options.file,\n option: options.memory,\n positional,\n stdin: context.runtime.stdin,\n });\n const recallInput = {\n memory,\n observationDate: parseDateOption(\n options.observationDate,\n \"--observation-date\"\n ),\n };\n const client = context.client(actionCommand);\n const result =\n contract === \"recall\"\n ? await client.recall.addMemory(recallInput)\n : await client.addMemory({\n ...recallInput,\n lobeKey: resolveLobeKey(options),\n source: options.source,\n });\n context.output(actionCommand).data(result, () => \"Memory queued.\");\n }\n );\n};\n\nconst configureSearchCommand = (\n command: Command,\n context: MerraiCommandContext,\n contract: \"legacy\" | \"recall\"\n): void => {\n command\n .argument(\"[query]\", \"Search query\")\n .option(\"--query <text>\", \"Search query\")\n .option(\"--limit <number>\", \"Maximum results\");\n if (contract === \"legacy\") {\n command\n .option(\"--lobe <key>\", \"Restrict to a lobe\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\")\n .option(\"--threshold <number>\", \"Minimum vector similarity\")\n .option(\"--mode <mode>\", \"fast, adaptive, or reflective\", \"fast\")\n .option(\"--no-graph\", \"Disable graph expansion\")\n .option(\"--graph-per-seed <number>\", \"Maximum neighbors per seed\")\n .option(\"--graph-max <number>\", \"Maximum graph neighbors\");\n }\n command.action(\n async (\n positional: string | undefined,\n options: SearchOptions,\n actionCommand: Command\n ) => {\n const query = options.query ?? positional;\n if (query === undefined || query.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide a search query\");\n }\n const mode = options.mode;\n if (\n contract === \"legacy\" &&\n mode !== \"fast\" &&\n mode !== \"adaptive\" &&\n mode !== \"reflective\"\n ) {\n throw new MerraiCliUsageError(\n \"--mode must be one of: fast, adaptive, reflective\"\n );\n }\n const limit = parseIntegerOption(options.limit, \"--limit\", {\n maximum: contract === \"recall\" ? 25 : 50,\n minimum: 1,\n });\n if (contract === \"recall\") {\n const result = await context\n .client(actionCommand)\n .recall.searchMemory({ limit, query });\n context.output(actionCommand).data(result, (value) =>\n renderSearchHits(\n value.memories.map((memory) => ({\n ...memory,\n memoryDate: memory.recordedAt,\n score: 0,\n summary: null,\n }))\n )\n );\n return;\n }\n const graphPerSeed = parseIntegerOption(\n options.graphPerSeed,\n \"--graph-per-seed\",\n { maximum: 10, minimum: 0 }\n );\n const graphMax = parseIntegerOption(options.graphMax, \"--graph-max\", {\n maximum: 25,\n minimum: 0,\n });\n const includeGraphOptions =\n options.graph === false ||\n graphPerSeed !== undefined ||\n graphMax !== undefined;\n const input = {\n graph: includeGraphOptions\n ? {\n enabled: options.graph !== false,\n maxNeighborsPerSeed: graphPerSeed,\n maxTotalNeighbors: graphMax,\n }\n : undefined,\n limit,\n lobeKey: resolveLobeKey(options),\n mode:\n mode === \"fast\" || mode === \"adaptive\" || mode === \"reflective\"\n ? mode\n : undefined,\n query,\n threshold: parseNumberOption(options.threshold, \"--threshold\", {\n maximum: 1,\n minimum: 0,\n }),\n } as const;\n const result = await context.client(actionCommand).searchMemories(input);\n context.output(actionCommand).data(result, renderSearchHits);\n }\n );\n};\n\nconst configureDateCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .option(\"--start <datetime>\", \"Inclusive ISO 8601 lower bound\")\n .option(\"--end <datetime>\", \"Inclusive ISO 8601 upper bound\")\n .option(\"--limit <number>\", \"Maximum results\")\n .action(async (options: DateOptions, actionCommand: Command) => {\n const start = parseDateOption(options.start, \"--start\");\n const end = parseDateOption(options.end, \"--end\");\n if (start === undefined && end === undefined) {\n throw new MerraiCliUsageError(\n \"Provide at least one of --start or --end\"\n );\n }\n const input = {\n end,\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 50,\n minimum: 1,\n }),\n start,\n };\n const result = await context.client(actionCommand).memoriesByDate(input);\n context.output(actionCommand).data(result, renderDateResults);\n });\n};\n\nconst configureStatusCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .option(\"--lobe <key>\", \"Restrict to a lobe\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\")\n .action(async (options: LobeOptions, actionCommand: Command) => {\n const lobeKey = resolveLobeKey(options);\n const result: MemoryStatusOutput = await context\n .client(actionCommand)\n .memoryStatus({ lobeKey });\n context\n .output(actionCommand)\n .data(result, () =>\n lobeKey === undefined\n ? `${result.count} memories.`\n : `${result.count} memories in ${lobeKey}.`\n );\n });\n};\n\nconst configureClearCommand = (\n command: Command,\n context: MerraiCommandContext,\n requireConfirmation: boolean\n): void => {\n command\n .argument(\"[lobe]\", \"Lobe to clear\")\n .option(\"--lobe <key>\", \"Lobe to clear\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\")\n .option(\"--yes\", \"Skip confirmation\")\n .action(\n async (\n positional: string | undefined,\n options: ClearOptions,\n actionCommand: Command\n ) => {\n const lobeKey = resolveLobeKey(options) ?? positional;\n if (lobeKey === undefined || lobeKey.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide the lobe to clear\");\n }\n if (requireConfirmation && options.yes !== true) {\n const confirmed = await confirmAction({\n input: context.runtime.stdin,\n message: `Clear all memories in lobe '${lobeKey}'?`,\n output: context.runtime.stderr,\n });\n if (!confirmed) {\n throw new MerraiCliUsageError(\n \"Clear cancelled. Use --yes for noninteractive confirmation.\"\n );\n }\n }\n const result = await context\n .client(actionCommand)\n .clearLobe({ lobeKey });\n context\n .output(actionCommand)\n .data(result, () => `Cleared lobe ${lobeKey}.`);\n }\n );\n};\n\nexport const registerMemoryCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const memory = program\n .command(\"memory\")\n .description(\"Manage and recall memories\");\n\n configureAddCommand(\n memory.command(\"add\").description(\"Queue a memory\"),\n context,\n \"recall\"\n );\n configureAddCommand(\n program\n .command(\"add-memory\", { hidden: true })\n .description(\"Legacy memory add\"),\n context,\n \"legacy\"\n );\n\n configureSearchCommand(\n memory.command(\"search\").description(\"Search memories\"),\n context,\n \"recall\"\n );\n configureSearchCommand(\n program\n .command(\"search\", { hidden: true })\n .description(\"Legacy memory search\"),\n context,\n \"legacy\"\n );\n\n const listAction = async (command: Command): Promise<void> => {\n const result = await context.client(command).memories();\n context.output(command).data(result);\n };\n memory\n .command(\"list\")\n .description(\"List memories\")\n .action(async (_options: unknown, command: Command) => listAction(command));\n program\n .command(\"memories\", { hidden: true })\n .description(\"Legacy memory list\")\n .action(async (_options: unknown, command: Command) => listAction(command));\n\n const profileAction = async (command: Command): Promise<void> => {\n const result = await context.client(command).memoryOverview();\n context.output(command).data(result, renderProfile);\n };\n memory\n .command(\"profile\")\n .description(\"Show the account and memory profile\")\n .action(async (_options: unknown, command: Command) =>\n profileAction(command)\n );\n program\n .command(\"who-am-i\", { hidden: true })\n .aliases([\"whoami\"])\n .description(\"Legacy memory profile\")\n .action(async (_options: unknown, command: Command) =>\n profileAction(command)\n );\n\n configureDateCommand(\n memory.command(\"by-date\").description(\"Recall memories by date\"),\n context\n );\n configureDateCommand(\n program\n .command(\"search-memories-by-date\", { hidden: true })\n .description(\"Legacy date recall\"),\n context\n );\n\n configureStatusCommand(\n memory.command(\"status\").description(\"Count processed memories\"),\n context\n );\n configureStatusCommand(\n program\n .command(\"memory-status\", { hidden: true })\n .description(\"Legacy status\"),\n context\n );\n\n configureClearCommand(\n memory.command(\"clear\").description(\"Clear a memory lobe\"),\n context,\n true\n );\n configureClearCommand(\n program\n .command(\"clear-lobe\", { hidden: true })\n .description(\"Legacy lobe clear\"),\n context,\n false\n );\n};\n","import type { Command } from \"commander\";\n\nimport type { AuthSessionOutput } from \"../client\";\nimport type { MerraiCommandContext } from \"../runtime\";\n\nconst renderLabelledJson =\n (label: string) =>\n (value: unknown): string =>\n `${label}\\n${JSON.stringify(value, null, 2)}`;\n\nconst redactAuthSessionToken = (\n result: AuthSessionOutput\n): Omit<AuthSessionOutput, \"session\"> & {\n session: Omit<AuthSessionOutput[\"session\"], \"token\">;\n} => ({\n session: {\n createdAt: result.session.createdAt,\n expiresAt: result.session.expiresAt,\n id: result.session.id,\n ipAddress: result.session.ipAddress,\n updatedAt: result.session.updatedAt,\n userAgent: result.session.userAgent,\n userId: result.session.userId,\n },\n user: result.user,\n});\n\nexport const registerSystemCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n program\n .command(\"health\")\n .description(\"Check API connectivity\")\n .action(async (_options: unknown, command: Command) => {\n const result = await context.client(command).healthCheck();\n context\n .output(command)\n .data(result, renderLabelledJson(\"Merrai is reachable.\"));\n });\n\n program\n .command(\"session\")\n .description(\"Fetch the current session\")\n .action(async (_options: unknown, command: Command) => {\n const result = await context.client(command).session();\n const safeResult =\n result === null ? null : redactAuthSessionToken(result);\n context\n .output(command)\n .data(safeResult, renderLabelledJson(\"Current session:\"));\n });\n\n const account = program.command(\"account\").description(\"Account information\");\n const usageAction = async (command: Command): Promise<void> => {\n const result = await context.client(command).usageSummary();\n context.output(command).data(result, renderLabelledJson(\"Usage:\"));\n };\n\n account\n .command(\"usage\")\n .description(\"Fetch the current usage summary\")\n .action(async (_options: unknown, command: Command) =>\n usageAction(command)\n );\n program\n .command(\"usage-summary\", { hidden: true })\n .description(\"Legacy alias for account usage\")\n .action(async (_options: unknown, command: Command) =>\n usageAction(command)\n );\n};\n","import type { Writable } from \"node:stream\";\n\nexport type MerraiOutputFormat = \"json\" | \"text\";\nexport type MerraiTextRenderer<Value> = (value: Value) => string;\n\nexport interface MerraiCliOutput {\n data<Value>(value: Value, renderText?: MerraiTextRenderer<Value>): void;\n diagnostic(message: string): void;\n error(message: string): void;\n}\n\nconst ensureTrailingNewline = (value: string): string =>\n value.endsWith(\"\\n\") ? value : `${value}\\n`;\n\nexport const createMerraiCliOutput = (options: {\n format: MerraiOutputFormat;\n stderr: Writable;\n stdout: Writable;\n}): MerraiCliOutput => ({\n data: <Value>(value: Value, renderText?: MerraiTextRenderer<Value>) => {\n const rendered =\n options.format === \"text\" && renderText !== undefined\n ? renderText(value)\n : typeof value === \"string\" && options.format === \"text\"\n ? value\n : JSON.stringify(value, null, 2);\n options.stdout.write(ensureTrailingNewline(rendered ?? \"null\"));\n },\n diagnostic: (message) => {\n options.stderr.write(ensureTrailingNewline(message));\n },\n error: (message) => {\n options.stderr.write(ensureTrailingNewline(message));\n },\n});\n","import type { Command } from \"commander\";\nimport type { Readable, Writable } from \"node:stream\";\n\nimport { type MerraiClientOptions, type MerraiThrowingClient } from \"./client\";\nimport {\n type MerraiCliEnvironment,\n resolveMerraiClientOptions,\n} from \"./config\";\nimport {\n type MerraiCliOutput,\n type MerraiOutputFormat,\n createMerraiCliOutput,\n} from \"./output\";\n\nexport interface MerraiCliRuntime {\n argv: readonly string[];\n createClient: (options: MerraiClientOptions) => MerraiThrowingClient;\n cwd: string;\n env: MerraiCliEnvironment;\n stderr: Writable;\n stdin: Readable;\n stdout: Writable;\n}\n\ninterface GlobalOptions {\n apiKey?: string;\n baseUrl?: string;\n cookie?: string;\n format?: MerraiOutputFormat;\n json?: boolean;\n}\n\nconst globalOptions = (command: Command): GlobalOptions =>\n command.optsWithGlobals<GlobalOptions>();\n\nexport interface MerraiCommandContext {\n client(command: Command): MerraiThrowingClient;\n output(command: Command): MerraiCliOutput;\n runtime: MerraiCliRuntime;\n}\n\nexport const createMerraiCommandContext = (\n runtime: MerraiCliRuntime\n): MerraiCommandContext => ({\n client: (command) => {\n const options = globalOptions(command);\n return runtime.createClient(\n resolveMerraiClientOptions(runtime.env, {\n apiKey: options.apiKey,\n baseURL: options.baseUrl,\n cookie: options.cookie,\n })\n );\n },\n output: (command) => {\n const options = globalOptions(command);\n return createMerraiCliOutput({\n format: options.json === true ? \"json\" : (options.format ?? \"json\"),\n stderr: runtime.stderr,\n stdout: runtime.stdout,\n });\n },\n runtime,\n});\n","import { Command, InvalidArgumentError } from \"commander\";\n\nimport packageMetadata from \"../package.json\" with { type: \"json\" };\nimport { registerAuthCommands } from \"./commands/auth\";\nimport { registerDebugCommands } from \"./commands/debug\";\nimport { registerEntityCommands } from \"./commands/entity\";\nimport { registerIngestCommands } from \"./commands/ingest\";\nimport { registerLivingDocumentCommands } from \"./commands/living-document\";\nimport { registerMemoryCommands } from \"./commands/memory\";\nimport { registerSystemCommands } from \"./commands/system\";\nimport { MERRAI_CLI_EXIT_CODES, classifyMerraiCliError } from \"./errors\";\nimport { createMerraiCommandContext, type MerraiCliRuntime } from \"./runtime\";\n\nconst CLI_VERSION = packageMetadata.version;\n\nconst parseFormat = (value: string): \"json\" | \"text\" => {\n if (value !== \"json\" && value !== \"text\") {\n throw new InvalidArgumentError(\"format must be json or text\");\n }\n return value;\n};\n\nexport const createMerraiProgram = (runtime: MerraiCliRuntime): Command => {\n const program = new Command();\n const context = createMerraiCommandContext(runtime);\n\n program\n .name(\"merrai\")\n .description(\"Store, recall, and ingest Merrai memories\")\n .version(CLI_VERSION)\n .option(\"--base-url <url>\", \"Merrai server base URL\")\n .option(\"--api-key <key>\", \"Merrai API key\")\n .option(\"--cookie <cookie>\", \"Session cookie fallback\")\n .option(\"--format <format>\", \"Output format: json or text\", parseFormat)\n .option(\"--json\", \"Alias for --format json\")\n .showHelpAfterError()\n .exitOverride()\n .configureOutput({\n writeErr: (value) => runtime.stderr.write(value),\n writeOut: (value) => runtime.stdout.write(value),\n });\n\n registerSystemCommands(program, context);\n registerMemoryCommands(program, context);\n registerEntityCommands(program, context);\n registerLivingDocumentCommands(program, context);\n registerIngestCommands(program, context);\n registerDebugCommands(program, context);\n registerAuthCommands(program, context);\n\n return program;\n};\n\nexport const runMerraiCli = async (\n runtime: MerraiCliRuntime\n): Promise<number> => {\n const program = createMerraiProgram(runtime);\n if (runtime.argv.length === 0) {\n program.outputHelp();\n return MERRAI_CLI_EXIT_CODES.success;\n }\n\n try {\n await program.parseAsync([...runtime.argv], { from: \"user\" });\n return MERRAI_CLI_EXIT_CODES.success;\n } catch (error) {\n const result = classifyMerraiCliError(error);\n if (result.shouldRender) {\n runtime.stderr.write(\n result.message.endsWith(\"\\n\") ? result.message : `${result.message}\\n`\n );\n }\n return result.exitCode;\n }\n};\n","#!/usr/bin/env node\n\nimport { createMerraiThrowingClient } from \"./client\";\nimport { runMerraiCli } from \"./program\";\n\nconst exitCode = await runMerraiCli({\n argv: process.argv.slice(2),\n createClient: createMerraiThrowingClient,\n cwd: process.cwd(),\n env: process.env,\n stderr: process.stderr,\n stdin: process.stdin,\n stdout: process.stdout,\n});\n\nprocess.exitCode = exitCode;\n"],"mappings":";;;;;;;;;;;AAgnBA,MAAa,kBAAkB,YAAqB;CAClD,MAAM,WAAW,SAAS,MAAM;AAEhC,KAAI,CAAC,SACH,OAAM,IAAI,MACR,6EACD;AAGH,QAAO,SAAS,SAAS,IAAI,GAAG,SAAS,MAAM,GAAG,GAAG,GAAG;;AAG1D,MAAM,kBACJ,SACA,QACA,WAC2B;CAC3B,MAAM,kBAAkB,IAAI,QAAQ,QAAQ;AAE5C,KAAI,OACF,iBAAgB,IAAI,aAAa,OAAO;AAG1C,KAAI,OACF,iBAAgB,IAAI,UAAU,OAAO;AAGvC,QAAO,OAAO,YAAY,gBAAgB,SAAS,CAAC;;AAGtD,MAAa,yBAAyB,UAA+B,EAAE,KAAK;AAQ1E,QAAO,iBAPM,IAAI,QAAQ;EACvB,OAAO,QAAQ;EACf,eACE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,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC7D,SAAO,sBAAsB;UACtB,OAAO;EACd,MAAM,SAAS,uBAAuB,MAAM;AAC5C,MAAI,OAAO,aACT,SAAQ,OAAO,MACb,OAAO,QAAQ,SAAS,KAAK,GAAG,OAAO,UAAU,GAAG,OAAO,QAAQ,IACpE;AAEH,SAAO,OAAO;;;;;;ACnElB,MAAM,WAAW,MAAM,aAAa;CAClC,MAAM,QAAQ,KAAK,MAAM,EAAE;CAC3B,cAAc;CACd,KAAK,QAAQ,KAAK;CAClB,KAAK,QAAQ;CACb,QAAQ,QAAQ;CAChB,OAAO,QAAQ;CACf,QAAQ,QAAQ;CACjB,CAAC;AAEF,QAAQ,WAAW"}
1
+ {"version":3,"file":"bin.mjs","names":["parseCursorJson","parseCursorJson","parseCursorJson","packageMetadata.version"],"sources":["../src/client.ts","../package.json","../src/errors.ts","../src/app-source-files.ts","../src/input.ts","../src/commands/shared.ts","../src/commands/apps.ts","../src/config.ts","../src/commands/auth.ts","../src/commands/debug.ts","../src/memory-replacement.ts","../src/commands/entity.ts","../src/idempotency.ts","../src/commands/ingest.ts","../src/commands/ingestion.ts","../src/commands/living-document.ts","../src/commands/lobe.ts","../src/commands/memory.ts","../src/commands/sources.ts","../src/commands/system.ts","../src/commands/topic.ts","../src/output.ts","../src/runtime.ts","../src/program.ts","../src/bin.ts"],"sourcesContent":["import { createORPCClient, createSafeClient } from \"@orpc/client\";\nimport type { Client, ClientContext, SafeClient } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\n\nexport type ThrowingRpcProcedure<Input = unknown, Output = unknown> = Client<\n ClientContext,\n Input | undefined,\n Output,\n unknown\n>;\nexport type RpcProcedure<Input = unknown, Output = unknown> = SafeClient<\n ThrowingRpcProcedure<Input, Output>\n>;\n\nexport type EntityType =\n | \"person\"\n | \"event\"\n | \"action\"\n | \"knowledge\"\n | \"document\";\n\nexport type JsonValue =\n | boolean\n | number\n | string\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport interface AddMemoryInput {\n idempotencyKey: string;\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n}\n\nexport interface AddMemoryOutput {\n /** Poll `ingestionStatus` with this ID to follow processing. */\n ingestionId: string;\n queued: boolean;\n}\n\nexport interface AddMemoryRecallInput {\n idempotencyKey: string;\n /** An existing lobe of the account; the main lobe when omitted. */\n lobeKey?: string;\n memory: string;\n observationDate?: string;\n}\n\nexport interface AddMemoryRecallOutput {\n ingestionId: string;\n processing: true;\n status: \"enqueued\";\n}\n\nexport interface AddMemoriesInput {\n idempotencyKey: string;\n memories: {\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n }[];\n}\n\nexport interface AddMemoriesOutput {\n ingestionId: string;\n queued: number;\n}\n\nexport interface FindMemoryEntitiesInput {\n name: string;\n type?: EntityType;\n limit?: number;\n}\n\n/**\n * How a known time relates to what it dates: it took place then, it is\n * planned for then, or it is due then (a deadline). Absent or null on times\n * recorded before roles existed: unspecified.\n */\nexport type EventTimeRole = \"happened\" | \"planned\" | \"due\";\n\nexport type EventTime =\n | {\n precision: \"day\" | \"week\" | \"month\" | \"year\";\n value: string;\n phrase: string | null;\n role?: EventTimeRole | null;\n }\n | {\n /** A span of calendar days, both ends included. */\n precision: \"range\";\n start: string;\n end: string;\n phrase: string | null;\n role?: EventTimeRole | null;\n }\n | {\n precision: \"unknown\";\n value: null;\n phrase: string | null;\n role?: null;\n };\nexport type MemoryEventTime =\n | EventTime\n | { precision: \"multiple\"; alternatives: EventTime[] };\n\nexport interface MemoryRecallResult {\n eventTime: MemoryEventTime | null;\n category: string | null;\n content: string;\n id: string;\n lobeKey: string;\n recordedAt: string | null;\n}\n\n/** The earlier value a Memory replaced: the latest Memory it supersedes. */\nexport interface MemoryReplacement {\n content: string;\n eventTime: MemoryEventTime | null;\n}\n\n/**\n * A current memory an update mark ties to a search result. A later value\n * never retires the earlier one: both stay current.\n */\nexport interface MemoryUpdateMark {\n /**\n * updated_by: the linked memory is a newer value of something the result\n * states, shown under it as \"↳ updated by: …\". updates: the result is a\n * newer value of something the linked memory states, shown as\n * \"replaces: …\".\n */\n relation: \"updated_by\" | \"updates\";\n id: string;\n content: string;\n eventTime: MemoryEventTime | null;\n /** The day the linked memory was last said (YYYY-MM-DD); null when unknown. */\n said: string | null;\n}\n\n/** A search result: a recall result plus what it replaced. */\nexport interface SearchMemoryRecallResult extends MemoryRecallResult {\n /**\n * Shown under it as \"replaces: …\" (renderMemoryReplacement). Null when it\n * replaced none; absent from servers that predate it.\n */\n replaces?: MemoryReplacement | null;\n /**\n * The current memories update marks tie to it, newer values first\n * (renderMemoryUpdateMarks). Absent from servers that predate it.\n */\n linked?: MemoryUpdateMark[];\n /** True for a guess from what the user asked, which no source states. */\n inferred?: boolean;\n}\n\nexport interface FindMemoryEntitiesOutput {\n entities: {\n displayName: string;\n id: string;\n memoryCount: number;\n name: string;\n type: EntityType;\n }[];\n}\n\n/**\n * MCP search_memories' selectors: at least one of query, an entity (id, or\n * name with an optional type), start or end. Date bounds are inclusive ISO\n * 8601 bounds on when a memory was recorded.\n */\nexport interface SearchMemoriesRecallInput {\n end?: string;\n entityId?: string;\n entityName?: string;\n entityType?: EntityType;\n /** 1-25; defaults to 10. */\n limit?: number;\n /** One of the caller's lobes to search instead of the owner-recall lobes. */\n lobeKey?: string;\n query?: string;\n start?: string;\n /** Memories carrying at least one of these topic keys. */\n topics?: string[];\n about?: MemoryAbout;\n /** Memories with one of these stances. */\n stance?: MemoryStance[];\n}\n\n/** Who a memory is about: the account owner, someone else, or no one. */\nexport type MemoryAbout = \"none\" | \"other\" | \"owner\";\n/** A stated fact, someone's view, or a decision. */\nexport type MemoryStance = \"decision\" | \"inferred\" | \"reported\" | \"view\";\n\n/** MCP search_memories' reply. */\nexport interface SearchMemoriesRecallOutput {\n appliedFilters: {\n end: string | null;\n entityId: string | null;\n entityName: string | null;\n entityType: EntityType | null;\n query: string | null;\n start: string | null;\n /** Absent from servers that predate label filters. */\n lobeKey?: string | null;\n topics?: string[];\n about?: MemoryAbout | null;\n stance?: MemoryStance[];\n };\n /** Several entries with status needs_disambiguation: choose one by id. */\n matchedEntities: {\n displayName: string;\n id: string;\n memoryCount: number;\n name: string;\n type: EntityType;\n }[];\n memories: SearchMemoryRecallResult[];\n status: \"complete\" | \"needs_disambiguation\";\n /** Undated memories a start/end bound could not include. */\n undatedExcludedCount: number;\n}\n\nexport interface MemoryOverviewOutput {\n account: {\n name: string;\n numberOfAiTools: number | null;\n preferredMessagingChannel: string | null;\n primaryRole: string | null;\n workplace: string | null;\n };\n profile: {\n dynamicContext: (Omit<MemoryRecallResult, \"id\"> & {\n profileExpiresAt: string;\n })[];\n facts: Omit<MemoryRecallResult, \"id\">[];\n ongoingContext: Omit<MemoryRecallResult, \"id\">[];\n scope: string;\n updatedAt: string;\n } | null;\n refresh: {\n candidateMemoryCount: number;\n status: \"current\" | \"failed\" | \"queued\";\n };\n}\n\nexport interface ListLivingDocumentsInput {\n status?: (\"enabled\" | \"disabled\" | \"archived\")[];\n}\n\nexport type LivingDocumentStatus = \"enabled\" | \"disabled\" | \"archived\";\n\n/**\n * Which of the user's lobes a document takes Memories from: every lobe\n * (including ones created later) or only the listed ones.\n */\nexport type LivingDocumentLobeScope =\n | { kind: \"all\" }\n | { kind: \"selected\"; lobeKeys: string[] };\n\nexport interface LivingDocument {\n autoPublish: boolean;\n createdAt: string;\n currentApprovedVersionId: string | null;\n currentVersionId: string | null;\n description: string | null;\n entities: string[];\n extractionPrompt: string;\n id: string;\n /**\n * Set while saved Memories of newly added lobes are brought in: `pending`\n * while running, `failed` if unfinished (`retryLivingDocumentLobeBackfill`).\n * Absent from servers before lobe scopes; `status` is absent from servers\n * before backfill failures, where every backfill is pending.\n */\n lobeBackfill?: {\n lobeKeys: string[];\n requestedAt: string;\n status?: \"failed\" | \"pending\";\n } | null;\n lobeScope?: LivingDocumentLobeScope;\n patchFailureCount: number;\n /**\n * Set while the document is rebuilt without Memories from deleted sources\n * (`memory_removed`, also when `reason` is absent) or removed lobes\n * (`lobe_scope_narrowed`). `pending`/`failed` as for `lobeBackfill` (retry\n * with `retryLivingDocumentRebuild`); content is withheld meanwhile.\n */\n rebuild: {\n reason?: \"lobe_scope_narrowed\" | \"memory_removed\";\n requestedAt: string | null;\n status: \"failed\" | \"pending\";\n } | null;\n routingSummary: string | null;\n routingSummaryDirty: boolean;\n status: LivingDocumentStatus;\n title: string;\n triggerKeywords: string[];\n updatedAt: string;\n}\n\nexport interface LivingDocumentVersion {\n causedByMemoryIds: string[];\n causedByRunId: string | null;\n contentMd: string;\n contentMdSummary: string | null;\n createdAt: string;\n documentId: string;\n extractorModel: string | null;\n id: string;\n parentVersionId: string | null;\n patch: JsonValue;\n updatedAt: string;\n versionNumber: number;\n}\n\nexport interface LivingDocumentShare {\n createdAt: string;\n documentId: string;\n expiresAt: string | null;\n id: string;\n mode: \"pinned\" | \"live\";\n permissions: \"view\" | \"view+comment\";\n revokedAt: string | null;\n shareToken: string;\n updatedAt: string;\n versionId: string | null;\n}\n\nexport interface ListLivingDocumentsOutput {\n documents: LivingDocument[];\n slots: {\n limit: number;\n plan: string;\n remaining: number;\n used: number;\n };\n}\n\nexport interface ListLivingDocumentsRecallOutput {\n documents: {\n currentVersion: { createdAt: string; number: number } | null;\n id: string;\n /** Absent from a server that predates lobe scopes. */\n lobeScope?: LivingDocumentLobeScope;\n status: string;\n summary: string;\n title: string;\n }[];\n pagination: {\n limit: number;\n nextOffset: number | null;\n offset: number;\n };\n}\n\nexport interface ListLivingDocumentsRecallInput {\n limit?: number;\n offset?: number;\n}\n\nexport interface ReadLivingDocumentRecallInput {\n contentOffset?: number;\n documentId: string;\n maxCharacters?: number;\n}\n\nexport interface ReadLivingDocumentRecallOutput {\n document: {\n currentVersion: {\n contentMarkdown: string;\n contentOffset: number;\n createdAt: string;\n nextContentOffset: number | null;\n number: number;\n returnedCharacters: number;\n totalCharacters: number;\n } | null;\n description: string | null;\n headings: string[];\n id: string;\n /** Absent from a server that predates lobe scopes. */\n lobeScope?: LivingDocumentLobeScope;\n status: string;\n summary: string;\n title: string;\n };\n}\n\nexport interface GetLivingDocumentOutput {\n currentVersion: LivingDocumentVersion | null;\n document: LivingDocument;\n}\n\nexport interface ListLivingDocumentSharesOutput {\n shares: LivingDocumentShare[];\n}\n\nexport interface GetLivingDocumentInput {\n id: string;\n}\n\nexport interface ListLivingDocumentSharesInput {\n documentId: string;\n}\n\nexport interface AddChatSessionInput {\n idempotencyKey: string;\n memories: {\n memory: string;\n observationDate?: string;\n source?: string;\n }[];\n lobeKey?: string;\n source?: string;\n sessionMetadata?: Record<string, JsonValue>;\n}\n\nexport interface AddChatSessionOutput {\n ingestionId: string;\n queued: number;\n}\n\nexport interface AddChatSessionsInput {\n lobeKey?: string;\n source?: string;\n questionMetadata?: Record<string, JsonValue>;\n /**\n * Idempotency key (1-64 chars, [A-Za-z0-9_-]). A retry with the same key and\n * payload joins the first ingestion; reusing a key with other content is\n * refused with CONFLICT (`IDEMPOTENCY_KEY_REUSED`), so derive it from content.\n */\n idempotencyKey: string;\n sessions: {\n sessionId: string;\n /**\n * Opaque session metadata. `date` is the session's source time, in the\n * same format as a turn's `sourceTime`; it dates every turn without its\n * own time and cannot change once stored.\n */\n metadata?: Record<string, JsonValue>;\n turns: {\n content: string;\n role: \"user\" | \"assistant\";\n /**\n * When the turn was said: an ISO 8601 instant with an offset\n * (`2026-03-04T09:30:00Z`) or a local calendar date (`2026-03-04`).\n * Part of the turn's identity: a resent turn must repeat it exactly.\n */\n sourceTime?: string;\n speaker?: string;\n turnIndex: number;\n }[];\n }[];\n}\n\nexport interface AddChatSessionsOutput {\n ingestionId: string;\n queuedSessions: number;\n}\n\nexport interface MemoryStatusInput {\n lobeKey?: string;\n}\n\nexport interface MemoryStatusOutput {\n count: number;\n}\n\nexport interface ClearLobeInput {\n lobeKey: string;\n}\n\n/**\n * A lobe clear runs as durable server work. `clearLobe` starts it (or joins\n * the clear already running for the lobe); `clearLobeStatus` follows it.\n */\nexport interface ClearLobeOutput {\n clearId: string;\n completedAt: string | null;\n /** Memories removed so far; final once `status` is `complete`. */\n deleted: number;\n deletedSources: number;\n lobeKey: string;\n remainingSources: number;\n startedAt: string;\n status: \"complete\" | \"failed\" | \"running\";\n}\n\n/** Omitted `lobeKey` means every lobe of the caller. */\nexport interface MemoryBackfillInput {\n lobeKey?: string;\n}\n\n/** A label backfill: the caller's run and each requested lobe's progress. */\nexport interface MemoryBackfillStatusOutput {\n /** Why deciding views' bases last failed: retried while running, kept once given up. */\n lastError: string | null;\n lobes: {\n completedAt: string | null;\n /** Observations the current or last pass labelled. */\n labelled: number;\n lastError: string | null;\n lobeKey: string;\n /** `failed` is retried by the next start. */\n state: \"complete\" | \"failed\" | \"queued\" | \"running\";\n /** Observations that needed labels when that pass began. */\n total: number;\n updatedAt: string;\n }[];\n status: \"complete\" | \"never\" | \"running\";\n}\n\n/** Omitted `lobeKey` means every lobe of the caller. */\nexport interface MemorySynthesisInput {\n lobeKey?: string;\n}\n\n/** The caller's pattern and style synthesis and each requested lobe's state. */\nexport interface MemorySynthesisStatusOutput {\n lobes: {\n lastError: string | null;\n lobeKey: string;\n /** The pass waits until this time; a start runs it now. */\n notBefore: string;\n patternCount: number;\n patternsBuiltAt: string | null;\n /** `failed` is retried by the next start or ingestion. */\n state: \"complete\" | \"failed\" | \"pending\";\n styleBuiltAt: string | null;\n }[];\n status: \"complete\" | \"never\" | \"running\";\n}\n\n/** Omitted `lobeKey` reads main, where the owner's own chats and notes are kept. */\nexport interface GetStyleProfileInput {\n /** Omit or true for the passages' text; false reads the summary only. */\n includeExemplars?: boolean;\n lobeKey?: string;\n}\n\n/** How the owner writes, built only from their own words. */\nexport interface GetStyleProfileOutput {\n lobeKey: string;\n style: {\n builtAt: string;\n /** Passages shown as exemplars, whether or not their text was read. */\n exemplarCount: number;\n exemplars: { id: string; recordedAt: string | null; text: string }[];\n sampleSize: number;\n summary: {\n aspect: \"length\" | \"structure\" | \"tone\" | \"vocabulary\";\n exemplarIds: string[];\n text: string;\n }[];\n } | null;\n}\n\nexport interface ClearLobeStatusInput {\n clearId: string;\n}\n\nexport interface RetryLivingDocumentRebuildInput {\n id: string;\n}\n\nexport interface RetryLivingDocumentRebuildOutput {\n document: LivingDocument;\n}\n\nexport interface RetryLivingDocumentLobeBackfillInput {\n id: string;\n}\n\nexport interface RetryLivingDocumentLobeBackfillOutput {\n document: LivingDocument;\n}\n\nexport interface CreateLobeInput {\n lobeKey: string;\n}\n\nexport interface CreateLobeOutput {\n lobeKey: string;\n}\n\nexport interface ListLobesOutput {\n createdAt: string;\n lobeKey: string;\n /** What the lobe is called wherever it is shown. */\n name: string;\n /** Whether the owner's agent and default recall read this lobe. */\n ownerRecall: boolean;\n /** What this lobe is for, given to extraction as focus. */\n purpose: string | null;\n updatedAt: string;\n}\n\n/** Where a page of lobes ended; pass it back unchanged. */\nexport interface LobesCursor {\n createdAt: string;\n lobeKey: string;\n}\n\nexport interface ListLobesPageInput {\n cursor?: LobesCursor;\n /** 1-50; defaults to 20. */\n limit?: number;\n}\n\n/** One of the caller's lobes as a page lists it, oldest first. */\nexport interface LobePageItem {\n lobeKey: string;\n /** What the lobe is called wherever it is shown. */\n name: string;\n /** Whether the owner's agent and default recall read this lobe. */\n ownerRecall: boolean;\n purpose: string | null;\n}\n\nexport interface ListLobesPageOutput {\n lobes: LobePageItem[];\n nextCursor: LobesCursor | null;\n}\n\nexport interface UpdateLobeInput {\n lobeKey: string;\n ownerRecall?: boolean;\n /** Null clears the purpose. */\n purpose?: string | null;\n}\n\n/** Omitted `lobeKey` means every lobe of the user. */\nexport interface MemoryTopicScopeInput {\n lobeKey?: string;\n}\n\nexport interface SetMemoryTopicInput extends MemoryTopicScopeInput {\n description: string;\n key: string;\n}\n\nexport interface RetireMemoryTopicInput extends MemoryTopicScopeInput {\n key: string;\n}\n\n/** A lobe's topic catalogue: built-ins, then the user's and the lobe's changes. */\nexport interface MemoryTopicCatalogueOutput {\n topics: {\n description: string;\n key: string;\n origin: \"core\" | \"lobe\" | \"user\";\n }[];\n lobeKey: string | null;\n}\n\n/** Where a page of open items ended; pass it back unchanged. */\nexport interface OpenItemsCursor {\n /** The first page's day; later pages keep counting from it. */\n asOf: string;\n id: string;\n startsOn: string;\n}\n\n/** Omitted `lobeKey` reads the owner-recall lobes; `asOf` defaults to today in UTC. */\nexport interface ListOpenItemsInput {\n asOf?: string;\n cursor?: OpenItemsCursor;\n /** 1-50; defaults to 20. */\n limit?: number;\n lobeKey?: string;\n until?: string;\n}\n\n/** A current memory planned or due ahead, or a decision still ahead. */\nexport interface OpenItem {\n category: string | null;\n content: string;\n eventTime: MemoryEventTime;\n id: string;\n lobeKey: string;\n recordedAt: string | null;\n role: \"due\" | \"planned\" | null;\n stance: MemoryStance | null;\n /** First day of its earliest time still ahead (YYYY-MM-DD). */\n startsOn: string;\n topics: string[];\n}\n\nexport interface ListOpenItemsOutput {\n asOf: string;\n items: OpenItem[];\n nextCursor: OpenItemsCursor | null;\n}\n\n/** Where a page of judgments ended; pass it back unchanged. */\nexport interface JudgmentsCursor {\n createdAt: string;\n id: string;\n}\n\nexport interface ListJudgmentsInput {\n cursor?: JudgmentsCursor;\n /** 1-50; defaults to 20. */\n limit?: number;\n lobeKey?: string;\n reviewState?: \"evidence_changed\";\n stance?: \"decision\" | \"view\";\n}\n\n/** A current view or decision with the facts it was formed on. */\nexport interface Judgment {\n basis: {\n content: string;\n /** False once the fact was replaced or expired. */\n current: boolean;\n id: string;\n link: \"rests_on\" | \"weighs_against\";\n }[];\n content: string;\n eventTime: MemoryEventTime | null;\n holder: string | null;\n id: string;\n lobeKey: string;\n recordedAt: string | null;\n reviewState: \"evidence_changed\" | null;\n stance: \"decision\" | \"view\";\n topics: string[];\n}\n\nexport interface ListJudgmentsOutput {\n items: Judgment[];\n nextCursor: JudgmentsCursor | null;\n}\n\n/** A current memory as `memories` lists it, with its update marks. */\nexport interface MemoryListItem {\n eventTime: MemoryEventTime | null;\n category: string | null;\n content: string;\n createdAt: string;\n expiresAt: string | null;\n id: string;\n /** Current memories an update mark ties to this one. */\n linked: MemoryUpdateMark[];\n lobeKey: string;\n memoryAt: string | null;\n memoryKind: string;\n /** When its source recorded it; null when unknown. */\n recordedAt: string | null;\n /** The earlier value this memory replaced. */\n replaces: MemoryReplacement | null;\n summary: string | null;\n updatedAt: string;\n}\n\n/** Where a `memories` page ended; pass it back unchanged. */\nexport interface MemoriesCursor {\n createdAt: string;\n id: string;\n}\n\nexport interface MemoriesInput {\n cursor?: MemoriesCursor | null;\n /** 1-100; the server's default is 50. */\n limit?: number;\n lobeKey?: string;\n}\n\nexport interface MemoriesOutput {\n items: MemoryListItem[];\n nextCursor: MemoriesCursor | null;\n}\n\nexport interface AuthSessionOutput {\n session: {\n createdAt: string | null;\n expiresAt: string | null;\n id: string;\n ipAddress: string | null;\n token: string;\n updatedAt: string | null;\n userAgent: string | null;\n userId: string;\n };\n user: {\n createdAt: string | null;\n email: string;\n emailVerified: boolean;\n id: string;\n image: string | null;\n name: string;\n onboardingComplete: boolean;\n updatedAt: string | null;\n };\n}\n\nexport type UsagePlan = \"free\" | \"beta\";\nexport type UsageMeter =\n | \"assistant_messages\"\n | \"automation_executions\"\n | \"llm_tokens\"\n | \"memory_processed\";\n\nexport interface UsageMeterSummary {\n allowed: boolean;\n current: number;\n limit: number | null;\n meter: UsageMeter;\n periodKey: string;\n plan: UsagePlan;\n remaining: number | null;\n userId: string;\n}\n\nexport interface UsageSummaryOutput {\n billing: {\n hasPaidPlan: boolean;\n plan: UsagePlan;\n /** A personal subscription or an organisation seat; null on the free plan. */\n planSource: \"personal\" | \"organisation\" | null;\n scheduledDowngradeAt: string | null;\n };\n llm: {\n byModel: {\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n requests: number;\n totalTokens: number;\n }[];\n bySurface: {\n inputTokens: number;\n outputTokens: number;\n requests: number;\n surface: string;\n totalTokens: number;\n }[];\n recentRequests: {\n cachedInputTokens: number;\n createdAt: string;\n id: string;\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n reasoningTokens: number;\n requestId: string | null;\n surface: string;\n totalTokens: number;\n }[];\n totals: {\n cachedInputTokens: number;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number;\n requests: number;\n totalTokens: number;\n };\n };\n meters: {\n automationExecutions: UsageMeterSummary;\n llmTokens: UsageMeterSummary;\n memoryProcessed: UsageMeterSummary;\n };\n periodStart: string;\n plan: UsagePlan;\n plans: {\n automations: number | null;\n id: UsagePlan;\n memories: number | null;\n tokens: number | null;\n }[];\n}\n\nexport interface GetSessionStartContextInput {\n /**\n * Restrict to a single lobe. Plugin callers pass `cc:<repo-slug>` so memory\n * is scoped to the active project. Omit to read across every lobe.\n */\n lobeKey?: string;\n /**\n * Short retrieval hints biased toward what the caller is about to do\n * (e.g. current git branch name, last commit subject, cwd basename).\n * Cap: 5 hints × 200 chars.\n */\n recentHints?: string[];\n /**\n * Caller-side budget. Server hard caps both numbers regardless.\n */\n budget?: {\n /** Default 15, hard cap 30. */\n maxMemories?: number;\n /** Default 2000, hard cap 4000. Char-based estimate (chars / 4). */\n maxTokens?: number;\n };\n}\n\nexport interface GetSessionStartContextOutput {\n /** Markdown block ready to drop into a hook's `additionalContext`. */\n markdown: string;\n /** IDs of every memory referenced in the markdown. */\n memoryIds: string[];\n /** True when the response was truncated by the budget. */\n hasMore: boolean;\n /** Server-side ISO 8601 timestamp the context was generated. */\n generatedAt: string;\n}\n\nexport type SourceKind =\n | \"agent_conversation\"\n | \"external_chat\"\n | \"imported_chat\"\n | \"manual_entry\"\n | \"memory_source\"\n | \"upload\";\n\n/**\n * pending: stored, awaiting extraction. processing: extraction or memory\n * creation is running or will resume. partial: some windows failed, the rest\n * created memories. failed: not fetched, converted or processed. complete:\n * extraction finished and its memories were created. deleted: deleted.\n */\nexport type SourceProcessingStatus =\n | \"complete\"\n | \"deleted\"\n | \"failed\"\n | \"partial\"\n | \"pending\"\n | \"processing\";\n\nexport type SourceAction = \"delete\" | \"reprocess\" | \"retry_blocked_windows\";\n\n/**\n * Where a source came from. Agent chat: app (web, desktop or mobile), voice,\n * telegram, whatsapp, slack, discord or linear. Synced or plugin-imported chat:\n * its provider. Also granola and upload. Saved entry: app, mcp, api (an API\n * key: this CLI, the Claude Code plugin or a script) or onboarding.\n */\nexport type SourceOrigin = string;\n\nexport type SourceDetailRoute =\n | { entryId: string; kind: \"manual_entry\" }\n | {\n connectionId: string;\n conversationId: string;\n kind: \"external_chat\";\n provider: string;\n }\n | { kind: \"imported_chat\"; sessionKey: string; source: string }\n | {\n connectionId: string;\n itemId: string;\n kind: \"memory_source\";\n provider: string;\n }\n | { conversationKey: string; kind: \"agent_conversation\"; lobeKey: string }\n | { kind: \"upload\"; uploadId: string };\n\nexport interface SourceArtifact {\n artifactId: string;\n artifactType: string;\n availableActions: SourceAction[];\n blockedWindows: number;\n createdAt: string;\n detailRoute: SourceDetailRoute | null;\n lastActivityAt: string;\n lobeKey: string;\n memoryCount: number;\n /** Null when Merrai did not record it (some older sources) and once deleted. */\n origin: SourceOrigin | null;\n pausedReason: \"quota_exceeded\" | null;\n retryableBlockedWindows: number;\n sourceId: string;\n sourceKind: SourceKind;\n sourceProvider: string | null;\n status: SourceProcessingStatus;\n title: string;\n updatedAt: string;\n}\n\nexport interface SourceArtifactCursor {\n createdAt: string;\n id: string;\n}\n\nexport interface SourceArtifactListInput {\n cursor?: SourceArtifactCursor;\n limit?: number;\n lobeKey?: string;\n providers?: string[];\n sourceKinds?: SourceKind[];\n statuses?: SourceProcessingStatus[];\n}\n\nexport interface SourceArtifactListOutput {\n items: SourceArtifact[];\n /** A status-filtered page may be short while more remain. */\n nextCursor: SourceArtifactCursor | null;\n}\n\nexport interface SourceArtifactReferenceInput {\n artifactId: string;\n}\n\nexport interface SourceArtifactDeleteOutput {\n ok: true;\n sourceKind: SourceKind;\n}\n\nexport interface IngestionReferenceInput {\n ingestionId: string;\n}\n\nexport interface IngestionEnqueuedOutput {\n /** Poll `ingestionStatus` with this ID to follow processing. */\n ingestionId: string;\n status: \"enqueued\";\n}\n\nexport type IngestionRuntimeStatus =\n | \"complete\"\n | \"errored\"\n | \"paused\"\n | \"queued\"\n | \"running\"\n | \"terminated\"\n | \"unknown\"\n | \"waiting\"\n | \"waitingForEvent\"\n | \"waitingForPause\";\n\nexport type IngestionMemoryResult =\n | {\n created: number;\n reinforced: number;\n status: \"completed\";\n updated: number;\n }\n | { reason: \"source_deleted\" | \"source_policy\"; status: \"skipped\" }\n | {\n reason: \"bootstrap_required\" | \"incomplete_observations\";\n status: \"deferred\";\n }\n | {\n created: number;\n reason: \"repair_scheduled\";\n reinforced: number;\n status: \"deferred\";\n updated: number;\n };\n\nexport interface IngestionResult {\n artifacts: { artifactId: string; lobeKey: string; sourceEntryId: string }[];\n memory: IngestionMemoryResult;\n observation: {\n blockedWindows?: number;\n retryableBlockedWindows?: number;\n status: \"completed\" | \"deferred\" | \"partial\" | \"skipped\";\n };\n status: \"completed\";\n}\n\nexport interface IngestionStatusOutput {\n attempt: number;\n error: \"INGESTION_FAILED\" | null;\n ingestionId: string;\n pausedReason: \"quota_exceeded\" | null;\n result: IngestionResult | null;\n status: IngestionRuntimeStatus;\n}\n\ninterface MerraiProcedureContract {\n addChatSession: {\n input: AddChatSessionInput;\n output: AddChatSessionOutput;\n };\n addChatSessions: {\n input: AddChatSessionsInput;\n output: AddChatSessionsOutput;\n };\n addMemories: { input: AddMemoriesInput; output: AddMemoriesOutput };\n addMemory: { input: AddMemoryInput; output: AddMemoryOutput };\n clearLobe: { input: ClearLobeInput; output: ClearLobeOutput };\n clearLobeStatus: { input: ClearLobeStatusInput; output: ClearLobeOutput };\n createLobe: { input: CreateLobeInput; output: CreateLobeOutput };\n findMemoryEntities: {\n input: FindMemoryEntitiesInput;\n output: FindMemoryEntitiesOutput;\n };\n getLivingDocument: {\n input: GetLivingDocumentInput;\n output: GetLivingDocumentOutput;\n };\n getStyleProfile: {\n input: GetStyleProfileInput;\n output: GetStyleProfileOutput;\n };\n getSessionStartContext: {\n input: GetSessionStartContextInput;\n output: GetSessionStartContextOutput;\n };\n healthCheck: { input: undefined; output: \"OK\" };\n ingestionStatus: {\n input: IngestionReferenceInput;\n output: IngestionStatusOutput;\n };\n listLivingDocuments: {\n input: ListLivingDocumentsInput;\n output: ListLivingDocumentsOutput;\n };\n listTopics: {\n input: MemoryTopicScopeInput;\n output: MemoryTopicCatalogueOutput;\n };\n listLobes: { input: undefined; output: ListLobesOutput[] };\n listLobesPage: { input: ListLobesPageInput; output: ListLobesPageOutput };\n listJudgments: { input: ListJudgmentsInput; output: ListJudgmentsOutput };\n listOpenItems: { input: ListOpenItemsInput; output: ListOpenItemsOutput };\n listLivingDocumentShares: {\n input: ListLivingDocumentSharesInput;\n output: ListLivingDocumentSharesOutput;\n };\n memories: { input: MemoriesInput | undefined; output: MemoriesOutput };\n memoryOverview: {\n input: { lobeKey?: string } | undefined;\n output: MemoryOverviewOutput;\n };\n memoryBackfillStatus: {\n input: MemoryBackfillInput;\n output: MemoryBackfillStatusOutput;\n };\n memoryStatus: { input: MemoryStatusInput; output: MemoryStatusOutput };\n memorySynthesisStatus: {\n input: MemorySynthesisInput;\n output: MemorySynthesisStatusOutput;\n };\n retireTopic: {\n input: RetireMemoryTopicInput;\n output: MemoryTopicCatalogueOutput;\n };\n retryIngestionBlockedWindows: {\n input: IngestionReferenceInput;\n output: IngestionEnqueuedOutput;\n };\n retryLivingDocumentLobeBackfill: {\n input: RetryLivingDocumentLobeBackfillInput;\n output: RetryLivingDocumentLobeBackfillOutput;\n };\n retryLivingDocumentRebuild: {\n input: RetryLivingDocumentRebuildInput;\n output: RetryLivingDocumentRebuildOutput;\n };\n session: { input: undefined; output: AuthSessionOutput | null };\n setTopic: {\n input: SetMemoryTopicInput;\n output: MemoryTopicCatalogueOutput;\n };\n startMemoryBackfill: {\n input: MemoryBackfillInput;\n output: MemoryBackfillStatusOutput;\n };\n startMemorySynthesis: {\n input: MemorySynthesisInput;\n output: MemorySynthesisStatusOutput;\n };\n sourceArtifactDelete: {\n input: SourceArtifactReferenceInput;\n output: SourceArtifactDeleteOutput;\n };\n sourceArtifactGet: {\n input: SourceArtifactReferenceInput;\n output: SourceArtifact;\n };\n sourceArtifactList: {\n input: SourceArtifactListInput;\n output: SourceArtifactListOutput;\n };\n sourceArtifactReprocess: {\n input: SourceArtifactReferenceInput;\n output: IngestionEnqueuedOutput;\n };\n sourceArtifactRetry: {\n input: SourceArtifactReferenceInput;\n output: IngestionEnqueuedOutput;\n };\n updateLobe: { input: UpdateLobeInput; output: ListLobesOutput };\n usageSummary: { input: undefined; output: UsageSummaryOutput };\n}\n\n/** JSON an App Artifact handler takes or returns. */\nexport type AppArtifactJson =\n | null\n | boolean\n | number\n | string\n | AppArtifactJson[]\n | { [key: string]: AppArtifactJson };\n\nexport type AppArtifactCallKind = \"query\" | \"mutation\" | \"action\";\n\n/** One query, mutation or action a Version declares. */\nexport interface AppArtifactHandler {\n name: string;\n description: string;\n /** Callable only from the App Artifact's own UI, not the CLI. */\n internal: boolean;\n input: Record<string, AppArtifactJson>;\n}\n\nexport type AppArtifactSampleDataState = \"valid\" | \"missing\" | \"invalid\";\n\nexport interface AppArtifactVersion {\n id: string;\n number: number;\n commitOid: string;\n manifest: {\n name: string;\n description: string;\n accountSlots: { name: string; toolkit: string; tools: string[] }[];\n sync: boolean;\n };\n api: {\n tables: string[];\n queries: AppArtifactHandler[];\n mutations: AppArtifactHandler[];\n actions: AppArtifactHandler[];\n hasSync: boolean;\n };\n allowedTools: string[];\n /** Whether its `sample-data.json` loaded into a throwaway copy when published. */\n sampleData: AppArtifactSampleDataState;\n createdAt: string;\n}\n\nexport interface AppArtifact {\n id: string;\n name: string;\n status: \"active\" | \"archived\";\n currentVersion: AppArtifactVersion | null;\n /** Tools the Current Version uses that the owner has not allowed yet. */\n pendingTools: string[];\n slotAccounts: Record<string, { connectedAccountId: string; toolkit: string }>;\n sync: {\n state: \"off\" | \"never\" | \"ok\" | \"failing\" | \"paused\";\n lastSuccessAt: string | null;\n failingSince: string | null;\n lastError: string | null;\n consecutiveFailures: number;\n nextSyncAt: string | null;\n };\n recentErrors: { source: \"ui\" | \"server\"; message: string; at: string }[];\n createdAt: string;\n updatedAt: string;\n}\n\n/** A handler's result; App Artifact failures are values, not errors. */\nexport type AppArtifactCallResult =\n | { ok: true; value: AppArtifactJson; dataVersion?: number }\n | {\n ok: false;\n error: string;\n dataVersion?: number;\n /** `app`: the App Artifact's code failed; `refused`: Merrai refused the call. */\n fault?: \"app\" | \"refused\";\n /** A share level stopped a tool: it cannot act, or it now waits for the owner. */\n code?: \"needs_act\" | \"needs_approval\";\n tool?: string;\n requestId?: string;\n };\n\n/** An App Artifact someone else owns and shared with the caller (ADR 0009). */\nexport interface SharedAppArtifact {\n id: string;\n name: string;\n description: string;\n owner: { id: string; name: string };\n level: \"use\" | \"ask\" | \"act\";\n via: (\"user\" | \"organization\" | \"link\")[];\n api: AppArtifactVersion[\"api\"] | null;\n}\n\n/** One action the caller asked the owner to approve, and what became of it. */\nexport interface AppArtifactActionRequest {\n id: string;\n appArtifactId: string;\n action: string;\n tool: string;\n status:\n | \"pending\"\n | \"approved\"\n | \"denied\"\n | \"cancelled\"\n | \"withdrawn\"\n | \"done\"\n | \"failed\";\n error: string | null;\n createdAt: string;\n resolvedAt: string | null;\n}\n\n/** Working source: path → UTF-8 text. */\nexport type AppArtifactSourceFiles = Record<string, string>;\n\nexport type AppArtifactBuildingGuideTopic = \"authoring\" | \"design\";\n\n/** How to build an app from a folder; MCP and the public agent skill serve the same text. */\nexport interface AppArtifactBuildingGuide {\n topic: AppArtifactBuildingGuideTopic;\n text: string;\n}\n\n/** An archived app deleted for good; its stored data may still be on its way out. */\nexport interface AppArtifactDeleted {\n appArtifactId: string;\n dataRemoved: boolean;\n}\n\nexport interface PublishedAppArtifact {\n artifact: AppArtifact;\n version: AppArtifactVersion;\n pendingTools: string[];\n smokeRender: { ok: boolean; detail: string };\n /** Reported, never blocking: why sample data is missing or did not load. */\n sampleData: { state: AppArtifactSampleDataState; detail: string };\n}\n\ninterface MerraiAppArtifactProcedureContract {\n list: {\n input: { status?: \"active\" | \"archived\" } | undefined;\n output: AppArtifact[];\n };\n get: { input: { appArtifactId: string }; output: AppArtifact };\n /** Archived apps only; the server refuses an active one. */\n delete: { input: { appArtifactId: string }; output: AppArtifactDeleted };\n call: {\n input: {\n appArtifactId: string;\n kind: AppArtifactCallKind;\n name: string;\n input?: AppArtifactJson;\n };\n output: AppArtifactCallResult;\n };\n openUrl: {\n input: { appArtifactId: string; mode?: \"window\" | \"embed\" };\n output: { url: string };\n };\n create: {\n input: { name: string; creationKey?: string };\n output: AppArtifact;\n };\n buildingGuide: {\n input: { topic?: AppArtifactBuildingGuideTopic };\n output: AppArtifactBuildingGuide;\n };\n source: {\n input: { appArtifactId: string };\n output: { files: AppArtifactSourceFiles; revision: string };\n };\n saveSource: {\n input: {\n appArtifactId: string;\n files: AppArtifactSourceFiles;\n message: string;\n /** Refused when the Working source moved on since this revision. */\n expectedRevision?: string;\n };\n output: { ok: true; revision: string };\n };\n publish: {\n input: {\n appArtifactId: string;\n message: string;\n publishKey?: string;\n expectedRevision?: string;\n };\n output: PublishedAppArtifact;\n };\n sharedWithMe: { input: undefined; output: SharedAppArtifact[] };\n getShared: { input: { appArtifactId: string }; output: SharedAppArtifact };\n actionRequests: {\n input: { appArtifactId: string };\n output: AppArtifactActionRequest[];\n };\n cancelActionRequest: {\n input: { appArtifactId: string; requestId: string };\n output: AppArtifactActionRequest;\n };\n}\n\ninterface MerraiRecallProcedureContract {\n addMemory: {\n input: AddMemoryRecallInput;\n output: AddMemoryRecallOutput;\n };\n listLivingDocuments: {\n input: ListLivingDocumentsRecallInput;\n output: ListLivingDocumentsRecallOutput;\n };\n readLivingDocument: {\n input: ReadLivingDocumentRecallInput;\n output: ReadLivingDocumentRecallOutput;\n };\n /** MCP search_memories over oRPC; no model call. */\n searchMemories: {\n input: SearchMemoriesRecallInput;\n output: SearchMemoriesRecallOutput;\n };\n}\n\ntype ThrowingProcedureClient<Contract> = {\n [ProcedureName in keyof Contract]: Contract[ProcedureName] extends {\n input: infer Input;\n output: infer Output;\n }\n ? ThrowingRpcProcedure<Input, Output>\n : never;\n};\n\nexport type MerraiClient = SafeClient<MerraiThrowingClient>;\n\nexport type MerraiThrowingClient =\n ThrowingProcedureClient<MerraiProcedureContract> & {\n recall: ThrowingProcedureClient<MerraiRecallProcedureContract>;\n appArtifacts: ThrowingProcedureClient<MerraiAppArtifactProcedureContract>;\n };\n\nexport interface MerraiClientOptions {\n baseURL?: string;\n apiKey?: string;\n cookie?: string;\n fetch?: ConstructorParameters<typeof RPCLink>[0][\"fetch\"];\n headers?: HeadersInit;\n}\n\nexport const resolveBaseURL = (baseURL?: string): string => {\n const resolved = baseURL?.trim();\n\n if (resolved === undefined || resolved === \"\") {\n throw new Error(\n \"baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials\"\n );\n }\n\n return resolved.endsWith(\"/\") ? resolved.slice(0, -1) : resolved;\n};\n\nconst resolveHeaders = (\n headers?: HeadersInit,\n apiKey?: string,\n cookie?: string\n): Record<string, string> => {\n const resolvedHeaders = new Headers(headers);\n // Merrai omits fields older clients cannot decode unless told they are dropped;\n // this client keeps no strict copies, so it takes every field.\n resolvedHeaders.set(\"x-merrai-unknown-fields\", \"strip\");\n\n if (apiKey !== undefined && apiKey !== \"\") {\n resolvedHeaders.set(\"x-api-key\", apiKey);\n }\n\n if (cookie !== undefined && cookie !== \"\") {\n resolvedHeaders.set(\"Cookie\", cookie);\n }\n\n return Object.fromEntries(resolvedHeaders.entries());\n};\n\nconst createMerraiRpcLink = (options: MerraiClientOptions) =>\n new RPCLink({\n fetch: options.fetch,\n headers: () =>\n resolveHeaders(options.headers, options.apiKey, options.cookie),\n url: `${resolveBaseURL(options.baseURL)}/rpc`,\n });\n\nexport const createRawMerraiClient = (\n options: MerraiClientOptions = {}\n): MerraiThrowingClient =>\n createORPCClient<MerraiThrowingClient>(createMerraiRpcLink(options));\n\n/** Debug names address the remote router independently of the published client mirror. */\nexport const createMerraiDebugProcedure = (\n options: MerraiClientOptions,\n procedureName: string\n): ThrowingRpcProcedure<JsonValue, JsonValue> =>\n createORPCClient<ThrowingRpcProcedure<JsonValue, JsonValue>>(\n createMerraiRpcLink(options),\n { path: [procedureName] }\n );\n\nexport const createMerraiClient = (\n options: MerraiClientOptions = {}\n): MerraiClient => {\n const client = createSafeClient(createRawMerraiClient(options));\n return client;\n};\n\nexport const createMerraiThrowingClient = (\n options: MerraiClientOptions = {}\n): MerraiThrowingClient => createRawMerraiClient(options);\n","","import { CommanderError } from \"commander\";\nimport { z } from \"zod\";\n\nimport type { JsonValue } from \"./client\";\n\nexport const MERRAI_CLI_EXIT_CODES = {\n /** An App Artifact handler ran and failed: its own error, not Merrai's. */\n appFailed: 6,\n auth: 3,\n network: 10,\n notFound: 4,\n rateLimit: 5,\n success: 0,\n usage: 2,\n} as const;\n\n/**\n * An App Artifact call that answered with a failure. Handler failures are\n * values on the wire; the CLI still exits non-zero so scripts notice.\n */\nexport class MerraiCliAppArtifactCallError extends Error {\n public constructor(\n message: string,\n readonly fault: \"app\" | \"refused\" | undefined\n ) {\n super(message);\n this.name = \"MerraiCliAppArtifactCallError\";\n }\n}\n\nexport class MerraiCliUsageError extends Error {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"MerraiCliUsageError\";\n }\n}\n\n/** Nothing of the caller's matched; exits as the server's not found does. */\nexport class MerraiCliNotFoundError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"MerraiCliNotFoundError\";\n }\n}\n\nexport interface MerraiCliErrorResult {\n exitCode: number;\n message: string;\n shouldRender: boolean;\n}\n\ninterface MerraiCliErrorMetadata {\n code?: string;\n data?: JsonValue;\n status?: number;\n}\n\nconst orpcErrorSchema = z.object({\n code: z.string(),\n data: z.unknown().optional(),\n message: z.string(),\n status: z.number(),\n});\ntype ParsedOrpcError = z.infer<typeof orpcErrorSchema>;\n\nexport const INVALID_API_KEY_CLI_MESSAGE =\n \"Invalid or revoked API key. Create a new key in Merrai settings, then save it with `merrai auth set-key` or set MERRAI_API_KEY.\";\n\nconst invalidApiKeyErrorSchema = z.object({\n code: z.literal(\"UNAUTHORIZED\"),\n // The server's `data.reason` for a key that authenticates no one.\n data: z.object({ reason: z.literal(\"INVALID_API_KEY\") }),\n});\n\n/**\n * True when the server refused the request's API key as unknown, malformed,\n * revoked or expired. That key will not work again.\n */\nexport const isInvalidApiKeyError = (\n // Callers pass caught values; the schema narrows them.\n error: unknown\n): error is z.infer<typeof invalidApiKeyErrorSchema> =>\n invalidApiKeyErrorSchema.safeParse(error).success;\n\n/** True when Merrai answered that nothing of the caller's has that id. */\nexport const isMerraiNotFoundError = (\n // Callers pass caught values; the schema narrows them.\n error: unknown\n): boolean => orpcErrorSchema.safeParse(error).data?.code === \"NOT_FOUND\";\n\nconst refusalReasonSchema = z.object({\n code: z.literal(\"NOT_FOUND\"),\n data: z.object({ reason: z.string() }),\n});\n\n/** The server's `data.reason` on a NOT_FOUND refusal, such as `archived`. */\nexport const merraiNotFoundReason = (\n // Callers pass caught values; the schema narrows them.\n error: unknown\n): string | undefined => refusalReasonSchema.safeParse(error).data?.data.reason;\n\nconst renderJsonError = (\n message: string,\n metadata: Readonly<MerraiCliErrorMetadata> = {}\n): string => JSON.stringify({ error: { ...metadata, message } }, null, 2);\n\nconst renderOrpcError = (error: ParsedOrpcError): string => {\n const metadata: MerraiCliErrorMetadata = {\n code: error.code,\n status: error.status,\n };\n const data = z.json().safeParse(error.data);\n if (data.success) {\n metadata.data = data.data;\n }\n return renderJsonError(error.message, metadata);\n};\n\nexport const classifyMerraiCliError = (\n // This is the CLI process boundary that normalizes all thrown values before rendering.\n error: unknown\n): MerraiCliErrorResult => {\n if (error instanceof CommanderError) {\n const isSuccessfulControlFlow =\n error.code === \"commander.helpDisplayed\" ||\n error.code === \"commander.version\";\n return {\n exitCode: isSuccessfulControlFlow\n ? MERRAI_CLI_EXIT_CODES.success\n : MERRAI_CLI_EXIT_CODES.usage,\n message: error.message,\n shouldRender: false,\n };\n }\n\n if (error instanceof MerraiCliAppArtifactCallError) {\n return {\n // Merrai refusing the call (not allowed, archived) is a permission\n // problem; anything else is the App Artifact's own failure.\n exitCode:\n error.fault === \"refused\"\n ? MERRAI_CLI_EXIT_CODES.auth\n : MERRAI_CLI_EXIT_CODES.appFailed,\n message: renderJsonError(error.message, {\n code: error.fault === \"refused\" ? \"CALL_REFUSED\" : \"CALL_FAILED\",\n }),\n shouldRender: true,\n };\n }\n\n if (error instanceof MerraiCliUsageError) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.usage,\n message: renderJsonError(error.message, { code: \"USAGE_ERROR\" }),\n shouldRender: true,\n };\n }\n\n if (error instanceof MerraiCliNotFoundError) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.notFound,\n message: renderJsonError(error.message, { code: \"NOT_FOUND\" }),\n shouldRender: true,\n };\n }\n\n const orpcError = orpcErrorSchema.safeParse(error);\n if (orpcError.success) {\n const code = orpcError.data.code;\n if (code === \"BAD_REQUEST\" || code === \"UNPROCESSABLE_CONTENT\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.usage,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n if (code === \"UNAUTHORIZED\" || code === \"FORBIDDEN\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.auth,\n message: renderOrpcError(\n isInvalidApiKeyError(orpcError.data)\n ? { ...orpcError.data, message: INVALID_API_KEY_CLI_MESSAGE }\n : orpcError.data\n ),\n shouldRender: true,\n };\n }\n if (code === \"NOT_FOUND\" || code === \"CONFLICT\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.notFound,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n if (\n code === \"RATE_LIMITED\" ||\n code === \"TOO_MANY_REQUESTS\" ||\n code === \"PAYLOAD_TOO_LARGE\" ||\n code === \"RESOURCE_EXHAUSTED\" ||\n orpcError.data.status === 429\n ) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.rateLimit,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.network,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n\n const nativeError = z.instanceof(Error).safeParse(error);\n const stringError = z.string().safeParse(error);\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.network,\n message: renderJsonError(\n nativeError.success\n ? nativeError.data.message\n : stringError.success\n ? stringError.data\n : \"Unexpected CLI failure\",\n { code: \"NETWORK_ERROR\" }\n ),\n shouldRender: true,\n };\n};\n","/*\n * An App Artifact's Working source as a local folder, for `merrai apps`.\n * The server owns the rules (paths, sizes, the build); this only reads and\n * writes text files and leaves out what is never source.\n */\nimport * as NodeFSP from \"node:fs/promises\";\nimport * as NodePath from \"node:path\";\n\nimport type { AppArtifactSourceFiles } from \"./client\";\nimport { MerraiCliUsageError } from \"./errors\";\n\nconst MANIFEST = \"app-artifact.json\";\n/** The Working source revision this folder was last pulled or pushed at; never uploaded. */\nconst REVISION_FILE = NodePath.join(\".merrai\", \"revision\");\n/** Never source: version control, installed packages and Merrai's own build output. */\nconst SKIPPED_DIRECTORIES = new Set([\".git\", \"node_modules\", \".merrai\"]);\n/** The server's own limits, checked here so a mistake fails before upload. */\nconst MAX_FILES = 64;\nconst MAX_FILE_BYTES = 256 * 1024;\n\nconst isSkipped = (name: string) =>\n name.startsWith(\".\") || SKIPPED_DIRECTORIES.has(name);\n\nconst listFiles = async (\n root: string,\n directory: string\n): Promise<string[]> => {\n const entries = await NodeFSP.readdir(NodePath.join(root, directory), {\n withFileTypes: true,\n });\n const nested = await Promise.all(\n entries\n .filter((entry) => !isSkipped(entry.name))\n .map(async (entry) => {\n const relative = NodePath.posix.join(directory, entry.name);\n if (entry.isDirectory()) return await listFiles(root, relative);\n return entry.isFile() ? [relative] : [];\n })\n );\n return nested.flat();\n};\n\nconst readText = async (root: string, file: string): Promise<string> => {\n const bytes = await NodeFSP.readFile(NodePath.join(root, file));\n if (bytes.byteLength > MAX_FILE_BYTES)\n throw new MerraiCliUsageError(\n `${file} is larger than ${MAX_FILE_BYTES / 1024} KB, the most one source file may be`\n );\n // Source is text; a NUL byte means a binary file that cannot be built.\n if (bytes.includes(0))\n throw new MerraiCliUsageError(\n `${file} is not a text file. App Artifact source is text only.`\n );\n return bytes.toString(\"utf8\");\n};\n\n/** Every source file under `directory`, keyed by its slash-separated relative path. */\nexport const readAppSourceFolder = async (\n directory: string\n): Promise<AppArtifactSourceFiles> => {\n let files: string[];\n try {\n files = (await listFiles(directory, \"\")).toSorted();\n } catch (error) {\n throw new MerraiCliUsageError(\n `Unable to read ${directory}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n );\n }\n if (!files.includes(MANIFEST))\n throw new MerraiCliUsageError(\n `${directory} has no ${MANIFEST}. An App Artifact folder needs one at its root.`\n );\n if (files.length > MAX_FILES)\n throw new MerraiCliUsageError(\n `${directory} has ${files.length} files; an App Artifact may have at most ${MAX_FILES}.`\n );\n const contents = await Promise.all(\n files.map(async (file) => [file, await readText(directory, file)] as const)\n );\n return Object.fromEntries(contents);\n};\n\n/**\n * Refuses a path whose existing parts include a symlink: the lexical check\n * alone would let `--force` follow one and overwrite files elsewhere.\n */\nconst assertNoSymlink = async (root: string, target: string) => {\n const parts = NodePath.relative(root, target).split(NodePath.sep);\n const prefixes = parts.map((_, index) =>\n NodePath.join(root, ...parts.slice(0, index + 1))\n );\n const stats = await Promise.all(\n prefixes.map((prefix) => NodeFSP.lstat(prefix).catch(() => null))\n );\n const link = prefixes.find(\n (_, index) => stats[index]?.isSymbolicLink() === true\n );\n if (link !== undefined)\n throw new MerraiCliUsageError(\n `Refusing to write through the symlink ${link}`\n );\n};\n\n/**\n * Writes the Working source into `directory`. Without `force` it refuses a\n * folder that already has files, so a pull never overwrites local edits.\n */\nexport const writeAppSourceFolder = async (\n directory: string,\n files: AppArtifactSourceFiles,\n options: { readonly force: boolean }\n): Promise<void> => {\n const existing = await NodeFSP.readdir(directory).catch(() => []);\n if (existing.length > 0 && !options.force)\n throw new MerraiCliUsageError(\n `${directory} is not empty. Pull into an empty folder, or pass --force to overwrite.`\n );\n const root = NodePath.resolve(directory);\n await Promise.all(\n Object.entries(files).map(async ([file, content]) => {\n const target = NodePath.resolve(root, file);\n // The server's paths are relative, but a file must never land outside the folder.\n if (!target.startsWith(root + NodePath.sep))\n throw new MerraiCliUsageError(\n `Refusing to write ${file} outside ${directory}`\n );\n await assertNoSymlink(root, target);\n await NodeFSP.mkdir(NodePath.dirname(target), { recursive: true });\n await NodeFSP.writeFile(target, content, \"utf8\");\n })\n );\n};\n\n/** The revision recorded in `directory`, or undefined when it has none. */\nexport const readAppSourceRevision = async (\n directory: string\n): Promise<string | undefined> => {\n try {\n const revision = (\n await NodeFSP.readFile(NodePath.join(directory, REVISION_FILE), \"utf8\")\n ).trim();\n return revision.length === 0 ? undefined : revision;\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\")\n return undefined;\n throw error;\n }\n};\n\n/**\n * Records the revision the folder matches, so the next push is refused if\n * someone else changed the app meanwhile.\n */\nexport const writeAppSourceRevision = async (\n directory: string,\n revision: string\n): Promise<void> => {\n const target = NodePath.resolve(directory, REVISION_FILE);\n await assertNoSymlink(NodePath.resolve(directory), target);\n await NodeFSP.mkdir(NodePath.dirname(target), { recursive: true });\n await NodeFSP.writeFile(target, `${revision}\\n`, \"utf8\");\n};\n","import * as NodeFSP from \"node:fs/promises\";\nimport * as NodePath from \"node:path\";\nimport * as NodeReadlinePromises from \"node:readline/promises\";\nimport type * as NodeStream from \"node:stream\";\n\nimport { z } from \"zod\";\n\nimport type { JsonValue } from \"./client\";\nimport { MerraiCliUsageError } from \"./errors\";\n\nconst structuredInputSchema = z.json();\n\nconst readStream = async (stream: NodeStream.Readable): Promise<string> => {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readFileOrStdin = async (options: {\n cwd: string;\n file: string;\n stdin: NodeStream.Readable;\n}): Promise<string> => {\n if (options.file === \"-\") {\n return readStream(options.stdin);\n }\n const resolvedPath = NodePath.resolve(options.cwd, options.file);\n try {\n return await NodeFSP.readFile(resolvedPath, \"utf8\");\n } catch (error) {\n throw new MerraiCliUsageError(\n `Unable to read ${resolvedPath}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n );\n }\n};\n\nexport const readStructuredInput = async (options: {\n cwd: string;\n file?: string;\n input?: string;\n stdin: NodeStream.Readable;\n}): Promise<JsonValue> => {\n if (options.file !== undefined && options.input !== undefined) {\n throw new MerraiCliUsageError(\"Use only one of --input or --file\");\n }\n if (options.file === undefined && options.input === undefined) {\n throw new MerraiCliUsageError(\"Provide --input <json> or --file <path|->\");\n }\n\n const source =\n options.input !== undefined\n ? options.input\n : await readFileOrStdin({\n cwd: options.cwd,\n file: options.file ?? \"-\",\n stdin: options.stdin,\n });\n try {\n return structuredInputSchema.parse(JSON.parse(source));\n } catch (error) {\n const label = options.file === undefined ? \"--input\" : options.file;\n throw new MerraiCliUsageError(\n `Invalid JSON from ${label}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n );\n }\n};\n\nexport const readTextInput = async (options: {\n cwd: string;\n file?: string;\n option?: string;\n positional?: string;\n stdin: NodeStream.Readable;\n}): Promise<string> => {\n const directValues = [options.positional, options.option].filter(\n (value): value is string => value !== undefined\n );\n if (\n directValues.length > 1 ||\n (options.file !== undefined && directValues.length > 0)\n ) {\n throw new MerraiCliUsageError(\n \"Provide memory text using only one positional value, --memory, or --file\"\n );\n }\n\n const value =\n directValues[0] ??\n (options.file === undefined\n ? undefined\n : await readFileOrStdin({\n cwd: options.cwd,\n file: options.file,\n stdin: options.stdin,\n }));\n if (value === undefined || value.trim().length === 0) {\n throw new MerraiCliUsageError(\"Memory text cannot be empty\");\n }\n return value;\n};\n\nexport const confirmAction = async (options: {\n input: NodeStream.Readable;\n message: string;\n output: NodeStream.Writable;\n}): Promise<boolean> => {\n const terminal = \"isTTY\" in options.input && options.input.isTTY === true;\n if (!terminal) {\n return false;\n }\n const prompt = NodeReadlinePromises.createInterface({\n input: options.input,\n output: options.output,\n });\n try {\n const answer = await prompt.question(`${options.message} [y/N] `);\n return (\n answer.trim().toLowerCase() === \"y\" ||\n answer.trim().toLowerCase() === \"yes\"\n );\n } finally {\n prompt.close();\n }\n};\n\n/** One typed line from a terminal; undefined when nobody can type one. */\nexport const readTypedConfirmation = async (options: {\n input: NodeStream.Readable;\n message: string;\n output: NodeStream.Writable;\n}): Promise<string | undefined> => {\n const terminal = \"isTTY\" in options.input && options.input.isTTY === true;\n if (!terminal) return undefined;\n const prompt = NodeReadlinePromises.createInterface({\n input: options.input,\n output: options.output,\n });\n try {\n return await prompt.question(`${options.message} `);\n } finally {\n prompt.close();\n }\n};\n\ninterface RawModeReadable extends NodeStream.Readable {\n isRaw?: boolean;\n isTTY?: boolean;\n setRawMode?: (mode: boolean) => void;\n}\n\nexport const readSecretInput = async (options: {\n input: NodeStream.Readable;\n message: string;\n output: NodeStream.Writable;\n}): Promise<string> => {\n // SAFETY: Node Readable instances may expose the documented TTY raw-mode\n // methods at runtime; the capability checks below run before either is used.\n const input = options.input as RawModeReadable;\n if (input.isTTY !== true || input.setRawMode === undefined) {\n throw new MerraiCliUsageError(\n \"Provide the API key as an argument or through MERRAI_API_KEY in noninteractive use\"\n );\n }\n\n options.output.write(options.message);\n const wasRaw = input.isRaw === true;\n input.setRawMode(true);\n\n return new Promise<string>((resolve, reject) => {\n let value = \"\";\n const cleanup = (): void => {\n input.off(\"data\", onData);\n input.off(\"end\", onEnd);\n input.off(\"error\", onError);\n input.setRawMode?.(wasRaw);\n input.pause();\n };\n const rejectInput = (error: Error): void => {\n cleanup();\n reject(error);\n };\n const onEnd = (): void => {\n rejectInput(new MerraiCliUsageError(\"API key entry ended unexpectedly\"));\n };\n const onError = (error: Error): void => {\n rejectInput(\n new MerraiCliUsageError(`Unable to read API key: ${error.message}`, {\n cause: error,\n })\n );\n };\n const onData = (chunk: Buffer | string): void => {\n const text = Buffer.isBuffer(chunk) ? chunk.toString(\"utf8\") : chunk;\n for (const character of text) {\n if (character === \"\\r\" || character === \"\\n\") {\n options.output.write(\"\\n\");\n cleanup();\n resolve(value);\n return;\n }\n if (character === \"\\u0003\" || character === \"\\u0004\") {\n options.output.write(\"\\n\");\n rejectInput(new MerraiCliUsageError(\"API key entry cancelled\"));\n return;\n }\n if (character === \"\\u007f\" || character === \"\\b\") {\n if (value.length > 0) {\n value = value.slice(0, -1);\n options.output.write(\"\\b \\b\");\n }\n continue;\n }\n value += character;\n options.output.write(\"*\");\n }\n };\n input.on(\"data\", onData);\n input.once(\"end\", onEnd);\n input.once(\"error\", onError);\n input.resume();\n });\n};\n","import type { z } from \"zod\";\n\nimport type { JudgmentsCursor, LobesCursor, OpenItemsCursor } from \"../client\";\nimport { MerraiCliUsageError } from \"../errors\";\n\nconst ISO_8601_DATETIME_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/;\n\n/**\n * Text output for queued work: names the ingestion and how to follow it,\n * since the save is not processed or searchable yet.\n */\nexport const describeQueuedIngestion = (\n what: string,\n ingestionId: string\n): string =>\n `${what} queued as ingestion ${ingestionId}. Follow it with \\`merrai ingestion status ${ingestionId}\\`.`;\n\nexport const resolveLobeKey = (options: {\n lobe?: string;\n lobeKey?: string;\n}): string | undefined => options.lobe ?? options.lobeKey;\n\nexport const parseIntegerOption = (\n value: string | undefined,\n name: string,\n range: { maximum: number; minimum: number }\n): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n const parsed = Number(value);\n if (\n !Number.isInteger(parsed) ||\n parsed < range.minimum ||\n parsed > range.maximum\n ) {\n throw new MerraiCliUsageError(\n `${name} must be an integer from ${range.minimum} to ${range.maximum}`\n );\n }\n return parsed;\n};\n\nexport const parseDateOption = (\n value: string | undefined,\n name: string\n): string | undefined => {\n if (value === undefined) {\n return undefined;\n }\n if (\n !ISO_8601_DATETIME_PATTERN.test(value) ||\n Number.isNaN(new Date(value).getTime())\n ) {\n throw new MerraiCliUsageError(`${name} must be a valid ISO 8601 datetime`);\n }\n return value;\n};\n\nexport const parseEntityType = (\n value: string | undefined\n): import(\"../client\").EntityType | undefined => {\n if (value === undefined) {\n return undefined;\n }\n switch (value) {\n case \"action\":\n case \"document\":\n case \"event\":\n case \"knowledge\":\n case \"person\":\n return value;\n default:\n throw new MerraiCliUsageError(\n \"--type must be one of: person, event, action, knowledge, document\"\n );\n }\n};\n\n/** Commander's collector for an option given more than once. */\nexport const collectOption = (value: string, previous: string[]): string[] => [\n ...previous,\n value,\n];\n\n/** A calendar day (YYYY-MM-DD) that exists. */\nexport const parseDayOption = (\n value: string | undefined,\n name: string\n): string | undefined => {\n if (value === undefined) return undefined;\n const parsed = new Date(`${value}T00:00:00.000Z`);\n if (\n Number.isNaN(parsed.getTime()) ||\n parsed.toISOString().slice(0, 10) !== value\n ) {\n throw new MerraiCliUsageError(`${name} must be a day as YYYY-MM-DD`);\n }\n return value;\n};\n\n/** The day it is where the CLI runs (YYYY-MM-DD). */\nexport const localDay = (now: Date): string =>\n [\n String(now.getFullYear()).padStart(4, \"0\"),\n String(now.getMonth() + 1).padStart(2, \"0\"),\n String(now.getDate()).padStart(2, \"0\"),\n ].join(\"-\");\n\n/** Parses a `nextCursor` JSON a previous page printed. */\nexport const parseCursorJson = <Cursor>(\n schema: z.ZodType<Cursor>,\n value: string | undefined,\n example: string\n): Cursor | undefined => {\n if (value === undefined) return undefined;\n let json: unknown;\n try {\n json = JSON.parse(value);\n } catch {\n json = undefined;\n }\n const parsed = schema.safeParse(json);\n if (!parsed.success) {\n throw new MerraiCliUsageError(\n `cursor must be the nextCursor JSON from a previous page, for example ${example}`\n );\n }\n return parsed.data;\n};\n\n/** The line that tells a reader how to fetch the next page, if any. */\nexport const renderMoreCursor = (\n cursor: JudgmentsCursor | LobesCursor | OpenItemsCursor | null\n): string[] =>\n cursor === null ? [] : [`More: --cursor '${JSON.stringify(cursor)}'`];\n\n/** Commander passes an empty options object to commands that declare none. */\nexport type NoCommandOptions = Readonly<Record<string, never>>;\n\n/** `--input <json>` or `--file <path|->`, read by `readStructuredInput`. */\nexport interface StructuredInputOptions {\n file?: string;\n input?: string;\n}\n","import * as NodeCrypto from \"node:crypto\";\nimport * as NodePath from \"node:path\";\n\nimport type { Command } from \"commander\";\n\nimport {\n readAppSourceFolder,\n readAppSourceRevision,\n writeAppSourceFolder,\n writeAppSourceRevision,\n} from \"../app-source-files\";\nimport type {\n AppArtifact,\n AppArtifactActionRequest,\n AppArtifactBuildingGuideTopic,\n AppArtifactCallKind,\n AppArtifactCallResult,\n AppArtifactDeleted,\n PublishedAppArtifact,\n SharedAppArtifact,\n} from \"../client\";\nimport {\n MerraiCliAppArtifactCallError,\n MerraiCliNotFoundError,\n MerraiCliUsageError,\n isMerraiNotFoundError,\n merraiNotFoundReason,\n} from \"../errors\";\nimport { readStructuredInput, readTypedConfirmation } from \"../input\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { type NoCommandOptions, type StructuredInputOptions } from \"./shared\";\n\n/*\n * App Artifacts: the owner's small apps (docs/app-artifacts) and those shared\n * with them (ADR 0009). Use them (list, shared, show, call, open, requests)\n * and build your own from a folder (guide, create, pull, push, publish). Sharing and\n * Allowed tools stay in the Merrai app; delete takes an archived app's name.\n */\n\nconst GUIDE_TOPICS: readonly AppArtifactBuildingGuideTopic[] = [\n \"authoring\",\n \"design\",\n];\n\nconst parseGuideTopic = (topic: string): AppArtifactBuildingGuideTopic => {\n const match = GUIDE_TOPICS.find((candidate) => candidate === topic);\n if (match === undefined)\n throw new MerraiCliUsageError(\n `Unknown guide topic ${topic}. Use one of: ${GUIDE_TOPICS.join(\", \")}`\n );\n return match;\n};\n\nconst CALL_KINDS: readonly AppArtifactCallKind[] = [\n \"query\",\n \"mutation\",\n \"action\",\n];\n\ninterface ListOptions {\n archived?: boolean;\n}\n\ninterface CreateOptions {\n from?: string;\n message?: string;\n publish?: boolean;\n}\n\ninterface PullOptions {\n force?: boolean;\n}\n\ninterface PushOptions {\n message?: string;\n}\n\ninterface PublishOptions {\n message?: string;\n push?: string;\n}\n\ninterface DeleteOptions {\n confirm?: string;\n}\n\nconst parseCallKind = (kind: string): AppArtifactCallKind => {\n const match = CALL_KINDS.find((candidate) => candidate === kind);\n if (match === undefined)\n throw new MerraiCliUsageError(\n `Unknown handler kind ${kind}. Use one of: ${CALL_KINDS.join(\", \")}`\n );\n return match;\n};\n\nconst requireMessage = (message: string | undefined): string => {\n const trimmed = message?.trim() ?? \"\";\n if (trimmed.length === 0)\n throw new MerraiCliUsageError(\n \"Describe the change with -m <message>; it is kept with the Version.\"\n );\n return trimmed;\n};\n\nconst describeVersion = (artifact: AppArtifact): string =>\n artifact.currentVersion === null\n ? \"no Version yet\"\n : `Version ${artifact.currentVersion.number}`;\n\nconst renderList = (artifacts: AppArtifact[]): string =>\n artifacts.length === 0\n ? \"No apps.\"\n : artifacts\n .map(\n (artifact) =>\n `- ${artifact.name}: ${describeVersion(artifact)}${\n artifact.pendingTools.length > 0 ? \", needs permission\" : \"\"\n } (${artifact.id})`\n )\n .join(\"\\n\");\n\nconst SHARE_LEVELS = {\n use: \"Can view\",\n ask: \"Asks before changes\",\n act: \"Can make changes\",\n} as const satisfies Record<SharedAppArtifact[\"level\"], string>;\n\nconst renderShared = (artifacts: SharedAppArtifact[]): string =>\n artifacts.length === 0\n ? \"Nothing is shared with you.\"\n : artifacts\n .map(\n (artifact) =>\n `- ${artifact.name}, shared by ${artifact.owner.name} (${SHARE_LEVELS[artifact.level]}) (${artifact.id})`\n )\n .join(\"\\n\");\n\nconst renderRequests = (requests: AppArtifactActionRequest[]): string =>\n requests.length === 0\n ? \"No requests.\"\n : requests\n .map(\n (request) =>\n `- ${request.action} (${request.tool}): ${request.status}${\n request.error === null ? \"\" : `, ${request.error}`\n } (${request.id})`\n )\n .join(\"\\n\");\n\ntype AppArtifactApi = NonNullable<AppArtifact[\"currentVersion\"]>[\"api\"];\n\nconst handlerLines = (api: AppArtifactApi | undefined): string[] => {\n if (api === undefined) return [];\n const callable = (kind: AppArtifactCallKind, handlers: typeof api.queries) =>\n handlers\n .filter((handler) => !handler.internal)\n .map((handler) => ` ${kind} ${handler.name}: ${handler.description}`);\n const lines = [\n ...callable(\"query\", api.queries),\n ...callable(\"mutation\", api.mutations),\n ...callable(\"action\", api.actions),\n ];\n return lines.length === 0 ? [] : [\"Handlers:\", ...lines];\n};\n\nconst renderArtifact = (artifact: AppArtifact): string => {\n const description = artifact.currentVersion?.manifest.description ?? \"\";\n return [\n artifact.name,\n `ID: ${artifact.id}`,\n `Status: ${artifact.status}, ${describeVersion(artifact)}`,\n ...(description === \"\" ? [] : [description]),\n `Sync: ${artifact.sync.state}${\n artifact.sync.lastError === null ? \"\" : ` (${artifact.sync.lastError})`\n }`,\n ...(artifact.pendingTools.length > 0\n ? [\n `Needs permission for: ${artifact.pendingTools.join(\", \")} (allow them in Merrai)`,\n ]\n : []),\n ...handlerLines(artifact.currentVersion?.api),\n ...(artifact.recentErrors.length > 0\n ? [\n \"Recent errors:\",\n ...artifact.recentErrors.map(\n (error) => `- ${error.at} ${error.source}: ${error.message}`\n ),\n ]\n : []),\n ].join(\"\\n\");\n};\n\nconst renderSharedArtifact = (artifact: SharedAppArtifact): string =>\n [\n artifact.name,\n `ID: ${artifact.id}`,\n `Shared by ${artifact.owner.name}: ${SHARE_LEVELS[artifact.level]}`,\n ...(artifact.description === \"\" ? [] : [artifact.description]),\n ...handlerLines(artifact.api ?? undefined),\n ].join(\"\\n\");\n\nconst renderDeleted =\n (name: string) =>\n (deleted: AppArtifactDeleted): string =>\n deleted.dataRemoved\n ? `Deleted ${name} (${deleted.appArtifactId}).`\n : `Deleted ${name} (${deleted.appArtifactId}). Its stored data is still being removed.`;\n\nconst renderAlreadyDeleted = (deleted: AppArtifactDeleted): string =>\n deleted.dataRemoved\n ? `${deleted.appArtifactId} was already deleted. Its stored data is now removed.`\n : `${deleted.appArtifactId} was already deleted. Its stored data is still being removed.`;\n\n/**\n * Repeats a delete whose app is already gone: the server only retries\n * removing the owner's own pending data, so there is no name to confirm.\n */\nconst finishDeleted = async (\n client: ReturnType<MerraiCommandContext[\"client\"]>,\n appArtifactId: string\n): Promise<AppArtifactDeleted> => {\n try {\n return await client.appArtifacts.delete({ appArtifactId });\n } catch (error) {\n if (!isMerraiNotFoundError(error)) throw error;\n throw new MerraiCliNotFoundError(\n `Nothing to delete: ${appArtifactId} is not one of your apps. An app already deleted for good reads the same.`\n );\n }\n};\n\n/**\n * Not yours: it may be shared with you. Null for a plain refusal, which reads\n * as the owner lookup's; one with a reason (archived) is the grantee's to see.\n */\nconst sharedOrPlainRefusal = async (\n client: ReturnType<MerraiCommandContext[\"client\"]>,\n appArtifactId: string\n): Promise<SharedAppArtifact | null> => {\n try {\n return await client.appArtifacts.getShared({ appArtifactId });\n } catch (sharedError) {\n if (\n isMerraiNotFoundError(sharedError) &&\n merraiNotFoundReason(sharedError) === undefined\n )\n return null;\n throw sharedError;\n }\n};\n\nconst renderPublished = (published: PublishedAppArtifact): string =>\n [\n `Published ${published.artifact.name} Version ${published.version.number} (${published.artifact.id})`,\n published.smokeRender.ok\n ? \"Smoke render: ok\"\n : `Smoke render failed: ${published.smokeRender.detail}`,\n published.sampleData.state === \"valid\"\n ? \"Sample data: ok\"\n : `Sample data ${published.sampleData.state}: ${published.sampleData.detail}`,\n ...(published.pendingTools.length > 0\n ? [\n `Needs permission for: ${published.pendingTools.join(\", \")} (allow them in Merrai)`,\n ]\n : []),\n ].join(\"\\n\");\n\nexport const registerAppCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const apps = program\n .command(\"apps\")\n .description(\"Use your App Artifacts and build them from a local folder\");\n\n apps\n .command(\"list\")\n .description(\"List your apps\")\n .option(\"--archived\", \"List archived apps instead\")\n .action(async (options: ListOptions, command: Command) => {\n const result = await context.client(command).appArtifacts.list({\n status: options.archived === true ? \"archived\" : \"active\",\n });\n context.output(command).data(result, renderList);\n });\n\n apps\n .command(\"shared\")\n .description(\"List apps other people shared with you\")\n .action(async (_options: NoCommandOptions, command: Command) => {\n const result = await context.client(command).appArtifacts.sharedWithMe();\n context.output(command).data(result, renderShared);\n });\n\n apps\n .command(\"show\")\n .description(\"Show one app, its sync state and the handlers you can call\")\n .argument(\"<id>\", \"App Artifact ID\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const client = context.client(command);\n let owned: AppArtifact;\n try {\n owned = await client.appArtifacts.get({ appArtifactId: id });\n } catch (ownerError) {\n if (!isMerraiNotFoundError(ownerError)) throw ownerError;\n const shared = await sharedOrPlainRefusal(client, id);\n if (shared === null) throw ownerError;\n context.output(command).data(shared, renderSharedArtifact);\n return;\n }\n context.output(command).data(owned, renderArtifact);\n }\n );\n\n apps\n .command(\"call\")\n .description(\"Run one of an app's queries, mutations or actions\")\n .argument(\"<id>\", \"App Artifact ID\")\n .argument(\"<kind>\", `Handler kind: ${CALL_KINDS.join(\", \")}`)\n .argument(\"<name>\", \"Handler name, as `merrai apps show` lists it\")\n .option(\"--input <json>\", \"The handler's input as JSON (default {})\")\n .option(\"--file <path>\", \"Read the input JSON from a file, or - for stdin\")\n .action(\n async (\n id: string,\n kind: string,\n name: string,\n options: StructuredInputOptions,\n command: Command\n ) => {\n const callKind = parseCallKind(kind);\n const input =\n options.input === undefined && options.file === undefined\n ? {}\n : await readStructuredInput({\n cwd: context.runtime.cwd,\n file: options.file,\n input: options.input,\n stdin: context.runtime.stdin,\n });\n const result: AppArtifactCallResult = await context\n .client(command)\n .appArtifacts.call({\n appArtifactId: id,\n kind: callKind,\n name,\n input,\n });\n if (!result.ok)\n throw new MerraiCliAppArtifactCallError(\n result.code === \"needs_approval\"\n ? `${result.error} Follow it with \\`merrai apps requests ${id}\\`.`\n : result.error,\n result.fault\n );\n context.output(command).data(result.value);\n }\n );\n\n apps\n .command(\"requests\")\n .description(\"Your requests waiting for, or decided by, an app's owner\")\n .argument(\"<id>\", \"App Artifact ID\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .appArtifacts.actionRequests({ appArtifactId: id });\n context.output(command).data(result, renderRequests);\n }\n );\n\n apps\n .command(\"cancel-request\")\n .description(\"Take back a request that still waits for the owner\")\n .argument(\"<id>\", \"App Artifact ID\")\n .argument(\"<request>\", \"Request ID, as `merrai apps requests` lists it\")\n .action(\n async (\n id: string,\n requestId: string,\n _options: NoCommandOptions,\n command: Command\n ) => {\n const result = await context\n .client(command)\n .appArtifacts.cancelActionRequest({ appArtifactId: id, requestId });\n context\n .output(command)\n .data(\n result,\n (request) => `Request ${request.id}: ${request.status}`\n );\n }\n );\n\n apps\n .command(\"open\")\n .description(\"Print a link that opens the app in your browser\")\n .argument(\"<id>\", \"App Artifact ID\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .appArtifacts.openUrl({ appArtifactId: id, mode: \"window\" });\n // The link signs the browser in and works for about a minute.\n context.output(command).data(result, (value) => value.url);\n }\n );\n\n apps\n .command(\"guide\")\n .description(\n \"Print how to build an app: read authoring first, then design before any UI\"\n )\n .argument(\"[topic]\", GUIDE_TOPICS.join(\" or \"), \"authoring\")\n .action(\n async (topic: string, _options: NoCommandOptions, command: Command) => {\n const guide = await context\n .client(command)\n .appArtifacts.buildingGuide({ topic: parseGuideTopic(topic) });\n // A guide is read, not parsed: text unless JSON is asked for.\n const { format, json } = command.optsWithGlobals<{\n format?: string;\n json?: boolean;\n }>();\n if (json === true || format === \"json\") {\n context.output(command).data(guide);\n return;\n }\n context.runtime.stdout.write(`${guide.text.trimEnd()}\\n`);\n }\n );\n\n apps\n .command(\"create\")\n .description(\"Create an app, optionally from a folder and published\")\n .argument(\"<name>\", \"The app's name\")\n .option(\"--from <dir>\", \"Save this folder as the app's Working source\")\n .option(\"--publish\", \"Publish the folder as Version 1 (needs --from)\")\n .option(\"-m, --message <message>\", \"Describe the change (with --from)\")\n .action(async (name: string, options: CreateOptions, command: Command) => {\n if (options.publish === true && options.from === undefined)\n throw new MerraiCliUsageError(\"--publish needs --from <dir>\");\n const directory =\n options.from === undefined\n ? undefined\n : NodePath.resolve(context.runtime.cwd, options.from);\n const files =\n directory === undefined\n ? undefined\n : await readAppSourceFolder(directory);\n const message =\n files === undefined ? undefined : requireMessage(options.message);\n const client = context.client(command);\n // A retried create returns the app it already made.\n const created = await client.appArtifacts.create({\n name,\n creationKey: NodeCrypto.randomUUID(),\n });\n if (\n directory === undefined ||\n files === undefined ||\n message === undefined\n ) {\n context.output(command).data(created, renderArtifact);\n return;\n }\n const saved = await client.appArtifacts.saveSource({\n appArtifactId: created.id,\n files,\n message,\n });\n await writeAppSourceRevision(directory, saved.revision);\n if (options.publish !== true) {\n context\n .output(command)\n .data(\n await client.appArtifacts.get({ appArtifactId: created.id }),\n renderArtifact\n );\n return;\n }\n const published = await client.appArtifacts.publish({\n appArtifactId: created.id,\n message,\n publishKey: NodeCrypto.randomUUID(),\n expectedRevision: saved.revision,\n });\n context.output(command).data(published, renderPublished);\n });\n\n apps\n .command(\"pull\")\n .description(\"Write an app's Working source into a folder\")\n .argument(\"<id>\", \"App Artifact ID\")\n .argument(\"<dir>\", \"An empty folder\")\n .option(\"--force\", \"Overwrite files already in the folder\")\n .action(\n async (\n id: string,\n dir: string,\n options: PullOptions,\n command: Command\n ) => {\n const { files, revision } = await context\n .client(command)\n .appArtifacts.source({ appArtifactId: id });\n const directory = NodePath.resolve(context.runtime.cwd, dir);\n await writeAppSourceFolder(directory, files, {\n force: options.force === true,\n });\n await writeAppSourceRevision(directory, revision);\n context.output(command).data(\n {\n appArtifactId: id,\n directory,\n files: Object.keys(files).toSorted(),\n },\n (value) => `Wrote ${value.files.length} files to ${value.directory}`\n );\n }\n );\n\n apps\n .command(\"push\")\n .description(\n \"Save a folder as an app's Working source without publishing it\"\n )\n .argument(\"<id>\", \"App Artifact ID\")\n .argument(\"<dir>\", \"The app's folder\")\n .option(\"-m, --message <message>\", \"Describe the change\")\n .action(\n async (\n id: string,\n dir: string,\n options: PushOptions,\n command: Command\n ) => {\n const message = requireMessage(options.message);\n const directory = NodePath.resolve(context.runtime.cwd, dir);\n const saved = await context.client(command).appArtifacts.saveSource({\n appArtifactId: id,\n files: await readAppSourceFolder(directory),\n message,\n expectedRevision: await readAppSourceRevision(directory),\n });\n await writeAppSourceRevision(directory, saved.revision);\n context\n .output(command)\n .data(\n { appArtifactId: id, revision: saved.revision },\n (value) =>\n `Saved the Working source at ${value.revision}. Publish it with merrai apps publish ${value.appArtifactId} -m <message>.`\n );\n }\n );\n\n apps\n .command(\"publish\")\n .description(\"Build the Working source into a new Version\")\n .argument(\"<id>\", \"App Artifact ID\")\n .option(\"--push <dir>\", \"First save this folder as the Working source\")\n .option(\"-m, --message <message>\", \"Describe the change\")\n .action(async (id: string, options: PublishOptions, command: Command) => {\n const message = requireMessage(options.message);\n const client = context.client(command);\n let expectedRevision: string | undefined;\n if (options.push !== undefined) {\n const directory = NodePath.resolve(context.runtime.cwd, options.push);\n const files = await readAppSourceFolder(directory);\n // A folder pulled or pushed before carries its revision, so a push\n // over someone else's newer change is refused instead of lost.\n const saved = await client.appArtifacts.saveSource({\n appArtifactId: id,\n files,\n message,\n expectedRevision: await readAppSourceRevision(directory),\n });\n await writeAppSourceRevision(directory, saved.revision);\n expectedRevision = saved.revision;\n }\n const published = await client.appArtifacts.publish({\n appArtifactId: id,\n message,\n publishKey: NodeCrypto.randomUUID(),\n expectedRevision,\n });\n context.output(command).data(published, renderPublished);\n });\n\n apps\n .command(\"delete\")\n .description(\n \"Delete an archived app forever: its data, Versions, source and sharing\"\n )\n .argument(\"<id>\", \"App Artifact ID\")\n .option(\n \"--confirm <name>\",\n \"The app's exact name, to delete without being asked\"\n )\n .action(async (id: string, options: DeleteOptions, command: Command) => {\n const client = context.client(command);\n let artifact: AppArtifact;\n try {\n artifact = await client.appArtifacts.get({ appArtifactId: id });\n } catch (error) {\n if (!isMerraiNotFoundError(error)) throw error;\n context\n .output(command)\n .data(await finishDeleted(client, id), renderAlreadyDeleted);\n return;\n }\n if (artifact.status !== \"archived\")\n throw new MerraiCliUsageError(\n `Archive this app before you delete it: ${artifact.name} is still active.`\n );\n const typed =\n options.confirm ??\n (await readTypedConfirmation({\n input: context.runtime.stdin,\n message: `This deletes ${artifact.name} forever, with everything it saved, its Versions, its source and who it was shared with. Your connected accounts stay connected. Type ${artifact.name} to confirm:`,\n output: context.runtime.stderr,\n }));\n if (typed === undefined)\n throw new MerraiCliUsageError(\n `Delete cancelled. Use --confirm \"${artifact.name}\" for noninteractive confirmation.`\n );\n if (typed !== artifact.name)\n throw new MerraiCliUsageError(\n `Delete cancelled: that is not this app's name (${artifact.name}).`\n );\n const deleted = await client.appArtifacts.delete({ appArtifactId: id });\n context.output(command).data(deleted, renderDeleted(artifact.name));\n });\n};\n","import * as NodeFS from \"node:fs\";\nimport * as NodeOS from \"node:os\";\nimport * as NodePath from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport type { MerraiClientOptions } from \"./client\";\n\nexport const DEFAULT_MERRAI_BASE_URL = \"https://api.merrai.app\";\nconst CREDENTIALS_VERSION = 1;\n\nexport type MerraiCliEnvironment = Readonly<Record<string, string | undefined>>;\n\nexport interface MerraiCliConnectionOverrides {\n apiKey?: string;\n baseURL?: string;\n cookie?: string;\n}\n\nexport interface MerraiCredentials {\n apiKey: string;\n baseURL?: string;\n savedAt: string;\n version: typeof CREDENTIALS_VERSION;\n}\n\nexport interface MerraiConfigPaths {\n credentials: string;\n directory: string;\n legacyClaudeCredentials: string;\n}\n\nconst trimmed = (value: string | undefined): string | undefined => {\n const result = value?.trim();\n return result === undefined || result.length === 0 ? undefined : result;\n};\n\nconst credentialsValueSchema = z.object({\n apiKey: z.string().trim().min(1),\n baseURL: z.string().trim().min(1).nullish(),\n savedAt: z.string().optional(),\n version: z.literal(CREDENTIALS_VERSION).optional(),\n});\n\nconst systemErrorSchema = z.object({ code: z.string() });\n\nconst resolveHomeDirectory = (env: MerraiCliEnvironment): string =>\n trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? NodeOS.homedir();\n\nexport const resolveMerraiConfigPaths = (\n env: MerraiCliEnvironment\n): MerraiConfigPaths => {\n const home = resolveHomeDirectory(env);\n const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);\n const windowsAppData = trimmed(env.APPDATA);\n const directory =\n xdgConfigHome !== undefined\n ? NodePath.join(xdgConfigHome, \"merrai\")\n : process.platform === \"win32\" && windowsAppData !== undefined\n ? NodePath.join(windowsAppData, \"Merrai\")\n : NodePath.join(home, \".config\", \"merrai\");\n\n return {\n credentials: NodePath.join(directory, \"credentials.json\"),\n directory,\n legacyClaudeCredentials: NodePath.join(\n home,\n \".merrai-claude-code\",\n \"credentials.json\"\n ),\n };\n};\n\nconst parseCredentials = (\n raw: string,\n options: { requireVersion: boolean }\n): MerraiCredentials | null => {\n try {\n const parsed = credentialsValueSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) {\n return null;\n }\n const value = parsed.data;\n\n if (options.requireVersion && value.version !== CREDENTIALS_VERSION) {\n return null;\n }\n\n const credentials: MerraiCredentials = {\n apiKey: value.apiKey,\n savedAt: value.savedAt ?? new Date(0).toISOString(),\n version: CREDENTIALS_VERSION,\n };\n if (value.baseURL !== undefined && value.baseURL !== null) {\n credentials.baseURL = value.baseURL;\n }\n return credentials;\n } catch {\n return null;\n }\n};\n\nconst readCredentialsFile = (\n file: string,\n options: { requireVersion: boolean; strict: boolean }\n): MerraiCredentials | null => {\n if (!NodeFS.existsSync(file)) {\n return null;\n }\n try {\n const credentials = parseCredentials(NodeFS.readFileSync(file, \"utf8\"), {\n requireVersion: options.requireVersion,\n });\n if (credentials === null && options.strict) {\n throw new Error(\n `Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`\n );\n }\n return credentials;\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n return null;\n }\n};\n\nexport const loadMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { strict?: boolean } = {}\n): MerraiCredentials | null => {\n const paths = resolveMerraiConfigPaths(env);\n return (\n readCredentialsFile(paths.credentials, {\n requireVersion: true,\n strict: options.strict === true,\n }) ??\n readCredentialsFile(paths.legacyClaudeCredentials, {\n requireVersion: false,\n strict: options.strict === true,\n })\n );\n};\n\nexport const saveMerraiCredentials = (\n env: MerraiCliEnvironment,\n input: { apiKey: string; baseURL?: string }\n): MerraiCredentials => {\n const apiKey = trimmed(input.apiKey);\n if (apiKey === undefined) {\n throw new Error(\"API key cannot be empty\");\n }\n\n const paths = resolveMerraiConfigPaths(env);\n NodeFS.mkdirSync(paths.directory, { mode: 0o700, recursive: true });\n NodeFS.chmodSync(paths.directory, 0o700);\n const credentials: MerraiCredentials = {\n apiKey,\n baseURL: trimmed(input.baseURL) ?? DEFAULT_MERRAI_BASE_URL,\n savedAt: new Date().toISOString(),\n version: CREDENTIALS_VERSION,\n };\n NodeFS.writeFileSync(\n paths.credentials,\n JSON.stringify(credentials, null, 2),\n {\n mode: 0o600,\n }\n );\n NodeFS.chmodSync(paths.credentials, 0o600);\n return credentials;\n};\n\nconst removeFileIfPresent = (file: string): boolean => {\n try {\n NodeFS.unlinkSync(file);\n return true;\n } catch (error) {\n const systemError = systemErrorSchema.safeParse(error);\n if (systemError.success && systemError.data.code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n};\n\nexport const clearMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { includeLegacy?: boolean } = {}\n): boolean => {\n const paths = resolveMerraiConfigPaths(env);\n const removedShared = removeFileIfPresent(paths.credentials);\n const removedLegacy =\n options.includeLegacy === true\n ? removeFileIfPresent(paths.legacyClaudeCredentials)\n : false;\n return removedShared || removedLegacy;\n};\n\nexport const resolveMerraiClientOptions = (\n env: MerraiCliEnvironment,\n overrides: MerraiCliConnectionOverrides,\n options: { strictCredentials?: boolean } = {}\n): MerraiClientOptions => {\n const apiKeyOverride =\n trimmed(overrides.apiKey) ?? trimmed(env.MERRAI_API_KEY);\n const baseURLOverride =\n trimmed(overrides.baseURL) ?? trimmed(env.MERRAI_BASE_URL);\n const credentials =\n apiKeyOverride !== undefined && baseURLOverride !== undefined\n ? null\n : loadMerraiCredentials(env, {\n strict: options.strictCredentials !== false,\n });\n return {\n apiKey: apiKeyOverride ?? credentials?.apiKey,\n baseURL: baseURLOverride ?? credentials?.baseURL ?? DEFAULT_MERRAI_BASE_URL,\n cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE),\n };\n};\n","import type { Command } from \"commander\";\n\nimport {\n clearMerraiCredentials,\n loadMerraiCredentials,\n resolveMerraiClientOptions,\n resolveMerraiConfigPaths,\n saveMerraiCredentials,\n} from \"../config\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport { confirmAction, readSecretInput } from \"../input\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { type NoCommandOptions } from \"./shared\";\n\ninterface GlobalOptions {\n apiKey?: string;\n baseUrl?: string;\n}\n\ninterface LogoutOptions {\n yes?: boolean;\n}\n\nexport const registerAuthCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const auth = program.command(\"auth\").description(\"Manage CLI credentials\");\n\n auth\n .command(\"set-key\")\n .argument(\"[apiKey]\", \"Merrai API key\")\n .description(\"Validate and save an API key\")\n .action(\n async (\n positional: string | undefined,\n _options: NoCommandOptions,\n actionCommand: Command\n ) => {\n const globals = actionCommand.optsWithGlobals<GlobalOptions>();\n const apiKey =\n [positional, globals.apiKey, context.runtime.env.MERRAI_API_KEY]\n .map((value) => value?.trim())\n .find(\n (value): value is string =>\n value !== undefined && value.length > 0\n ) ??\n (await readSecretInput({\n input: context.runtime.stdin,\n message: \"Merrai API key: \",\n output: context.runtime.stderr,\n }));\n if (apiKey.length === 0) {\n throw new MerraiCliUsageError(\"API key cannot be empty\");\n }\n const connection = resolveMerraiClientOptions(\n context.runtime.env,\n {\n apiKey,\n baseURL: globals.baseUrl,\n },\n { strictCredentials: false }\n );\n await context.runtime.createClient(connection).memoryStatus({});\n const credentials = saveMerraiCredentials(context.runtime.env, {\n apiKey,\n baseURL: connection.baseURL,\n });\n context\n .output(actionCommand)\n .data(\n { authenticated: true, baseURL: credentials.baseURL },\n () => `Saved API key for ${credentials.baseURL}.`\n );\n }\n );\n\n auth\n .command(\"status\")\n .description(\"Show credential status without revealing the key\")\n .action(async (_options: NoCommandOptions, actionCommand: Command) => {\n const credentials = loadMerraiCredentials(context.runtime.env, {\n strict: true,\n });\n const paths = resolveMerraiConfigPaths(context.runtime.env);\n const result = {\n authenticated:\n credentials !== null ||\n (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0,\n baseURL: credentials?.baseURL ?? null,\n configured: credentials !== null,\n credentialsPath: paths.credentials,\n environmentKeySet:\n (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0,\n };\n context\n .output(actionCommand)\n .data(result, () =>\n result.configured\n ? `Authenticated for ${result.baseURL}.`\n : result.environmentKeySet\n ? \"Authenticated through MERRAI_API_KEY.\"\n : \"No saved CLI credentials.\"\n );\n });\n\n auth\n .command(\"logout\")\n .description(\"Remove saved CLI credentials\")\n .option(\"--yes\", \"Skip confirmation\")\n .action(async (options: LogoutOptions, actionCommand: Command) => {\n if (options.yes !== true) {\n const confirmed = await confirmAction({\n input: context.runtime.stdin,\n message: \"Remove saved Merrai CLI credentials?\",\n output: context.runtime.stderr,\n });\n if (!confirmed) {\n throw new MerraiCliUsageError(\n \"Logout cancelled. Use --yes for noninteractive confirmation.\"\n );\n }\n }\n const removed = clearMerraiCredentials(context.runtime.env, {\n includeLegacy: true,\n });\n const output = context.output(actionCommand);\n output.data({ removed }, () =>\n removed ? \"Removed saved credentials.\" : \"No saved credentials found.\"\n );\n if ((context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0) {\n output.diagnostic(\n \"MERRAI_API_KEY is still set; commands will continue using it.\"\n );\n }\n });\n};\n","import type { Command } from \"commander\";\nimport { z } from \"zod\";\n\nimport { readStructuredInput } from \"../input\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { type StructuredInputOptions } from \"./shared\";\n\nconst configureRpcCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"<procedure>\", \"Top-level oRPC procedure\")\n .option(\"--input <json>\", \"Inline JSON input\")\n .option(\"--file <path>\", \"Read JSON input from a file, or - for stdin\")\n .action(\n async (\n procedureName: string,\n options: StructuredInputOptions,\n actionCommand: Command\n ) => {\n const procedure = context.debugProcedure(actionCommand, procedureName);\n const hasInput =\n options.input !== undefined || options.file !== undefined;\n const input = hasInput\n ? await readStructuredInput({\n cwd: context.runtime.cwd,\n file: options.file,\n input: options.input,\n stdin: context.runtime.stdin,\n })\n : undefined;\n const result = z.json().parse(await procedure(input));\n context.output(actionCommand).data(result);\n }\n );\n};\n\nexport const registerDebugCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const debug = program\n .command(\"debug\")\n .description(\"Unstable debugging commands\");\n configureRpcCommand(\n debug.command(\"rpc\").description(\"Call a top-level oRPC procedure\"),\n context\n );\n configureRpcCommand(\n program\n .command(\"rpc\", { hidden: true })\n .description(\"Legacy raw oRPC command\"),\n context\n );\n};\n","import type {\n EventTime,\n MemoryEventTime,\n MemoryReplacement,\n MemoryUpdateMark,\n} from \"./client\";\n\n// Mirrors the reader lines of Merrai's Search (packages/api search-render:\n// replacesText and memoryLinkLines) for a published client that does not\n// depend on the server packages.\n\n/**\n * Exhaustive at compile time; a precision this client does not know reads as\n * unknown rather than failing the output.\n */\nconst unsupportedPrecision = (_time: never): string => \"unknown\";\n\n/**\n * The calendar reading alone: \"2024-04-05\", \"week of 2024-04-01\",\n * \"2024-04-20 to 2024-04-21\".\n */\nconst calendarText = (time: EventTime): string => {\n switch (time.precision) {\n case \"week\":\n return `week of ${time.value}`;\n case \"day\":\n case \"month\":\n case \"year\":\n return time.value;\n case \"range\":\n return `${time.start} to ${time.end}`;\n case \"unknown\":\n return \"unknown\";\n default:\n return unsupportedPrecision(time);\n }\n};\n\n/** A plan's or deadline's role; null for what happened or an unstated role. */\nconst forwardRole = (time: EventTime): \"planned\" | \"due\" | null => {\n const role = time.precision === \"unknown\" ? null : time.role;\n return role === \"planned\" || role === \"due\" ? role : null;\n};\n\n/**\n * An event time as the server words it: a plan or a deadline names its role\n * (\"due 2024-04-20\"); what happened is the calendar reading alone.\n */\nexport const describeEventTime = (time: MemoryEventTime): string => {\n if (time.precision === \"multiple\")\n return time.alternatives.map(describeEventTime).join(\" or \");\n const role = forwardRole(time);\n return role === null ? calendarText(time) : `${role} ${calendarText(time)}`;\n};\n\n/** Whether any reading of the time is a plan or a deadline. */\nconst hasForwardRole = (time: MemoryEventTime): boolean =>\n (time.precision === \"multiple\" ? time.alternatives : [time]).some(\n (reading) => forwardRole(reading) !== null\n );\n\n/**\n * \"replaces: <earlier text> (due 2024-04-20)\": the line Merrai's Search and\n * recall evidence show under a Memory that replaced an earlier value (the\n * latest Memory it supersedes), so a terse update keeps its subject and the\n * old value. Null when it replaced none.\n */\nexport const renderMemoryReplacement = (\n replaced: MemoryReplacement | null | undefined\n): string | null => {\n if (replaced === null || replaced === undefined) return null;\n const time =\n replaced.eventTime === null || replaced.eventTime.precision === \"unknown\"\n ? null\n : describeEventTime(replaced.eventTime);\n return time === null\n ? `replaces: ${replaced.content}`\n : `replaces: ${replaced.content} (${time})`;\n};\n\nconst UPDATE_MARK_LABELS = {\n updated_by: \"↳ updated by\",\n updates: \"replaces\",\n} as const satisfies Record<MemoryUpdateMark[\"relation\"], string>;\n\n/**\n * A linked memory as a mark names it: by its id when the reader is shown it\n * too, otherwise its text with when it happened or is planned or due and the\n * day it was said: \"Budget is now $4,000. (said 2024-03-16)\".\n */\nconst linkedMemoryText = (\n mark: MemoryUpdateMark,\n shownIds: ReadonlySet<string>\n): string => {\n if (shownIds.has(mark.id)) return mark.id;\n const time = mark.eventTime;\n const notes = [\n time === null || time.precision === \"unknown\"\n ? null\n : hasForwardRole(time)\n ? describeEventTime(time)\n : `happened ${describeEventTime(time)}`,\n mark.said === null ? null : `said ${mark.said}`,\n ].filter((note) => note !== null);\n return notes.length === 0\n ? mark.content\n : `${mark.content} (${notes.join(\"; \")})`;\n};\n\n/**\n * \"↳ updated by: …\" and \"replaces: …\": the update marks Merrai's Search shows\n * under a memory, newer values first, one line per relation. A later value\n * never retires the earlier one; both stay current. A relation this client\n * does not know is left out rather than failing the output.\n */\nexport const renderMemoryUpdateMarks = (\n marks: readonly MemoryUpdateMark[] | undefined,\n shownIds: ReadonlySet<string>\n): string[] =>\n ([\"updated_by\", \"updates\"] as const).flatMap((relation) => {\n const members = (marks ?? []).filter((mark) => mark.relation === relation);\n return members.length === 0\n ? []\n : [\n `${UPDATE_MARK_LABELS[relation]}: ${members\n .map((mark) => linkedMemoryText(mark, shownIds))\n .join(\"; \")}`,\n ];\n });\n\n/**\n * Each search result's lines as Merrai's Search shows them: its own line\n * (`renderLine`), labelled with its id when another result's mark names it,\n * then what it replaced and its update marks.\n */\nexport const searchResultLines = <\n Result extends {\n id: string;\n linked?: readonly MemoryUpdateMark[];\n replaces?: MemoryReplacement | null;\n },\n>(\n results: readonly Result[],\n renderLine: (result: Result) => string\n): string[][] => {\n const shownIds = new Set(results.map((result) => result.id));\n const named = new Set(\n results.flatMap((result) =>\n (result.linked ?? []).flatMap((mark) =>\n shownIds.has(mark.id) ? [mark.id] : []\n )\n )\n );\n return results.map((result) => {\n const line = renderLine(result);\n const replaced = renderMemoryReplacement(result.replaces);\n return [\n named.has(result.id) ? `${line} [${result.id}]` : line,\n ...(replaced === null ? [] : [replaced]),\n ...renderMemoryUpdateMarks(result.linked, shownIds),\n ];\n });\n};\n","import type { Command } from \"commander\";\n\nimport type {\n FindMemoryEntitiesOutput,\n SearchMemoriesRecallOutput,\n} from \"../client\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport { searchResultLines } from \"../memory-replacement\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { parseEntityType, parseIntegerOption } from \"./shared\";\n\n/** `entity memories` keeps its earlier default of 20 within the shared maximum of 25. */\nconst ENTITY_MEMORIES_DEFAULT_LIMIT = 20;\n\ninterface FindEntityOptions {\n limit?: string;\n name?: string;\n type?: string;\n}\n\ninterface EntityMemoriesOptions {\n entityId?: string;\n limit?: string;\n}\n\nconst renderEntities = (result: FindMemoryEntitiesOutput): string => {\n if (result.entities.length === 0) {\n return \"No matching entities found.\";\n }\n return result.entities\n .map(\n (entity) =>\n `- ${entity.displayName} (${entity.type}, ${entity.memoryCount} memories, ${entity.id})`\n )\n .join(\"\\n\");\n};\n\n/**\n * \"# Ada (person)\", then each linked memory as `memory search` shows it:\n * its line, then what it replaced and its update marks beneath it.\n */\nconst renderEntityMemories = (result: SearchMemoriesRecallOutput): string => {\n const [entity] = result.matchedEntities;\n const heading =\n entity === undefined\n ? \"# Entity\"\n : `# ${entity.displayName} (${entity.type})`;\n if (result.memories.length === 0) {\n return `${heading}\\nNo linked memories.`;\n }\n return [\n heading,\n ...searchResultLines(\n result.memories,\n (memory) =>\n `- ${memory.recordedAt?.slice(0, 10) ?? \"undated\"}: ${memory.content}`\n ).map((lines) => lines.join(\"\\n \")),\n ].join(\"\\n\");\n};\n\nconst configureFindCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"[name]\", \"Entity name\")\n .option(\"--name <name>\", \"Entity name\")\n .option(\"--type <type>\", \"person, event, action, knowledge, or document\")\n .option(\"--limit <number>\", \"Maximum results\")\n .action(\n async (\n positional: string | undefined,\n options: FindEntityOptions,\n actionCommand: Command\n ) => {\n const name = options.name ?? positional;\n if (name === undefined || name.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide an entity name\");\n }\n const input = {\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 25,\n minimum: 1,\n }),\n name,\n type: parseEntityType(options.type),\n };\n const result = await context\n .client(actionCommand)\n .findMemoryEntities(input);\n context.output(actionCommand).data(result, renderEntities);\n }\n );\n};\n\nconst configureMemoriesCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"[entityId]\", \"Entity id\")\n .option(\"--entity-id <id>\", \"Entity id\")\n .option(\"--limit <number>\", \"Maximum results, 1-25 (default 20)\")\n .action(\n async (\n positional: string | undefined,\n options: EntityMemoriesOptions,\n actionCommand: Command\n ) => {\n const entityId = options.entityId ?? positional;\n if (entityId === undefined || entityId.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide an entity id\");\n }\n const input = {\n entityId,\n limit:\n parseIntegerOption(options.limit, \"--limit\", {\n maximum: 25,\n minimum: 1,\n }) ?? ENTITY_MEMORIES_DEFAULT_LIMIT,\n };\n // MCP search_memories with an entity alone: no model call, the\n // entity's current memories newest recorded first, with update marks.\n const result = await context\n .client(actionCommand)\n .recall.searchMemories(input);\n context.output(actionCommand).data(result, renderEntityMemories);\n }\n );\n};\n\nexport const registerEntityCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const entity = program.command(\"entity\").description(\"Find memory entities\");\n configureFindCommand(\n entity.command(\"find\").description(\"Find entities by name\"),\n context\n );\n configureFindCommand(\n program\n .command(\"find-entity\", { hidden: true })\n .description(\"Legacy entity find\"),\n context\n );\n configureMemoriesCommand(\n entity\n .command(\"memories\")\n .description(\"Recall memories linked to an entity\"),\n context\n );\n configureMemoriesCommand(\n program\n .command(\"search-memories-by-entity\", { hidden: true })\n .description(\"Legacy entity recall\"),\n context\n );\n};\n","import * as NodeCrypto from \"node:crypto\";\n\n/** Accepted by every write API's `idempotencyKey`, including `addChatSessions`. */\nconst IDEMPOTENCY_KEY_HEX_LENGTH = 48;\n\n/** JSON-shaped request content; `undefined` object fields are omitted. */\nexport type IdempotencyKeyMaterial =\n | boolean\n | number\n | string\n | null\n | undefined\n | readonly IdempotencyKeyMaterial[]\n | { readonly [key: string]: IdempotencyKeyMaterial };\n\ntype IdempotencyKeyRecord = {\n readonly [key: string]: IdempotencyKeyMaterial;\n};\n\nconst isKeyMaterialRecord = (\n value: IdempotencyKeyMaterial\n): value is IdempotencyKeyRecord =>\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.toString.call(value) === \"[object Object]\";\n\n// Sorted keys, so the same content always serializes to the same bytes.\nconst canonicalJson = (value: IdempotencyKeyMaterial): string => {\n if (value === undefined) {\n return \"null\";\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n if (isKeyMaterialRecord(value)) {\n return `{${Object.entries(value)\n .filter(([, entry]) => entry !== undefined)\n .toSorted(([left], [right]) => (left < right ? -1 : 1))\n .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n};\n\n/**\n * A stable idempotency key derived from what one write sends, so a rerun joins\n * the existing ingestion; any change to content, source, lobe or dates changes\n * it. `operation` namespaces keys by API shape. Undefined fields are omitted,\n * so an absent option and an explicit `undefined` produce the same key.\n */\nexport const deriveIdempotencyKey = (\n operation: string,\n payload: { readonly [key: string]: IdempotencyKeyMaterial }\n): string =>\n NodeCrypto.createHash(\"sha256\")\n .update(canonicalJson({ operation, payload, version: 1 }))\n .digest(\"hex\")\n .slice(0, IDEMPOTENCY_KEY_HEX_LENGTH);\n\n/**\n * The key for saving one memory (CLI `memory add`, the plugin's\n * `/merrai:save`). Without a supplied observation time, the same sentence\n * saved on a later day is a new occurrence (\"went running\"), not a retry, so\n * the UTC day joins the key; same-day reruns still collapse into one save.\n */\nexport const deriveMemorySaveIdempotencyKey = (input: {\n lobeKey?: string;\n memory: string;\n now: Date;\n observationDate?: string;\n source?: string;\n}): string =>\n deriveIdempotencyKey(\"memory-save\", {\n lobeKey: input.lobeKey,\n memory: input.memory,\n observationDate: input.observationDate,\n occurrenceDay:\n input.observationDate === undefined\n ? input.now.toISOString().slice(0, 10)\n : undefined,\n source: input.source,\n });\n","import type { Command } from \"commander\";\nimport { z } from \"zod\";\n\nimport type {\n AddChatSessionInput,\n AddChatSessionsInput,\n AddMemoriesInput,\n JsonValue,\n} from \"../client\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport { deriveIdempotencyKey } from \"../idempotency\";\nimport { readStructuredInput } from \"../input\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { describeQueuedIngestion, type StructuredInputOptions } from \"./shared\";\n\nconst memoryInputSchema = z.object({\n lobeKey: z.string().optional(),\n memory: z.string(),\n observationDate: z.string().optional(),\n source: z.string().optional(),\n});\n\nconst chatMemoryInputSchema = z.object({\n memory: z.string(),\n observationDate: z.iso.datetime().optional(),\n source: z.string().optional(),\n});\n\nconst addMemoriesInputSchema = z.object({\n memories: z.array(memoryInputSchema),\n});\n\nconst addChatSessionInputSchema = z.object({\n idempotencyKey: z.string().optional(),\n lobeKey: z.string().optional(),\n memories: z.array(chatMemoryInputSchema),\n sessionMetadata: z.record(z.string(), z.json()).optional(),\n source: z.string().optional(),\n});\n\nconst addChatSessionsInputSchema = z.object({\n idempotencyKey: z.string().optional(),\n lobeKey: z.string().optional(),\n questionMetadata: z.record(z.string(), z.json()).optional(),\n sessions: z.array(\n z.object({\n metadata: z.record(z.string(), z.json()).optional(),\n sessionId: z.string(),\n turns: z.array(\n z.object({\n content: z.string(),\n role: z.enum([\"user\", \"assistant\"]),\n sourceTime: z.string().optional(),\n speaker: z.string().optional(),\n turnIndex: z.number(),\n })\n ),\n })\n ),\n source: z.string().optional(),\n});\n\nconst parseUsageInput = <Output>(\n schema: z.ZodType<Output>,\n value: JsonValue,\n message: string\n): Output => {\n const result = schema.safeParse(value);\n if (!result.success) {\n throw new MerraiCliUsageError(message, { cause: result.error });\n }\n return result.data;\n};\n\n// Without a caller key, the key is derived from the parsed payload (content,\n// sources, lobes, supplied times), so re-running the same import joins the\n// first ingestion instead of storing everything twice. Callers that need a\n// different identity (for example, a deliberate re-import) pass their own key.\n\nconst parseMemoriesInput = (value: JsonValue): AddMemoriesInput => {\n if (!Array.isArray(value)) {\n throw new MerraiCliUsageError(\"Memory ingest input must be a JSON array\");\n }\n const input = parseUsageInput(\n addMemoriesInputSchema,\n { memories: value },\n \"Memory ingest input does not match the expected schema\"\n );\n return {\n idempotencyKey: deriveIdempotencyKey(\"ingest-memories\", input),\n ...input,\n };\n};\n\nconst parseChatInput = (value: JsonValue): AddChatSessionInput => {\n const { idempotencyKey, ...input } = parseUsageInput(\n addChatSessionInputSchema,\n value,\n \"Chat ingest input does not match the expected schema\"\n );\n return {\n ...input,\n idempotencyKey:\n idempotencyKey ?? deriveIdempotencyKey(\"ingest-chat\", input),\n };\n};\n\nconst parseChatsInput = (value: JsonValue): AddChatSessionsInput => {\n const { idempotencyKey, ...input } = parseUsageInput(\n addChatSessionsInputSchema,\n value,\n \"Multi-chat ingest input does not match the expected schema\"\n );\n return {\n ...input,\n idempotencyKey:\n idempotencyKey ?? deriveIdempotencyKey(\"ingest-chats\", input),\n };\n};\n\nconst configureStructuredCommand = <\n Input,\n Output extends { ingestionId: string },\n>(\n command: Command,\n context: MerraiCommandContext,\n parse: (value: JsonValue) => Input,\n submit: (command: Command, input: Input) => Promise<Output>\n): void => {\n command\n .option(\"--input <json>\", \"Inline JSON input\")\n .option(\"--file <path>\", \"Read JSON from a file, or - for stdin\")\n .action(async (options: StructuredInputOptions, actionCommand: Command) => {\n const value = await readStructuredInput({\n cwd: context.runtime.cwd,\n file: options.file,\n input: options.input,\n stdin: context.runtime.stdin,\n });\n const result = await submit(actionCommand, parse(value));\n context\n .output(actionCommand)\n .data(result, (value) =>\n describeQueuedIngestion(\"Ingest\", value.ingestionId)\n );\n });\n};\n\nexport const registerIngestCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const ingest = program.command(\"ingest\").description(\"Bulk memory ingestion\");\n\n const registerMemories = (command: Command): void =>\n configureStructuredCommand(\n command,\n context,\n parseMemoriesInput,\n async (actionCommand, input) =>\n context.client(actionCommand).addMemories(input)\n );\n registerMemories(ingest.command(\"memories\").description(\"Ingest memories\"));\n registerMemories(\n program\n .command(\"add-memories\", { hidden: true })\n .description(\"Legacy memory ingest\")\n );\n\n const registerChat = (command: Command): void =>\n configureStructuredCommand(\n command,\n context,\n parseChatInput,\n async (actionCommand, input) =>\n context.client(actionCommand).addChatSession(input)\n );\n registerChat(ingest.command(\"chat\").description(\"Ingest one chat session\"));\n registerChat(\n program\n .command(\"add-chat-session\", { hidden: true })\n .description(\"Legacy chat ingest\")\n );\n\n const registerChats = (command: Command): void =>\n configureStructuredCommand(\n command,\n context,\n parseChatsInput,\n async (actionCommand, input) =>\n context.client(actionCommand).addChatSessions(input)\n );\n registerChats(\n ingest.command(\"chats\").description(\"Ingest multiple chat sessions\")\n );\n registerChats(\n program\n .command(\"add-chat-sessions\", { hidden: true })\n .description(\"Legacy multi-chat ingest\")\n );\n};\n","import type { Command } from \"commander\";\n\nimport type { IngestionStatusOutput } from \"../client\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { describeQueuedIngestion, type NoCommandOptions } from \"./shared\";\n\nconst renderIngestionStatus = (status: IngestionStatusOutput): string => {\n const lines = [\n `Ingestion ${status.ingestionId}: ${status.status} (attempt ${status.attempt})`,\n ];\n if (status.pausedReason === \"quota_exceeded\") {\n lines.push(\"Waiting for memory quota; it resumes automatically.\");\n }\n if (status.error !== null) {\n lines.push(`Error: ${status.error}`);\n }\n const result = status.result;\n if (result !== null) {\n lines.push(`Sources: ${result.artifacts.length}`);\n lines.push(`Extraction: ${result.observation.status}`);\n if ((result.observation.blockedWindows ?? 0) > 0) {\n lines.push(\n `Blocked windows: ${result.observation.blockedWindows ?? 0} (${result.observation.retryableBlockedWindows ?? 0} retryable with \\`merrai ingestion retry\\`)`\n );\n }\n lines.push(\n result.memory.status === \"completed\" ||\n (result.memory.status === \"deferred\" &&\n result.memory.reason === \"repair_scheduled\")\n ? `Memories: ${result.memory.created} created, ${result.memory.updated} updated, ${result.memory.reinforced} reinforced`\n : `Memories: ${result.memory.status} (${result.memory.reason})`\n );\n }\n return lines.join(\"\\n\");\n};\n\nexport const registerIngestionCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const ingestion = program\n .command(\"ingestion\")\n .description(\"Follow and retry the processing of saved content\");\n\n ingestion\n .command(\"status\")\n .description(\"Show an ingestion's progress and result\")\n .argument(\"<id>\", \"Ingestion ID returned by a save or retry\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .ingestionStatus({ ingestionId: id });\n context.output(command).data(result, renderIngestionStatus);\n }\n );\n\n ingestion\n .command(\"retry\")\n .description(\n \"Extract again the windows a finished ingestion could not extract\"\n )\n .argument(\"<id>\", \"Ingestion ID of a finished partial ingestion\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .retryIngestionBlockedWindows({ ingestionId: id });\n context\n .output(command)\n .data(result, (value) =>\n describeQueuedIngestion(\"Retry\", value.ingestionId)\n );\n }\n );\n};\n","import type { Command } from \"commander\";\n\nimport type {\n ListLivingDocumentsRecallOutput,\n LivingDocument,\n LivingDocumentLobeScope,\n} from \"../client\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { parseIntegerOption } from \"./shared\";\n\ninterface DocumentGetOptions {\n contentOffset?: string;\n documentId?: string;\n maxCharacters?: string;\n}\n\ninterface DocumentListOptions {\n limit?: string;\n offset?: string;\n}\n\nconst renderLobeScope = (scope: LivingDocumentLobeScope | undefined): string =>\n scope?.kind === \"selected\" ? ` (lobes: ${scope.lobeKeys.join(\", \")})` : \"\";\n\nconst renderDocumentList = (value: ListLivingDocumentsRecallOutput): string => {\n if (value.documents.length === 0) {\n return \"No living documents found.\";\n }\n return value.documents\n .map(\n (document) =>\n `- ${document.title} (${document.id})${renderLobeScope(document.lobeScope)}`\n )\n .join(\"\\n\");\n};\n\nconst renderRetriedRebuild = (document: LivingDocument): string => {\n if (document.rebuild === null) {\n return `${document.title} is up to date.`;\n }\n return document.rebuild.reason === \"lobe_scope_narrowed\"\n ? `${document.title} is being updated to remove memories from lobes it no longer uses.`\n : `${document.title} is being updated to remove deleted sources.`;\n};\n\nconst renderRetriedBackfill = (document: LivingDocument): string => {\n const backfill = document.lobeBackfill;\n if (backfill === undefined || backfill === null) {\n return `${document.title} is up to date.`;\n }\n return `${document.title} is adding the memories already saved in ${backfill.lobeKeys.join(\", \")}.`;\n};\n\nconst configureGetCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"[documentId]\", \"Living document id\")\n .option(\"--document-id <id>\", \"Living document id\")\n .option(\n \"--content-offset <number>\",\n \"Character offset into document content\"\n )\n .option(\n \"--max-characters <number>\",\n \"Maximum document content characters to return\"\n )\n .action(\n async (\n positional: string | undefined,\n options: DocumentGetOptions,\n actionCommand: Command\n ) => {\n const documentId = options.documentId ?? positional;\n if (documentId === undefined || documentId.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide a living document id\");\n }\n const result = await context\n .client(actionCommand)\n .recall.readLivingDocument({\n contentOffset: parseIntegerOption(\n options.contentOffset,\n \"--content-offset\",\n { maximum: 10_000_000, minimum: 0 }\n ),\n documentId,\n maxCharacters: parseIntegerOption(\n options.maxCharacters,\n \"--max-characters\",\n { maximum: 20_000, minimum: 1 }\n ),\n });\n context\n .output(actionCommand)\n .data(result, (value) => JSON.stringify(value, null, 2));\n }\n );\n};\n\nexport const registerLivingDocumentCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const document = program\n .command(\"document\")\n .description(\"Read living documents\");\n const listAction = async (\n options: DocumentListOptions,\n command: Command\n ): Promise<void> => {\n const result = await context.client(command).recall.listLivingDocuments({\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 50,\n minimum: 1,\n }),\n offset: parseIntegerOption(options.offset, \"--offset\", {\n maximum: 100_000,\n minimum: 0,\n }),\n });\n context.output(command).data(result, renderDocumentList);\n };\n\n document\n .command(\"list\")\n .description(\"List living documents\")\n .option(\"--limit <number>\", \"Maximum documents to return\")\n .option(\"--offset <number>\", \"Zero-based document offset\")\n .action(async (options: DocumentListOptions, command: Command) =>\n listAction(options, command)\n );\n program\n .command(\"list-living-documents\", { hidden: true })\n .description(\"Legacy living document list\")\n .option(\"--limit <number>\", \"Maximum documents to return\")\n .option(\"--offset <number>\", \"Zero-based document offset\")\n .action(async (options: DocumentListOptions, command: Command) =>\n listAction(options, command)\n );\n\n configureGetCommand(\n document\n .command(\"get\")\n .description(\"Read a bounded living document content chunk\"),\n context\n );\n document\n .command(\"retry-rebuild\")\n .description(\n \"Retry a living document update (removing deleted sources or removed lobes) that failed\"\n )\n .argument(\"<documentId>\", \"Living document id\")\n .action(\n async (\n documentId: string,\n _options: Record<string, never>,\n command: Command\n ) => {\n const result = await context\n .client(command)\n .retryLivingDocumentRebuild({ id: documentId });\n context\n .output(command)\n .data(result, ({ document: updated }) =>\n renderRetriedRebuild(updated)\n );\n }\n );\n document\n .command(\"retry-backfill\")\n .description(\n \"Retry adding the memories already saved in lobes added to a living document, when that failed\"\n )\n .argument(\"<documentId>\", \"Living document id\")\n .action(\n async (\n documentId: string,\n _options: Record<string, never>,\n command: Command\n ) => {\n const result = await context\n .client(command)\n .retryLivingDocumentLobeBackfill({ id: documentId });\n context\n .output(command)\n .data(result, ({ document: updated }) =>\n renderRetriedBackfill(updated)\n );\n }\n );\n configureGetCommand(\n program\n .command(\"read-living-document\", { hidden: true })\n .description(\"Legacy living document read\"),\n context\n );\n};\n","import type { Command } from \"commander\";\nimport { z } from \"zod\";\n\nimport type {\n LobePageItem,\n LobesCursor,\n ListLobesPageOutput,\n UpdateLobeInput,\n} from \"../client\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport {\n parseCursorJson,\n parseIntegerOption,\n renderMoreCursor,\n type NoCommandOptions,\n} from \"./shared\";\n\ninterface ListLobesOptions {\n cursor?: string;\n limit?: string;\n}\n\nconst lobesCursorSchema = z.object({\n createdAt: z.string().min(1),\n lobeKey: z.string().min(1),\n}) satisfies z.ZodType<LobesCursor>;\n\ninterface UpdateLobeOptions {\n clearPurpose?: boolean;\n ownerRecall?: string;\n purpose?: string;\n}\n\nconst parseOwnerRecall = (value: string | undefined): boolean | undefined => {\n if (value === undefined) return undefined;\n if (value === \"on\") return true;\n if (value === \"off\") return false;\n throw new MerraiCliUsageError(\"--owner-recall must be on or off\");\n};\n\nconst describeLobe = (lobe: LobePageItem): string =>\n [\n `- ${lobe.name} (${lobe.lobeKey})`,\n lobe.ownerRecall ? \"\" : \" (kept out of owner recall)\",\n lobe.purpose === null ? \"\" : `: ${lobe.purpose}`,\n ].join(\"\");\n\nexport const registerLobeCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const lobe = program\n .command(\"lobe\")\n .description(\"Create, list and configure memory lobes\");\n\n lobe\n .command(\"create\")\n .description(\"Create a memory lobe\")\n .argument(\"<key>\", \"Lobe key\")\n .action(\n async (key: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .createLobe({ lobeKey: key });\n context\n .output(command)\n .data(result, (value) => `Created lobe ${value.lobeKey}.`);\n }\n );\n\n lobe\n .command(\"list\")\n .description(\"List memory lobes, oldest first, a page at a time\")\n .option(\"--limit <count>\", \"Lobes per page, from 1 to 50\")\n .option(\"--cursor <json>\", \"Continue from a previous page's nextCursor\")\n .action(async (options: ListLobesOptions, command: Command) => {\n const result = await context.client(command).listLobesPage({\n cursor: parseCursorJson(\n lobesCursorSchema,\n options.cursor,\n '{\"createdAt\":\"…\",\"lobeKey\":\"…\"}'\n ),\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 50,\n minimum: 1,\n }),\n });\n context\n .output(command)\n .data(result, (page: ListLobesPageOutput) =>\n [\n ...(page.lobes.length === 0 ? [\"No lobes found.\"] : []),\n ...page.lobes.map(describeLobe),\n ...renderMoreCursor(page.nextCursor),\n ].join(\"\\n\")\n );\n });\n\n lobe\n .command(\"update\")\n .description(\"Set a lobe's purpose or whether the owner's agent reads it\")\n .argument(\"<key>\", \"Lobe key\")\n .option(\"--purpose <text>\", \"What this lobe is for\")\n .option(\"--clear-purpose\", \"Remove the lobe's purpose\")\n .option(\"--owner-recall <on|off>\", \"Whether the owner's agent reads it\")\n .action(\n async (key: string, options: UpdateLobeOptions, command: Command) => {\n if (options.purpose !== undefined && options.clearPurpose === true)\n throw new MerraiCliUsageError(\n \"Use --purpose or --clear-purpose, not both\"\n );\n const input: UpdateLobeInput = { lobeKey: key };\n const ownerRecall = parseOwnerRecall(options.ownerRecall);\n if (ownerRecall !== undefined) input.ownerRecall = ownerRecall;\n if (options.purpose !== undefined) input.purpose = options.purpose;\n if (options.clearPurpose === true) input.purpose = null;\n if (input.ownerRecall === undefined && input.purpose === undefined)\n throw new MerraiCliUsageError(\n \"Give --purpose, --clear-purpose or --owner-recall\"\n );\n const result = await context.client(command).updateLobe(input);\n context.output(command).data(result, describeLobe);\n }\n );\n};\n","import type { Command } from \"commander\";\nimport { z } from \"zod\";\n\nimport type {\n ClearLobeOutput,\n GetStyleProfileOutput,\n JudgmentsCursor,\n ListJudgmentsOutput,\n ListOpenItemsOutput,\n MemoriesCursor,\n MemoriesOutput,\n MemoryAbout,\n MemoryBackfillStatusOutput,\n MemoryOverviewOutput,\n MemoryReplacement,\n MemoryStance,\n MemoryStatusOutput,\n MemorySynthesisStatusOutput,\n MemoryUpdateMark,\n OpenItemsCursor,\n SearchMemoriesRecallOutput,\n} from \"../client\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport { deriveMemorySaveIdempotencyKey } from \"../idempotency\";\nimport { confirmAction, readTextInput } from \"../input\";\nimport { searchResultLines } from \"../memory-replacement\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport {\n collectOption,\n describeQueuedIngestion,\n localDay,\n parseDateOption,\n parseDayOption,\n parseCursorJson,\n parseIntegerOption,\n renderMoreCursor,\n resolveLobeKey,\n} from \"./shared\";\n\ninterface AddMemoryOptions {\n file?: string;\n lobe?: string;\n lobeKey?: string;\n memory?: string;\n observationDate?: string;\n source?: string;\n}\n\ninterface SearchOptions {\n about?: string;\n limit?: string;\n lobe?: string;\n query?: string;\n stance: string[];\n topic: string[];\n}\n\ninterface OpenItemsOptions {\n asOf?: string;\n cursor?: string;\n limit?: string;\n lobe?: string;\n until?: string;\n}\n\ninterface JudgmentsOptions {\n cursor?: string;\n evidenceChanged?: boolean;\n limit?: string;\n lobe?: string;\n stance?: string;\n}\n\ninterface DateOptions {\n end?: string;\n limit?: string;\n start?: string;\n}\n\ninterface LobeOptions {\n lobe?: string;\n lobeKey?: string;\n}\n\ninterface ListOptions extends LobeOptions {\n cursor?: string;\n limit?: string;\n}\n\ninterface ClearOptions extends LobeOptions {\n wait?: boolean;\n yes?: boolean;\n}\n\n/** How often and for how long `memory clear` follows a clear it started. */\nconst CLEAR_POLL_INTERVAL_MS = 1000;\nconst CLEAR_WAIT_LIMIT_MS = 10 * 60 * 1000;\n\nconst defaultSleep = async (milliseconds: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n\nconst renderClearStatus = (status: ClearLobeOutput): string => {\n const counts = `${status.deleted} memories and ${status.deletedSources} sources deleted`;\n switch (status.status) {\n case \"complete\":\n return `Cleared lobe ${status.lobeKey}: ${counts}.`;\n case \"running\":\n return `Clearing lobe ${status.lobeKey} continues in the background (${counts}, ${status.remainingSources} sources left). Follow it with: merrai memory clear-status ${status.clearId}`;\n case \"failed\":\n return `Clearing lobe ${status.lobeKey} stopped (${counts}, ${status.remainingSources} sources left). Run the clear again to finish it.`;\n default:\n return status.status satisfies never;\n }\n};\n\n/**\n * Follows a clear until it leaves `running` or the wait limit passes,\n * reporting progress on stderr whenever it changes.\n */\nconst followClear = async (\n context: MerraiCommandContext,\n command: Command,\n started: ClearLobeOutput\n): Promise<ClearLobeOutput> => {\n const sleep = context.runtime.sleep ?? defaultSleep;\n const client = context.client(command);\n const output = context.output(command);\n let status = started;\n let lastProgress = \"\";\n for (\n let waited = 0;\n status.status === \"running\" && waited < CLEAR_WAIT_LIMIT_MS;\n waited += CLEAR_POLL_INTERVAL_MS\n ) {\n const progress = `Clearing lobe ${status.lobeKey}: ${status.deletedSources} sources and ${status.deleted} memories deleted, ${status.remainingSources} sources left.`;\n if (progress !== lastProgress) {\n output.diagnostic(progress);\n lastProgress = progress;\n }\n // Status polls are sequential by design.\n await sleep(CLEAR_POLL_INTERVAL_MS);\n // Status polls are sequential by design.\n status = await client.clearLobeStatus({ clearId: status.clearId });\n }\n return status;\n};\n\n/** A clear that stopped is a server-side failure: report it and exit non-zero. */\nconst finishClear = (\n context: MerraiCommandContext,\n command: Command,\n status: ClearLobeOutput\n): void => {\n context.output(command).data(status, renderClearStatus);\n if (status.status === \"failed\") {\n throw new Error(renderClearStatus(status));\n }\n};\n\ninterface RecalledMemoryLine {\n category: string | null;\n content: string;\n id: string;\n /** A guess from what the user asked, rendered as \"(inferred)\". */\n inferred?: boolean;\n /** Update marks, rendered under it as Search shows them. */\n linked?: readonly MemoryUpdateMark[];\n /** Null when no source time is known; rendered as \"undated\". */\n recordedAt: string | null;\n /** What it replaced, rendered on the next line. */\n replaces?: MemoryReplacement | null;\n}\n\nconst renderRecordedDate = (recordedAt: string | null): string =>\n recordedAt === null ? \"undated\" : recordedAt.slice(0, 10);\n\n/**\n * \"- [category] 2026-07-17: text\", \"(inferred)\" after a guess, then what it\n * replaced and its update marks (\"↳ updated by: …\", \"replaces: …\") indented under it.\n */\nconst renderMemoryLines = (\n memories: readonly RecalledMemoryLine[],\n emptyText = \"No memories found.\"\n): string => {\n if (memories.length === 0) {\n return emptyText;\n }\n return searchResultLines(memories, (memory) => {\n const category = memory.category === null ? \"\" : `[${memory.category}] `;\n const inferred = memory.inferred === true ? \" (inferred)\" : \"\";\n return `- ${category}${renderRecordedDate(memory.recordedAt)}: ${memory.content}${inferred}`;\n })\n .map((lines) => lines.join(\"\\n \"))\n .join(\"\\n\");\n};\n\ninterface ProfileMemoryLine {\n content: string;\n}\n\nconst renderProfileMemorySection = <Memory extends ProfileMemoryLine>(\n title: string,\n memories: Memory[],\n renderMemory: (memory: Memory) => string\n): string[] =>\n memories.length === 0\n ? []\n : [`${title}:`, ...memories.map((memory) => `- ${renderMemory(memory)}`)];\n\nconst renderProfileDetails = (\n profile: NonNullable<MemoryOverviewOutput[\"profile\"]>\n): string[] => [\n `Scope: ${profile.scope}`,\n ...renderProfileMemorySection(\n \"Facts\",\n profile.facts,\n (memory) => memory.content\n ),\n ...renderProfileMemorySection(\n \"Ongoing context\",\n profile.ongoingContext,\n (memory) => memory.content\n ),\n ...renderProfileMemorySection(\n \"Dynamic context\",\n profile.dynamicContext,\n (memory) => `${memory.content} (expires ${memory.profileExpiresAt})`\n ),\n];\n\nconst renderProfileRefresh = (\n refresh: MemoryOverviewOutput[\"refresh\"]\n): string | null => {\n if (refresh.status === \"queued\") {\n return `Profile refresh queued (${refresh.candidateMemoryCount} pending).`;\n }\n if (refresh.status === \"failed\") {\n return \"Profile refresh could not be scheduled; retry shortly.\";\n }\n return null;\n};\n\nconst renderProfile = (overview: MemoryOverviewOutput): string => {\n const lines = [`# ${overview.account.name}`];\n if (overview.account.primaryRole !== null) {\n lines.push(`Role: ${overview.account.primaryRole}`);\n }\n if (overview.account.workplace !== null) {\n lines.push(`Workplace: ${overview.account.workplace}`);\n }\n if (overview.profile !== null) {\n lines.push(...renderProfileDetails(overview.profile));\n }\n const refreshLine = renderProfileRefresh(overview.refresh);\n if (refreshLine !== null) {\n lines.push(refreshLine);\n }\n return lines.join(\"\\n\");\n};\n\nconst renderUndatedExclusion = (count: number): string[] =>\n count === 0\n ? []\n : [\n `${count} undated ${count === 1 ? \"memory was\" : \"memories were\"} excluded by the date range.`,\n ];\n\n/** A search_memories reply: its memories, then any undated ones a date range excluded. */\nconst renderSearchReply = (\n result: SearchMemoriesRecallOutput,\n emptyText: string\n): string =>\n [\n renderMemoryLines(result.memories, emptyText),\n ...renderUndatedExclusion(result.undatedExcludedCount),\n ].join(\"\\n\");\n\nconst memoriesCursorSchema = z.object({\n createdAt: z.string().min(1),\n id: z.string().min(1),\n}) satisfies z.ZodType<MemoriesCursor>;\n\nconst parseMemoriesCursorJson = (value: string) => {\n try {\n return memoriesCursorSchema.safeParse(JSON.parse(value));\n } catch {\n return null;\n }\n};\n\n/** Accepts the `nextCursor` JSON a previous `memory list` printed. */\nconst parseMemoriesCursor = (\n value: string | undefined\n): MemoriesCursor | undefined => {\n if (value === undefined) return undefined;\n const parsed = parseMemoriesCursorJson(value);\n if (parsed?.success !== true) {\n throw new MerraiCliUsageError(\n 'cursor must be the nextCursor JSON from a previous list, for example {\"createdAt\":\"…\",\"id\":\"…\"}'\n );\n }\n return parsed.data;\n};\n\n/** A page of current memories in Search's lines, then how to continue. */\nconst renderMemoryList = (page: MemoriesOutput): string => {\n const lines = [renderMemoryLines(page.items, \"No memories found.\")];\n if (page.nextCursor !== null) {\n lines.push(`More: --cursor '${JSON.stringify(page.nextCursor)}'`);\n }\n return lines.join(\"\\n\");\n};\n\nconst aboutSchema = z.enum([\n \"owner\",\n \"other\",\n \"none\",\n]) satisfies z.ZodType<MemoryAbout>;\nconst stanceSchema = z.enum([\n \"reported\",\n \"view\",\n \"decision\",\n \"inferred\",\n]) satisfies z.ZodType<MemoryStance>;\nconst judgmentStanceSchema = z.enum([\"view\", \"decision\"]);\n\nconst parseChoice = <Value extends string>(\n schema: z.ZodType<Value>,\n value: string,\n name: string,\n values: readonly string[]\n): Value => {\n const parsed = schema.safeParse(value);\n if (!parsed.success) {\n throw new MerraiCliUsageError(\n `${name} must be one of: ${values.join(\", \")}`\n );\n }\n return parsed.data;\n};\n\nconst openItemsCursorSchema = z.object({\n asOf: z.string().min(1),\n id: z.string().min(1),\n startsOn: z.string().min(1),\n}) satisfies z.ZodType<OpenItemsCursor>;\n\nconst judgmentsCursorSchema = z.object({\n createdAt: z.string().min(1),\n id: z.string().min(1),\n}) satisfies z.ZodType<JudgmentsCursor>;\n\n/** \"- 2026-11-10 (planned): text\", earliest first. */\nconst renderOpenItems = (result: ListOpenItemsOutput): string =>\n [\n result.items.length === 0\n ? `Nothing coming up from ${result.asOf}.`\n : `Coming up from ${result.asOf}:`,\n ...result.items.map(\n (item) =>\n `- ${item.startsOn}${item.role === null ? \"\" : ` (${item.role})`}: ${item.content}`\n ),\n ...renderMoreCursor(result.nextCursor),\n ].join(\"\\n\");\n\n/** Each view or decision, then the facts it rests on or weighs against. */\nconst renderJudgments = (result: ListJudgmentsOutput): string =>\n [\n ...(result.items.length === 0 ? [\"No views or decisions found.\"] : []),\n ...result.items.map((item) =>\n [\n `- ${item.stance}${item.holder === null ? \"\" : ` (${item.holder})`}${item.reviewState === null ? \"\" : \" [evidence changed]\"}: ${item.content}`,\n ...item.basis.map(\n (fact) =>\n ` ${fact.link === \"rests_on\" ? \"rests on\" : \"weighs against\"}${fact.current ? \"\" : \" (no longer current)\"}: ${fact.content}`\n ),\n ].join(\"\\n\")\n ),\n ...renderMoreCursor(result.nextCursor),\n ].join(\"\\n\");\n\n/** The summary, each line with the exemplars it cites, then the exemplars. */\nconst renderStyle = (result: GetStyleProfileOutput): string =>\n result.style === null\n ? `No style profile for ${result.lobeKey} yet.`\n : [\n `How you write in ${result.lobeKey} (from ${result.style.sampleSize} of your own passages):`,\n ...result.style.summary.map(\n (claim) =>\n `- ${claim.aspect}: ${claim.text} [${claim.exemplarIds.join(\", \")}]`\n ),\n \"\",\n \"Exemplars:\",\n ...result.style.exemplars.flatMap((exemplar) => [\n `[${exemplar.id}]`,\n exemplar.text,\n \"\",\n ]),\n ]\n .join(\"\\n\")\n .trimEnd();\n\n/** `memory by-date` keeps its earlier default of 20 within the shared maximum of 25. */\nconst BY_DATE_DEFAULT_LIMIT = 20;\n\nconst configureAddCommand = (\n command: Command,\n context: MerraiCommandContext,\n contract: \"legacy\" | \"recall\"\n): void => {\n command\n .argument(\"[text]\", \"Memory text\")\n .option(\"--memory <text>\", \"Memory text\")\n .option(\"--file <path>\", \"Read memory text from a file, or - for stdin\")\n .option(\"--observation-date <datetime>\", \"ISO 8601 observation time\")\n .option(\"--lobe <key>\", \"Existing lobe to save into (default: main)\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\");\n if (contract === \"legacy\") {\n command.option(\"--source <source>\", \"Source identifier\");\n }\n command.action(\n async (\n positional: string | undefined,\n options: AddMemoryOptions,\n actionCommand: Command\n ) => {\n const memory = await readTextInput({\n cwd: context.runtime.cwd,\n file: options.file,\n option: options.memory,\n positional,\n stdin: context.runtime.stdin,\n });\n const observationDate = parseDateOption(\n options.observationDate,\n \"--observation-date\"\n );\n const lobeKey = resolveLobeKey(options);\n const source = contract === \"legacy\" ? options.source : undefined;\n // Same content, source, lobe and date → same key, so rerunning a\n // command that timed out joins the first save instead of duplicating it.\n const idempotencyKey = deriveMemorySaveIdempotencyKey({\n lobeKey,\n memory,\n now: context.runtime.now?.() ?? new Date(),\n observationDate,\n source,\n });\n const client = context.client(actionCommand);\n const result =\n contract === \"recall\"\n ? await client.recall.addMemory({\n idempotencyKey,\n lobeKey,\n memory,\n observationDate,\n })\n : await client.addMemory({\n idempotencyKey,\n lobeKey,\n memory,\n observationDate,\n source,\n });\n context\n .output(actionCommand)\n .data(result, (value) =>\n describeQueuedIngestion(\"Memory\", value.ingestionId)\n );\n }\n );\n};\n\nconst configureSearchCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .argument(\"[query]\", \"Search query\")\n .option(\"--query <text>\", \"Search query\")\n .option(\"--limit <number>\", \"Maximum results\")\n .option(\n \"--lobe <key>\",\n \"Search one of your lobes instead of the lobes your agent reads\"\n )\n .option(\n \"--topic <key>\",\n \"Only memories with this topic; repeat for any of several\",\n collectOption,\n []\n )\n .option(\"--about <who>\", \"Only memories about: owner, other or none\")\n .option(\n \"--stance <stance>\",\n \"Only memories with this stance (reported, view, decision or inferred); repeat for any of several\",\n collectOption,\n []\n );\n command.action(\n async (\n positional: string | undefined,\n options: SearchOptions,\n actionCommand: Command\n ) => {\n const query = (options.query ?? positional)?.trim();\n const topics = options.topic.length === 0 ? undefined : options.topic;\n const about =\n options.about === undefined\n ? undefined\n : parseChoice(aboutSchema, options.about, \"--about\", [\n \"owner\",\n \"other\",\n \"none\",\n ]);\n const stance =\n options.stance.length === 0\n ? undefined\n : options.stance.map((value) =>\n parseChoice(stanceSchema, value, \"--stance\", [\n \"reported\",\n \"view\",\n \"decision\",\n \"inferred\",\n ])\n );\n if (\n (query === undefined || query.length === 0) &&\n topics === undefined &&\n about === undefined &&\n stance === undefined\n ) {\n throw new MerraiCliUsageError(\n \"Provide a search query, or filter with --topic, --about or --stance\"\n );\n }\n const limit = parseIntegerOption(options.limit, \"--limit\", {\n maximum: 25,\n minimum: 1,\n });\n // MCP search_memories' contract: no model call, update marks.\n const result = await context.client(actionCommand).recall.searchMemories({\n about,\n limit,\n lobeKey: options.lobe,\n query: query === undefined || query.length === 0 ? undefined : query,\n stance,\n topics,\n });\n context\n .output(actionCommand)\n .data(result, (value) =>\n renderSearchReply(value, \"No memories found.\")\n );\n }\n );\n};\n\nconst configureDateCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .option(\"--start <datetime>\", \"Inclusive ISO 8601 lower bound\")\n .option(\"--end <datetime>\", \"Inclusive ISO 8601 upper bound\")\n .option(\"--limit <number>\", \"Maximum results, 1-25 (default 20)\")\n .action(async (options: DateOptions, actionCommand: Command) => {\n const start = parseDateOption(options.start, \"--start\");\n const end = parseDateOption(options.end, \"--end\");\n if (start === undefined && end === undefined) {\n throw new MerraiCliUsageError(\n \"Provide at least one of --start or --end\"\n );\n }\n const input = {\n end,\n limit:\n parseIntegerOption(options.limit, \"--limit\", {\n maximum: 25,\n minimum: 1,\n }) ?? BY_DATE_DEFAULT_LIMIT,\n start,\n };\n // MCP search_memories with date bounds alone: newest recorded first.\n const result = await context\n .client(actionCommand)\n .recall.searchMemories(input);\n context\n .output(actionCommand)\n .data(result, (value) =>\n renderSearchReply(\n value,\n \"No memories found in the requested date range.\"\n )\n );\n });\n};\n\nconst configureStatusCommand = (\n command: Command,\n context: MerraiCommandContext\n): void => {\n command\n .option(\"--lobe <key>\", \"Restrict to a lobe\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\")\n .action(async (options: LobeOptions, actionCommand: Command) => {\n const lobeKey = resolveLobeKey(options);\n const result: MemoryStatusOutput = await context\n .client(actionCommand)\n .memoryStatus({ lobeKey });\n context\n .output(actionCommand)\n .data(result, () =>\n lobeKey === undefined\n ? `${result.count} memories.`\n : `${result.count} memories in ${lobeKey}.`\n );\n });\n};\n\nconst configureClearCommand = (\n command: Command,\n context: MerraiCommandContext,\n requireConfirmation: boolean\n): void => {\n command\n .argument(\"[lobe]\", \"Lobe to clear\")\n .option(\"--lobe <key>\", \"Lobe to clear\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\")\n .option(\"--yes\", \"Skip confirmation\")\n .option(\n \"--no-wait\",\n \"Return once the clear has started instead of following it\"\n )\n .action(\n async (\n positional: string | undefined,\n options: ClearOptions,\n actionCommand: Command\n ) => {\n const lobeKey = resolveLobeKey(options) ?? positional;\n if (lobeKey === undefined || lobeKey.trim().length === 0) {\n throw new MerraiCliUsageError(\"Provide the lobe to clear\");\n }\n if (requireConfirmation && options.yes !== true) {\n const confirmed = await confirmAction({\n input: context.runtime.stdin,\n message: `Clear all memories in lobe '${lobeKey}'?`,\n output: context.runtime.stderr,\n });\n if (!confirmed) {\n throw new MerraiCliUsageError(\n \"Clear cancelled. Use --yes for noninteractive confirmation.\"\n );\n }\n }\n // The clear runs as durable server work; by default the command\n // follows it to the end so \"Cleared\" is only printed when it is.\n const started = await context\n .client(actionCommand)\n .clearLobe({ lobeKey });\n finishClear(\n context,\n actionCommand,\n options.wait === false\n ? started\n : await followClear(context, actionCommand, started)\n );\n }\n );\n};\n\nexport const registerMemoryCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const memory = program\n .command(\"memory\")\n .description(\"Manage and recall memories\");\n\n configureAddCommand(\n memory.command(\"add\").description(\"Queue a memory\"),\n context,\n \"recall\"\n );\n configureAddCommand(\n program\n .command(\"add-memory\", { hidden: true })\n .description(\"Legacy memory add\"),\n context,\n \"legacy\"\n );\n\n configureSearchCommand(\n memory.command(\"search\").description(\"Search memories\"),\n context\n );\n\n const configureListCommand = (command: Command): void => {\n command\n .option(\"--lobe <key>\", \"Only memories in this lobe\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\")\n .option(\"--limit <count>\", \"Memories per page, from 1 to 100\")\n .option(\"--cursor <json>\", \"Continue from a previous page's nextCursor\")\n .action(async (options: ListOptions, actionCommand: Command) => {\n const result = await context.client(actionCommand).memories({\n cursor: parseMemoriesCursor(options.cursor),\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 100,\n minimum: 1,\n }),\n lobeKey: resolveLobeKey(options),\n });\n context.output(actionCommand).data(result, renderMemoryList);\n });\n };\n configureListCommand(\n memory\n .command(\"list\")\n .description(\"List current memories, newest first, one page at a time\")\n );\n configureListCommand(\n program\n .command(\"memories\", { hidden: true })\n .description(\"Legacy memory list\")\n );\n\n const profileAction = async (\n command: Command,\n lobeKey?: string\n ): Promise<void> => {\n const result = await context\n .client(command)\n .memoryOverview(lobeKey === undefined ? undefined : { lobeKey });\n context.output(command).data(result, renderProfile);\n };\n memory\n .command(\"profile\")\n .description(\"Show the account and memory profile\")\n .option(\n \"--lobe <key>\",\n \"Read one lobe's profile instead of the lobes your agent reads\"\n )\n .action(async (options: { lobe?: string }, command: Command) =>\n profileAction(command, options.lobe)\n );\n program\n .command(\"who-am-i\", { hidden: true })\n .aliases([\"whoami\"])\n .description(\"Legacy memory profile\")\n .action(async (_options: Record<string, never>, command: Command) =>\n profileAction(command)\n );\n\n configureDateCommand(\n memory.command(\"by-date\").description(\"Recall memories by date\"),\n context\n );\n\n memory\n .command(\"open-items\")\n .description(\n \"List what is coming up: plans and deadlines still ahead, and decisions not yet carried out, earliest first\"\n )\n .option(\n \"--lobe <key>\",\n \"Read one of your lobes instead of the lobes your agent reads\"\n )\n .option(\n \"--as-of <day>\",\n \"Count from this day, YYYY-MM-DD (default: today here)\"\n )\n .option(\n \"--until <day>\",\n \"Only items starting on or before this day, YYYY-MM-DD\"\n )\n .option(\"--limit <count>\", \"Items per page, from 1 to 50\")\n .option(\"--cursor <json>\", \"Continue from a previous page's nextCursor\")\n .action(async (options: OpenItemsOptions, command: Command) => {\n const result = await context.client(command).listOpenItems({\n asOf:\n parseDayOption(options.asOf, \"--as-of\") ??\n localDay(context.runtime.now?.() ?? new Date()),\n cursor: parseCursorJson(\n openItemsCursorSchema,\n options.cursor,\n '{\"asOf\":\"…\",\"id\":\"…\",\"startsOn\":\"…\"}'\n ),\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 50,\n minimum: 1,\n }),\n lobeKey: options.lobe,\n until: parseDayOption(options.until, \"--until\"),\n });\n context.output(command).data(result, renderOpenItems);\n });\n\n memory\n .command(\"judgments\")\n .description(\n \"List current views and decisions, newest first, with the facts each rests on or weighs against\"\n )\n .option(\n \"--lobe <key>\",\n \"Read one of your lobes instead of the lobes your agent reads\"\n )\n .option(\"--stance <stance>\", \"Only view or only decision\")\n .option(\n \"--evidence-changed\",\n \"Only those whose supporting facts changed after they were formed\"\n )\n .option(\"--limit <count>\", \"Items per page, from 1 to 50\")\n .option(\"--cursor <json>\", \"Continue from a previous page's nextCursor\")\n .action(async (options: JudgmentsOptions, command: Command) => {\n const result = await context.client(command).listJudgments({\n cursor: parseCursorJson(\n judgmentsCursorSchema,\n options.cursor,\n '{\"createdAt\":\"…\",\"id\":\"…\"}'\n ),\n limit: parseIntegerOption(options.limit, \"--limit\", {\n maximum: 50,\n minimum: 1,\n }),\n lobeKey: options.lobe,\n reviewState:\n options.evidenceChanged === true ? \"evidence_changed\" : undefined,\n stance:\n options.stance === undefined\n ? undefined\n : parseChoice(judgmentStanceSchema, options.stance, \"--stance\", [\n \"view\",\n \"decision\",\n ]),\n });\n context.output(command).data(result, renderJudgments);\n });\n configureDateCommand(\n program\n .command(\"search-memories-by-date\", { hidden: true })\n .description(\"Legacy date recall\"),\n context\n );\n\n configureStatusCommand(\n memory.command(\"status\").description(\"Count processed memories\"),\n context\n );\n configureStatusCommand(\n program\n .command(\"memory-status\", { hidden: true })\n .description(\"Legacy status\"),\n context\n );\n\n configureClearCommand(\n memory.command(\"clear\").description(\"Clear a memory lobe\"),\n context,\n true\n );\n memory\n .command(\"clear-status\")\n .description(\"Show the progress of a lobe clear\")\n .argument(\"<clearId>\", \"Clear id printed when the clear started\")\n .action(\n async (\n clearId: string,\n _options: Record<string, never>,\n command: Command\n ) => {\n finishClear(\n context,\n command,\n await context.client(command).clearLobeStatus({ clearId })\n );\n }\n );\n configureClearCommand(\n program\n .command(\"clear-lobe\", { hidden: true })\n .description(\"Legacy lobe clear\"),\n context,\n false\n );\n\n memory\n .command(\"style\")\n .description(\n \"Show how you write: passages in your own words and a summary citing them\"\n )\n .option(\n \"--lobe <key>\",\n \"Read one of your lobes instead of main, where your own chats and notes are kept\"\n )\n .action(async (options: { lobe?: string }, command: Command) => {\n const result = await context\n .client(command)\n .getStyleProfile(\n options.lobe === undefined ? {} : { lobeKey: options.lobe }\n );\n context.output(command).data(result, renderStyle);\n });\n\n const synthesis = memory\n .command(\"synthesis\")\n .description(\n \"Rebuild the patterns of how you think and the profile of how you write\"\n );\n synthesis\n .command(\"start\")\n .description(\n \"Rebuild every lobe, or one, now; unchanged inputs are not sent to a model again\"\n )\n .option(\"--lobe <key>\", \"Lobe key; omitted means every lobe\")\n .action(async (options: { lobe?: string }, command: Command) => {\n const result = await context\n .client(command)\n .startMemorySynthesis(\n options.lobe === undefined ? {} : { lobeKey: options.lobe }\n );\n context.output(command).data(result, renderSynthesis);\n });\n synthesis\n .command(\"status\")\n .description(\"Show each lobe's patterns and style, or one lobe's\")\n .option(\"--lobe <key>\", \"Lobe key; omitted means every lobe\")\n .action(async (options: { lobe?: string }, command: Command) => {\n const result = await context\n .client(command)\n .memorySynthesisStatus(\n options.lobe === undefined ? {} : { lobeKey: options.lobe }\n );\n context.output(command).data(result, renderSynthesis);\n });\n\n const backfill = memory\n .command(\"backfill\")\n .description(\n \"Label stored memories with topics, who they are about and their stance\"\n );\n backfill\n .command(\"start\")\n .description(\"Label every lobe, or one; a start while one runs joins it\")\n .option(\"--lobe <key>\", \"Lobe key; omitted means every lobe\")\n .action(async (options: { lobe?: string }, command: Command) => {\n const result = await context\n .client(command)\n .startMemoryBackfill(\n options.lobe === undefined ? {} : { lobeKey: options.lobe }\n );\n context.output(command).data(result, renderBackfill);\n });\n backfill\n .command(\"status\")\n .description(\"Show the backfill's progress for every lobe, or one\")\n .option(\"--lobe <key>\", \"Lobe key; omitted means every lobe\")\n .action(async (options: { lobe?: string }, command: Command) => {\n const result = await context\n .client(command)\n .memoryBackfillStatus(\n options.lobe === undefined ? {} : { lobeKey: options.lobe }\n );\n context.output(command).data(result, renderBackfill);\n });\n};\n\nconst renderSynthesis = (result: MemorySynthesisStatusOutput): string => {\n if (result.status === \"never\") return \"No synthesis has run.\";\n return [\n `Synthesis ${result.status}.`,\n ...result.lobes.map((lobe) => {\n const progress =\n lobe.state === \"pending\"\n ? `pending until ${lobe.notBefore}`\n : `${lobe.state}, ${lobe.patternCount} ${lobe.patternCount === 1 ? \"pattern\" : \"patterns\"}, style ${lobe.styleBuiltAt === null ? \"not built\" : \"built\"}`;\n return lobe.lastError === null\n ? `- ${lobe.lobeKey}: ${progress}`\n : `- ${lobe.lobeKey}: ${progress} (${lobe.lastError})`;\n }),\n ].join(\"\\n\");\n};\n\nconst renderBackfill = (result: MemoryBackfillStatusOutput): string => {\n if (result.status === \"never\") return \"No backfill has run.\";\n return [\n result.lastError === null\n ? `Backfill ${result.status}.`\n : `Backfill ${result.status} (${result.lastError}).`,\n ...result.lobes.map((lobe) => {\n const progress =\n lobe.state === \"queued\"\n ? \"queued\"\n : `${lobe.state}, ${lobe.labelled} of ${lobe.total} labelled`;\n return lobe.lastError === null\n ? `- ${lobe.lobeKey}: ${progress}`\n : `- ${lobe.lobeKey}: ${progress} (${lobe.lastError})`;\n }),\n ].join(\"\\n\");\n};\n","import type { Command } from \"commander\";\nimport { z } from \"zod\";\n\nimport type {\n SourceArtifact,\n SourceArtifactCursor,\n SourceArtifactListOutput,\n SourceKind,\n SourceProcessingStatus,\n} from \"../client\";\nimport { MerraiCliUsageError } from \"../errors\";\nimport { confirmAction } from \"../input\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport {\n describeQueuedIngestion,\n parseIntegerOption,\n resolveLobeKey,\n type NoCommandOptions,\n} from \"./shared\";\n\nconst SOURCE_KINDS: readonly SourceKind[] = [\n \"agent_conversation\",\n \"external_chat\",\n \"imported_chat\",\n \"manual_entry\",\n \"memory_source\",\n \"upload\",\n];\n\nconst SOURCE_STATUSES: readonly SourceProcessingStatus[] = [\n \"complete\",\n \"deleted\",\n \"failed\",\n \"partial\",\n \"pending\",\n \"processing\",\n];\n\ninterface ListOptions {\n cursor?: string;\n kind?: string[];\n limit?: string;\n lobe?: string;\n lobeKey?: string;\n provider?: string[];\n status?: string[];\n}\n\ninterface DeleteOptions {\n yes?: boolean;\n}\n\nconst parseChoices = <TChoice extends string>(\n values: string[] | undefined,\n choices: readonly TChoice[],\n name: string\n): TChoice[] | undefined => {\n if (values === undefined) return undefined;\n return values.map((value) => {\n const choice = choices.find((candidate) => candidate === value);\n if (choice === undefined) {\n throw new MerraiCliUsageError(\n `${name} must be one of: ${choices.join(\", \")}`\n );\n }\n return choice;\n });\n};\n\nconst cursorSchema = z.object({\n createdAt: z.string().min(1),\n id: z.string().min(1),\n}) satisfies z.ZodType<SourceArtifactCursor>;\n\nconst parseCursorJson = (value: string) => {\n try {\n return cursorSchema.safeParse(JSON.parse(value));\n } catch {\n return null;\n }\n};\n\n/** Accepts the `nextCursor` JSON a previous `sources list` printed. */\nconst parseCursor = (\n value: string | undefined\n): SourceArtifactCursor | undefined => {\n if (value === undefined) return undefined;\n const parsed = parseCursorJson(value);\n if (parsed?.success !== true) {\n throw new MerraiCliUsageError(\n 'cursor must be the nextCursor JSON from a previous list, for example {\"createdAt\":\"…\",\"id\":\"…\"}'\n );\n }\n return parsed.data;\n};\n\nconst describeKind = (source: SourceArtifact): string =>\n source.sourceProvider === null\n ? source.sourceKind\n : `${source.sourceKind}/${source.sourceProvider}`;\n\n/**\n * The list's source segment: its kind, then where it came from when that is\n * known and says more than the kind or provider already does.\n */\nconst describeOrigin = (source: SourceArtifact): string =>\n source.origin === null ||\n source.origin === source.sourceKind ||\n source.origin === source.sourceProvider\n ? describeKind(source)\n : `${describeKind(source)} from ${source.origin}`;\n\nconst describeStatus = (source: SourceArtifact): string =>\n source.pausedReason === \"quota_exceeded\"\n ? `${source.status} (waiting for memory quota)`\n : source.status;\n\nconst renderSourceList = (page: SourceArtifactListOutput): string => {\n const lines =\n page.items.length === 0\n ? [\"No sources found.\"]\n : page.items.map(\n (source) =>\n `- ${source.title}: ${describeStatus(source)}, ${describeOrigin(source)}, ${source.memoryCount} memories (${source.artifactId})`\n );\n if (page.nextCursor !== null) {\n lines.push(`More: --cursor '${JSON.stringify(page.nextCursor)}'`);\n }\n return lines.join(\"\\n\");\n};\n\nconst renderSource = (source: SourceArtifact): string =>\n [\n source.title,\n `ID: ${source.artifactId}`,\n `Status: ${describeStatus(source)}`,\n `Source: ${describeKind(source)}`,\n ...(source.origin === null ? [] : [`From: ${source.origin}`]),\n `Lobe: ${source.lobeKey}`,\n `Memories: ${source.memoryCount}`,\n ...(source.blockedWindows > 0\n ? [\n `Blocked windows: ${source.blockedWindows} (${source.retryableBlockedWindows} retryable${\n source.availableActions.includes(\"retry_blocked_windows\")\n ? ` with \\`merrai sources retry ${source.artifactId}\\``\n : \"\"\n })`,\n ]\n : []),\n `Last activity: ${source.lastActivityAt}`,\n `Actions: ${source.availableActions.join(\", \") || \"none\"}`,\n ].join(\"\\n\");\n\nexport const registerSourceCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const sources = program\n .command(\"sources\")\n .description(\n \"List, inspect, retry, reprocess and delete the sources memories come from\"\n );\n\n sources\n .command(\"list\")\n .description(\"List sources, newest first\")\n .option(\"--kind <kind...>\", `Only these kinds: ${SOURCE_KINDS.join(\", \")}`)\n .option(\n \"--provider <provider...>\",\n \"Only these providers, such as granola or claude-code\"\n )\n .option(\n \"--status <status...>\",\n `Only these states: ${SOURCE_STATUSES.join(\", \")}`\n )\n .option(\"--lobe <key>\", \"Only sources in this lobe\")\n .option(\"--lobe-key <key>\", \"Legacy alias for --lobe\")\n .option(\"--limit <count>\", \"Sources per page, from 1 to 100\")\n .option(\"--cursor <json>\", \"Continue from a previous page's nextCursor\")\n .action(async (options: ListOptions, command: Command) => {\n const input = {\n cursor: parseCursor(options.cursor),\n limit: parseIntegerOption(options.limit, \"limit\", {\n maximum: 100,\n minimum: 1,\n }),\n lobeKey: resolveLobeKey(options),\n providers: options.provider,\n sourceKinds: parseChoices(options.kind, SOURCE_KINDS, \"kind\"),\n statuses: parseChoices(options.status, SOURCE_STATUSES, \"status\"),\n };\n const result = await context.client(command).sourceArtifactList(input);\n context.output(command).data(result, renderSourceList);\n });\n\n sources\n .command(\"show\")\n .description(\"Show one source's processing state and actions\")\n .argument(\"<id>\", \"Source artifact ID\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .sourceArtifactGet({ artifactId: id });\n context.output(command).data(result, renderSource);\n }\n );\n\n sources\n .command(\"retry\")\n .description(\n \"Extract again the parts a partly processed source could not extract\"\n )\n .argument(\"<id>\", \"Source artifact ID of a partial source\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .sourceArtifactRetry({ artifactId: id });\n context\n .output(command)\n .data(result, (value) =>\n describeQueuedIngestion(\"Retry\", value.ingestionId)\n );\n }\n );\n\n sources\n .command(\"reprocess\")\n .description(\"Process a failed source again from the start\")\n .argument(\"<id>\", \"Source artifact ID of a failed source\")\n .action(\n async (id: string, _options: NoCommandOptions, command: Command) => {\n const result = await context\n .client(command)\n .sourceArtifactReprocess({ artifactId: id });\n context\n .output(command)\n .data(result, (value) =>\n describeQueuedIngestion(\"Reprocess\", value.ingestionId)\n );\n }\n );\n\n sources\n .command(\"delete\")\n .description(\"Delete a source and the memories that came only from it\")\n .argument(\"<id>\", \"Source artifact ID\")\n .option(\"--yes\", \"Skip confirmation\")\n .action(async (id: string, options: DeleteOptions, command: Command) => {\n if (options.yes !== true) {\n const confirmed = await confirmAction({\n input: context.runtime.stdin,\n message: `Delete source ${id} and the memories that came only from it?`,\n output: context.runtime.stderr,\n });\n if (!confirmed) {\n throw new MerraiCliUsageError(\n \"Delete cancelled. Use --yes for noninteractive confirmation.\"\n );\n }\n }\n const result = await context\n .client(command)\n .sourceArtifactDelete({ artifactId: id });\n context.output(command).data(result, () => `Deleted source ${id}.`);\n });\n};\n","import type { Command } from \"commander\";\n\nimport type { AuthSessionOutput } from \"../client\";\nimport type { MerraiTextRenderer } from \"../output\";\nimport type { MerraiCommandContext } from \"../runtime\";\nimport { type NoCommandOptions } from \"./shared\";\n\nconst renderLabelledJson =\n <Value>(label: string): MerraiTextRenderer<Value> =>\n (value: Value): string =>\n `${label}\\n${JSON.stringify(value, null, 2)}`;\n\nconst redactAuthSessionToken = (\n result: AuthSessionOutput\n): Omit<AuthSessionOutput, \"session\"> & {\n session: Omit<AuthSessionOutput[\"session\"], \"token\">;\n} => ({\n session: {\n createdAt: result.session.createdAt,\n expiresAt: result.session.expiresAt,\n id: result.session.id,\n ipAddress: result.session.ipAddress,\n updatedAt: result.session.updatedAt,\n userAgent: result.session.userAgent,\n userId: result.session.userId,\n },\n user: result.user,\n});\n\nexport const registerSystemCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n program\n .command(\"health\")\n .description(\"Check API connectivity\")\n .action(async (_options: NoCommandOptions, command: Command) => {\n const result = await context.client(command).healthCheck();\n context\n .output(command)\n .data(result, renderLabelledJson(\"Merrai is reachable.\"));\n });\n\n program\n .command(\"session\")\n .description(\"Fetch the current session\")\n .action(async (_options: NoCommandOptions, command: Command) => {\n const result = await context.client(command).session();\n const safeResult =\n result === null ? null : redactAuthSessionToken(result);\n context\n .output(command)\n .data(safeResult, renderLabelledJson(\"Current session:\"));\n });\n\n const account = program.command(\"account\").description(\"Account information\");\n const usageAction = async (command: Command): Promise<void> => {\n const result = await context.client(command).usageSummary();\n context.output(command).data(result, renderLabelledJson(\"Usage:\"));\n };\n\n account\n .command(\"usage\")\n .description(\"Fetch the current usage summary\")\n .action(async (_options: NoCommandOptions, command: Command) =>\n usageAction(command)\n );\n program\n .command(\"usage-summary\", { hidden: true })\n .description(\"Legacy alias for account usage\")\n .action(async (_options: NoCommandOptions, command: Command) =>\n usageAction(command)\n );\n};\n","import type { Command } from \"commander\";\n\nimport type { MemoryTopicCatalogueOutput } from \"../client\";\nimport type { MerraiCommandContext } from \"../runtime\";\n\ninterface TopicScopeOptions {\n lobe?: string;\n}\n\nconst scopeInput = (options: TopicScopeOptions): { lobeKey?: string } =>\n options.lobe === undefined ? {} : { lobeKey: options.lobe };\n\nconst renderCatalogue = (catalogue: MemoryTopicCatalogueOutput): string => {\n const scope =\n catalogue.lobeKey === null ? \"every lobe\" : `lobe ${catalogue.lobeKey}`;\n if (catalogue.topics.length === 0) return `No topics for ${scope}.`;\n return [\n `Topics for ${scope}:`,\n ...catalogue.topics.map(\n (topic) => `- ${topic.key} (${topic.origin}): ${topic.description}`\n ),\n ].join(\"\\n\");\n};\n\nexport const registerTopicCommands = (\n program: Command,\n context: MerraiCommandContext\n): void => {\n const topic = program\n .command(\"topic\")\n .description(\n \"List and change the topics memories are assigned, for every lobe or one\"\n );\n\n topic\n .command(\"list\")\n .description(\"List the topics for every lobe, or for one lobe\")\n .option(\"--lobe <key>\", \"Lobe key; omitted means every lobe\")\n .action(async (options: TopicScopeOptions, command: Command) => {\n const result = await context\n .client(command)\n .listTopics(scopeInput(options));\n context.output(command).data(result, renderCatalogue);\n });\n\n topic\n .command(\"set\")\n .description(\"Add a topic, or reword one, for every lobe or one lobe\")\n .argument(\"<key>\", \"Topic key, such as training\")\n .argument(\"<description>\", \"What the topic holds\")\n .option(\"--lobe <key>\", \"Lobe key; omitted means every lobe\")\n .action(\n async (\n key: string,\n description: string,\n options: TopicScopeOptions,\n command: Command\n ) => {\n const result = await context\n .client(command)\n .setTopic({ ...scopeInput(options), description, key });\n context.output(command).data(result, renderCatalogue);\n }\n );\n\n topic\n .command(\"retire\")\n .description(\"Stop assigning a topic, for every lobe or one lobe\")\n .argument(\"<key>\", \"Topic key\")\n .option(\"--lobe <key>\", \"Lobe key; omitted means every lobe\")\n .action(\n async (key: string, options: TopicScopeOptions, command: Command) => {\n const result = await context\n .client(command)\n .retireTopic({ ...scopeInput(options), key });\n context.output(command).data(result, renderCatalogue);\n }\n );\n};\n","import type * as NodeStream from \"node:stream\";\n\nimport { z } from \"zod\";\n\nexport type MerraiOutputFormat = \"json\" | \"text\";\nexport type MerraiTextRenderer<Value> = (value: Value) => string;\n\nexport interface MerraiCliOutput {\n data<Value>(value: Value, renderText?: MerraiTextRenderer<Value>): void;\n diagnostic(message: string): void;\n error(message: string): void;\n}\n\nconst ensureTrailingNewline = (value: string): string =>\n value.endsWith(\"\\n\") ? value : `${value}\\n`;\n\nexport const createMerraiCliOutput = (options: {\n format: MerraiOutputFormat;\n stderr: NodeStream.Writable;\n stdout: NodeStream.Writable;\n}): MerraiCliOutput => ({\n data: <Value>(value: Value, renderText?: MerraiTextRenderer<Value>) => {\n const stringValue = z.string().safeParse(value);\n const rendered =\n options.format === \"text\" && renderText !== undefined\n ? renderText(value)\n : stringValue.success && options.format === \"text\"\n ? stringValue.data\n : JSON.stringify(value, null, 2);\n options.stdout.write(ensureTrailingNewline(rendered ?? \"null\"));\n },\n diagnostic: (message) => {\n options.stderr.write(ensureTrailingNewline(message));\n },\n error: (message) => {\n options.stderr.write(ensureTrailingNewline(message));\n },\n});\n","import type * as NodeStream from \"node:stream\";\n\nimport type { Command } from \"commander\";\n\nimport {\n createMerraiDebugProcedure,\n type JsonValue,\n type MerraiClientOptions,\n type MerraiThrowingClient,\n type ThrowingRpcProcedure,\n} from \"./client\";\nimport {\n type MerraiCliEnvironment,\n resolveMerraiClientOptions,\n} from \"./config\";\nimport {\n type MerraiCliOutput,\n type MerraiOutputFormat,\n createMerraiCliOutput,\n} from \"./output\";\n\nexport interface MerraiCliRuntime {\n argv: readonly string[];\n createClient: (options: MerraiClientOptions) => MerraiThrowingClient;\n cwd: string;\n env: MerraiCliEnvironment;\n /** Clock for date-scoped idempotency keys; defaults to the system clock. */\n now?: () => Date;\n /** Waits between status polls; defaults to a timer. */\n sleep?: (milliseconds: number) => Promise<void>;\n stderr: NodeStream.Writable;\n stdin: NodeStream.Readable;\n stdout: NodeStream.Writable;\n}\n\ninterface GlobalOptions {\n apiKey?: string;\n baseUrl?: string;\n cookie?: string;\n format?: MerraiOutputFormat;\n json?: boolean;\n}\n\nconst globalOptions = (command: Command): GlobalOptions =>\n command.optsWithGlobals<GlobalOptions>();\n\nexport interface MerraiCommandContext {\n client(command: Command): MerraiThrowingClient;\n debugProcedure(\n command: Command,\n procedureName: string\n ): ThrowingRpcProcedure<JsonValue, JsonValue>;\n output(command: Command): MerraiCliOutput;\n runtime: MerraiCliRuntime;\n}\n\nconst clientOptions = (\n runtime: MerraiCliRuntime,\n command: Command\n): MerraiClientOptions => {\n const options = globalOptions(command);\n return resolveMerraiClientOptions(runtime.env, {\n apiKey: options.apiKey,\n baseURL: options.baseUrl,\n cookie: options.cookie,\n });\n};\n\nexport const createMerraiCommandContext = (\n runtime: MerraiCliRuntime\n): MerraiCommandContext => ({\n client: (command) => runtime.createClient(clientOptions(runtime, command)),\n debugProcedure: (command, procedureName) =>\n createMerraiDebugProcedure(clientOptions(runtime, command), procedureName),\n output: (command) => {\n const options = globalOptions(command);\n return createMerraiCliOutput({\n format: options.json === true ? \"json\" : (options.format ?? \"json\"),\n stderr: runtime.stderr,\n stdout: runtime.stdout,\n });\n },\n runtime,\n});\n","import { Command, InvalidArgumentError } from \"commander\";\n\nimport packageMetadata from \"../package.json\" with { type: \"json\" };\nimport { registerAppCommands } from \"./commands/apps\";\nimport { registerAuthCommands } from \"./commands/auth\";\nimport { registerDebugCommands } from \"./commands/debug\";\nimport { registerEntityCommands } from \"./commands/entity\";\nimport { registerIngestCommands } from \"./commands/ingest\";\nimport { registerIngestionCommands } from \"./commands/ingestion\";\nimport { registerLivingDocumentCommands } from \"./commands/living-document\";\nimport { registerLobeCommands } from \"./commands/lobe\";\nimport { registerMemoryCommands } from \"./commands/memory\";\nimport { registerSourceCommands } from \"./commands/sources\";\nimport { registerSystemCommands } from \"./commands/system\";\nimport { registerTopicCommands } from \"./commands/topic\";\nimport { MERRAI_CLI_EXIT_CODES, classifyMerraiCliError } from \"./errors\";\nimport { createMerraiCommandContext, type MerraiCliRuntime } from \"./runtime\";\n\nconst CLI_VERSION = packageMetadata.version;\n\nconst parseFormat = (value: string): \"json\" | \"text\" => {\n if (value !== \"json\" && value !== \"text\") {\n throw new InvalidArgumentError(\"format must be json or text\");\n }\n return value;\n};\n\nexport const createMerraiProgram = (runtime: MerraiCliRuntime): Command => {\n const program = new Command();\n const context = createMerraiCommandContext(runtime);\n\n program\n .name(\"merrai\")\n .description(\"Store, recall, and ingest Merrai memories\")\n .version(CLI_VERSION)\n .option(\"--base-url <url>\", \"Merrai server base URL\")\n .option(\"--api-key <key>\", \"Merrai API key\")\n .option(\"--cookie <cookie>\", \"Session cookie fallback\")\n .option(\"--format <format>\", \"Output format: json or text\", parseFormat)\n .option(\"--json\", \"Alias for --format json\")\n .showHelpAfterError()\n .exitOverride()\n .configureOutput({\n writeErr: (value) => runtime.stderr.write(value),\n writeOut: (value) => runtime.stdout.write(value),\n });\n\n registerSystemCommands(program, context);\n registerMemoryCommands(program, context);\n registerEntityCommands(program, context);\n registerLivingDocumentCommands(program, context);\n registerLobeCommands(program, context);\n registerTopicCommands(program, context);\n registerIngestCommands(program, context);\n registerSourceCommands(program, context);\n registerAppCommands(program, context);\n registerIngestionCommands(program, context);\n registerDebugCommands(program, context);\n registerAuthCommands(program, context);\n\n return program;\n};\n\nexport const runMerraiCli = async (\n runtime: MerraiCliRuntime\n): Promise<number> => {\n const program = createMerraiProgram(runtime);\n if (runtime.argv.length === 0) {\n program.outputHelp();\n return MERRAI_CLI_EXIT_CODES.success;\n }\n\n try {\n await program.parseAsync([...runtime.argv], { from: \"user\" });\n return MERRAI_CLI_EXIT_CODES.success;\n } catch (error) {\n const result = classifyMerraiCliError(error);\n if (result.shouldRender) {\n runtime.stderr.write(\n result.message.endsWith(\"\\n\") ? result.message : `${result.message}\\n`\n );\n }\n return result.exitCode;\n }\n};\n","#!/usr/bin/env node\n\nimport { createMerraiThrowingClient } from \"./client\";\nimport { runMerraiCli } from \"./program\";\n\nconst exitCode = await runMerraiCli({\n argv: process.argv.slice(2),\n createClient: createMerraiThrowingClient,\n cwd: process.cwd(),\n env: process.env,\n stderr: process.stderr,\n stdin: process.stdin,\n stdout: process.stdout,\n});\n\nprocess.exitCode = exitCode;\n"],"mappings":";;;;;;;;;;;;AAi6CA,MAAa,kBAAkB,YAA6B;CAC1D,MAAM,WAAW,SAAS,KAAK;CAE/B,IAAI,aAAa,KAAA,KAAa,aAAa,IACzC,MAAM,IAAI,MACR,4EACF;CAGF,OAAO,SAAS,SAAS,GAAG,IAAI,SAAS,MAAM,GAAG,EAAE,IAAI;AAC1D;AAEA,MAAM,kBACJ,SACA,QACA,WAC2B;CAC3B,MAAM,kBAAkB,IAAI,QAAQ,OAAO;CAG3C,gBAAgB,IAAI,2BAA2B,OAAO;CAEtD,IAAI,WAAW,KAAA,KAAa,WAAW,IACrC,gBAAgB,IAAI,aAAa,MAAM;CAGzC,IAAI,WAAW,KAAA,KAAa,WAAW,IACrC,gBAAgB,IAAI,UAAU,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