@anureo/host 0.0.0-stage → 0.3.12

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,45 @@
1
+ import type { SqliteConnection } from './sqlite-driver'
2
+ import { validateHxResult, type HxHarnessModelsResult } from './legacy-protocol'
3
+ export type CatalogModel = HxHarnessModelsResult['models'][number]
4
+ export interface ModelSnapshot {
5
+ models: CatalogModel[]; contentHash: string; engineFingerprint: string
6
+ lastSuccessAt: number; freshUntil: number
7
+ }
8
+ export interface CatalogAttempt { lastAttemptAt: number; failureCount: number; lastErrorCode?: string; nextRetryAt?: number }
9
+ export function validateCatalogModels(models: unknown): asserts models is CatalogModel[] {
10
+ if (!Array.isArray(models) || models.length > 10_000 || new TextEncoder().encode(JSON.stringify(models)).byteLength > 4 * 1024 * 1024) throw new Error('CATALOG_LIMIT_EXCEEDED')
11
+ validateHxResult('hx.harness.models', { models, source: 'live' })
12
+ }
13
+ export class CatalogStore {
14
+ constructor(private readonly db: SqliteConnection) {}
15
+ identityEpoch(runtimeId: string): string {
16
+ const row = this.db.query('SELECT value FROM hx_meta WHERE key=?').get(`catalog-auth:${runtimeId}`) as { value: string } | null
17
+ return row?.value ?? 'initial'
18
+ }
19
+ rotateIdentity(runtimeId: string, epoch: string): void {
20
+ this.db.query('INSERT INTO hx_meta VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(`catalog-auth:${runtimeId}`, epoch)
21
+ }
22
+ load(key: string): ModelSnapshot | undefined {
23
+ const row = this.db.query('SELECT * FROM hx_model_catalog_snapshots WHERE identity_key=?').get(key) as { schema_version: number; models_json: string; content_hash: string; engine_fingerprint: string; last_success_at: number; fresh_until: number } | null
24
+ if (!row) return
25
+ if (row.schema_version !== 1 || !Number.isSafeInteger(row.last_success_at) || !Number.isSafeInteger(row.fresh_until) || row.last_success_at < 0 || row.fresh_until < row.last_success_at) throw new Error('CATALOG_SNAPSHOT_INVALID')
26
+ const models: unknown = JSON.parse(row.models_json); validateCatalogModels(models)
27
+ return { models, contentHash: row.content_hash, engineFingerprint: row.engine_fingerprint, lastSuccessAt: row.last_success_at, freshUntil: row.fresh_until }
28
+ }
29
+ attempt(key: string): CatalogAttempt | undefined {
30
+ const row = this.db.query('SELECT * FROM hx_model_catalog_attempts WHERE identity_key=?').get(key) as { last_attempt_at: number; failure_count: number; last_error_code: string | null; next_retry_at: number | null } | null
31
+ return row ? { lastAttemptAt: row.last_attempt_at, failureCount: row.failure_count, ...(row.last_error_code ? { lastErrorCode: row.last_error_code } : {}), ...(row.next_retry_at === null ? {} : { nextRetryAt: row.next_retry_at }) } : undefined
32
+ }
33
+ success(key: string, runtimeConfigId: string, providerId: string, value: ModelSnapshot): void {
34
+ validateCatalogModels(value.models)
35
+ this.db.transaction(() => {
36
+ this.db.query(`INSERT INTO hx_model_catalog_snapshots VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(identity_key) DO UPDATE SET schema_version=excluded.schema_version,models_json=excluded.models_json,content_hash=excluded.content_hash,engine_fingerprint=excluded.engine_fingerprint,last_success_at=excluded.last_success_at,fresh_until=excluded.fresh_until`).run(key, runtimeConfigId, providerId, 1, JSON.stringify(value.models), value.contentHash, value.engineFingerprint, value.lastSuccessAt, value.freshUntil)
37
+ this.db.query('DELETE FROM hx_model_catalog_attempts WHERE identity_key=?').run(key)
38
+ })()
39
+ }
40
+ failure(key: string, value: CatalogAttempt): void {
41
+ this.db.query(`INSERT INTO hx_model_catalog_attempts VALUES(?,?,?,?,?) ON CONFLICT(identity_key) DO UPDATE SET last_attempt_at=excluded.last_attempt_at,last_error_code=excluded.last_error_code,failure_count=excluded.failure_count,next_retry_at=excluded.next_retry_at`).run(key, value.lastAttemptAt, value.lastErrorCode ?? null, value.failureCount, value.nextRetryAt ?? null)
42
+ }
43
+ }
44
+
45
+ export type CatalogStorage = Pick<CatalogStore, keyof CatalogStore>
@@ -0,0 +1,14 @@
1
+ import type { CatalogProbeOptions, CatalogProbeEvent } from '@anureo/sdk/diagnostics'
2
+ import type { CatalogModel } from './catalog-store'
3
+ export { safeCatalogErrorCode as catalogErrorCode } from '@anureo/sdk/diagnostics'
4
+ export interface CatalogWorker {
5
+ prepare(options: CatalogProbeOptions): Promise<void>
6
+ readModels(options: CatalogProbeOptions): Promise<readonly CatalogModel[]>
7
+ dispose(): Promise<void>
8
+ }
9
+ export interface CatalogDiagnostic {
10
+ event: string; runtimeConfigId: string; providerId: string; generation: number
11
+ refreshId?: string; trigger?: string; phase?: CatalogProbeEvent['phase'] | 'queue' | 'persist'
12
+ outcome?: string; durationMs?: number; totalDurationMs?: number; cacheAgeMs?: number
13
+ modelCount?: number; errorCode?: string; nativeRpcCode?: number; retainedSnapshot?: boolean; nextRetryAt?: number
14
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,179 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { catalogPhase, type CatalogProbeOptions } from '@anureo/sdk/diagnostics'
3
+ import type { CatalogCache, HxCatalogRefreshResult } from './legacy-protocol'
4
+ import type { RuntimeRegistration } from './host'
5
+ import { validateCatalogModels, type CatalogStorage, type ModelSnapshot, type CatalogAttempt } from './catalog-store'
6
+ import { catalogErrorCode, type CatalogDiagnostic, type CatalogWorker } from './catalog-worker'
7
+ import { HostError } from './errors'
8
+
9
+ interface Entry {
10
+ registration: RuntimeRegistration; key: string; fingerprint: string; generation: number
11
+ snapshot?: ModelSnapshot; attempt?: CatalogAttempt; worker?: CatalogWorker; cleanup?: Promise<void>
12
+ refresh?: { id: string; abort: AbortController; promise: Promise<void> }
13
+ }
14
+ export interface CatalogOptions {
15
+ store: CatalogStorage; digest(value: unknown): string
16
+ onChanged(runtimeConfigId: string, changes: Array<'models' | 'refresh'>): void
17
+ onDiagnostic?(event: CatalogDiagnostic): void
18
+ freshMs?: number; refreshTimeoutMs?: number; concurrency?: number; now?: () => number
19
+ }
20
+ /** Success values live independently of both worker lifetime and refresh failures. */
21
+ export class HarnessCatalogService {
22
+ private readonly entries = new Map<string, Entry>()
23
+ private readonly queue: Array<() => Promise<void>> = []
24
+ private running = 0
25
+ private closed = false
26
+ private started = false
27
+ private timer?: ReturnType<typeof setInterval>
28
+ private generation = 0
29
+ private readonly now: () => number
30
+ constructor(private readonly options: CatalogOptions) { this.now = options.now ?? Date.now }
31
+ private diagnostic(entry: Entry, event: Omit<CatalogDiagnostic, 'runtimeConfigId' | 'providerId' | 'generation'>): void {
32
+ try { this.options.onDiagnostic?.({ runtimeConfigId: entry.registration.id, providerId: entry.registration.providerId ?? entry.registration.adapterId, generation: entry.generation, ...event }) } catch {}
33
+ }
34
+ private changed(id: string, changes: Array<'models' | 'refresh'>): void { try { this.options.onChanged(id, changes) } catch {} }
35
+ replace(registrations: RuntimeRegistration[]): void {
36
+ const remaining = new Set(registrations.map(r => r.id))
37
+ for (const [id, old] of this.entries) if (!remaining.has(id)) { this.entries.delete(id); this.retire(old) }
38
+ for (const registration of registrations) {
39
+ const key = this.options.digest({ kind: 'model-catalog', id: registration.id, provider: registration.providerId ?? registration.adapterId, scope: registration.catalogScope ?? registration.id, authEpoch: this.options.store.identityEpoch(registration.id) })
40
+ const fingerprint = registration.catalogFingerprint ?? registration.version ?? registration.id
41
+ const old = this.entries.get(registration.id)
42
+ if (old?.key === key && old.fingerprint === fingerprint && old.registration.available === registration.available && (registration.catalogFingerprint !== undefined || old.registration === registration)) { old.registration = registration; continue }
43
+ if (old) this.retire(old)
44
+ const entry: Entry = { registration, key, fingerprint, generation: ++this.generation, cleanup: old?.cleanup }
45
+ try { entry.snapshot = this.options.store.load(key); if (entry.snapshot && this.options.digest(entry.snapshot.models) !== entry.snapshot.contentHash) { entry.snapshot = undefined; throw new Error('CATALOG_SNAPSHOT_INVALID') }; if (entry.snapshot && old && old.registration !== registration && registration.catalogFingerprint === undefined) entry.snapshot.freshUntil = 0; entry.attempt = this.options.store.attempt(key) }
46
+ catch (cause) { this.diagnostic(entry, { event: 'cache.load', outcome: 'error', errorCode: catalogErrorCode(cause) }) }
47
+ this.entries.set(registration.id, entry)
48
+ }
49
+ if (this.started) this.warm()
50
+ }
51
+ resetIdentity(runtimeIds: string[]): void {
52
+ for (const id of runtimeIds) this.options.store.rotateIdentity(id, randomUUID())
53
+ this.replace([...this.entries.values()].map(entry => entry.registration))
54
+ for (const id of runtimeIds) { this.changed(id, ['models', 'refresh']); this.schedule(id, 'auth') }
55
+ }
56
+ private cleanup(entry: Entry, worker: CatalogWorker): Promise<void> {
57
+ const started = performance.now()
58
+ this.diagnostic(entry, { event: 'worker.cleanup', outcome: 'started' })
59
+ return Promise.resolve().then(() => worker.dispose()).then(() => { this.diagnostic(entry, { event: 'worker.cleanup', outcome: 'success', durationMs: performance.now() - started }) }, cause => { this.diagnostic(entry, { event: 'worker.cleanup', outcome: 'error', durationMs: performance.now() - started, errorCode: catalogErrorCode(cause) }); throw cause })
60
+ }
61
+ private retire(entry: Entry): void {
62
+ entry.refresh?.abort.abort()
63
+ if (entry.worker) {
64
+ const worker = entry.worker; entry.worker = undefined
65
+ entry.cleanup = this.cleanup(entry, worker); void entry.cleanup.catch(() => {})
66
+ }
67
+ }
68
+ private entry(id: string): Entry { const entry = this.entries.get(id); if (!entry) throw new HostError('HARNESS_UNAVAILABLE'); return entry }
69
+ private stale(entry: Entry): boolean {
70
+ return !entry.snapshot || entry.snapshot.lastSuccessAt > this.now() || entry.snapshot.freshUntil <= this.now() || entry.snapshot.engineFingerprint !== entry.fingerprint
71
+ }
72
+ view(id: string, includeModels = false): { models?: ModelSnapshot['models']; cache: CatalogCache } {
73
+ const entry = this.entry(id)
74
+ if (this.stale(entry)) this.schedule(id, 'expired')
75
+ this.diagnostic(entry, { event: 'cache.read', outcome: entry.snapshot ? 'hit' : 'miss', ...(entry.refresh ? { refreshId: entry.refresh.id } : {}), ...(entry.snapshot ? { cacheAgeMs: Math.max(0, this.now() - entry.snapshot.lastSuccessAt) } : {}) })
76
+ return {
77
+ ...(includeModels ? { models: structuredClone(entry.snapshot?.models ?? []) } : {}),
78
+ cache: { state: entry.snapshot ? this.stale(entry) ? 'stale' : 'fresh' : 'empty', lastSuccessAt: entry.snapshot?.lastSuccessAt ?? null, freshUntil: entry.snapshot?.freshUntil ?? null, refreshing: !!entry.refresh, ...(entry.attempt?.lastErrorCode ? { lastErrorCode: entry.attempt.lastErrorCode } : {}), ...(entry.attempt?.nextRetryAt ? { nextRetryAt: entry.attempt.nextRetryAt } : {}) },
79
+ }
80
+ }
81
+ /** Legacy callers may await the first result; subsequent reads always retain the last success. */
82
+ async legacyModels(id: string): Promise<ModelSnapshot['models']> {
83
+ const entry = this.entry(id)
84
+ if (entry.snapshot) { this.view(id); return structuredClone(entry.snapshot.models) }
85
+ this.schedule(id, 'expired')
86
+ await entry.refresh?.promise
87
+ const refreshed = this.entry(id).snapshot
88
+ if (!refreshed) throw new HostError(entry.attempt?.lastErrorCode ?? 'CATALOG_WARMING', undefined, true, false)
89
+ return structuredClone(refreshed.models)
90
+ }
91
+ coalescedRefresh(id: string): HxCatalogRefreshResult | undefined {
92
+ const refresh = this.entry(id).refresh
93
+ return refresh ? { accepted: true, coalesced: true, refreshId: refresh.id } : undefined
94
+ }
95
+ schedule(id: string, trigger: string): HxCatalogRefreshResult {
96
+ const entry = this.entry(id)
97
+ if (entry.refresh) return { accepted: true, coalesced: true, refreshId: entry.refresh.id }
98
+ const registration = entry.registration
99
+ if (this.closed || registration.available === false || (!registration.models && !registration.catalogWorker) || (trigger !== 'manual' && (entry.attempt?.nextRetryAt ?? 0) > this.now())) return { accepted: false, coalesced: false, refreshId: 'not-scheduled' }
100
+ const refreshId = randomUUID(), abort = new AbortController(), queuedAt = performance.now()
101
+ let complete!: () => void
102
+ const promise = new Promise<void>(resolve => { complete = resolve })
103
+ entry.refresh = { id: refreshId, abort, promise }
104
+ this.diagnostic(entry, { event: 'refresh.queued', refreshId, trigger, outcome: 'queued' })
105
+ this.queue.push(async () => {
106
+ const started = performance.now(), current = () => !this.closed && !abort.signal.aborted && this.entries.get(id) === entry
107
+ let timer: ReturnType<typeof setTimeout> | undefined, onAbort: (() => void) | undefined
108
+ try {
109
+ if (!current()) return
110
+ this.diagnostic(entry, { event: 'refresh.started', refreshId, trigger, phase: 'queue', outcome: 'success', durationMs: started - queuedAt })
111
+ this.changed(id, ['refresh'])
112
+ const timeoutMs = this.options.refreshTimeoutMs ?? 30_000
113
+ const probe: CatalogProbeOptions = { signal: abort.signal, timeoutMs: Math.min(timeoutMs, 10_000), onPhase: event => this.diagnostic(entry, { event: event.outcome === 'started' ? 'phase.started' : 'phase.completed', refreshId, trigger, ...event }) }
114
+ const work = async () => {
115
+ await entry.cleanup
116
+ if (!current()) throw new HostError('CATALOG_CANCELLED')
117
+ entry.worker ??= registration.catalogWorker?.() ?? { prepare: async () => {}, readModels: () => catalogPhase(probe, 'models', () => registration.models!()), dispose: async () => {} }
118
+ await entry.worker.prepare(probe)
119
+ return await entry.worker.readModels(probe)
120
+ }
121
+ const models = await Promise.race([work(), new Promise<never>((_, reject) => {
122
+ let expired = false
123
+ onAbort = () => reject(new HostError(expired ? 'CATALOG_REFRESH_TIMEOUT' : 'CATALOG_CANCELLED'))
124
+ abort.signal.addEventListener('abort', onAbort, { once: true })
125
+ if (abort.signal.aborted) onAbort()
126
+ else timer = setTimeout(() => { expired = true; abort.abort() }, timeoutMs)
127
+ })])
128
+ if (!current()) return
129
+ validateCatalogModels(models)
130
+ const now = this.now(), next: ModelSnapshot = { models: structuredClone(models), contentHash: this.options.digest(models), engineFingerprint: entry.fingerprint, lastSuccessAt: now, freshUntil: now + (this.options.freshMs ?? 15 * 60_000) }
131
+ const changed = !entry.snapshot || entry.snapshot.contentHash !== next.contentHash
132
+ const persistStart = performance.now()
133
+ this.options.store.success(entry.key, id, registration.providerId ?? registration.adapterId, next)
134
+ entry.snapshot = next; entry.attempt = undefined
135
+ this.diagnostic(entry, { event: 'phase.completed', refreshId, phase: 'persist', outcome: 'success', durationMs: performance.now() - persistStart })
136
+ this.changed(id, changed ? ['models', 'refresh'] : ['refresh'])
137
+ this.diagnostic(entry, { event: 'refresh.completed', refreshId, trigger, outcome: 'success', modelCount: models.length, totalDurationMs: performance.now() - started })
138
+ } catch (cause) {
139
+ if (this.closed || this.entries.get(id) !== entry) return
140
+ const errorCode = catalogErrorCode(cause), failureCount = (entry.attempt?.failureCount ?? 0) + 1
141
+ const delays = [5_000, 30_000, 120_000, 300_000]
142
+ entry.attempt = { lastAttemptAt: this.now(), lastErrorCode: errorCode, failureCount, nextRetryAt: this.now() + delays[Math.min(failureCount - 1, delays.length - 1)]! }
143
+ try { this.options.store.failure(entry.key, entry.attempt) } catch { this.diagnostic(entry, { event: 'cache.persist', outcome: 'error', errorCode: 'CATALOG_PERSIST_FAILED' }) }
144
+ const worker = entry.worker; entry.worker = undefined
145
+ if (worker) entry.cleanup = this.cleanup(entry, worker)
146
+ void entry.cleanup?.catch(() => {})
147
+ this.diagnostic(entry, { event: 'refresh.completed', refreshId, trigger, outcome: 'error', errorCode, retainedSnapshot: !!entry.snapshot, nextRetryAt: entry.attempt.nextRetryAt, totalDurationMs: performance.now() - started })
148
+ } finally {
149
+ if (timer) clearTimeout(timer)
150
+ if (onAbort) abort.signal.removeEventListener('abort', onAbort)
151
+ if (entry.refresh?.id === refreshId) entry.refresh = undefined
152
+ if (!this.closed && this.entries.get(id) === entry) this.changed(id, ['refresh'])
153
+ complete()
154
+ }
155
+ })
156
+ queueMicrotask(() => this.pump())
157
+ return { accepted: true, coalesced: false, refreshId }
158
+ }
159
+ private pump(): void {
160
+ while (this.queue.length && this.running < (this.options.concurrency ?? 2)) {
161
+ const job = this.queue.shift()!; this.running++
162
+ void job().finally(() => { this.running--; this.pump() })
163
+ }
164
+ }
165
+ private warm(): void { for (const [id, entry] of this.entries) if (this.stale(entry) || !entry.worker) this.schedule(id, 'startup') }
166
+ startBackground(): void {
167
+ if (this.started || this.closed) return
168
+ this.started = true; this.warm()
169
+ this.timer = setInterval(() => { for (const [id, entry] of this.entries) if (this.stale(entry)) this.schedule(id, 'retry') }, 5_000)
170
+ this.timer.unref?.()
171
+ }
172
+ async close(): Promise<void> {
173
+ this.closed = true; if (this.timer) clearInterval(this.timer)
174
+ const pending = [...this.entries.values()].map(entry => { this.retire(entry); return Promise.allSettled([entry.refresh?.promise, entry.cleanup]) })
175
+ this.pump()
176
+ let timer: ReturnType<typeof setTimeout> | undefined
177
+ try { await Promise.race([Promise.allSettled(pending), new Promise<void>(resolve => { timer = setTimeout(resolve, 5_000) })]) } finally { if (timer) clearTimeout(timer) }
178
+ }
179
+ }
package/src/compat.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from './catalog-worker'
2
+ export * from './errors'
3
+ export * from './interaction-capture'
4
+ export * from './persistent-secrets'
5
+ export * from './subagents'
6
+ export * from './swarm-client'
7
+ export * from './swarm-workflows'
package/src/errors.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { publicValue,type HarnessError,type JsonObject } from "@anureo/protocol";
2
+ export class HostError extends Error implements HarnessError {
3
+ constructor(readonly code:string, message=code, readonly retryable=false, readonly outcomeUnknown=false,readonly details?:JsonObject){super(message);}
4
+ }
5
+ export function hostError(cause:unknown,defaultCode="HOST_ERROR"):HarnessError {
6
+ if(cause instanceof HostError)return {code:cause.code,message:cause.message,retryable:cause.retryable,outcomeUnknown:cause.outcomeUnknown,...(cause.details?{details:cause.details}:{})};
7
+ if(cause && typeof cause==="object" && "code" in cause && typeof cause.code==="string") {
8
+ let details:JsonObject|undefined;
9
+ if("details"in cause&&cause.details&&typeof cause.details==="object"&&!Array.isArray(cause.details))try{details=publicValue(JSON.parse(JSON.stringify(cause.details))) as JsonObject;}catch{}
10
+ return {code:cause.code,message:cause.code,retryable:"retryable" in cause && cause.retryable===true,outcomeUnknown:"outcomeUnknown" in cause && cause.outcomeUnknown===true,...(details?{details}:{})};
11
+ }
12
+ return {code:defaultCode,message:defaultCode,retryable:false,outcomeUnknown:false};
13
+ }
14
+ export function rpcError(cause:unknown):{code:number;message:string;data:HarnessError} {
15
+ const error=hostError(cause);
16
+ const code=error.code==="AUTH_REQUIRED"?4010:error.code==="PROJECT_FORBIDDEN"?4013:error.code==="METHOD_NOT_FOUND"||error.code==="HX_DISABLED"?-32601:error.code==="INVALID_PARAMS"?-32602:-32070;
17
+ return {code,message:error.message,data:error};
18
+ }
19
+ /** History pages that exceed a transport frame limit are a stable, user-visible failure; keep every other error untouched. */
20
+ export function historyReadError(cause:unknown):unknown {
21
+ const code=cause && typeof cause==="object" && "code" in cause ? cause.code : undefined;
22
+ if(code==="FRAME_TOO_LARGE"||code==="HISTORY_TOO_LARGE")return new HostError("HISTORY_TOO_LARGE","Session history is too large to load",false,false);
23
+ return cause;
24
+ }