/** * @fileoverview Obsidian Local REST API service. Wraps every upstream HTTP * endpoint we use, builds the right URL/headers/body for the consolidated * `target` discriminator, and classifies errors for the framework. * @module services/obsidian/obsidian-service */ import type { Context } from '@cyanheads/mcp-ts-core'; import { type Dispatcher, type RequestInit, fetch as undiciFetch } from 'undici'; import { type ServerConfig } from '../../config/server-config.js'; import { PathPolicy } from './path-policy.js'; import type { DocumentMap, FileListing, NoteJson, NoteTarget, ObsidianCommand, ObsidianTag, OmnisearchHit, PatchInstruction, PathTarget, StructuredSearchHit, TextSearchHit, VaultStatus } from './types.js'; type UndiciResponse = Awaited>; /** * The HTTP fetch contract this service depends on. Defaults to undici's * `fetch`; tests inject a stub here instead of mocking the `undici` module * (Bun's runtime treats `undici` as a builtin, so `vi.mock('undici')` has no * effect under `bunx vitest`). * * `tls` is Bun's per-request TLS option. It is absent from undici's own * `RequestInit`, and declared here because the two runtimes read the * relaxation off different places — see `#tlsInit`. */ export type ObsidianFetch = (url: string, init: RequestInit & { dispatcher?: Dispatcher; signal?: AbortSignal; tls?: { rejectUnauthorized: boolean; }; }) => Promise; /** A text hit with its match locations capped at `maxMatchesPerHit`; a capped hit carries `truncated` and `totalMatches`. */ type ClippedTextHit = TextSearchHit & { totalMatches?: number; truncated?: boolean; }; export declare class ObsidianService { #private; /** * @param config - Validated server config (api key, base URL, TLS, timeouts). * @param fetchImpl - Optional fetch override for tests. Defaults to undici's * `fetch`, which honors the constructed TLS dispatcher in production. */ constructor(config: ServerConfig, fetchImpl?: ObsidianFetch); /** Path-policy accessor for tools that filter results or check scope themselves. */ get policy(): PathPolicy; /** Resolved Omnisearch URL (derived from baseUrl or OBSIDIAN_OMNISEARCH_URL override). */ get omnisearchUrl(): string; /** * Close the undici dispatcher, releasing its keep-alive sockets to the Local * REST API and Omnisearch, after rejecting the note-body reads still queued. * Wired through `createApp({ teardown })`; waits for in-flight requests to * settle rather than aborting them. * * Bun resolves `undici` to a built-in shim whose `Agent` is an inert object * with no `close` — Bun's `fetch` pools sockets itself and ignores the * dispatcher — so there is nothing to release there. */ close(): Promise; /** * The plugin's root capability report: reachability, versions, manifest, and * the registered API extensions. * * Sent authenticated. `GET /` never 401s — it answers `200` either way and * self-reports `authenticated`, which is a direct string comparison against * the configured key upstream — so the misconfigured-key case still returns * the full reachability payload with `authenticated: false` rather than * throwing. `apiExtensions` appears only on the authenticated response, * which is why the request carries the key at all. */ getStatus(ctx: Context): Promise; getNoteContent(ctx: Context, target: NoteTarget): Promise; getNoteJson(ctx: Context, target: NoteTarget): Promise; /** * Pin `target` to the note it names right now. A path target comes back as * sent; an `active` or `periodic` target is resolved upstream (read-gated) * and comes back as a path target for that note, so every later call acts on * the same file however the target moves in between. */ resolveTarget(ctx: Context, target: NoteTarget): Promise; /** * `target` as a path target for `path`, the note a read of `target` returned. * A path target already names its note and comes back as sent. A pinned * `active` / `periodic` target carries the target's label as `resolvedFrom`, * the identifier `no_active_file` and `periodic_not_found` use, so a * `path_forbidden` denial on it names the target rather than the note. */ pinTarget(target: NoteTarget, path: string): PathTarget; /** * The note's headings, block ids, and frontmatter field names. An `active` / * `periodic` target is resolved once (read-gated, a denial named by the * target's label) and the map read from the resolved `/vault/` path, which * the plugin's `/active/` and `/periodic/…` routes delegate to anyway, so the * map describes the note the resolution returned even if the target moves. */ getDocumentMap(ctx: Context, target: NoteTarget): Promise; writeNote(ctx: Context, target: NoteTarget, content: string, contentType?: 'markdown' | 'json'): Promise; appendToNote(ctx: Context, target: NoteTarget, content: string, contentType?: 'markdown' | 'json'): Promise; /** * Apply a section-targeted PATCH in the markdown-patch format the plugin * speaks: a 2.0 JSON instruction on Local REST API 5.x and later, 1.x * request headers on 4.x and for the table-row writes 2.0 cannot express * (`#wireFormat`). Returns the section locator the edit was actually * applied to — identical to `instruction.target` unless a bare heading leaf * was expanded to its full `Parent::Child` path (see `#resolveHeadingTarget`), * which callers echo back so an agent can see where the write landed. * * A heading write placed by a heading the note has is checked against the * note's link definitions first (`#refuseDroppedDefinition`). Every step * that needs the note's text shares one read of it: the one * `#headingIndex` made, or else one made on first need. */ patchNote(ctx: Context, target: NoteTarget, content: string, instruction: PatchInstruction): Promise; deleteNote(ctx: Context, target: NoteTarget): Promise; /** * Byte size of a note at `target`, derived from the HEAD `Content-Length` * header. Returns `null` on 404 — distinct from a 0-byte file. * * Source-of-truth rule for note byte sizes across mutating tools: * 1. HEAD `Content-Length` (this method) — when no GET is in flight. * 2. `Buffer.byteLength(deliveredContent)` — when a GET happens anyway (free). * 3. `note.stat.size` from the JSON envelope — REJECTED: shares the upstream * `getAbstractFileByPath` cache path with the rest of the envelope, so it * can't act as an independent cross-check (cache-desync scenario in * coddingtonbear/obsidian-local-rest-api#237). Always prefer delivered * bytes or HEAD over the metadata field. * * One attempt, never retried (HEAD is not in `RETRY_SAFE_METHODS`; a 404 is * the answer, not a transient failure), and gates readable on path targets * before issuing the HEAD. */ tryGetSize(ctx: Context, target: NoteTarget): Promise; /** * Like `tryGetSize`, but throws `note_missing` on 404 — for verification * reads that come *after* a write where the file is expected to exist. */ getSize(ctx: Context, target: NoteTarget): Promise; listFiles(ctx: Context, dirPath?: string): Promise; /** * Vault tags with usage counts, hierarchical parents included. Unscoped, the * plugin's `/tags/` with its occurrence counts. That payload carries no * per-note attribution, so under OBSIDIAN_READ_PATHS or OBSIDIAN_DENY_PATHS * the tags are read from the readable notes' contexts instead (one upstream * search, no bodies), and each one counts the readable notes carrying it or a * tag nested under it. */ listTags(ctx: Context): Promise; listCommands(ctx: Context): Promise; /** * Text search. Each upstream span gets its `context` offsets resolved * (`contextRelativeSpan`), then a multi-token query's spans are merged into * match locations (`mergeIntoLocations`). * * The upstream serializes every match in the vault, its context window and * about 150 characters of offsets and framing, into one response, so a * broad query exhausts V8's string capacity, even at a small * `contextLength`, and comes back as an opaque 500 — caught * here and re-thrown typed, the way `searchOmnisearch` re-throws its own * reachability failure. Under OBSIDIAN_READ_PATHS or OBSIDIAN_DENY_PATHS * that would make the outcome depend on notes outside the scope, so the * search runs here instead (`#searchTextScoped`). */ searchText(ctx: Context, query: string, contextLength?: number): Promise; /** * JSONLogic search. Unscoped, the tree goes to the plugin unchanged. Under * OBSIDIAN_READ_PATHS or OBSIDIAN_DENY_PATHS (`restrictsReads`) the plugin * would evaluate it against every note in the vault, denied ones included, * so the tree stays here instead: the readable notes' contexts * are fetched and the tree is evaluated over those alone * (`createJsonLogicEvaluation`), the way the plugin evaluates it. No hit, * result, or error then reads a note outside the read scope. The contexts * carry no `links`, `backlinks`, or `unresolvedLinks`, since which note a * link resolves to depends on notes outside the scope; a tree that names * one fails before any request (`assertNoLinkFields`). * * The plugin hands a tree note bodies only when its JSON holds the string * `"content"` (`readsContent`); such a tree gets them here too, one read * per readable note, evaluated in batches of at most `CONTENT_BATCH_BYTES` * so a broad scope never holds every readable body at once. Every request * the search makes shares `ctx.signal` and one deadline, * `SCOPED_SEARCH_DEADLINE_MS`; past it the search fails with * `logic_too_costly`. */ searchJsonLogic(ctx: Context, logic: Record): Promise; /** * A JSONLogic search for a caller paging through its hits, whose page this * call serves ends at index `pageEnd`. Unscoped, it is `searchJsonLogic`. * Under a read scope a call without `walk` evaluates fresh and, when the * hits run past `pageEnd`, so a later page will read them, stores the full * ordered hit list under a new walk id, returned as `walk`; * a call naming that id with the same tree is served from the stored list * without evaluating. The store belongs to this service, whose read scope * is fixed at construction, so a list is only read under the scope that * produced it. Anything else — an expired, evicted, or unknown id, a text * walk's id, or a different tree — evaluates fresh, and a call cancelled * before it answers stores nothing. */ pageJsonLogic(ctx: Context, logic: Record, walk: string | undefined, pageEnd: number): Promise<{ hits: StructuredSearchHit[]; walk?: string; }>; /** * A text search for a caller paging through its hits, whose page this call * serves ends at index `pageEnd`: each hit's match locations capped at * `maxMatchesPerHit`, and only the hits whose filename starts with * `pathPrefix` when one is given. Unscoped, every page runs `searchText`. * Under a read scope a call without `walk` searches fresh and, when the * prefixed hits run past `pageEnd`, so a later page will read them, stores * the capped hits, unprefixed, under a new walk id, returned as * `walk`. A call naming that id with the same `query`, `contextLength`, and * `maxMatchesPerHit` is served from the stored hits with no request, its own * `pathPrefix` applied to them; the scope is fixed for this service, so it * is no part of the key. Anything else — an expired, evicted, or unknown * id, a JSONLogic walk's id, or a changed input — searches fresh, and a * call cancelled before it answers stores nothing. */ pageText(ctx: Context, search: { contextLength: number; maxMatchesPerHit: number; pathPrefix?: string | undefined; query: string; }, walk: string | undefined, pageEnd: number): Promise<{ hits: ClippedTextHit[]; walk?: string; }>; /** * One-shot startup probe for the Omnisearch plugin's HTTP endpoint. Returns * `true` only when the response is `HTTP 200`, declares `application/json`, * and the body parses as a JSON array — unrouted paths on the Omnisearch * server also return `200` with an empty body, so status alone is * insufficient. `omnisearchAvailability` calls it, and only when reads are * unscoped, to decide between the `offered` and `unreachable` states of the * `omnisearch` mode. */ probeOmnisearch(signal?: AbortSignal): Promise; /** * Query the Omnisearch HTTP endpoint. Normalizes the response on the way * out: decodes HTML entities + `
` → `\n` in `excerpt`, renames `path` * to `filename`, and drops `vault`. Throws `omnisearch_unreachable` * (ServiceUnavailable) on network failures, on a query that outlasts * `OBSIDIAN_REQUEST_TIMEOUT_MS`, and on non-2xx responses — the plugin can * shut down mid-session (Obsidian quits, plugin disabled), and the tool * needs a distinct signal from the upstream's success cases. One attempt, * the body read under the same timer as the fetch. */ searchOmnisearch(ctx: Context, query: string): Promise; executeCommand(ctx: Context, commandId: string): Promise; /** * Open a file in the Obsidian UI. * * Obsidian materializes the file when the path does not exist, so the call * is only a read when the caller has established that the file is already * there. `createIfMissing` marks the create-capable variant and gates it as * a write, which is what makes `OBSIDIAN_READ_ONLY` and * `OBSIDIAN_WRITE_PATHS` constrain it — the creation happens inside Obsidian * and never passes through any other write check. */ openInUi(ctx: Context, path: string, opts?: { newLeaf?: boolean; createIfMissing?: boolean; }): Promise; } /** * `path` less its leading and trailing `/` runs, as `/^\/+|\/+$/g` leaves it, * found by scanning in from each end: the regex retries at every `/` of a run * inside the path, in time quadratic in the run. */ export declare function trimSlashes(path: string): string; /** * Encode a vault-relative path for the URL. Splits on `/` and `\` (so * Windows-style separators are honored), URL-encodes each segment, and * rejoins with `/` since the Local REST API plugin expects forward slashes. * * Rejects `.` and `..` segments here rather than relying on the upstream Local * REST API plugin to normalize them — with `OBSIDIAN_READ_PATHS` unset, * `PathPolicy` allows every path no deny prefix covers, and `..` is * unreserved per RFC 3986 so * `encodeURIComponent` leaves it intact. This is the single chokepoint before * URL construction, so guard vault escape here. Backslash is treated as a * separator so `..\..\etc` traverses identically to `../../etc` and can't * sneak past as a single opaque segment. */ export declare function encodeVaultPath(path: string): string; export declare function initObsidianService(config?: ServerConfig, fetchImpl?: ObsidianFetch): void; /** Test-only: directly install an instance (e.g., one backed by a stub fetch). */ export declare function setObsidianService(service: ObsidianService | undefined): void; export declare function getObsidianService(): ObsidianService; export {}; //# sourceMappingURL=obsidian-service.d.ts.map