import type { ReadManyOptions, UpdateManyOptions, VisibilityMode, XronoxStore } from '@x12i/xronox-store'; import type { ActivixActivityInnerStepShape, ActivixActivityOuterTierShape, ActivixActivityRecord, ActivixCollectionLegendOwner, ActivixCollectionLegendRecord, ActivixExportResult, ActivixIdentityObject, ActivixIdentityObjectSource, ActivixIdentityObjectSourceIdentifier, ActivixJobRecord, ActivixJobStatus, ActivixQueryableClient, ActivixRecordMetadata, ActivixRunContext, FindByRunContextCriteria, GetJobActivitiesInput, GetJobActivitiesResult, StartRecordResult } from '@x12i/activix-contracts'; import type { ActivixAutoCostOptions } from './activityCost.js'; export type { ActivixActivityInnerStepShape, ActivixActivityOuterTierShape, ActivixActivityRecord, ActivixCollectionLegendOwner, ActivixCollectionLegendRecord, ActivixExportResult, ActivixIdentityObject, ActivixIdentityObjectSource, ActivixIdentityObjectSourceIdentifier, ActivixJobRecord, ActivixJobStatus, ActivixQueryableClient, ActivixRecordMetadata, ActivixRunContext, FindByRunContextCriteria, GetJobActivitiesInput, GetJobActivitiesResult, StartRecordResult, }; /** @deprecated Use {@link ActivixActivityRecord} from @x12i/activix-contracts. */ export type ActivixRecord = ActivixActivityRecord; /** * Minimal store surface used by Activix (`XronoxStore` and local file/memory store implementations). */ /** Resolved after **`init()`** for automatic mode (`pending` only until then). */ export type ActivixStorageBackend = 'database' | 'local' | 'pending'; export interface ActivixStore { init(): Promise; close(): Promise; isConnected(): boolean; collection>(name: string): ActivixCollectionHandle; } export interface ActivixCollectionHandle = Record> { insert(doc: Partial): Promise; update(keyValue: string, doc: Partial): Promise; patchByKey(keyValue: string, fields: Partial): Promise; getByKey(keyValue: string): Promise; readMany(filter: Record, options?: ReadManyOptions): Promise; updateMany(filter: Record, set: Partial, options?: UpdateManyOptions): Promise; } /** Same shape as xronox-store `IndexSpec` — duplicated to keep the public API self-contained. */ export interface ActivixIndexSpec { keys: Record; options?: { unique?: boolean; sparse?: boolean; name?: string; }; } export type ActivixPersistenceOperation = 'insert' | 'update'; export interface ActivixPersistenceWarning { /** Metric/event name, e.g. `activix.record.insert_failed`. */ event: `activix.record.${ActivixPersistenceOperation}_failed`; operation: ActivixPersistenceOperation; collection: string; phase: string; primaryKey: string; activityId?: string; error: { name?: string; message: string; }; /** * Forwarded from xronox-store clone diagnostics when available, allowing callers * to distinguish clone-safety failures from storage failures. */ clone?: { path: Array; valueType: string; constructorName?: string; }; } export interface ActivixCollectionConfig { /** MongoDB collection name for this activity log stream. */ name: string; /** Primary key field name. Default: 'activityId' */ primaryKey?: string; /** Prefix for auto-generated primary key values. Default: 'act-' */ primaryKeyPrefix?: string; /** * BSON field name for the per-run correlation object (**run context**). Default: **`runContext`** (see {@link ActivixRunContext}). * `sessionId` is taken from `runContext.sessionId` or top-level `sessionId` when present; Activix does **not** invent one if both are missing (see internal warning in that case). */ runContextField?: string; /** Status field name. Default: 'status' */ statusField?: string; /** Start timestamp field name (Unix ms). Default: 'startTime' */ startTimeField?: string; /** End timestamp field name (Unix ms). Default: 'endTime' */ endTimeField?: string; /** Duration field name (ms). Default: 'duration' */ durationField?: string; /** * When set, `markInProgress()` writes `Date.now()` here so consumers can tell “last update” * while the activity is neither completed nor failed. */ progressAtField?: string; /** * Soft-purge / tombstone field written by `purgeOldRecords()` and enforced by xronox-store **`visibility`** * when Activix constructs the store (same field name; default **`hiddenIfNonNull`**). * Default: `purgedAt` */ purgeAtField?: string; /** * Tombstone visibility mode for xronox-store (only when Activix builds `XronoxStore`). * Default: `hiddenIfNonNull` (visible only when the field is missing or null). */ purgeVisibilityMode?: VisibilityMode; /** Status value strings. All have defaults — override any or all. */ statusValues?: { started?: string; /** Mid-flight updates via `markInProgress()`. Default: `'in_progress'`. */ inProgress?: string; completed?: string; failed?: string; /** Set on records that stayed `started` past TTL when `reconcileAbandonedActivities()` / `markStaleRecords()` runs. Default: `'timeout'`. */ timeout?: string; }; /** Extra indexes (unique index on primaryKey is always created by the store). */ indexes?: ActivixIndexSpec[]; /** * Per-collection in-memory cache (xronox-store). Merged with xronox-store defaults via `resolveCacheConfig` * when Activix creates the store (`maxSize` 10000, `ttlMs` 0). */ cache?: { maxSize?: number; ttlMs?: number; }; } export interface ActivixOptionsCommon { /** * Pre-built `XronoxStore`. Each collection Activix uses must use the same **`primaryKey`** / **`primaryKeyPrefix`** * as in Activix config, and define **`visibility.field`** equal to this package’s **`purgeAtField`** (default `purgedAt`) * with matching mode, or soft-purged rows will still appear in queries and `getRecord`. */ store?: XronoxStore | ActivixStore; /** * - *(omit)* — when **`mongoUri`** (or env via **`resolveActivixMongoUriFromEnv()`**) is set → **`database`** (no probe; fails at store init if Mongo is down). When no URI → **`local`** playground. * - **`automatic`** — explicit opt-in: on **`await init()`**, run a **single** MongoDB connectivity check, then use **`XronoxStore`** if reachable or the **playground** folder if not. Until **`init()`** completes, **`storageBackend`** is **`'pending'`**. * - **`database`** — always MongoDB (same as omitted mode when a URI is available). * - **`local`** — always playground folder (see **`playground`**) — no MongoDB. */ storageMode?: 'database' | 'local' | 'automatic'; /** * When **`storageMode`** is **`'local'`** (including automatic fallback), persists the activity-centric playground layout: * **`report.md`**, append-only **`activities.jsonl`**, **`collections//records/.json`**, and optional * **`NN--request.json` / `-response.json`** when rows carry `work:request` / `work:response` shapes, `fullRequest` / `fullOutput`, top-level **`outer`**, or legacy nested **`structure.outer`**. */ playground?: { /** Root directory. Default: `"playground"`. */ outputDir?: string; /** Run label in the Markdown report header. */ runId?: string; }; /** If the store is already initialized, skip `store.init()` inside `Activix.init()`. */ skipStoreInit?: boolean; /** * Called when Activix observes a persistence failure before it rethrows or swallows * the error according to the method's compatibility contract. */ onPersistenceWarning?: (warning: ActivixPersistenceWarning) => void; /** * Re-throw persistence failures that are otherwise non-fatal for compatibility * (currently `patchRecord` update failures). */ strictPersistence?: boolean; /** Used only when `store` is omitted. */ mongoUri?: string; xronox?: import('@x12i/xronox').Xronox; /** Optional diagnostics metadata included in Activix internal logs. */ diagnostics?: { owner?: string; component?: string; instanceLabel?: string; workerId?: string; }; /** * How long (ms) a record may remain in `started` before `reconcileAbandonedActivities()` / `markStaleRecords()` * rewrites it to `statusValues.timeout`. Compared against `startTimeField`. Default: 300000. */ staleRecordTTL?: number; /** * Default maximum age (ms) for `purgeOldRecords()`: documents with `startTimeField` older than * `Date.now() - olderThanMs` are **soft-purged** (marked and hidden). Default: **7 days** (604800000 ms). */ purgeRecordMaxAgeMs?: number; /** Passed through when Activix creates the store internally. */ errorHandling?: { onConnectionError?: 'throw' | 'queue' | 'silent'; onPersistError?: 'throw' | 'queue' | 'silent'; retry?: { maxRetries?: number; retryDelay?: number; exponentialBackoff?: boolean; }; queue?: { maxSize?: number; flushInterval?: number; }; }; /** * Custom logger for Activix and the built-in **`XronoxStore`** (when you omit this, both use the same default). * Internal diagnostics are error-only unless **`ENABLE_ACTIVIX_LOGXER=true`**. When enabled, level follows **`ACTIVIX_LOGS_LEVEL`** (canonical; legacy **`ACTIVIX_LOG_LEVEL`** fallback); default when unset is **`warn`**. Set **`ACTIVIX_LOGS_LEVEL=error`** to keep only errors while diagnostics are enabled. Injected loggers are also gated: without the enable flag, only `error` is called. */ logger?: { debug(msg: string, meta?: Record): void; info(msg: string, meta?: Record): void; warn(msg: string, meta?: Record): void; error(msg: string, meta?: Record): void; }; /** * Default MongoDB collection name for job helpers (`startJob`, `endJob`, `getJob`, `listJobs`, `getJobBundle`). * Omit only if you never call those methods, or pass `{ collection }` on every job call. */ jobsCollection?: string; /** * Seconds between legend **`state`** refreshes per collection when deciding whether to persist rows. * Overrides **`ACTIVIX_COLLECTION_TRACKING_STATE_TTL_SEC`**; default **600**. Use **`0`** to re-read on every write. */ collectionTrackingStateRefreshIntervalSec?: number; /** * When Activix creates the store, registers **`activix-collections`** (or **`legendCollection`**) if absent, * then after **`init()`** inserts missing legend rows for **every** configured collection (including the registry itself). * Requires **`diagnostics.owner`** (recommended) or **`collectionRegistry.owner`** as the owning npm package id. * Set **`false`** to disable (no extra collection, no automatic inserts). */ collectionRegistry?: ActivixCollectionRegistryOptions; /** * When enabled, Activix fills **`outer.cost`** on writes when missing: it reuses a **valid** cost already * present on the row (e.g. `outer.output.usage.total_cost`, `inner[].cost`) and only calls * **`@x12i/ai-tools`** when no valid cost was found but token usage + model are extractable. * Default: **`false`** (opt in). Pass **`true`** or an options object to enable. */ autoCost?: boolean | ActivixAutoCostOptions; } export type { ActivixAutoCostOptions } from './activityCost.js'; /** One collection: pass its name (or full config) once; method calls use it automatically. */ export type ActivixSingleCollectionOptions = ActivixOptionsCommon & { collection: string | ActivixCollectionConfig; }; /** Several collections: list them here; pass `options.collection` on a method when using a non-default one. */ export type ActivixMultiCollectionOptions = ActivixOptionsCommon & { collections: ActivixCollectionConfig[]; /** Must name the default activity stream explicitly (package-owned collection name in source). */ defaultCollection: string; }; export type ActivixOptions = ActivixSingleCollectionOptions | ActivixMultiCollectionOptions; /** Options for `markStaleRecords()` and `reconcileAbandonedActivities()`. */ export interface MarkStaleOptions { collection?: string; /** Overrides `staleRecordTTL` from constructor for this call only. */ ttlMs?: number; } /** Options for `purgeOldRecords()`. */ export interface PurgeOldRecordsOptions { collection?: string; /** * Soft-purge rows where `startTimeField < Date.now() - olderThanMs`. * Default: constructor `purgeRecordMaxAgeMs` (default 7 days). */ olderThanMs?: number; } /** Options for `cleanKeepLastHours()`, `cleanAll()`, and purge-by-window helpers. */ export interface CleanKeepLastHoursOptions { /** When set, only this configured collection; otherwise every configured collection. */ collection?: string; } /** Options for `exportRecordsToDirectory()` and related export helpers. */ export interface ExportRecordsToDirectoryOptions extends CleanKeepLastHoursOptions { /** * When set, only rows with `startTimeField >= Date.now() - keepLastHours` (in hours, fractional OK). * When omitted, exports all matching rows (including tombstoned if `includeHidden` is true). */ keepLastHours?: number; /** Passed to `readMany` / `findRecords` (xronox-store). Default: true. */ mergeCache?: boolean; /** Include soft-purged / tombstoned rows in export. Default: true. */ includeHidden?: boolean; /** * Attach a normalized `trace` block per row for studio report joins. * @default true */ traceShape?: boolean; } export interface GetJobInput { jobId: string; } export interface GetJobResult { job: ActivixJobRecord | null; } export interface GetJobBundleInput extends GetJobActivitiesInput { } export interface GetJobBundleResult { job: ActivixJobRecord | null; graphRun?: unknown; activities: unknown[]; } export interface ListJobsInput { limit?: number; /** Case-insensitive search within `description` (best-effort; database-only when using Mongo). */ searchText?: string; } export interface ListJobsResult { jobs: ActivixJobRecord[]; } /** * Built-in collection registry (`activix-collections` by default): one legend row per configured collection after init. * Set to **`false`** to disable injecting the registry collection and automatic legend inserts (e.g. CLI). */ export type ActivixCollectionRegistryOptions = false | { /** Mongo collection name for legend rows. Default: **`activix-collections`**. */ legendCollection?: string; /** Overrides **`diagnostics.owner`** / **`diagnostics.component`** for generated legend rows. */ owner?: ActivixCollectionLegendOwner; /** `{name}` is replaced with the Mongo collection name. */ aboutTemplate?: string; /** * Collection names that skip automatic legend inserts so you can call **`initializeCollection`** * yourself after **`init()`** (insert-only; automatic rows would block that). */ skipAutoInsertForCollections?: string[]; /** * @deprecated Prefer **`collectionTrackingStateRefreshIntervalSec`** on Activix constructor. */ trackingStateRefreshIntervalSec?: number; }; //# sourceMappingURL=types.d.ts.map