{"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,eAAe,QAAQ,SAAS,QAAQ,QAAQ,QAAQ,OAAO;EACjE,KAAK,GAAG,eAAe,QAAQ,QAAQ,CAAC;EACzC,CAAC,CAE2B;;AAO/B,MAAa,8BACX,UAA+B,EAAE,KAGjC,sBAAsB,QAAQ;;;;;;;;AE3pBhC,MAAa,0BAA0B;AACvC,MAAM,sBAAsB;AAuB5B,MAAM,WAAW,UAAkD;CACjE,MAAM,SAAS,OAAO,MAAM;AAC5B,QAAO,WAAW,UAAa,OAA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