@getbourdon/participants 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,398 @@
1
+ import { L5ManifestModel, SessionModel } from '@getbourdon/l5';
2
+ export { EntityModel, L5ManifestModel, SessionModel, Visibility, VisibilityPolicyModel, applyVisibility, filterForFederation, toDict, validateManifest } from '@getbourdon/l5';
3
+ import DatabaseT from 'better-sqlite3';
4
+
5
+ /**
6
+ * Bourdon participant base — the Protocol → TS interface, errors, and the
7
+ * AgentStore / HealthStatus types. Faithful port of `participants/base.py`.
8
+ *
9
+ * The L5 dataclass model (AgentInfo/Entity/Session/VisibilityPolicy/L5Manifest),
10
+ * the `toDict` omission rules, and the visibility helpers all live in
11
+ * `@getbourdon/l5` and are reused verbatim — only THAT output shape is the parity
12
+ * contract. This module owns the participant CONTRACT surface around them.
13
+ *
14
+ * Contract semantics (enforced by every reader, asserted by the conformance
15
+ * fixtures, never by trust):
16
+ * 1. visibility filter BEFORE emission (`filterForFederation`) — private wins.
17
+ * 2. deterministic / idempotent `exportL5` — same store → identical `toDict`.
18
+ * 3. `healthCheck` NEVER throws — catch-all → degraded/blocked.
19
+ * 4. every native string through `@getbourdon/redaction` before it enters L5.
20
+ */
21
+
22
+ /** Tied to Bourdon spec v0.1 — same literals as the Python oracle. */
23
+ declare const CONTRACT_VERSION = "0.1";
24
+ declare const SPEC_VERSION = "0.1";
25
+ /** Base class for participant errors. */
26
+ declare class ParticipantError extends Error {
27
+ constructor(message?: string);
28
+ }
29
+ /** Raised by `discover()` when the native store cannot be found or read.
30
+ * Non-fatal: L6 skips this agent rather than aborting the whole export. */
31
+ declare class ParticipantDiscoveryError extends ParticipantError {
32
+ }
33
+ /** Raised by `exportL5()` / `exportSessions()` when an export fails mid-op
34
+ * (the store WAS present — distinct from a discovery miss). */
35
+ declare class ParticipantExportError extends ParticipantError {
36
+ }
37
+ /** Raised when the native store's version is outside the supported range.
38
+ * Subtype of discovery error (a version mismatch is a discovery-time miss). */
39
+ declare class ParticipantVersionMismatchError extends ParticipantDiscoveryError {
40
+ }
41
+ /** Metadata describing the native agent store. Returned by `discover()`. */
42
+ interface AgentStore {
43
+ path: string;
44
+ version: string;
45
+ metadata: Record<string, unknown>;
46
+ }
47
+ /** Returned by `healthCheck()`. Consumed by the `bourdon doctor` CLI. */
48
+ interface HealthStatus {
49
+ status: "ok" | "degraded" | "blocked";
50
+ reason?: string;
51
+ details: Record<string, unknown>;
52
+ /** A human-runnable command to remedy a non-ok status. */
53
+ proposedFix?: string;
54
+ }
55
+ /**
56
+ * Structural interface every participant must satisfy (the Python
57
+ * `@runtime_checkable Protocol`). Duck-typed at registration: a class is a
58
+ * participant iff it has `agentId` + `agentType` + `exportL5` + `healthCheck`.
59
+ *
60
+ * Optional members (`displayName`, a `defaultNativePath` static) are documented
61
+ * here as in the Python Protocol; discovery + the setup wizard fall back to
62
+ * sensible defaults when absent.
63
+ */
64
+ interface BourdonParticipant {
65
+ agentId: string;
66
+ agentType: string;
67
+ nativePath: string;
68
+ /** Human-friendly label (e.g. "GitHub Copilot"). Optional. */
69
+ displayName?: string;
70
+ /** Confirm the native store exists; return metadata. Throws
71
+ * {@link ParticipantDiscoveryError} when missing/unreadable. */
72
+ discover(): AgentStore;
73
+ /** Build the L5 manifest from native memory, applying the visibility filter
74
+ * BEFORE return. Deterministic — same store yields the same manifest. */
75
+ exportL5(since?: Date): L5ManifestModel;
76
+ /** Export recent sessions in normalized schema. */
77
+ exportSessions(since?: Date, limit?: number): SessionModel[];
78
+ /** Return ok / degraded / blocked with a reason. MUST NOT throw. */
79
+ healthCheck(): HealthStatus;
80
+ }
81
+ /**
82
+ * Tiny structural guard mirroring Python's `_PARTICIPANT_MARKER_ATTRS`
83
+ * duck-type: a value is a participant iff it carries the four marker members.
84
+ */
85
+ declare function isParticipant(obj: unknown): obj is BourdonParticipant;
86
+
87
+ /**
88
+ * Shared read-only SQLite + normalization helpers — port of
89
+ * `participants/_sqlite_base.py`.
90
+ *
91
+ * A SQLite-backed participant (hermes today; cursor/copilot_cli in the follow-on
92
+ * slice) reads a foreign agent's native DB read-only so a live writer's lock can
93
+ * never block the export, probes the schema defensively (native schemas drift
94
+ * across versions), and turns epoch timestamps + paths into the L5 shapes.
95
+ *
96
+ * `better-sqlite3` is a NATIVE addon. It is loaded lazily through `createRequire`
97
+ * inside a try/catch so this package — and the file/network readers — keep
98
+ * working even on a toolchain where the addon failed to build: in that case
99
+ * {@link sqliteAvailable} returns false and the sqlite readers degrade rather
100
+ * than crashing import. Nothing here applies visibility or builds manifests;
101
+ * that stays in the participant (per PARTICIPANT_CONTRACT.md).
102
+ */
103
+
104
+ /** A better-sqlite3 connection (re-exported type alias for reader signatures). */
105
+ type SqliteDatabase = DatabaseT.Database;
106
+ /** True when the better-sqlite3 native addon loaded successfully. Tests gate
107
+ * the SQLite-reader assertions on this so a missing addon skips, not fails. */
108
+ declare function sqliteAvailable(): boolean;
109
+ interface OpenReadonlyOptions {
110
+ /** `immutable=1`: skip locks + ignore the WAL. Only for genuinely static
111
+ * snapshots; against a live writer it risks stale reads / SQLITE_CORRUPT. */
112
+ immutable?: boolean;
113
+ /** SQLite busy-timeout in milliseconds (Python's `timeout=2.0` seconds). */
114
+ timeoutMs?: number;
115
+ }
116
+ /**
117
+ * Open a SQLite DB read-only so a live writer is never disturbed. The default
118
+ * (`immutable` omitted) is the safe `mode=ro`: it respects SQLite locking and
119
+ * reads the `-wal` sidecar of a live, actively-writing agent. Raises on a
120
+ * genuine open failure; callers wanting the never-raises contract use
121
+ * {@link tryOpenReadonly}.
122
+ */
123
+ declare function openReadonly(dbPath: string, opts?: OpenReadonlyOptions): SqliteDatabase;
124
+ /**
125
+ * Like {@link openReadonly} but returns null instead of raising — for the
126
+ * export/health path where a missing or corrupt DB must degrade to "no rows".
127
+ */
128
+ declare function tryOpenReadonly(dbPath: string, opts?: OpenReadonlyOptions): SqliteDatabase | null;
129
+ /** True if `name` is a table in the connected DB (swallows errors → false). */
130
+ declare function tableExists(db: SqliteDatabase, name: string): boolean;
131
+ /** Column names for `table` (empty set if absent / on error). PRAGMA cannot be
132
+ * parameterized, matching the Python f-string. */
133
+ declare function tableColumns(db: SqliteDatabase, table: string): Set<string>;
134
+ /**
135
+ * Convert epoch seconds (number/string) to an ISO `YYYY-MM-DD` UTC date, or
136
+ * null for missing/unparseable values. Mirrors `epoch_to_iso_date`.
137
+ */
138
+ declare function epochToIsoDate(value: unknown): string | null;
139
+ /**
140
+ * Convert epoch seconds to a full ISO 8601 UTC datetime, or null. The offset is
141
+ * rendered `+00:00` (Python `datetime(...).isoformat()` style) rather than `Z`.
142
+ */
143
+ declare function epochToIsoDatetime(value: unknown): string | null;
144
+ /**
145
+ * Derive a lowercase project key from a working-directory path: the basename
146
+ * lowercased, or null when the cwd is empty or its basename is "generic"
147
+ * (carries no project identity). Mirrors `project_key_from_cwd`.
148
+ */
149
+ declare function projectKeyFromCwd(cwd: string | null | undefined, genericNames?: ReadonlySet<string>): string | null;
150
+ /** Turn a slug-ish key (`my-cool_project`) into a Title Case label. */
151
+ declare function friendlyLabel(key: string): string;
152
+
153
+ /**
154
+ * Network-shaped participant base — port of `participants/_network_base.py`
155
+ * (v0.3 adapter contract). Same `exportL5` / `exportSessions` half as a file
156
+ * participant; only the discovery half differs (fetch from an authenticated
157
+ * API). The base provides the three guarantees so adapters don't reimplement:
158
+ *
159
+ * 1. Local TTL cache under `~/.cache/bourdon/<slug>/payload.json` storing ONLY
160
+ * `{fetched_at, payload}` — NEVER the token. A cache hit = zero network.
161
+ * 2. Graceful degradation: network down → serve the most recent cached payload
162
+ * (even expired) and report `degraded` (not silence).
163
+ * 3. Auth boundary: an injected lazy {@link AuthProvider} (env / keychain).
164
+ * An invalid token (401/403 non-ratelimit) ALWAYS propagates as `blocked`
165
+ * and is NEVER masked by stale cache; a missing token serves stale when a
166
+ * cache exists, else blocks; rate-limit degrades.
167
+ *
168
+ * A subclass sets `participantSlug` / `agentId` / `agentType` (+ `nativePath`)
169
+ * and implements `fetchPayload(token)` + `payloadToL5(payload)` (pure, no I/O).
170
+ */
171
+
172
+ declare const NETWORK_CONTRACT_VERSION = "0.3";
173
+ /** Default cache TTL — adapters override via `cacheTtlSeconds`. */
174
+ declare const DEFAULT_CACHE_TTL_SECONDS: number;
175
+ /** Transport failure / timeout / 5xx / rate-limit — recoverable via cache fallback. */
176
+ declare class NetworkUnavailable extends ParticipantError {
177
+ }
178
+ /** 401/403 / missing credential — NOT recoverable via cache. The user must fix
179
+ * auth; surfaced as `blocked`, never silently served from stale cache (stale
180
+ * data would mask a broken token indefinitely). */
181
+ declare class ParticipantAuthError extends ParticipantError {
182
+ }
183
+ /** A zero-arg callable returning the token string, or null if no credential is
184
+ * available. Kept a callable (not a bare string) so the token is fetched lazily
185
+ * at call time and never sits in the participant's fields or the cache. */
186
+ type AuthProvider = () => string | null;
187
+ /** Auth provider that reads a token from an environment variable. */
188
+ declare function envAuthProvider(varName: string): AuthProvider;
189
+ /** `$XDG_CACHE_HOME/bourdon` or `~/.cache/bourdon`. */
190
+ declare function defaultCacheRoot(): string;
191
+ /** A cached payload + the wall-clock time it was fetched (epoch seconds). */
192
+ declare class CacheEntry {
193
+ readonly fetchedAt: number;
194
+ readonly payload: Record<string, unknown>;
195
+ constructor(fetchedAt: number, payload: Record<string, unknown>);
196
+ get ageSeconds(): number;
197
+ isFresh(ttlSeconds: number): boolean;
198
+ }
199
+ /**
200
+ * A tiny JSON file cache, one file per participant slug. Stores only
201
+ * `{fetched_at, payload}` — never the auth token. Read/write are best-effort: a
202
+ * corrupt or unwritable cache degrades to "no cache", never raises.
203
+ */
204
+ declare class PayloadCache {
205
+ readonly slug: string;
206
+ readonly root: string;
207
+ readonly path: string;
208
+ constructor(slug: string, rootDir?: string);
209
+ read(): CacheEntry | null;
210
+ write(payload: Record<string, unknown>): void;
211
+ }
212
+ interface NetworkParticipantOptions {
213
+ authProvider?: AuthProvider | null;
214
+ cacheRoot?: string;
215
+ }
216
+ /**
217
+ * Base for participants whose native state lives behind an authenticated API.
218
+ * Caching, degradation, the auth boundary, and the
219
+ * `discover`/`exportL5`/`exportSessions`/`healthCheck` plumbing live here;
220
+ * subclasses provide only `fetchPayload` + `payloadToL5`.
221
+ */
222
+ declare abstract class NetworkParticipant implements BourdonParticipant {
223
+ participantSlug: string;
224
+ agentId: string;
225
+ agentType: string;
226
+ cacheTtlSeconds: number;
227
+ nativePath: string;
228
+ protected readonly authProvider: AuthProvider | null;
229
+ private readonly cacheRoot?;
230
+ private cacheInstance?;
231
+ constructor(opts?: NetworkParticipantOptions);
232
+ /** Lazily built so it reads the SUBCLASS's `participantSlug` — subclass field
233
+ * initializers run after `super()`, so building the cache in the constructor
234
+ * would capture the base "network" slug instead. */
235
+ protected get cache(): PayloadCache;
236
+ /** Do the authenticated API call; return a JSON-serializable dict. Raise
237
+ * {@link NetworkUnavailable} on transport/5xx/rate-limit (→ cache fallback) or
238
+ * {@link ParticipantAuthError} on 401/403 (→ blocked, no fallback). */
239
+ abstract fetchPayload(token: string): Record<string, unknown>;
240
+ /** Normalize a (fresh or cached) payload into an L5 manifest. Pure, no I/O. */
241
+ abstract payloadToL5(payload: Record<string, unknown>): L5ManifestModel;
242
+ /**
243
+ * Resolve (payload, source) where source is 'cache' | 'network' | 'stale-cache'.
244
+ * 1. Fresh cache hit → 'cache' (no network)
245
+ * 2. Miss/expired + token → 'network' (fetch + refresh cache)
246
+ * 3. Net fails + any cache → 'stale-cache' (serve last good payload)
247
+ * 4. Net fails + no cache → raise
248
+ * Auth errors are never swallowed — they propagate so health surfaces
249
+ * 'blocked' rather than serving stale data behind a dead token.
250
+ */
251
+ protected getPayload(): {
252
+ payload: Record<string, unknown>;
253
+ source: string;
254
+ };
255
+ discover(): AgentStore;
256
+ exportL5(_since?: Date): L5ManifestModel;
257
+ exportSessions(since?: Date, limit?: number): SessionModel[];
258
+ healthCheck(): HealthStatus;
259
+ }
260
+
261
+ /**
262
+ * Hermes participant — normalize Hermes Agent (Nous Research) memory + sessions
263
+ * into L5. Port of `participants/hermes.py`.
264
+ *
265
+ * Reads two surfaces under `~/.hermes/` (override `$HERMES_HOME`):
266
+ * * `state.db` — a SQLite store (`sessions` + `messages` tables). Recent
267
+ * non-archived sessions + project entities (from cwd basename) come from it.
268
+ * * `memories/{memory.md,user.md}` — durable cross-session facts (one
269
+ * Markdown bullet/line per memory). The highest-signal entities.
270
+ *
271
+ * Read-only (`mode=ro`), deterministic, visibility-enforced-before-emission,
272
+ * and redaction on every native string. `healthCheck` never throws; `discover`
273
+ * raises only {@link ParticipantDiscoveryError}.
274
+ */
275
+
276
+ /** External participant for local Hermes Agent memory + sessions. */
277
+ declare class HermesParticipant implements BourdonParticipant {
278
+ agentId: string;
279
+ agentType: string;
280
+ displayName: string;
281
+ nativePath: string;
282
+ private readonly home;
283
+ static defaultNativePath(home?: string): string;
284
+ /** `hermesHome` is the `.hermes` directory itself (matching the Python ctor). */
285
+ constructor(hermesHome?: string);
286
+ private sources;
287
+ discover(): AgentStore;
288
+ exportSessions(since?: Date, limit?: number): SessionModel[];
289
+ exportL5(since?: Date): L5ManifestModel;
290
+ healthCheck(): HealthStatus;
291
+ }
292
+
293
+ /**
294
+ * Claude Code participant — reads claude-brain + auto-memory + MCP knowledge
295
+ * graph. Port of `participants/claude_code.py`.
296
+ *
297
+ * Three optional sources (the participant degrades gracefully):
298
+ * 1. claude-brain/ — git-synced markdown records
299
+ * 2. ~/.claude/projects/<ws>/memory/ — per-machine auto-memory frontmatter
300
+ * 3. ~/claude-memory/memory.jsonl — MCP knowledge-graph JSONL
301
+ *
302
+ * Privacy: entities typed `person` (+ family/contact variants) and observations
303
+ * containing credential-like strings default to PRIVATE and are filtered before
304
+ * federation. Entities are deduped by case-insensitive name and sorted
305
+ * alphabetically.
306
+ */
307
+
308
+ /** External participant for Anthropic's Claude Code CLI. */
309
+ declare class ClaudeCodeParticipant implements BourdonParticipant {
310
+ agentId: string;
311
+ agentType: string;
312
+ nativePath: string;
313
+ /** Public so a hermetic test can seed the discovered sources directly (path
314
+ * RESOLUTION is not the parity contract — only the export output shape is). */
315
+ brainPath: string | null;
316
+ autoMemoryPath: string | null;
317
+ knowledgeGraphPath: string | null;
318
+ static defaultNativePath(home?: string): string;
319
+ constructor();
320
+ discover(): AgentStore;
321
+ exportL5(since?: Date): L5ManifestModel;
322
+ exportSessions(since?: Date, limit?: number): SessionModel[];
323
+ healthCheck(): HealthStatus;
324
+ }
325
+
326
+ /**
327
+ * GitHub-embedded Copilot participant — the v0.3 network-adapter reference.
328
+ * Port of `participants/github_copilot.py`.
329
+ *
330
+ * Cloud-side Copilot (PR review, `@copilot` comments) persists nothing on the
331
+ * user's machine — its state lives on github.com. This adapter federates it by
332
+ * reading the user's GitHub activity over the REST API. The
333
+ * {@link NetworkParticipant} base provides the cache, degradation, and auth
334
+ * boundary; this class provides only the GitHub-specific fetch + payload→L5.
335
+ *
336
+ * Auth: a token with `repo` + `read:user` scope, sourced from `$GITHUB_TOKEN` /
337
+ * `$GH_TOKEN`, else `gh auth token`. Fetched lazily; never stored in the cache
338
+ * or the manifest.
339
+ */
340
+
341
+ /** Resolve a GitHub token: env var first, then the `gh` CLI keychain. */
342
+ declare function ghTokenProvider(): string | null;
343
+ /** Federates cloud-side GitHub Copilot activity via the GitHub REST API. */
344
+ declare class GitHubCopilotParticipant extends NetworkParticipant {
345
+ participantSlug: string;
346
+ agentId: string;
347
+ agentType: string;
348
+ nativePath: string;
349
+ displayName: string;
350
+ private readonly maxResults;
351
+ constructor(opts?: NetworkParticipantOptions & {
352
+ maxResults?: number;
353
+ });
354
+ static defaultNativePath(): string;
355
+ fetchPayload(token: string): Record<string, unknown>;
356
+ payloadToL5(payload: Record<string, unknown>): L5ManifestModel;
357
+ }
358
+
359
+ /**
360
+ * Participant discovery — a STATIC TS registry replacing Python's `pkgutil`
361
+ * package scan + entry-point duck-type (`participants/__init__.py`).
362
+ *
363
+ * Python scans the `participants/` package at runtime and duck-types each class
364
+ * by `_PARTICIPANT_MARKER_ATTRS`. A filesystem package scan does not survive
365
+ * bundling (`npx bourdon` is a single file), so the JS side declares an explicit
366
+ * {@link FIRST_PARTY} array. The three preserved invariants:
367
+ * - output sorted by `agentId`
368
+ * - first-wins dedupe on `agentId`
369
+ * - log-and-skip a participant that throws on construction (one broken reader
370
+ * must NOT abort discovery / crash the CLI)
371
+ *
372
+ * The marker-attr duck-typing collapses into the {@link BourdonParticipant}
373
+ * interface conformance (checked structurally via {@link isParticipant}).
374
+ */
375
+
376
+ /** A zero-arg-constructible participant class. */
377
+ type ParticipantCtor = new () => BourdonParticipant;
378
+ /**
379
+ * The first-party reader registry. Order here is irrelevant — discovery sorts by
380
+ * `agentId`. (cursor / codex / copilot_cli are the heavier SQLite readers of the
381
+ * follow-on slice; openclaw ships as the `@getbourdon/openclaw` plugin.)
382
+ */
383
+ declare const FIRST_PARTY: ParticipantCtor[];
384
+ /**
385
+ * Instantiate each registered participant, duck-type the contract, sort by
386
+ * `agentId`, and first-wins dedupe. A class that throws on construction is
387
+ * logged and skipped — never propagated.
388
+ */
389
+ declare function discoverParticipants(ctors?: ParticipantCtor[]): BourdonParticipant[];
390
+ /**
391
+ * Optional Layer 2: third-party plugins declared via a `package.json`
392
+ * `"bourdon": { participants: { ... } }` field. Gated behind `BOURDON_PLUGINS=1`
393
+ * and a no-op today (no external participant exists yet) — the resolver ships so
394
+ * the seam is wired, defaulted off so `npx bourdon` stays predictable.
395
+ */
396
+ declare function resolvePluginParticipants(): ParticipantCtor[];
397
+
398
+ export { type AgentStore, type AuthProvider, type BourdonParticipant, CONTRACT_VERSION, CacheEntry, ClaudeCodeParticipant, DEFAULT_CACHE_TTL_SECONDS, FIRST_PARTY, GitHubCopilotParticipant, type HealthStatus, HermesParticipant, NETWORK_CONTRACT_VERSION, NetworkParticipant, type NetworkParticipantOptions, NetworkUnavailable, type OpenReadonlyOptions, ParticipantAuthError, type ParticipantCtor, ParticipantDiscoveryError, ParticipantError, ParticipantExportError, ParticipantVersionMismatchError, PayloadCache, SPEC_VERSION, type SqliteDatabase, defaultCacheRoot, discoverParticipants, envAuthProvider, epochToIsoDate, epochToIsoDatetime, friendlyLabel, ghTokenProvider, isParticipant, openReadonly, projectKeyFromCwd, resolvePluginParticipants, sqliteAvailable, tableColumns, tableExists, tryOpenReadonly };