import type { BlogOperation } from './blog.js'; import type { EmailAttachmentContent, EmailComposeInput, EmailDraftInput, EmailForwardInput, EmailListInput, EmailMailbox, EmailMessage, EmailMessagePage, EmailMessageSummary, EmailReplyInput, } from './email.js'; import type { ActorDirectoryInput, ActorDirectoryPage, ActorProfile, ActorProfileInput, } from './actor-directory.js'; import type { NotificationInput as HpNotificationInput, NotificationPage as HpNotificationPage, } from './notifications.js'; import type { ReactionSetInput as HpReactionSetInput, ReactionSummary as HpReactionSummary, ReplyCreateInput as HpReplyCreateInput, ReplyDeleteInput as HpReplyDeleteInput, ReplyRecord as HpReplyRecord, ThreadInput as HpThreadInput, ThreadPage as HpThreadPage, } from './participation.js'; import type { BookmarkInput, BookmarkPage } from './bookmarks.js'; import type { SearchInput, SearchPage } from './search.js'; import type { OverrideTaskDecisionInput } from './types.js'; import type { ActorRef, AddressableActor } from './policy.js'; import { actorSchema } from './schemas.js'; import { errorCodes, SynomemError, type SynomemErrorCode } from './errors.js'; import type { SynomemService, SynomemServiceCapabilities, SynomemServiceInfo } from './service.js'; import type { ActorIdentity, ChangesInput, BindRuntimeInput, CreateAgentInput, CreatePostInput, UpdatePostInput, CreateNoteInput, CreateTaskInput, GiveKudosInput, ItemListInput, KudosListInput, ReviseNoteInput, SendMemoInput, UpdateAgentInput, UpdateTaskInput, UpdateTodoInput, CreateTodoInput, CreateTopicInput, UpdateTopicInput, TopicListInput, } from './types.js'; const defaultMaximumResponseBytes = 1024 * 1024; const defaultTimeoutMs = 15_000; export interface SynomemCredentialProvider { getAccessToken(signal?: AbortSignal): Promise; } /** * Where a remote service gets its bearer: an OAuth access token or a `syn_` access key * (identity contract §6.1). It may refresh; it must never be logged. */ export interface RemoteCredentialSource { bearer(): Promise; } export type RemoteCredential = RemoteCredentialSource | SynomemCredentialProvider | (() => Promise); export interface RemoteSynomemOptions { baseUrl: string; /** The workspace in the route. Must equal the selected context's workspace. */ workspaceId: string; /** * The stable target this service acts as. Sent as `Synomem-Context-Id` on every request. * Omit only for a fixed credential, whose single pinned context the API selects itself. */ contextId?: string; credential: RemoteCredential; fetch?: typeof fetch; signal?: AbortSignal; timeoutMs?: number; maximumResponseBytes?: number; } /** Normalizes any accepted credential shape into one bearer lookup. */ export function bearerFrom( credential: RemoteCredential, ): (signal?: AbortSignal) => Promise { if (typeof credential === 'function') return () => credential(); if ('bearer' in credential) return () => credential.bearer(); return (signal) => credential.getAccessToken(signal); } interface ApiErrorEnvelope { ok: false; error: { code: string; message: string; details?: Record; requestId?: string }; } interface ApiSuccessEnvelope { ok: true; data: T; requestId?: string; } function remoteBaseUrl(value: string): URL { let parsed: URL; try { parsed = new URL(value); } catch { throw new SynomemError('CONFIG_INVALID', 'Remote Synomem baseUrl must be an absolute URL.'); } const loopback = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '[::1]'; if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)) { throw new SynomemError( 'CONFIG_INVALID', 'Remote Synomem requires HTTPS except for explicit loopback development URLs.', ); } if ( parsed.username || parsed.password || parsed.search || parsed.hash || parsed.pathname !== '/' ) { throw new SynomemError( 'CONFIG_INVALID', 'Remote Synomem baseUrl cannot contain credentials, paths, query parameters, or fragments.', ); } return new URL(parsed.href.endsWith('/') ? parsed.href : `${parsed.href}/`); } function queryString(input: object): string { const parameters = new URLSearchParams(); for (const [key, value] of Object.entries(input)) { if (value === undefined) continue; if (Array.isArray(value)) { for (const item of value) parameters.append(key, String(item)); } else { parameters.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value)); } } const encoded = parameters.toString(); return encoded ? `?${encoded}` : ''; } /** Codes a caller must be able to branch on, never collapsed into AUTH_* by status. */ const contextCodes = new Set([ 'CONTEXT_REQUIRED', 'CONTEXT_FORBIDDEN', 'CONTEXT_AMBIGUOUS', 'REAUTHORIZATION_REQUIRED', ]); function knownErrorCode(value: string): SynomemErrorCode { return errorCodes.some((code) => code === value) ? (value as SynomemErrorCode) : 'REMOTE_PROTOCOL'; } async function boundedResponseBytes(response: Response, maximumBytes: number): Promise { if (!response.body) return new Uint8Array(); const reader = response.body.getReader() as unknown as { read(): Promise<{ done: boolean; value?: Uint8Array }>; cancel(): Promise; }; const chunks: Uint8Array[] = []; let length = 0; while (true) { const { done, value } = await reader.read(); if (done) break; if (!value) { throw new SynomemError('REMOTE_PROTOCOL', 'Remote response stream was malformed.'); } length += value.byteLength; if (length > maximumBytes) { await reader.cancel(); throw new SynomemError('REMOTE_PROTOCOL', 'Remote response exceeded the configured limit.'); } chunks.push(value); } const bytes = new Uint8Array(length); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } return bytes; } export function environmentCredentialProvider( env: NodeJS.ProcessEnv = process.env, ): SynomemCredentialProvider { return { async getAccessToken() { return env.SYNOMEM_ACCESS_TOKEN; }, }; } export class RemoteSynomemService implements SynomemService { /** * The actor this service acts as, learned from the server during `init()` — never asserted * by the caller. Before `init()` it is a placeholder that no request uses. */ actor: ActorIdentity = { kind: 'system', id: 'unbound' }; readonly contextId?: string; private readonly baseUrl: URL; private readonly workspaceId: string; private readonly bearer: (signal?: AbortSignal) => Promise; private readonly fetchImplementation: typeof fetch; private readonly signal?: AbortSignal; private readonly timeoutMs: number; private readonly maximumResponseBytes: number; private initialized = false; private cachedCapabilities?: SynomemServiceCapabilities; readonly bookmarks = { list: (input: BookmarkInput = {}) => this.request('GET', `bookmarks${queryString(input)}`), has: (rootId: string) => this.request<{ saved: boolean }>('GET', `items/${encodeURIComponent(rootId)}/bookmark`), set: (input: { rootId: string; present: boolean }) => this.request<{ saved: boolean }>( input.present ? 'PUT' : 'DELETE', `items/${encodeURIComponent(input.rootId)}/bookmark`, {}, ), }; readonly notifications = { list: (input: HpNotificationInput = {}) => this.request('GET', `inbox${queryString(input)}`), read: async (id: string) => { await this.request('POST', `inbox/${encodeURIComponent(id)}/read`, {}); }, dismiss: async (id: string) => { await this.request('POST', `inbox/${encodeURIComponent(id)}/dismiss`, {}); }, readThrough: async (through: string) => { await this.request('POST', 'inbox/read', { through }); }, }; readonly replies = { changes: (input: HpThreadInput) => this.request('GET', `replies/changes${queryString(input)}`), create: (input: HpReplyCreateInput) => this.request( 'POST', `items/${encodeURIComponent(input.rootId)}/replies`, input, ), get: (id: string) => this.request('GET', `replies/${encodeURIComponent(id)}`), delete: (input: HpReplyDeleteInput) => this.request('DELETE', `replies/${encodeURIComponent(input.replyId)}`, input), }; readonly threads = { read: async (input: { rootId: string; through: string }) => { await this.request('PUT', `items/${encodeURIComponent(input.rootId)}/thread/read`, { through: input.through, }); }, get: (input: HpThreadInput) => this.request( 'GET', `items/${encodeURIComponent(input.rootId)}/thread${queryString({ after: input.after, limit: input.limit })}`, ), subscription: (input: { rootId: string; following: boolean; muted: boolean }) => this.request( 'PUT', `items/${encodeURIComponent(input.rootId)}/thread/subscription`, input, ), }; readonly reactions = { set: (input: HpReactionSetInput) => this.request( input.present ? 'PUT' : 'DELETE', `reactions/${encodeURIComponent(input.targetId)}/${input.code}`, input, ), get: (targetId: string) => this.request('GET', `reactions/${encodeURIComponent(targetId)}`), }; readonly actors = { profile: (input: ActorProfileInput) => this.request( 'GET', `actor-directory/${input.target.kind}/${encodeURIComponent(input.target.id)}/profile${queryString({ after: input.after, limit: input.limit })}`, ), list: (input: ActorDirectoryInput = {}) => this.request('GET', `actor-directory${queryString(input)}`), get: (ref: ActorRef) => this.request( 'GET', `actor-directory/${ref.kind}/${encodeURIComponent(ref.id)}`, ), registerHuman: async (_input: { id: string; handle: string; displayName: string; }): Promise => { void _input; throw new SynomemError( 'MUTATION_FORBIDDEN', 'Hosted human identities are provisioned through workspace membership.', ); }, }; readonly agents = { create: (input: CreateAgentInput) => this.request>>( 'POST', 'agents', input, ), update: (id: string, changes: UpdateAgentInput) => this.request>>( 'PATCH', `agents/${encodeURIComponent(id)}`, changes, ), get: (idOrAlias: string) => this.request>>( 'GET', `agents/${encodeURIComponent(idOrAlias)}`, ), list: () => this.request>>('GET', 'agents'), resolve: (query: string) => this.request>>( 'GET', `agents/resolve?query=${encodeURIComponent(query)}`, ), archive: (idOrAlias: string) => this.mutation>>( 'POST', `agents/${encodeURIComponent(idOrAlias)}/archive`, {}, ), restore: (idOrAlias: string) => this.mutation>>( 'POST', `agents/${encodeURIComponent(idOrAlias)}/restore`, {}, ), addAliases: (idOrAlias: string, aliases: string[]) => this.mutation>>( 'POST', `agents/${encodeURIComponent(idOrAlias)}/aliases`, { aliases }, ), removeAliases: (idOrAlias: string, aliases: string[]) => this.mutation>>( 'POST', `agents/${encodeURIComponent(idOrAlias)}/aliases/remove`, { aliases }, ), directory: () => this.request>>( 'GET', 'agents/directory', ), bindings: (idOrAlias: string) => this.request>>( 'GET', `agents/${encodeURIComponent(idOrAlias)}/runtimes`, ), bindRuntime: (input: BindRuntimeInput) => this.mutation>>( 'POST', `agents/${encodeURIComponent(input.agentId)}/runtimes`, input, ), unbindRuntime: (bindingId: string) => this.request>>( 'DELETE', `agents/runtimes/${encodeURIComponent(bindingId)}`, ), }; readonly topics = { create: (input: CreateTopicInput) => this.mutation>>( 'POST', 'topics', input, ), update: (idOrAlias: string, changes: UpdateTopicInput) => this.mutation>>( 'PATCH', `topics/${encodeURIComponent(idOrAlias)}`, changes, ), get: (idOrAlias: string) => this.request>>( 'GET', `topics/${encodeURIComponent(idOrAlias)}`, ), list: (input: TopicListInput = {}) => this.request>>( 'GET', `topics${queryString(input)}`, ), resolve: (query: string) => this.request>>( 'GET', `topics/resolve?query=${encodeURIComponent(query)}`, ), archive: (idOrAlias: string) => this.mutation>>( 'POST', `topics/${encodeURIComponent(idOrAlias)}/archive`, {}, ), restore: (idOrAlias: string) => this.mutation>>( 'POST', `topics/${encodeURIComponent(idOrAlias)}/restore`, {}, ), }; readonly posts = { create: (input: CreatePostInput) => this.mutation>>('POST', 'posts', input), list: (input: Omit = {}) => this.request>>( 'GET', `posts${queryString(input)}`, ), get: (id: string) => this.request>>( 'GET', `posts/${encodeURIComponent(id)}`, ), update: (input: UpdatePostInput) => this.mutation>>( 'POST', `posts/${encodeURIComponent(input.postId)}/revisions`, input, ['postId'], ), archive: (input: { expectedVersion: number; postId: string; reason?: string; idempotencyKey?: string; }) => this.mutation>>( 'POST', `posts/${encodeURIComponent(input.postId)}/archive`, input, ['postId'], ), acknowledge: (input: { expectedVersion: number; postId: string; note?: string; idempotencyKey?: string; }) => this.mutation>>( 'POST', `posts/${encodeURIComponent(input.postId)}/acknowledgment`, input, ['postId'], ), withdrawAcknowledgment: (input: { expectedVersion: number; postId: string; reason?: string; idempotencyKey?: string; }) => this.mutation>>( 'DELETE', `posts/${encodeURIComponent(input.postId)}/acknowledgment`, input, ['postId'], ), roster: (postId: string) => this.request>>( 'GET', `posts/${encodeURIComponent(postId)}/roster`, ), }; readonly kudos = { give: (input: GiveKudosInput) => this.mutation>>('POST', 'kudos', input), list: (input: KudosListInput = {}) => this.request>>( 'GET', `kudos${queryString(input)}`, ), changes: (input: ChangesInput = {}) => this.request>>( 'GET', `kudos/changes${queryString(input)}`, ), get: (id: string) => this.request>>( 'GET', `kudos/${encodeURIComponent(id)}`, ), acknowledge: (input: { expectedVersion: number; kudosId: string; note?: string; idempotencyKey?: string; }) => this.mutation>>( 'POST', `kudos/${encodeURIComponent(input.kudosId)}/acknowledgment`, input, ['kudosId'], ), revoke: (input: { expectedVersion: number; kudosId: string; reason: string; administrative?: boolean; idempotencyKey?: string; }) => this.mutation>>( 'POST', `kudos/${encodeURIComponent(input.kudosId)}/revocation`, input, ['kudosId', 'administrative'], ), }; /** * Hosted email for the bound agent's own mailbox. There is no local equivalent: a mailbox * needs the hosted mail edge, so this exists only on the remote service. */ readonly blog = { call: (operation: BlogOperation, input: Record = {}) => { const { idempotencyKey, ...data } = input; return this.request>( 'POST', 'blog/call', { operation, input: data }, typeof idempotencyKey === 'string' ? idempotencyKey : undefined, ); }, }; readonly email = { mailbox: () => this.request('GET', 'email/mailbox'), list: (input: EmailListInput = {}) => this.request('GET', `email/messages${queryString(input)}`), get: (input: { messageId: string; includeHtml?: boolean; markSeen?: boolean }) => this.request( 'GET', `email/messages/${encodeURIComponent(input.messageId)}${queryString({ includeHtml: input.includeHtml, markSeen: input.markSeen, })}`, ), thread: (threadId: string) => this.request<{ threadId: string; messages: EmailMessage[] }>( 'GET', `email/threads/${encodeURIComponent(threadId)}`, ), attachment: (input: { messageId: string; index: number }) => this.request( 'GET', `email/messages/${encodeURIComponent(input.messageId)}/attachments/${input.index}`, undefined, undefined, // Attachments arrive base64-encoded; allow up to the API's 10 MiB fetch limit. 16 * 1024 * 1024, ), send: (input: EmailComposeInput) => this.mutation('POST', 'email/send', input), reply: (input: EmailReplyInput) => this.mutation( 'POST', `email/messages/${encodeURIComponent(input.messageId)}/reply`, input, ['messageId'], ), forward: (input: EmailForwardInput) => this.mutation( 'POST', `email/messages/${encodeURIComponent(input.messageId)}/forward`, input, ['messageId'], ), saveDraft: (input: EmailDraftInput) => input.draftId ? this.mutation( 'PATCH', `email/drafts/${encodeURIComponent(input.draftId)}`, input, ['draftId'], ) : this.mutation('POST', 'email/drafts', input, ['draftId']), sendDraft: (draftId: string) => this.mutation('POST', `email/drafts/${encodeURIComponent(draftId)}/send`, {}), move: (input: { messageId: string; folder: 'inbox' | 'spam' | 'archive' | 'trash' }) => this.mutation( 'POST', `email/messages/${encodeURIComponent(input.messageId)}/move`, input, ['messageId'], ), mark: (input: { messageId: string; seen?: boolean; flagged?: boolean }) => this.mutation( 'POST', `email/messages/${encodeURIComponent(input.messageId)}/flags`, input, ['messageId'], ), delete: (messageId: string) => this.mutation<{ id: string; deleted: boolean; folder?: string }>( 'DELETE', `email/messages/${encodeURIComponent(messageId)}`, {}, ), audit: (input: { limit?: number; cursor?: string } = {}) => this.request<{ entries: Record[]; nextCursor?: string }>( 'GET', `email/audit${queryString(input)}`, ), }; readonly memos = { send: (input: SendMemoInput) => this.mutation>>('POST', 'memos', input), list: (input: Omit = {}) => this.request>>( 'GET', `memos${queryString(input)}`, ), get: (id: string) => this.request>>( 'GET', `memos/${encodeURIComponent(id)}`, ), read: (input: { expectedVersion: number; memoId: string; idempotencyKey?: string }) => this.mutation>>( 'POST', `memos/${encodeURIComponent(input.memoId)}/read`, input, ['memoId'], ), archive: (input: { expectedVersion: number; memoId: string; idempotencyKey?: string }) => this.mutation>>( 'POST', `memos/${encodeURIComponent(input.memoId)}/archive`, input, ['memoId'], ), }; readonly notes = { create: (input: CreateNoteInput) => this.mutation>>('POST', 'notes', input), list: (input: Omit = {}) => this.request>>( 'GET', `notes${queryString(input)}`, ), get: (id: string) => this.request>>( 'GET', `notes/${encodeURIComponent(id)}`, ), revise: (input: ReviseNoteInput) => this.mutation>>( 'POST', `notes/${encodeURIComponent(input.noteId)}/revisions`, input, ['noteId'], ), archive: (input: { expectedVersion: number; noteId: string; idempotencyKey?: string }) => this.mutation>>( 'POST', `notes/${encodeURIComponent(input.noteId)}/archive`, input, ['noteId'], ), }; readonly tasks = { overrideDecision: (input: OverrideTaskDecisionInput) => this.taskTransition('override', input), create: (input: CreateTaskInput) => this.mutation>>('POST', 'tasks', input), list: (input: Omit = {}) => this.request>>( 'GET', `tasks${queryString(input)}`, ), get: (id: string) => this.request>>( 'GET', `tasks/${encodeURIComponent(id)}`, ), update: (input: UpdateTaskInput) => this.mutation>>( 'POST', `tasks/${encodeURIComponent(input.taskId)}/revisions`, input, ['taskId'], ), accept: (input: { expectedVersion: number; taskId: string; response?: string; idempotencyKey?: string; }) => this.taskTransition('accept', input), reject: (input: { expectedVersion: number; taskId: string; response: string; idempotencyKey?: string; }) => this.taskTransition('reject', input), complete: (input: { expectedVersion: number; taskId: string; note?: string; idempotencyKey?: string; }) => this.taskTransition('complete', input), reopen: (input: { expectedVersion: number; taskId: string; idempotencyKey?: string }) => this.taskTransition('reopen', input), cancel: (input: { expectedVersion: number; taskId: string; reason?: string; idempotencyKey?: string; }) => this.taskTransition('cancel', input), }; /** * Private self-reminders. The remote surface mirrors the local one exactly so * a caller does not have to know which backend it is talking to. */ readonly todos = { create: (input: CreateTodoInput) => this.mutation>>('POST', 'todos', input), list: (input: Omit = {}) => this.request>>( 'GET', `todos${queryString(input)}`, ), get: (id: string) => this.request>>( 'GET', `todos/${encodeURIComponent(id)}`, ), update: (input: UpdateTodoInput) => this.mutation>>( 'POST', `todos/${encodeURIComponent(input.todoId)}/revisions`, input, ['todoId'], ), complete: (input: { expectedVersion: number; todoId: string; note?: string; idempotencyKey?: string; }) => this.todoTransition('complete', input), reopen: (input: { expectedVersion: number; todoId: string; idempotencyKey?: string }) => this.todoTransition('reopen', input), cancel: (input: { expectedVersion: number; todoId: string; reason?: string; idempotencyKey?: string; }) => this.todoTransition('cancel', input), archive: (input: { expectedVersion: number; todoId: string; idempotencyKey?: string }) => this.todoTransition('archive', input), }; /** * Discovery mirrors the local semantics: the age/deadline is resolved here so * both backends answer the same question, rather than each server deciding * what "older than 24 hours" means. */ readonly discovery = { unanswered: ( input: Omit & { olderThanHours?: number } = {}, ) => { const { olderThanHours, awaitingSince, ...rest } = input; const since = awaitingSince ?? (olderThanHours !== undefined ? new Date(Date.now() - olderThanHours * 3_600_000).toISOString() : undefined); return this.request>>( 'GET', `items${queryString({ ...rest, awaitingResponse: true, ...(since ? { awaitingSince: since } : {}) })}`, ); }, overdue: (input: Omit & { asOf?: string } = {}) => { const { asOf, ...rest } = input; return this.request>>( 'GET', `items${queryString({ ...rest, overdueAsOf: asOf ?? new Date().toISOString() })}`, ); }, }; async search(input: SearchInput): Promise { const capabilities = await this.capabilities(); if (!capabilities.participation?.search) throw new SynomemError('UNSUPPORTED_BACKEND', 'This workspace does not support search.'); return this.request('GET', `search${queryString(input)}`); } readonly items = { list: (input: ItemListInput = {}) => this.request>>( 'GET', `items${queryString(input)}`, ), get: (id: string) => this.request>>( 'GET', `items/${encodeURIComponent(id)}`, ), changes: (input: ChangesInput = {}) => this.request>>( 'GET', `changes${queryString(input)}`, ), }; constructor(options: RemoteSynomemOptions) { this.baseUrl = remoteBaseUrl(options.baseUrl); if (!options.workspaceId.trim() || options.workspaceId.length > 100) { throw new SynomemError('CONFIG_INVALID', 'Remote Synomem workspaceId is required.'); } this.workspaceId = options.workspaceId; if (options.contextId !== undefined) { if (!/^[A-Za-z0-9_-]{1,100}$/.test(options.contextId)) { throw new SynomemError('CONFIG_INVALID', 'Remote Synomem contextId is malformed.'); } this.contextId = options.contextId; } this.bearer = bearerFrom(options.credential); this.fetchImplementation = options.fetch ?? fetch; this.signal = options.signal; this.timeoutMs = options.timeoutMs ?? defaultTimeoutMs; this.maximumResponseBytes = options.maximumResponseBytes ?? defaultMaximumResponseBytes; if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs < 1) { throw new SynomemError('CONFIG_INVALID', 'Remote timeoutMs must be a positive integer.'); } if (!Number.isSafeInteger(this.maximumResponseBytes) || this.maximumResponseBytes < 1024) { throw new SynomemError( 'CONFIG_INVALID', 'Remote maximumResponseBytes must be an integer of at least 1024.', ); } } async init(): Promise { if (this.initialized) return; this.cachedCapabilities = await this.request( 'GET', '../../capabilities', ); if (this.cachedCapabilities.backend !== 'remote') { throw new SynomemError('REMOTE_PROTOCOL', 'The configured server is not a remote backend.'); } if (this.cachedCapabilities.participation?.version !== 2) throw new SynomemError( 'UNSUPPORTED_SCHEMA', 'This client requires the human participation v2 contract.', ); const binding = this.cachedCapabilities.binding; if (binding.workspaceId !== this.workspaceId) { throw new SynomemError( 'CONTEXT_FORBIDDEN', 'The selected Synomem context does not belong to the workspace this service addresses.', ); } if (this.contextId && binding.contextId && binding.contextId !== this.contextId) { throw new SynomemError('CONTEXT_FORBIDDEN', 'The server bound a different context.'); } const actor = actorSchema.safeParse(binding.actor); if (!actor.success) { throw new SynomemError('REMOTE_PROTOCOL', 'The server reported an invalid bound actor.'); } // The server decides who this is; the client only learns it (plan §5 rule 7). this.actor = actor.data; this.initialized = true; } async close(): Promise { this.initialized = false; } stats(input: KudosListInput = {}) { return this.request>>( 'GET', `kudos/stats${queryString(input)}`, ); } doctor() { return this.request>>('GET', 'diagnostics'); } async export(format: 'json' | 'jsonl' | 'markdown'): Promise { const result = await this.request<{ content: string }>( 'GET', `export${queryString({ format })}`, ); return result.content; } rebuild() { return this.request>>( 'POST', 'administration/rebuild', {}, ); } async capabilities(): Promise { await this.init(); return this.cachedCapabilities!; } async info(): Promise { return { backend: 'remote', baseUrl: this.baseUrl.href, workspaceId: this.workspaceId }; } getCanonicalEvent(id: string) { return this.request>>( 'GET', `events/${encodeURIComponent(id)}`, ); } private taskTransition( transition: 'accept' | 'reject' | 'complete' | 'reopen' | 'cancel' | 'override', input: { expectedVersion: number; taskId: string; idempotencyKey?: string; reason?: string; note?: string; response?: string; }, ) { return this.mutation>>( 'POST', `tasks/${encodeURIComponent(input.taskId)}/${transition}`, input, ['taskId'], ); } private todoTransition( transition: 'complete' | 'reopen' | 'cancel' | 'archive', input: { expectedVersion: number; todoId: string; idempotencyKey?: string; reason?: string; note?: string; }, ) { return this.mutation>>( 'POST', `todos/${encodeURIComponent(input.todoId)}/${transition}`, input, ['todoId'], ); } private mutation( method: 'POST' | 'PATCH' | 'DELETE', path: string, input: object, omittedKeys: string[] = [], ): Promise { const body = { ...input } as Record; const idempotencyKey = typeof body.idempotencyKey === 'string' ? body.idempotencyKey : undefined; delete body.idempotencyKey; for (const key of omittedKeys) delete body[key]; return this.request(method, path, body, idempotencyKey); } private async request( method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE', path: string, body?: object, idempotencyKey?: string, maximumResponseBytes = this.maximumResponseBytes, ): Promise { if (method !== 'GET') { await this.init(); if (!this.cachedCapabilities?.participation?.canWrite) throw new SynomemError('READ_ONLY', 'The selected binding has no write capability.'); } const accessToken = await this.bearer(this.signal); if (!accessToken) { throw new SynomemError('AUTH_REQUIRED', 'Remote Synomem authentication is required.'); } const workspaceBase = new URL( `v1/workspaces/${encodeURIComponent(this.workspaceId)}/`, this.baseUrl, ); const url = new URL(path, workspaceBase); if (url.origin !== this.baseUrl.origin) { throw new SynomemError('CONFIG_INVALID', 'Remote request escaped the configured origin.'); } const timeoutSignal = AbortSignal.timeout(this.timeoutMs); const signal = this.signal ? AbortSignal.any([this.signal, timeoutSignal]) : timeoutSignal; let response: Response; try { response = await this.fetchImplementation(url, { method, redirect: 'manual', signal, headers: { accept: 'application/json', authorization: `Bearer ${accessToken}`, // The ONLY selector (identity contract §3). The server authorizes it against the // credential's grant on every request; knowing an id grants nothing. ...(this.contextId ? { 'synomem-context-id': this.contextId } : {}), ...(body ? { 'content-type': 'application/json' } : {}), ...(idempotencyKey ? { 'idempotency-key': idempotencyKey } : {}), }, ...(body ? { body: JSON.stringify(body) } : {}), }); } catch (error) { if (this.signal?.aborted) throw error; throw new SynomemError('REMOTE_UNAVAILABLE', 'The remote Synomem service is unavailable.', { cause: error instanceof Error ? error.name : 'network_error', }); } if (response.status >= 300 && response.status < 400) { throw new SynomemError('REMOTE_PROTOCOL', 'Remote redirects are not followed.'); } const declaredLength = Number(response.headers.get('content-length') ?? 0); if (declaredLength > maximumResponseBytes) { throw new SynomemError('REMOTE_PROTOCOL', 'Remote response exceeded the configured limit.'); } const bytes = await boundedResponseBytes(response, maximumResponseBytes); let envelope: ApiSuccessEnvelope | ApiErrorEnvelope; try { envelope = JSON.parse(new TextDecoder().decode(bytes)) as ApiSuccessEnvelope | ApiErrorEnvelope; } catch { throw new SynomemError('REMOTE_PROTOCOL', 'Remote Synomem returned invalid JSON.'); } if (!response.ok || envelope.ok !== true) { if (envelope.ok !== false || !envelope.error || typeof envelope.error.message !== 'string') { throw new SynomemError('REMOTE_PROTOCOL', 'Remote Synomem returned an invalid error.'); } const reported = knownErrorCode(envelope.error.code); // Hosted email and publishing report their own refusals (an operator's grant, limits, a // missing mailbox) precisely: "ask your operator" is not "your credential is bad". const code = contextCodes.has(reported) || reported.startsWith('EMAIL_') || reported === 'POLICY_FORBIDDEN' ? reported : response.status === 401 ? 'AUTH_REQUIRED' : response.status === 403 ? 'AUTH_FORBIDDEN' : response.status === 429 ? 'RATE_LIMITED' : knownErrorCode(envelope.error.code); throw new SynomemError(code, envelope.error.message, { ...(envelope.error.details ?? {}), ...(envelope.error.requestId ? { requestId: envelope.error.requestId } : {}), }); } if (!('data' in envelope)) { throw new SynomemError('REMOTE_PROTOCOL', 'Remote Synomem response omitted data.'); } return envelope.data; } }