/** * The wire types, transcribed from the Zod schemas the API validates against. * * Transcribed rather than generated, because generation from the OpenAPI * document would give this package a build step and a code generator to keep * working, and the surface is small enough to read. The contract they mirror * is `apps/api/src/schemas/*.ts` - those objects both parse requests AND * validate responses on the way out, so a field that is not there cannot be * returned. * * Every optional field below is optional in the schema. That matters more than * it looks: `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` are on, * so a caller reading `memory.supersedes` is forced to handle its absence, and * an absent field is the normal case rather than a bug. * * Timestamps are ISO 8601 strings with an offset, never Date. JSON has no date * type, and every client that has guessed at a format has eventually guessed * wrong. */ export type MemoryType = "fact" | "preference" | "decision" | "task" | "commitment" | "event" | "relationship" | "goal" | "plan" | "project" | "instruction" | "constraint" | "observation" | "experience" | "knowledge" | "change" | "status" | "question" | "assumption"; export type MemoryState = "candidate" | "active" | "confirmed" | "uncertain" | "superseded" | "expired" | "archived" | "deleted"; export type SpaceKind = "user" | "system" | "temporary" | "project" | "organizational"; export type ConflictType = "value" | "temporal" | "identity" | "relationship" | "state" | "source"; export type ResolutionStrategy = "user-confirmation" | "explicit-correction" | "temporal-validity" | "higher-confidence" | "corroboration" | "newer-source" | "unresolved"; export type JobStatus = "queued" | "running" | "completed" | "failed" | "dead" | "cancelled"; export type DocumentStatus = "pending" | "processing" | "processed" | "empty" | "failed"; export type IntegrationStatus = "connected" | "reauth_required" | "syncing" | "error" | "disabled"; export type MessageRole = "user" | "assistant" | "system" | "tool"; /** Which memories an operation may see. */ export type Scope = "universal" | "space" | "combined"; /** * The envelope every list endpoint returns. * * `nextCursor` absent is the ONLY signal to stop. An empty `data` array is not * the same thing - a page can come back empty because everything in it was * filtered after the fetch while more pages remain, and a client that stops on * an empty page silently truncates the user's results. */ export interface Page { readonly data: readonly T[]; readonly pagination: { readonly nextCursor?: string; readonly limit: number; }; } export interface EntityRef { readonly id?: string; readonly name: string; readonly type: string; /** How sure we are this mention IS that entity, not merely a name match. */ readonly confidence?: number; } export interface EvidenceRef { readonly id: string; readonly sourceId?: string; readonly documentId?: string; /** The passage the claim rests on, so a user can check it. */ readonly excerpt: string; readonly observedAt?: string; } export interface SourceRef { readonly id: string; readonly provider: string; readonly type: string; readonly externalId?: string; } export interface Temporal { readonly validFrom?: string; readonly validUntil?: string; /** True while the claim is believed to hold. */ readonly current: boolean; } /** * Whoever owns a memory that is not yours. * * A name, never a user id: the API does not send one, and nothing here takes * one. `name` is absent when the account set neither a display name nor a * username, which is why `mine` below and not this is what says the memory * belongs to somebody else. */ export interface SharedBy { readonly name: string; } export interface Memory { readonly id: string; readonly type: MemoryType; readonly state: MemoryState; /** * Whether YOU own this memory. * * Not always true. A listing returns everything your key may see, and that * includes memories owned by people who shared a Space with you — filed in * the same Spaces you file into, so `spaceIds` will not tell them apart. * Anything that reads a memory back to a person, or puts one in a model's * context, has to carry this: an unmarked claim from a colleague is * indistinguishable from one of your own, and a model will state it in your * voice. */ readonly mine: boolean; /** Who it belongs to, when `mine` is false and the API can name them. */ readonly sharedBy?: SharedBy; readonly title: string; readonly content: string; readonly value?: Readonly>; /** 0 to 1, like every score in this API. */ readonly confidence: number; readonly importance: number; readonly entities: readonly EntityRef[]; readonly sources: readonly SourceRef[]; readonly evidence: readonly EvidenceRef[]; readonly temporal: Temporal; readonly spaceIds?: readonly string[]; readonly version: number; readonly supersedes?: string; readonly supersededBy?: string; readonly createdAt: string; readonly updatedAt: string; readonly lastConfirmedAt?: string; } export interface ListMemoriesParams { readonly limit?: number; readonly cursor?: string; readonly type?: MemoryType | readonly MemoryType[]; readonly state?: MemoryState | readonly MemoryState[]; readonly scope?: Scope; readonly spaceIds?: readonly string[]; readonly createdAfter?: string; readonly createdBefore?: string; readonly minConfidence?: number; /** Off by default: a list of memories almost always means "what is true now". */ readonly includeHistorical?: boolean; } /** * What `POST /remember` takes. * * `text`, not `content`. The route parses its own body and this is the name it * uses - the schema file next door describes a richer capture shape that this * endpoint does not implement, and sending `content` gets a 400 that names * `text` as required. */ export interface RememberParams { readonly text: string; readonly title?: string; /** * The Spaces this is filed into. REQUIRED BY THE SERVER, though optional * here. * * A capture with no Space is refused with a 400 that names this account's * Spaces. It used to be filed into the account's default, its oldest Space, * or a new one made for it — three destinations nobody chose — and none of * those exists now: a Space is chosen or nothing is kept. * * It stays optional in the TYPE so that a caller upgrading this package gets * the explanation from the server, in a sentence listing the Spaces they * actually have, rather than a compile error that says "required" and leaves * them looking for a list. Every call that omits it now fails at runtime; * that break is intended and is the whole change. */ readonly spaceIds?: readonly string[]; } /** * The answer, which is NOT a memory. * * `remember` hands material to the ingestion pipeline and returns 202. * Extraction, entity resolution, deduplication and conflict detection all run * afterwards, and may produce one memory, several, or none. Poll `jobId` * through `client.jobs.get` to find out which. */ export interface RememberResult { readonly status: string; readonly jobId: string; readonly note: string; } export interface SearchParams { readonly query: string; /** Capped at 50 by the server. Every result costs a rerank. */ readonly limit?: number; readonly scope?: Scope; readonly spaceIds?: readonly string[]; readonly types?: MemoryType | readonly MemoryType[]; readonly minScore?: number; /** As of a moment: what was believed true then, not what is true now. */ readonly asOf?: string; readonly includeHistorical?: boolean; readonly includeEvidence?: boolean; readonly explain?: boolean; } export interface SearchExplanation { /** Which retrieval paths found it: `vector`, `structured`, `graph`. */ readonly paths: readonly string[]; readonly vectorScore?: number; readonly structuredScore?: number; readonly rerankScore?: number; readonly adjustments?: readonly { readonly reason: string; readonly delta: number; }[]; } export interface SearchResult { readonly memory: Memory; readonly score: number; readonly explanation?: SearchExplanation; } export interface SearchResponse { readonly results: readonly SearchResult[]; /** * What the planner actually did. * * Worth reading. Search DEGRADES rather than fails: with embeddings down it * falls back to deterministic retrieval and still answers. A client that * ignores `degraded` reports "search is broken" when it is merely narrower, * and - worse - never reports it when it silently is. */ readonly diagnostics: { readonly steps: readonly string[]; readonly degraded: boolean; readonly unavailable?: readonly string[]; /** A sentence to show the user when a capability is deliberately stopped. */ readonly notice?: string; readonly tookMs: number; }; /** Echoed, so an empty result can be told from a mis-sent query. */ readonly query: string; } export interface ContextParams { readonly query: string; /** * The budget, in TOKENS, not rows. * * The real constraint on the caller's side: ten long memories overflow a * window that fifty short ones fit inside. */ readonly tokenBudget?: number; readonly scope?: Scope; readonly spaceIds?: readonly string[]; /** Ids the caller already has in the prompt, so they are not spent twice. */ readonly exclude?: readonly string[]; readonly asOf?: string; } export interface ContextResponse { /** Ready to paste into a prompt. */ readonly context: string; readonly memories: readonly { readonly id: string; readonly title: string; readonly score: number; }[]; readonly usedTokens: number; /** True when something relevant was left out for budget. */ readonly truncated: boolean; } export interface Space { readonly id: string; readonly name: string; readonly kind: SpaceKind; readonly description?: string; readonly parentId?: string; readonly audience?: string; readonly retentionDays?: number; readonly memoryCount?: number; readonly createdAt: string; /** Set when archived. An archived Space is hidden, not deleted. */ readonly archivedAt?: string; } /** * Where one context is filing, and whether anybody decided it. * * TWO FIELDS BECAUSE THEY ARE TWO FACTS, and merging them is the mistake this * shape exists to make impossible. `chosen` is a Space somebody picked here: it * narrows what a question is answered from as well as where a note lands. * `fallback` is the account's own default, adopted automatically for captures * that name none, and it narrows NOTHING — reading through it would silently * scope every question the person ever asked to a Space they never picked. * * Neither present means no Space can be named at all, which is a real state * rather than a gap: an account with no Spaces yet. */ export interface WorkingSpace { /** The context this answers about — `cli:default`, `email`. The server owns it. */ readonly scope: string; /** * The Space chosen for this context. * * ABSENT MEANS NOTHING IS KEPT from it, not "kept somewhere else". There * used to be a `fallback` beside this — the account-wide Space a capture * fell into when nobody chose — and it is gone with the setting itself: a * Space is chosen or the capture is refused. */ readonly chosen?: { readonly id: string; readonly name: string; }; } export interface CreateSpaceParams { readonly name: string; readonly description?: string; readonly kind?: SpaceKind; readonly parentId?: string; readonly retentionDays?: number; } export interface UpdateSpaceParams { readonly name?: string; readonly description?: string; readonly retentionDays?: number; /** Archiving and restoring, as a field rather than a verb endpoint. */ readonly archived?: boolean; } export interface ListSpacesParams { readonly limit?: number; readonly cursor?: string; readonly includeArchived?: boolean; } /** * What somebody you shared a Space with may do with it. * * A WIDENING SCALE: every role sees everything filed in the Space, and the * role decides only what they may do BESIDES read. `viewer` reads it, * `editor` also files new memories into it, `owner` can additionally share it * onward and revoke people - including you. */ export type SpaceRole = "viewer" | "editor" | "owner"; /** * A role that may actually be GRANTED, which is not every role. * * `owner` is real — the Space's owner holds it and a collaborator listing * shows it — but no request can hand it out. `POST /collaborators` and * `PATCH /collaborators/:id` both take `["viewer", "editor"]`, and the store * throws `CannotGrantOwnership` behind them, so a call carrying `owner` is * refused with a 400 every time. * * Separate from `SpaceRole` rather than narrowing it, because the two are * genuinely different questions: what a collaborator MAY BE is three values, * what you may SET them to is two. Typing the parameters as `SpaceRole` made * the compiler accept a call the server always rejects — a typed client whose * types are wrong about the server is worse than an untyped one, because the * error arrives at runtime after the type system said it was fine. */ export type GrantableSpaceRole = Exclude; /** * One person who has been given, or merely offered, sight of a Space. * * `acceptedAt` is the field to read before you render anything. An invitation * grants NOTHING until the recipient accepts, so a UI that shows an invited * person the same way it shows an accepted one tells its user that somebody is * reading their memories when nobody is - and read the other way, hides that * an invitation never landed. */ export interface SpaceCollaborator { readonly email: string; readonly name?: string; readonly role: SpaceRole; readonly invitedBy?: string; readonly invitedAt?: string; /** Absent means they have accepted nothing and can see nothing. */ readonly acceptedAt?: string; } export interface ShareSpaceParams { /** The person to offer the Space to, by address. */ readonly email: string; /** See `GrantableSpaceRole` — `owner` cannot be given away. */ readonly role: GrantableSpaceRole; } export interface Source { readonly id: string; readonly provider: string; readonly type: string; readonly externalId?: string; readonly label?: string; readonly documentCount?: number; readonly lastIngestedAt?: string; readonly createdAt: string; } export interface ListSourcesParams { readonly limit?: number; readonly cursor?: string; readonly provider?: string; } export interface Document { readonly id: string; readonly sourceId: string; readonly contentType: string; /** Which normaliser handled it - `text`, `pdf`, `email`, `transcript`. */ readonly plugin: string; readonly status: DocumentStatus; readonly title?: string; readonly bytes?: number; readonly memoryCount?: number; /** Present only when `failed`, and sanitised - never a provider stack. */ readonly error?: string; readonly createdAt: string; readonly processedAt?: string; } export interface ListDocumentsParams { readonly limit?: number; readonly cursor?: string; readonly sourceId?: string; readonly status?: DocumentStatus | readonly DocumentStatus[]; } /** Detail reads return normalized content; the listing returns Document summaries. */ export interface DocumentDetail { readonly id: string; readonly content: unknown; /** Absent on older servers. Counts describe retained results across document versions. */ readonly outcome?: { readonly readState: "waiting_for_text" | "pending" | "complete" | "unknown"; readonly memoryCount: number; readonly memories: readonly { readonly id: string; readonly title: string; }[]; readonly retainedCandidateCount: number; readonly pendingCandidateCount: number; readonly extractedAt?: string; }; } export interface Job { readonly id: string; readonly type: string; readonly status: JobStatus; readonly subjectId?: string; readonly documentId?: string; readonly attempts: number; /** Sanitised. A provider's raw message can carry user content. */ readonly error?: string; /** 0 to 1 when the job can report it. Absent is normal, not a bug. */ readonly progress?: number; readonly queuedAt: string; readonly startedAt?: string; readonly finishedAt?: string; } export interface ListJobsParams { readonly limit?: number; readonly cursor?: string; readonly status?: JobStatus | readonly JobStatus[]; readonly type?: string; } export type ScanRecoveryStatus = "waiting" | "scheduled" | "due" | "window_ending" | "exhausted" | "expired" | "blocked" | "completed" | "superseded"; export type ScanRecoveryReason = "space_unavailable" | "capture_changed"; /** Recovery dispatches are not job attempts and do not establish processing completion. */ export type ScanRecovery = { readonly dispatches: number; readonly maxDispatches: 4; readonly automaticUntil: string; } & ({ readonly status: "waiting" | "scheduled" | "due"; readonly nextAttemptAt?: string; readonly reason?: ScanRecoveryReason; } | { readonly status: "blocked"; readonly reason: ScanRecoveryReason; readonly nextAttemptAt?: never; } | { readonly status: "window_ending" | "exhausted" | "expired" | "completed" | "superseded"; readonly reason?: ScanRecoveryReason; readonly nextAttemptAt?: never; }); /** Public scan metadata only. A scan can exist before a document or an actual job. */ export interface ScanRecoveryEntry { readonly id: string; readonly filename?: string; readonly createdAt: string; readonly documentId?: string; readonly job?: { readonly id: string; readonly status: JobStatus; }; readonly recovery: ScanRecovery; } export interface ScanRecoveryParams { /** One bounded page, 1–100; defaults to 20. */ readonly limit?: number; /** Defaults to open. All also includes retained terminal entries. */ readonly state?: "open" | "all"; /** Opaque base64url token of 1–256 characters, from pagination.nextCursor. */ readonly cursor?: string; } /** Returned once. Pass nextCursor explicitly to jobs.scans to read another page. */ export interface ScanRecoveryPage { readonly data: readonly ScanRecoveryEntry[]; readonly pagination: { readonly limit: number; readonly nextCursor?: string; }; } /** A failed capture and the server's current assessment of whether it can be replayed. */ export interface DeadJob { readonly jobId: string; readonly kind: string; readonly reason: string; readonly attempts: number; readonly failure: { readonly code?: string; readonly retryable?: boolean; }; readonly failedAt: string; readonly replay: { readonly available: boolean; readonly requiresForce: boolean; readonly reason?: string; readonly documentId?: string; }; } export interface DeadJobsParams { /** One page only; an integer from 1 to 100. Defaults to 20. */ readonly limit?: number; /** Job kind, 1–60 characters. */ readonly type?: string; } /** This endpoint has no cursor or automatic pagination. */ export interface DeadJobsPage { readonly data: readonly DeadJob[]; readonly pagination: { readonly limit: number; }; } export interface ReplayJobParams { /** Explicitly acknowledge a replay requiring force. The server still checks eligibility. */ readonly force?: boolean; } /** Queue acknowledgement only; use jobs.get(jobId) to check processing. */ export interface ReplayJobResult { readonly status: "replayed" | "already-queued"; readonly jobId: string; readonly kind: string; readonly warning?: string; } export interface Entity { readonly id: string; readonly name: string; readonly type: string; /** Other names the same thing goes by. */ readonly aliases: readonly string[]; readonly memoryCount?: number; readonly firstSeenAt?: string; readonly lastSeenAt?: string; readonly createdAt: string; } export interface ListEntitiesParams { readonly limit?: number; readonly cursor?: string; readonly type?: string; /** Prefix match on name or alias, for a picker. */ readonly q?: string; } export interface EntityMention { readonly memoryId: string; readonly role?: string; readonly confidence?: number; } export interface EntityMemoriesParams { readonly limit?: number; readonly cursor?: string; /** Subject, mention, participant. Two different questions. */ readonly role?: string; readonly minConfidence?: number; } export interface Relationship { readonly id: string; /** `works_at`, `uses`, `depends_on`, `other`. */ readonly predicate: string; readonly label?: string; readonly subject: { readonly id?: string; readonly name: string; readonly type: string; }; readonly object: { readonly id?: string; readonly name: string; readonly type: string; }; readonly confidence: number; readonly observedAt: string; } export interface GraphNode { readonly id: string; readonly name: string; readonly kind: string; /** Hops from the starting entity, so a client can lay the graph out. */ readonly distance: number; } /** * Walking the graph. * * `from` is an ENTITY id. Edges run between entities, not between memories, * and the walk reports the memories the edges were extracted from. */ export interface TraverseParams { readonly from: string; /** 1 to 4. Depth explodes exponentially, which is why it is bounded. */ readonly depth?: number; readonly maxNodes?: number; readonly memoryLimit?: number; } export interface GraphResponse { readonly nodes: readonly GraphNode[]; readonly edges: readonly Relationship[]; readonly memoryIds: readonly string[]; /** True when a bound stopped the walk. Silence would read as "this is all". */ readonly truncated: boolean; } export interface Conflict { readonly id: string; readonly type: ConflictType; readonly description?: string; readonly confidence: number; /** Both sides in full: a person cannot choose between two ids. */ readonly a: Memory; readonly b: Memory; readonly detectedAt: string; readonly resolution?: { readonly strategy: ResolutionStrategy; readonly winnerId?: string; readonly reason: string; readonly resolvedAt: string; }; } export interface ListConflictsParams { readonly limit?: number; readonly cursor?: string; /** Off by default: the list exists to be worked through. */ readonly includeResolved?: boolean; readonly type?: ConflictType | readonly ConflictType[]; } /** * Settling a conflict. * * `keep` names the winner and SUPERSEDES the other; it does not delete it. The * losing claim was true once, and a system that erases it cannot answer "what * did I think last month". */ export type ResolveConflictParams = { readonly action: "keep"; readonly keepId: string; readonly reason?: string; } | { readonly action: "dismiss"; readonly reason?: string; }; export interface Message { readonly id: string; readonly role: MessageRole; readonly content: string; /** Memories surfaced into this turn, for citation. */ readonly memoryIds?: readonly string[]; readonly createdAt: string; } export interface Conversation { readonly id: string; readonly title?: string; /** Which client this belongs to - `web`, `mcp`, an SDK's own label. */ readonly channel?: string; readonly spaceIds?: readonly string[]; readonly messageCount: number; readonly createdAt: string; readonly updatedAt: string; } export interface CreateConversationParams { readonly title?: string; readonly channel?: string; readonly spaceIds?: readonly string[]; } export interface ListConversationsParams { readonly limit?: number; readonly cursor?: string; readonly channel?: string; } export interface AppendMessagesParams { readonly messages: readonly { readonly role: MessageRole; readonly content: string; readonly createdAt?: string; }[]; /** On by default - that is the point of sending them. */ readonly extract?: boolean; } export interface AppendMessagesResult { readonly messages: readonly Message[]; /** * Whether extraction was actually queued. * * Reported honestly: with no queue configured the turns are stored and never * become memory, and `note` says so. A caller that ignores this believes a * memory is on its way that never arrives. */ readonly extracting: boolean; readonly note?: string; } export interface Integration { readonly id: string; readonly provider: string; readonly status: IntegrationStatus; /** Which account, so a user with two can tell them apart. Never a token. */ readonly accountLabel?: string; readonly scopes?: readonly string[]; readonly spaceIds?: readonly string[]; readonly lastSyncedAt?: string; /** Sanitised, and shown to the user - so it reads as an instruction. */ readonly error?: string; readonly createdAt: string; } export interface ListIntegrationsParams { readonly limit?: number; readonly cursor?: string; readonly provider?: string; readonly status?: IntegrationStatus; } export interface ConnectIntegrationParams { readonly provider: string; /** Where to land afterwards. Checked against an allow-list server-side. */ readonly returnTo?: string; readonly spaceIds?: readonly string[]; } export interface ConnectIntegrationResult { /** Send the user here. This endpoint never takes third-party credentials. */ readonly authorizeUrl: string; readonly state: string; readonly expiresAt: string; } export interface UpdateIntegrationParams { readonly enabled?: boolean; readonly spaceIds?: readonly string[]; } /** A file asked of one of the caller's own machines. */ export interface AgentRequest { readonly id: string; /** The requester. The answer lands in their chat, whichever machine answered. */ readonly userId?: string; /** The Space the request was raised in, when it was raised from inside one. */ readonly spaceId?: string; readonly surface: string; readonly kind: string; /** The path that was asked for, on the machine that was asked. */ readonly path: string; readonly status: string; /** * An opaque storage key, and deliberately not a URL. * * Nothing outside the server can do anything with it. Call `downloadLink` * for something that opens. */ readonly resultKey?: string; readonly resultBytes?: string; readonly resultType?: string; readonly error?: string; readonly createdAt: string; readonly completedAt?: string; /** Who said yes: the requester, or the owner of the machine it ran on. */ readonly approvedBy?: string; } /** A Space's requests, newest first. */ export interface AgentRequestList { readonly items: readonly AgentRequest[]; } /** What sharing or withdrawing a machine came to, in a sentence for the person. */ export interface MachineShareResult { readonly ok: boolean; readonly note: string; } export interface AgentDownloadLink { /** * A bearer credential for one file, in URL form. Short-lived. * * Do not log it, store it, or hand it anywhere the file itself would not be * safe: whoever holds this URL holds the bytes until it expires. */ readonly downloadUrl: string; readonly method: "GET"; readonly filename: string; readonly contentType: string; readonly sizeBytes?: number; readonly expiresInSeconds: number; } export interface HealthResponse { readonly status: string; readonly [key: string]: unknown; } export interface DriveFile { readonly id: string; readonly name: string; readonly mimeType: string; readonly size?: number; readonly modifiedTime?: string; readonly link?: string; readonly owner?: string; /** True for Docs, Sheets and Slides, which have no bytes of their own. */ readonly native: boolean; } export interface SearchDriveParams { readonly query?: string; readonly limit?: number; } export interface SaveToDriveParams { readonly name: string; readonly bytes: Uint8Array; readonly contentType?: string; readonly folderId?: string; } export interface MailSummary { readonly id: string; readonly threadId?: string; readonly from?: string; readonly to?: string; readonly subject?: string; readonly date?: string; /** Gmail's own one-line preview. Never the whole body. */ readonly snippet?: string; readonly unread: boolean; readonly hasAttachments: boolean; } export interface MailAttachment { readonly id: string; readonly filename: string; readonly mimeType: string; readonly size?: number; } export interface MailMessage extends MailSummary { readonly body: string; /** Named, not fetched. Use `downloadAttachment` for the bytes. */ readonly attachments: readonly MailAttachment[]; } export interface SearchMailParams { /** Gmail search syntax: `from:priya`, `has:attachment`, `newer_than:7d`. */ readonly query?: string; readonly limit?: number; } export interface Person { readonly id: string; readonly name?: string; readonly emails: readonly string[]; readonly phones: readonly string[]; readonly organisation?: string; }