hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3
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.
- package/LICENSE +202 -0
- package/README.md +89 -2
- package/dist/adapter-kit.d.ts +37 -0
- package/dist/adapter-kit.js +34 -0
- package/dist/adapter-kit.js.map +1 -0
- package/dist/agent-Bj5YPrO7.d.ts +169 -0
- package/dist/agent-D6OXR7UF.js +24 -0
- package/dist/agent-D6OXR7UF.js.map +1 -0
- package/dist/agent-readiness-KSGNKTGK.js +19 -0
- package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
- package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
- package/dist/chunk-2RK74GCA.js +2397 -0
- package/dist/chunk-2RK74GCA.js.map +1 -0
- package/dist/chunk-3TIYA3K5.js +55 -0
- package/dist/chunk-3TIYA3K5.js.map +1 -0
- package/dist/chunk-6FIXXWNM.js +1 -0
- package/dist/chunk-6FIXXWNM.js.map +1 -0
- package/dist/chunk-6XIJW65Q.js +52 -0
- package/dist/chunk-6XIJW65Q.js.map +1 -0
- package/dist/chunk-7LDQKJKI.js +248 -0
- package/dist/chunk-7LDQKJKI.js.map +1 -0
- package/dist/chunk-CPN4DOXH.js +115 -0
- package/dist/chunk-CPN4DOXH.js.map +1 -0
- package/dist/chunk-DAXPAV2L.js +810 -0
- package/dist/chunk-DAXPAV2L.js.map +1 -0
- package/dist/chunk-DQEMIGKC.js +291 -0
- package/dist/chunk-DQEMIGKC.js.map +1 -0
- package/dist/chunk-DZFFGUIA.js +81 -0
- package/dist/chunk-DZFFGUIA.js.map +1 -0
- package/dist/chunk-EEUYQFCP.js +106 -0
- package/dist/chunk-EEUYQFCP.js.map +1 -0
- package/dist/chunk-G6JV7WV6.js +521 -0
- package/dist/chunk-G6JV7WV6.js.map +1 -0
- package/dist/chunk-GFVYNPLS.js +118 -0
- package/dist/chunk-GFVYNPLS.js.map +1 -0
- package/dist/chunk-GS5U3KUN.js +201 -0
- package/dist/chunk-GS5U3KUN.js.map +1 -0
- package/dist/chunk-HB7FBSH2.js +960 -0
- package/dist/chunk-HB7FBSH2.js.map +1 -0
- package/dist/chunk-HZFZX5A3.js +21 -0
- package/dist/chunk-HZFZX5A3.js.map +1 -0
- package/dist/chunk-J7VAYJKM.js +595 -0
- package/dist/chunk-J7VAYJKM.js.map +1 -0
- package/dist/chunk-NCNSHOF7.js +52 -0
- package/dist/chunk-NCNSHOF7.js.map +1 -0
- package/dist/chunk-RH5A5U7G.js +202 -0
- package/dist/chunk-RH5A5U7G.js.map +1 -0
- package/dist/chunk-RX3XZENU.js +385 -0
- package/dist/chunk-RX3XZENU.js.map +1 -0
- package/dist/chunk-RXU2Q2HF.js +49 -0
- package/dist/chunk-RXU2Q2HF.js.map +1 -0
- package/dist/chunk-TG7NTMTR.js +208 -0
- package/dist/chunk-TG7NTMTR.js.map +1 -0
- package/dist/chunk-TWGEYWMO.js +1217 -0
- package/dist/chunk-TWGEYWMO.js.map +1 -0
- package/dist/chunk-UZPDDQVJ.js +2910 -0
- package/dist/chunk-UZPDDQVJ.js.map +1 -0
- package/dist/chunk-WMKO5XOE.js +601 -0
- package/dist/chunk-WMKO5XOE.js.map +1 -0
- package/dist/chunk-WOQBVJH5.js +175 -0
- package/dist/chunk-WOQBVJH5.js.map +1 -0
- package/dist/chunk-WVT5SEKC.js +581 -0
- package/dist/chunk-WVT5SEKC.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +26 -0
- package/dist/cli.js.map +1 -0
- package/dist/errors-BNHvvjn9.d.ts +98 -0
- package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
- package/dist/execution-types-ClYYqPQP.d.ts +239 -0
- package/dist/host-ledger-VPRWVVOS.js +25 -0
- package/dist/host-ledger-VPRWVVOS.js.map +1 -0
- package/dist/hosted-runtime.d.ts +168 -0
- package/dist/hosted-runtime.js +858 -0
- package/dist/hosted-runtime.js.map +1 -0
- package/dist/index-B86C6VAD.d.ts +41 -0
- package/dist/index.d.ts +344 -0
- package/dist/index.js +8825 -0
- package/dist/index.js.map +1 -0
- package/dist/memory-items-BSTC0_R0.d.ts +28 -0
- package/dist/memory-tools.d.ts +222 -0
- package/dist/memory-tools.js +923 -0
- package/dist/memory-tools.js.map +1 -0
- package/dist/orchestration/dynamic.d.ts +854 -0
- package/dist/orchestration/dynamic.js +3150 -0
- package/dist/orchestration/dynamic.js.map +1 -0
- package/dist/orchestration/graph.d.ts +11 -0
- package/dist/orchestration/graph.js +9 -0
- package/dist/orchestration/graph.js.map +1 -0
- package/dist/orchestration/index.d.ts +2385 -0
- package/dist/orchestration/index.js +6409 -0
- package/dist/orchestration/index.js.map +1 -0
- package/dist/orchestration/log.d.ts +301 -0
- package/dist/orchestration/log.js +3058 -0
- package/dist/orchestration/log.js.map +1 -0
- package/dist/orchestration/memory.d.ts +711 -0
- package/dist/orchestration/memory.js +27 -0
- package/dist/orchestration/memory.js.map +1 -0
- package/dist/provider-DX5Mf0uq.d.ts +151 -0
- package/dist/routing/index.d.ts +29 -0
- package/dist/routing/index.js +386 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/routing/learning/index.d.ts +433 -0
- package/dist/routing/learning/index.js +2502 -0
- package/dist/routing/learning/index.js.map +1 -0
- package/dist/runtime-BSjrnxeF.d.ts +283 -0
- package/dist/runtime-OISPXS4I.js +19 -0
- package/dist/runtime-OISPXS4I.js.map +1 -0
- package/dist/store-types-2YdceOMy.d.ts +78 -0
- package/dist/types-BB7KqceP.d.ts +52 -0
- package/dist/types-CIqkKXix.d.ts +86 -0
- package/dist/types-DTFc1qO6.d.ts +1065 -0
- package/dist/types-DYex3p7_.d.ts +88 -0
- package/docs/licenses/ruflo-memory-MIT.txt +21 -0
- package/docs/releases/0.1.0-beta.3.md +13 -0
- package/package.json +114 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/orchestration/budget/host-ledger.ts","../src/orchestration/budget/engine.ts","../src/orchestration/budget/sqlite.ts","../src/orchestration/budget/legacy-migration.ts","../src/orchestration/budget/host-options.ts","../src/orchestration/budget/priority.ts","../src/orchestration/budget/bell.ts","../src/orchestration/budget/host-types.ts"],"sourcesContent":["import type { ConcurrencyChange } from './host-types.ts';\nimport { closeSync, lstatSync, mkdirSync, openSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { randomUUID } from 'node:crypto';\nimport { observedUsageLimitReset } from '../../public/errors.ts';\nimport { BudgetEngine } from './engine.ts';\nimport { armBell } from './bell.ts';\nimport { validateHostOptions } from './host-options.ts';\nimport { LaunchRefusedError, LaunchReleaseError, LaunchQuotaRecordError } from './host-types.ts';\nimport { closedRecord, integer } from './validation.ts';\nimport { readLegacySnapshot, type LegacyMigrationOptions, type LegacyMigrationSource } from './legacy-migration.ts';\nimport type { BudgetResult, LaunchBudgetLimits } from './types.ts';\nimport { isLaunchPriority, type LaunchTurn } from './priority.ts';\nimport type { LaunchPriority } from './host-types.ts';\nimport type { AcquireOptions, HostLaunchAdmission, HostLaunchBudgetLimits, HostLaunchBudgetStatus, HostLedgerOptions, HostRecoveryOptions, SlotOptions, HostOwnerLookupOptions, HostOwnerLookup, HostLedgerIdentity } from './host-types.ts';\nexport * from './host-types.ts';\nexport { HOST_LAUNCH_LIMITS, hostLaunchLimits, hostLedgerPath } from './host-options.ts';\nexport { inspectLegacyLaunchBudget, type LegacyMigrationOptions, type LegacyMigrationSource } from './legacy-migration.ts';\nexport { WAITER_LEASE_MS } from './priority.ts';\n\nconst BACKSTOP_MS = 30_000;\nfunction snapshotAcquire(options: AcquireOptions | SlotOptions, slot = false): Readonly<SlotOptions> {\n const keys = ['maxWaitMs', 'signal', 'priority', ...(slot ? ['isQuotaError'] : [])];\n if (!closedRecord(options, keys, ['signal', 'priority', 'isQuotaError']) || !integer(options.maxWaitMs)\n || (options.signal !== undefined && !(options.signal instanceof AbortSignal))\n || ('isQuotaError' in options && options.isQuotaError !== undefined && typeof options.isQuotaError !== 'function')) {\n throw new TypeError('Wait options require a nonnegative safe integer maxWaitMs and an optional AbortSignal');\n }\n if (options.priority !== undefined && !isLaunchPriority(options.priority)) throw new TypeError('priority must be \"normal\" or \"low\"');\n const snapshot: SlotOptions = { maxWaitMs: options.maxWaitMs };\n if (options.priority !== undefined) snapshot.priority = options.priority;\n if (options.signal !== undefined) snapshot.signal = options.signal;\n if ('isQuotaError' in options && options.isQuotaError !== undefined) snapshot.isQuotaError = options.isQuotaError as (error: unknown) => boolean;\n return Object.freeze(snapshot);\n}\n\n/** Trusted local coordination for cooperating processes; this is not a vendor quota or authorization boundary. */\nexport class HostLedger {\n readonly #engine: BudgetEngine;\n readonly #bell: string;\n readonly #databasePath: string;\n readonly #waits = new Set<() => void>();\n /** Waiting callers of this handle whose declaration may be recorded in the shared file. */\n readonly #queued = new Set<string>();\n #closed = false;\n\n constructor(options: HostLedgerOptions = {}) {\n // Finish every validation before creating even the parent directory.\n const config = validateHostOptions(options);\n this.#databasePath = config.databasePath;\n this.#bell = `${config.databasePath}.bell`;\n const providers: Record<string, LaunchBudgetLimits> = Object.create(null);\n const modes = new Map<string, string>();\n for (const [key, policy] of config.policies) {\n const { concurrency, ...limits } = policy;\n providers[key] = { ...limits, maxConcurrent: concurrency.mode === 'limited' ? concurrency.maxConcurrent : 0 };\n modes.set(key, concurrency.mode);\n }\n mkdirSync(dirname(config.databasePath), { recursive: true, mode: 0o700 });\n this.#engine = new BudgetEngine({ databasePath: config.databasePath, providers, busyTimeoutMs: config.busyTimeoutMs }, modes);\n try { closeSync(openSync(this.#bell, 'a', 0o600)); } catch { /* Bounded waits remain safe without notification. */ }\n }\n\n /** One immediate attempt. A `low` priority is refused while a `normal` launch is waiting for the slot. */\n reserve(providerKey: string, owner: string, priority?: LaunchPriority): HostLaunchAdmission {\n return this.#engine.reserve(providerKey, owner, undefined, priority === undefined ? undefined : { priority });\n }\n release(token: string) {\n const result = this.#engine.release(token);\n if (result.ok && result.released) this.#ring();\n return result;\n }\n recordQuotaError(providerKey: string, retryAtMs?: number) {\n const result = this.#engine.recordQuotaError(providerKey, retryAtMs);\n if (result.ok) this.#ring();\n return result;\n }\n status(providerKey: string): BudgetResult<{ status: HostLaunchBudgetStatus }> {\n return this.#engine.hostStatus(providerKey);\n }\n getConcurrency(providerKey: string) { return this.#engine.concurrencyPolicy(providerKey); }\n setConcurrency(providerKey: string, change: ConcurrencyChange) {\n if (change === undefined) throw new TypeError('A concurrency change is required');\n const result = this.#engine.concurrencyPolicy(providerKey,change);\n if (result.ok) this.#ring();\n return result;\n }\n /** Private host evidence discovery, not an authorization or stopped-work proof; default bound detects duplicate owners. */\n lookupOwner(providerKey: string, owner: string, options: HostOwnerLookupOptions = { limit: 2 }): BudgetResult<HostOwnerLookup> {\n return this.#engine.lookupOwner(providerKey, owner, options);\n }\n /** Opaque identity of the actual pinned local database, never worker-supplied authority or stopped-work evidence. */\n storageIdentity(): BudgetResult<{ identity: HostLedgerIdentity }> { return this.#engine.storageIdentity(); }\n recover(options: HostRecoveryOptions) {\n const result = this.#engine.recover(options);\n if (result.ok && result.released > 0) this.#ring();\n return result;\n }\n\n verifyLegacyMigration(options: LegacyMigrationSource): BudgetResult<{ matched: boolean; sourceDigest: string }> {\n try { return this.#engine.verifyMigration(this.#legacy(options, false), options.ownerPrefix); }\n catch (error) { return { ok: false, reason: error instanceof TypeError ? 'invalid-input' : 'storage-unavailable' }; }\n }\n\n importLegacy(options: LegacyMigrationOptions): BudgetResult<{ imported: number; sourceDigest: string }> {\n try { return this.#engine.importLegacy(this.#legacy(options, true), options.ownerPrefix); }\n catch (error) { return { ok: false, reason: error instanceof TypeError ? 'invalid-input' : 'storage-unavailable' }; }\n }\n\n #legacy(options: LegacyMigrationSource | LegacyMigrationOptions, importing: boolean) {\n const keys = ['databasePath', 'ownerPrefix', ...(importing ? ['sourceStoppedConfirmed', 'expectedDigest'] : [])];\n if (!closedRecord(options, keys) || typeof options.ownerPrefix !== 'string' || !options.ownerPrefix.endsWith(':')\n || options.ownerPrefix.length > 128 || options.ownerPrefix.trim() !== options.ownerPrefix\n || /[\\x00-\\x20\\x7f]/.test(options.ownerPrefix)\n || (importing && (!('sourceStoppedConfirmed' in options) || options.sourceStoppedConfirmed !== true\n || !('expectedDigest' in options) || typeof options.expectedDigest !== 'string' || !/^[a-f0-9]{64}$/.test(options.expectedDigest)))) {\n throw new TypeError('A reviewed legacy source and explicit stopped-source acknowledgement are required');\n }\n const snapshot = readLegacySnapshot(options.databasePath as string), target = lstatSync(this.#databasePath);\n if (snapshot.identity.dev === target.dev && snapshot.identity.ino === target.ino) throw new TypeError('Legacy source and host ledger must differ');\n if (importing && 'expectedDigest' in options && options.expectedDigest !== snapshot.sourceDigest) throw new TypeError('Legacy source changed after inspection');\n return snapshot;\n }\n close(): void {\n this.#closed = true;\n this.#leaveQueue([...this.#queued]);\n this.#engine.close();\n for (const cancel of this.#waits) cancel();\n this.#waits.clear();\n }\n\n async acquire(providerKey: string, owner: string, options: AcquireOptions): Promise<HostLaunchAdmission> {\n const snapshot = snapshotAcquire(options);\n return this.#acquire(providerKey, owner, snapshot);\n }\n /**\n * Admission in priority order. A caller that waits is declared in the shared file from its first\n * refused attempt until it is admitted or stops waiting, and other handles are woken when it leaves.\n */\n #acquire(providerKey: string, owner: string, options: Readonly<AcquireOptions>): Promise<HostLaunchAdmission> {\n const turn: LaunchTurn = { priority: options.priority ?? 'normal' };\n // An immediate attempt never queues: it settles exactly as it did before priorities existed.\n if (options.maxWaitMs === 0) return this.#attempts(providerKey, owner, options, turn);\n const waiter = randomUUID();\n turn.waiter = waiter;\n return this.#attempts(providerKey, owner, options, turn).finally(() => {\n if (this.#queued.has(waiter)) this.#leaveQueue([waiter]);\n });\n }\n #leaveQueue(waiters: readonly string[]): void {\n for (const waiter of waiters) {\n this.#queued.delete(waiter);\n this.#engine.stopWaiting(waiter);\n }\n // A lower priority may have left a free slot to this waiter: let it look again.\n if (waiters.length > 0) this.#ring();\n }\n async #attempts(providerKey: string, owner: string, options: Readonly<AcquireOptions>, turn: LaunchTurn): Promise<HostLaunchAdmission> {\n const deadline = performance.now() + options.maxWaitMs;\n for (;;) {\n options.signal?.throwIfAborted();\n if (options.maxWaitMs > 0 && performance.now() >= deadline) return { allowed: false, reason: 'wait-timeout' };\n const bell = armBell(this.#bell, options.signal);\n this.#waits.add(bell.cancel);\n let admission: HostLaunchAdmission;\n try {\n // A waiter woken by the bell arms the watch above from inside the poll phase, so the next\n // poll is one loop turn away. Yield that turn first, or a release landing in it is not heard.\n if (options.maxWaitMs > 0) await new Promise<void>((resolve) => { setImmediate(resolve); });\n // A file watch starts listening when the loop next polls, which is before `setImmediate`\n // runs. Attempting sooner would miss a release that lands in this same turn.\n if (options.maxWaitMs > 0) {\n await new Promise<void>((resolve) => { setImmediate(resolve); });\n options.signal?.throwIfAborted();\n }\n admission = options.maxWaitMs === 0 ? this.#engine.reserve(providerKey, owner, undefined, turn)\n : this.#engine.reserve(providerKey, owner, () => performance.now() < deadline && !options.signal?.aborted, turn);\n if (!admission.allowed && turn.waiter !== undefined && !this.#closed) this.#queued.add(turn.waiter);\n if (!admission.allowed && 'outranked' in admission && options.maxWaitMs > 0) {\n // The slot belongs to a waiting launch of higher priority: sleep until something changes.\n options.signal?.throwIfAborted();\n const left = deadline - performance.now();\n if (left <= 0) return { allowed: false, reason: 'wait-timeout' };\n await bell.wait(Math.min(left, BACKSTOP_MS));\n continue;\n }\n options.signal?.throwIfAborted();\n if (admission.allowed || options.maxWaitMs === 0 || (admission.reason !== 'concurrency-limit' && admission.reason !== 'quota-cooldown')) return admission;\n const status = this.status(providerKey);\n if (!status.ok) { const { ok: _ok, ...failure } = status; return { allowed: false, ...failure }; }\n const state = status.status, concurrency = state.limits.concurrency;\n if (concurrency.mode === 'limited' && concurrency.maxConcurrent === 0) return admission;\n if (admission.reason === 'concurrency-limit' && (concurrency.mode === 'unlimited' || state.active < concurrency.maxConcurrent)) continue;\n const exhausted = state.launchesLastHour >= state.limits.maxLaunchesPerHour ? 'hourly-limit'\n : state.launchesLastDay >= state.limits.maxLaunchesPerDay ? 'daily-limit' : undefined;\n if (exhausted) return { allowed: false, reason: exhausted };\n const remaining = deadline - performance.now();\n if (remaining <= 0) return { allowed: false, reason: 'wait-timeout' };\n const untilQuota = admission.reason === 'quota-cooldown' && admission.retryAt !== undefined\n ? Math.max(1, admission.retryAt - Date.now()) : BACKSTOP_MS;\n await bell.wait(Math.min(remaining, BACKSTOP_MS, untilQuota));\n } finally { bell.cancel(); this.#waits.delete(bell.cancel); }\n }\n }\n\n async withSlot<T>(providerKey: string, owner: string, options: SlotOptions, operation: () => Promise<T>): Promise<T> {\n const snapshot = snapshotAcquire(options, true);\n if (typeof operation !== 'function') throw new TypeError('An operation is required');\n const admission = await this.#acquire(providerKey, owner, snapshot);\n if (!admission.allowed) throw new LaunchRefusedError(admission);\n let operationError: unknown;\n let operationStarted = false;\n try {\n // Admission and this continuation are separated by an await. Keep the hold protected\n // while checking whether the caller stopped or closed the ledger in that gap.\n snapshot.signal?.throwIfAborted();\n if (this.#closed) throw new LaunchRefusedError({ allowed: false, reason: 'closed' });\n operationStarted = true;\n return await operation();\n }\n catch (error) {\n operationError = error;\n if (operationStarted && snapshot.isQuotaError?.(error)) {\n const recorded = this.recordQuotaError(providerKey, observedUsageLimitReset(error, providerKey));\n if (!recorded.ok) {\n operationError = new LaunchQuotaRecordError(recorded, error);\n throw operationError;\n }\n }\n throw error;\n } finally {\n const release = this.release(admission.reservation.token);\n if (!release.ok) throw new LaunchReleaseError(release, operationError);\n }\n }\n #ring(): void {\n try { writeFileSync(this.#bell, String(process.hrtime.bigint()), { mode: 0o600 }); } catch { /* Event loss only delays a waiter. */ }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { types } from 'node:util';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { BudgetDatabase, CLOCK_AUDIT_TABLE } from './sqlite.ts';\nimport { closedRecord, integer, identifier, validateFiniteOptions } from './validation.ts';\nimport { LEGACY_MIGRATIONS, legacyKey, legacyToken, type LegacySnapshot } from './legacy-migration.ts';\nimport { validateConcurrency } from './host-options.ts';\nimport type { HostConcurrency, HostLaunchBudgetStatus, ConcurrencyChange, ConcurrencyPolicy, HostLaunchAdmission, HostRecoveryOptions, HostOwnerLookupOptions, HostOwnerLookup, HostOwnerReservation, HostLedgerIdentity } from './host-types.ts';\nimport type { SharedLaunchBudgetOptions, LaunchAdmission, BudgetResult, LaunchBudgetStatus,\n LaunchBudgetLimits, BudgetFailure, BudgetDenialReason, LaunchReservation, ClockAcknowledgement } from './types.ts';\nimport { declareWaiter, forgetWaiter, isOutranked, validTurn, type LaunchTurn } from './priority.ts';\n\nconst HOUR = 3_600_000;\nconst DAY = 86_400_000;\nclass Denied extends Error {\n readonly failure: BudgetFailure;\n constructor(reason: BudgetDenialReason, detail?: string, retryAt?: number) {\n super(detail ?? reason);\n this.failure = { reason, ...(detail === undefined ? {} : { detail }), ...(retryAt === undefined ? {} : { retryAt }) };\n }\n}\n\nfunction rollback(row: ProviderRow): Denied {\n return new Denied('clock-rollback', `The system clock is behind the ledger's last observed time ${new Date(row.last_observed_at).toISOString()}`, row.last_observed_at);\n}\n\ninterface ProviderRow {\n provider_key: string;\n max_concurrent: number;\n max_hour: number;\n max_day: number;\n cooldown_ms: number;\n paused_until: number;\n last_observed_at: number;\n}\nconst CONCURRENCY_MODES = `CREATE TABLE IF NOT EXISTS budget_concurrency_modes (\n provider_key TEXT PRIMARY KEY REFERENCES budget_providers(provider_key),\n mode TEXT NOT NULL CHECK(mode IN ('limited', 'unlimited'))\n) STRICT;`;\n\n\n/**\n * A conservative launch fuse shared by cooperating processes on one local file.\n * It does not infer subscription quota, spend money, or schedule denied work.\n * Every reservation consumes a launch immediately; release only frees concurrency.\n * Active reservations never expire, including after close() or a process crash.\n * Recover a token only after verifying its operation has stopped. This trusted-local\n * coordination primitive is not an authorization boundary against ledger writers.\n */\nexport class BudgetEngine {\n readonly #modes: ReadonlyMap<string, string>;\n readonly #providers = new Map<string, LaunchBudgetLimits>();\n #database: BudgetDatabase | undefined;\n #fault: string | undefined;\n #closed = false;\n\n /** Invalid configuration throws before I/O; unavailable storage fails closed in results. */\n constructor(options: SharedLaunchBudgetOptions, modes: ReadonlyMap<string, string> = new Map()) {\n validateFiniteOptions(options);\n this.#modes = modes;\n for (const [key, limits] of Object.entries(options.providers)) this.#providers.set(key, { ...limits });\n const busyTimeoutMs = options.busyTimeoutMs ?? 1000;\n try { this.#database = new BudgetDatabase(options.databasePath, busyTimeoutMs); }\n catch (error) { this.#fault = error instanceof Error ? error.message : String(error); }\n }\n\n reserve(providerKey: string, owner: string): LaunchAdmission;\n reserve(providerKey: string, owner: string, mayAdmit: (() => boolean) | undefined, turn?: LaunchTurn): HostLaunchAdmission;\n reserve(providerKey: string, owner: string, mayAdmit?: () => boolean, turn?: LaunchTurn): HostLaunchAdmission {\n const result = this.#operate(db => {\n if (!identifier(owner)) throw new Denied('invalid-input', 'Owner must be a nonempty identifier of at most 256 characters');\n const { row, limits, now, mode } = this.#provider(db, providerKey);\n if (mayAdmit && !mayAdmit()) return { allowed: false as const, reason: 'wait-timeout' as const };\n this.#observe(db, row, now);\n const status = this.#status(db, row, limits, now);\n if (turn !== undefined && !validTurn(turn)) throw new Denied('invalid-input', 'Priority must be normal or low');\n // A caller that will wait declares itself first, so a lower priority leaves the next slot to it.\n if (turn !== undefined) declareWaiter(db, providerKey, turn, now);\n let reason: BudgetDenialReason | undefined;\n if (row.paused_until > now) return { allowed: false as const, reason: 'quota-cooldown' as const, retryAt: row.paused_until };\n if (mode !== 'unlimited' && status.active >= limits.maxConcurrent) reason = 'concurrency-limit';\n else if (status.launchesLastHour >= limits.maxLaunchesPerHour) reason = 'hourly-limit';\n else if (status.launchesLastDay >= limits.maxLaunchesPerDay) reason = 'daily-limit';\n if (!reason && turn !== undefined && isOutranked(db, providerKey, turn, now)) {\n return { allowed: false as const, reason: 'concurrency-limit' as const, outranked: true as const };\n }\n if (reason) return { allowed: false as const, reason };\n if (mayAdmit && !mayAdmit()) return { allowed: false as const, reason: 'wait-timeout' as const };\n const reservation: LaunchReservation = { token: randomUUID(), providerKey, owner, admittedAt: now };\n db.prepare('INSERT INTO budget_reservations(token, provider_key, owner, admitted_at) VALUES (?, ?, ?, ?)')\n .run(reservation.token, providerKey, owner, now);\n if (turn?.waiter !== undefined) forgetWaiter(db, turn.waiter);\n return { allowed: true as const, reservation };\n });\n if (!result.ok) { const { ok: _ok, ...failure } = result; return { allowed: false, ...failure }; }\n return result.value;\n }\n\n /** Withdraws a waiting caller's declaration once it stops waiting. Frees and grants nothing. */\n stopWaiting(waiter: string): BudgetResult<{ withdrawn: boolean }> {\n return this.#flatten(this.#operate(db => {\n if (!identifier(waiter)) throw new Denied('invalid-input', 'Invalid waiter');\n return { withdrawn: forgetWaiter(db, waiter) };\n }));\n }\n\n /** Idempotent recovery/completion. Unknown tokens free nothing; no launch is refunded. */\n release(token: string): BudgetResult<{ released: boolean }> {\n return this.#flatten(this.#operate(db => {\n if (!identifier(token)) throw new Denied('invalid-input', 'Invalid reservation token');\n const result = db.prepare('UPDATE budget_reservations SET released = 1 WHERE token = ? AND released = 0').run(token);\n return { released: result.changes === 1 };\n }));\n }\n\n /** Call only after an explicit observed provider quota error. No text heuristics. */\n recordQuotaError(providerKey: string, retryAtMs?: number): BudgetResult<{ pausedUntil: number }> {\n return this.#flatten(this.#operate(db => {\n const { row, limits, now } = this.#provider(db, providerKey);\n this.#observe(db, row, now);\n if (retryAtMs !== undefined && !integer(retryAtMs)) throw new Denied('invalid-input', 'Invalid quota reset timestamp');\n const pausedUntil = Math.max(row.paused_until, now + limits.quotaCooldownMs, retryAtMs ?? 0);\n if (!integer(pausedUntil)) throw new Denied('invalid-input', 'Cooldown would exceed the safe timestamp range');\n db.prepare('UPDATE budget_providers SET paused_until = ? WHERE provider_key = ?').run(pausedUntil, providerKey);\n return { pausedUntil };\n }));\n }\n\n /** Read-only: compares the clock with the ledger's mark but never advances it. */\n status(providerKey: string): BudgetResult<{ status: LaunchBudgetStatus }> {\n return this.#flatten(this.#operate(db => {\n const { row, limits, now } = this.#provider(db, providerKey);\n if (now < row.last_observed_at) throw rollback(row);\n return { status: this.#status(db, row, limits, now) };\n }));\n }\n\n hostStatus(providerKey: string): BudgetResult<{status: HostLaunchBudgetStatus}> {\n return this.#flatten(this.#operate(db => {\n const { row, limits, now, mode } = this.#provider(db, providerKey);\n if (now < row.last_observed_at) throw rollback(row);\n const status = this.#status(db, row, limits, now);\n const {maxConcurrent, ...windows} = limits;\n const concurrency: HostConcurrency = mode === 'unlimited' ? {mode} : {mode:'limited', maxConcurrent};\n return {status: {...status, limits: {...windows, concurrency}}};\n }));\n }\n\n /** One revision per provider. Ordinary admissions never replace an existing operator policy. */\n concurrencyPolicy(providerKey: string, change?: ConcurrencyChange): BudgetResult<{policy: ConcurrencyPolicy}> {\n return this.#flatten(this.#operate(db => {\n if (!identifier(providerKey)) throw new Denied('invalid-input');\n if (change !== undefined) {\n if (types.isProxy(change) || !closedRecord(change, ['expectedRevision','concurrency']) || !integer(change.expectedRevision) || types.isProxy(change.concurrency))\n throw new Denied('invalid-input');\n try { validateConcurrency(change.concurrency); } catch { throw new Denied('invalid-input'); }\n }\n // The operator can inspect or edit an existing registered account with custom window limits.\n let row = db.prepare('SELECT max_concurrent FROM budget_providers WHERE provider_key=?').get(providerKey);\n if (!row) row = {max_concurrent: this.#provider(db, providerKey).row.max_concurrent};\n db.exec(CONCURRENCY_MODES);\n db.exec(`CREATE TABLE IF NOT EXISTS budget_concurrency_revisions (\n provider_key TEXT PRIMARY KEY REFERENCES budget_providers(provider_key),\n revision INTEGER NOT NULL CHECK(revision > 0)\n ) STRICT;`);\n const mode = db.prepare('SELECT mode FROM budget_concurrency_modes WHERE provider_key=?').get(providerKey)?.mode ?? 'limited';\n const revision = Number(db.prepare('SELECT revision FROM budget_concurrency_revisions WHERE provider_key=?').get(providerKey)?.revision ?? 0);\n if (!integer(revision) || !integer(row.max_concurrent) || !['limited','unlimited'].includes(String(mode))\n || mode === 'unlimited' && row.max_concurrent !== 0) throw Error('Invalid stored concurrency policy');\n const current: HostConcurrency = mode === 'unlimited' ? {mode} : {mode:'limited',maxConcurrent:Number(row.max_concurrent)};\n if (!change) return {policy:{revision,concurrency:current}};\n const next = change.concurrency;\n const same = next.mode === 'unlimited'\n ? current.mode === 'unlimited'\n : current.mode === 'limited' && current.maxConcurrent === next.maxConcurrent;\n // An exact repeated update is already satisfied even if the commit acknowledgement was lost.\n if (same && (revision === change.expectedRevision || revision === change.expectedRevision + 1)) return {policy:{revision,concurrency:current}};\n if (revision !== change.expectedRevision) throw new Denied('configuration-mismatch', 'Concurrency policy revision changed');\n if (!Number.isSafeInteger(revision + 1)) throw new Denied('invalid-input','Concurrency revision exhausted');\n db.prepare('UPDATE budget_providers SET max_concurrent=? WHERE provider_key=?').run(next.mode === 'limited' ? next.maxConcurrent : 0, providerKey);\n db.prepare('INSERT INTO budget_concurrency_modes(provider_key, mode) VALUES(?,?) ON CONFLICT(provider_key) DO UPDATE SET mode=excluded.mode').run(providerKey,next.mode);\n db.prepare('INSERT INTO budget_concurrency_revisions(provider_key, revision) VALUES(?,?) ON CONFLICT(provider_key) DO UPDATE SET revision=excluded.revision').run(providerKey,revision + 1);\n return {policy:{revision:revision + 1,concurrency:{...next}}};\n }));\n }\n\n /** Exact bounded inspection, including retained released rows. Absence never proves an old acquisition cannot commit. */\n lookupOwner(providerKey: string, owner: string, options: HostOwnerLookupOptions): BudgetResult<HostOwnerLookup> {\n return this.#flatten(this.#operate(db => {\n if (!identifier(owner) || !options || types.isProxy(options) || !closedRecord(options, ['limit'])\n || !integer(options.limit, 1) || options.limit > 100) throw new Denied('invalid-input', 'Exact owner and lookup limit 1..100 required');\n const { row, now } = this.#provider(db, providerKey);\n if (now < row.last_observed_at) throw rollback(row);\n const found = db.prepare(`SELECT token, provider_key AS providerKey, owner, admitted_at AS admittedAt, released\n FROM budget_reservations WHERE provider_key = ? AND owner = ? ORDER BY admitted_at, token LIMIT ?`)\n .all(providerKey, owner, options.limit + 1);\n const reservations = found.slice(0, options.limit).map(value => Object.freeze({ token: value.token as string,\n providerKey: value.providerKey as string, owner: value.owner as string, admittedAt: value.admittedAt as number,\n released: value.released === 1 }) satisfies HostOwnerReservation);\n return { reservations: Object.freeze(reservations), truncated: found.length > options.limit };\n }));\n }\n\n storageIdentity(): BudgetResult<{ identity: HostLedgerIdentity }> {\n const result = this.#flatten(this.#operate(() => ({ identity: Object.freeze({ format: 1 as const,\n digest: this.#database!.storageDigest() }) })));\n // Filesystem error messages can contain the private database path.\n return result.ok ? result : { ok: false, reason: result.reason };\n }\n\n /**\n * Explicit operator recovery from `clock-rollback` (a date advanced for a test and restored).\n * Moves the ledger's observed time to now. Nothing is refunded: every reservation stays held,\n * future-dated launches keep counting against the rolling windows and an active cooldown keeps\n * pausing. If pruning already removed history the current window could need, acknowledgement\n * is refused until that window expires; legacy ledgers conservatively assume possible pruning.\n * The acknowledgement is recorded in the ledger itself.\n */\n acknowledgeClock(providerKey: string, acknowledgement: ClockAcknowledgement): BudgetResult<{ previousObservedAt: number; acknowledgedAt: number }> {\n return this.#flatten(this.#operate(db => {\n if (!closedRecord(acknowledgement, ['operatorConfirmed']) || acknowledgement.operatorConfirmed !== true) {\n throw new Denied('invalid-input', 'Explicitly confirm that an operator verified the system clock');\n }\n const { row, now } = this.#provider(db, providerKey);\n const history = db.prepare('SELECT pruned_through FROM budget_pruning_state WHERE provider_key = ?').get(providerKey);\n if (history && Number(history.pruned_through) > now - DAY) {\n const safeAt = Number(history.pruned_through) + DAY;\n throw new Denied('clock-rollback', 'Pruned launch history may still belong to the current budget window; acknowledgement cannot refund it', Number.isSafeInteger(safeAt) ? safeAt : undefined);\n }\n db.exec(CLOCK_AUDIT_TABLE);\n db.prepare('INSERT INTO budget_clock_acknowledgements(provider_key, previous_observed_at, acknowledged_at, pid) VALUES (?, ?, ?, ?)')\n .run(providerKey, row.last_observed_at, now, process.pid);\n db.prepare('UPDATE budget_providers SET last_observed_at = ? WHERE provider_key = ?').run(now, providerKey);\n return { previousObservedAt: row.last_observed_at, acknowledgedAt: now };\n }));\n }\n\n /** Exact inspected bearer tokens only; no prefix sweep or automatic owner inference. */\n recover(options: HostRecoveryOptions): BudgetResult<{ released: number }> {\n if (!closedRecord(options, ['ownerPrefix', 'tokens', 'acknowledgement']) || !identifier(options.ownerPrefix)\n || !Array.isArray(options.tokens) || options.tokens.length > 1000\n || options.tokens.some(token => !identifier(token)) || new Set(options.tokens).size !== options.tokens.length\n || !closedRecord(options.acknowledgement, ['workStopped', 'evidenceDigest'])\n || options.acknowledgement.workStopped !== true || typeof options.acknowledgement.evidenceDigest !== 'string'\n || !/^[a-fA-F0-9]{64}$/u.test(options.acknowledgement.evidenceDigest)) {\n return { ok: false, reason: 'invalid-input', detail: 'Exact unique tokens and SHA256 evidence of stopped work are required' };\n }\n return this.#flatten(this.#operate(db => {\n for (const token of options.tokens) {\n const row = db.prepare('SELECT owner, provider_key FROM budget_reservations WHERE token = ?').get(token);\n if (!row || typeof row.owner !== 'string' || !row.owner.startsWith(options.ownerPrefix)) {\n throw new Denied('invalid-input', 'Selected token is missing or belongs to another owner');\n }\n this.#provider(db, String(row.provider_key));\n }\n let released = 0;\n const update = db.prepare('UPDATE budget_reservations SET released = 1 WHERE token = ? AND released = 0');\n for (const token of options.tokens) released += Number(update.run(token).changes);\n return { released };\n }));\n }\n\n /** Closing does not release reservations; an operation may still be running. */\n verifyMigration(snapshot: LegacySnapshot, ownerPrefix: string): BudgetResult<{ matched: boolean; sourceDigest: string }> {\n return this.#flatten(this.#operate(db => {\n const exists = db.prepare(\"SELECT 1 FROM sqlite_schema WHERE type='table' AND name='budget_legacy_migrations'\").get();\n const row = exists ? db.prepare('SELECT source_digest FROM budget_legacy_migrations WHERE migration_key=?').get(legacyKey(snapshot.databasePath, ownerPrefix)) : undefined;\n return { matched: row?.source_digest === snapshot.sourceDigest, sourceDigest: snapshot.sourceDigest };\n }));\n }\n\n importLegacy(snapshot: LegacySnapshot, ownerPrefix: string): BudgetResult<{ imported: number; sourceDigest: string }> {\n return this.#flatten(this.#operate(db => {\n const key = legacyKey(snapshot.databasePath, ownerPrefix);\n db.exec(LEGACY_MIGRATIONS);\n const prior = db.prepare('SELECT source_digest FROM budget_legacy_migrations WHERE migration_key=?').get(key);\n if (prior?.source_digest === snapshot.sourceDigest) return { imported: 0, sourceDigest: snapshot.sourceDigest };\n for (const provider of snapshot.providers) {\n this.#provider(db, provider.providerKey);\n db.prepare('UPDATE budget_providers SET paused_until=MAX(paused_until,?),last_observed_at=MAX(last_observed_at,?) WHERE provider_key=?')\n .run(provider.pausedUntil, provider.observedAt, provider.providerKey);\n db.prepare(`INSERT INTO budget_pruning_state(provider_key,pruned_through) VALUES (?,?)\n ON CONFLICT(provider_key) DO UPDATE SET pruned_through=MAX(pruned_through,excluded.pruned_through)`)\n .run(provider.providerKey, provider.prunedThrough);\n }\n let imported = 0;\n // Provenance must outlive reservation pruning: recovering an imported hold may\n // never be undone by a later source revision whose old row is still active.\n const remember = db.prepare('INSERT INTO budget_legacy_imported_tokens(token) VALUES (?) ON CONFLICT(token) DO NOTHING');\n const insert = db.prepare('INSERT INTO budget_reservations(token,provider_key,owner,admitted_at,released) VALUES (?,?,?,?,?) ON CONFLICT(token) DO NOTHING');\n for (const reservation of snapshot.reservations) {\n const owner = ownerPrefix + reservation.owner;\n if (!identifier(owner)) throw new Denied('invalid-input', 'Prefixed legacy owner exceeds identifier bounds');\n const token = legacyToken(key, reservation.token);\n if (remember.run(token).changes === 0) continue;\n imported += Number(insert.run(token, reservation.providerKey, owner, reservation.admittedAt, reservation.released).changes);\n }\n db.prepare(`INSERT INTO budget_legacy_migrations(migration_key,source_digest,imported_at) VALUES (?,?,?)\n ON CONFLICT(migration_key) DO UPDATE SET source_digest=excluded.source_digest,imported_at=excluded.imported_at`)\n .run(key, snapshot.sourceDigest, Date.now());\n return { imported, sourceDigest: snapshot.sourceDigest };\n }));\n }\n\n close(): void {\n if (!this.#closed) { this.#closed = true; this.#database?.close(); }\n }\n\n #provider(db: DatabaseSync, providerKey: string) {\n const limits = this.#providers.get(providerKey);\n if (!limits) throw new Denied('unknown-provider');\n const now = Date.now();\n if (!integer(now)) throw new Denied('invalid-input', 'Invalid system clock');\n // A new row starts unobserved (0): only #observe (reserve, recordQuotaError) stamps the clock,\n // so a status() read under a forward clock cannot create a provider already marked ahead.\n db.exec(CONCURRENCY_MODES);\n const inserted = db.prepare(`INSERT INTO budget_providers\n (provider_key, max_concurrent, max_hour, max_day, cooldown_ms, paused_until, last_observed_at)\n VALUES (?, ?, ?, ?, ?, 0, 0) ON CONFLICT(provider_key) DO NOTHING`)\n .run(providerKey, limits.maxConcurrent, limits.maxLaunchesPerHour, limits.maxLaunchesPerDay, limits.quotaCooldownMs);\n const mode = this.#modes.get(providerKey) ?? 'limited';\n if (inserted.changes === 1) db.prepare('INSERT INTO budget_concurrency_modes(provider_key, mode) VALUES (?, ?)').run(providerKey, mode);\n const persistedMode = db.prepare('SELECT mode FROM budget_concurrency_modes WHERE provider_key = ?').get(providerKey)?.mode ?? 'limited';\n if (persistedMode !== 'limited' && persistedMode !== 'unlimited') throw Error('Invalid stored concurrency mode');\n const row = db.prepare('SELECT * FROM budget_providers WHERE provider_key = ?').get(providerKey) as unknown as ProviderRow;\n const legacyMismatch = !this.#modes.has(providerKey) && (persistedMode !== mode || row.max_concurrent !== limits.maxConcurrent);\n if (legacyMismatch || row.max_hour !== limits.maxLaunchesPerHour\n || row.max_day !== limits.maxLaunchesPerDay || row.cooldown_ms !== limits.quotaCooldownMs) throw new Denied('configuration-mismatch');\n if (persistedMode === 'unlimited' && row.max_concurrent !== 0) throw Error('Invalid stored unlimited policy');\n return { row, limits: {...limits, maxConcurrent:row.max_concurrent}, now, mode:persistedMode };\n }\n\n /** Only a ledger mutation (reserve, recordQuotaError) advances the observed clock; reads never do. */\n #observe(db: DatabaseSync, row: ProviderRow, now: number): void {\n if (now < row.last_observed_at) throw rollback(row);\n db.prepare('UPDATE budget_providers SET last_observed_at = ? WHERE provider_key = ?').run(now, row.provider_key);\n // Expired, completed records no longer affect a rolling window. Active rows are never pruned.\n db.prepare('DELETE FROM budget_reservations WHERE provider_key = ? AND admitted_at <= ? AND released = 1').run(row.provider_key, now - DAY);\n }\n\n #status(db: DatabaseSync, row: ProviderRow, limits: LaunchBudgetLimits, now: number): LaunchBudgetStatus {\n const counts = db.prepare(`SELECT COUNT(*) FILTER (WHERE released = 0) AS active,\n COUNT(*) FILTER (WHERE admitted_at > ?) AS hour,\n COUNT(*) FILTER (WHERE admitted_at > ?) AS day FROM budget_reservations WHERE provider_key = ?`)\n .get(now - HOUR, now - DAY, row.provider_key)!;\n const reservations = db.prepare(`SELECT token, provider_key AS providerKey, owner, admitted_at AS admittedAt\n FROM budget_reservations WHERE provider_key = ? AND released = 0 ORDER BY admitted_at, token`).all(row.provider_key) as unknown as LaunchReservation[];\n return { providerKey: row.provider_key, limits: { ...limits }, active: Number(counts.active),\n launchesLastHour: Number(counts.hour), launchesLastDay: Number(counts.day),\n pausedUntil: row.paused_until > now ? row.paused_until : null, reservations };\n }\n\n #operate<T>(work: (db: DatabaseSync) => T): BudgetResult<{ value: T }> {\n if (this.#closed) return { ok: false, reason: 'closed' };\n if (!this.#database) return { ok: false, reason: 'storage-unavailable', detail: this.#fault ?? 'Database unavailable' };\n try { return { ok: true, value: this.#database.transaction(work) }; }\n catch (error) {\n if (error instanceof Denied) return { ok: false, ...error.failure };\n return { ok: false, reason: 'storage-unavailable', detail: error instanceof Error ? error.message : String(error) };\n }\n }\n\n #flatten<T>(result: BudgetResult<{ value: T }>): BudgetResult<T> {\n return result.ok ? { ok: true, ...result.value } : result;\n }\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { closeSync, fsyncSync, linkSync, lstatSync, openSync, realpathSync, unlinkSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\n\nconst APPLICATION_ID = 0x4f415242; // OARB: dedicated HiveAgents Runtime budget database.\n/** Additive audit of operator clock acknowledgements. Created lazily in ledgers published before\n * it existed, so a cooperating process on an older build keeps sharing the same version-1 file. */\nexport const CLOCK_AUDIT_TABLE = `\nCREATE TABLE IF NOT EXISTS budget_clock_acknowledgements (\n provider_key TEXT NOT NULL REFERENCES budget_providers(provider_key),\n previous_observed_at INTEGER NOT NULL CHECK(previous_observed_at BETWEEN 0 AND 9007199254740991),\n acknowledged_at INTEGER NOT NULL CHECK(acknowledged_at BETWEEN 0 AND 9007199254740991),\n pid INTEGER NOT NULL CHECK(pid BETWEEN 0 AND 9007199254740991)\n) STRICT;`;\n/** A bounded watermark, maintained by SQLite even for an older process's prepared DELETE.\n * Once history was pruned, a clock acknowledgement must not reopen a window that needed it. */\nconst PRUNING_SCHEMA = `\nCREATE TABLE IF NOT EXISTS budget_pruning_state (\n provider_key TEXT PRIMARY KEY REFERENCES budget_providers(provider_key),\n pruned_through INTEGER NOT NULL CHECK(pruned_through BETWEEN 0 AND 9007199254740991)\n) STRICT;\nCREATE TRIGGER IF NOT EXISTS budget_track_pruning AFTER DELETE ON budget_reservations\nBEGIN\n INSERT INTO budget_pruning_state(provider_key, pruned_through) VALUES (OLD.provider_key, OLD.admitted_at)\n ON CONFLICT(provider_key) DO UPDATE SET pruned_through = MAX(budget_pruning_state.pruned_through, excluded.pruned_through);\nEND;`;\n\nfunction installPruningTracking(db: DatabaseSync): void {\n const tracked = db.prepare(\"SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'budget_pruning_state'\").get();\n db.exec(PRUNING_SCHEMA);\n // Before this tracker existed, a cooperating writer could have pruned through observed time minus\n // a day. There is no evidence of what was deleted: retain that conservative upper bound once.\n if (!tracked) db.exec(`INSERT INTO budget_pruning_state(provider_key, pruned_through)\n SELECT provider_key, last_observed_at - 86400000 FROM budget_providers WHERE last_observed_at >= 86400000;`);\n}\nconst SCHEMA = `\nCREATE TABLE budget_providers (\n provider_key TEXT PRIMARY KEY NOT NULL CHECK(length(provider_key) BETWEEN 1 AND 256),\n max_concurrent INTEGER NOT NULL CHECK(max_concurrent BETWEEN 0 AND 9007199254740991),\n max_hour INTEGER NOT NULL CHECK(max_hour BETWEEN 0 AND 9007199254740991),\n max_day INTEGER NOT NULL CHECK(max_day BETWEEN 0 AND 9007199254740991),\n cooldown_ms INTEGER NOT NULL CHECK(cooldown_ms BETWEEN 1 AND 9007199254740991),\n paused_until INTEGER NOT NULL CHECK(paused_until BETWEEN 0 AND 9007199254740991),\n last_observed_at INTEGER NOT NULL CHECK(last_observed_at BETWEEN 0 AND 9007199254740991)\n) STRICT;\nCREATE TABLE budget_reservations (\n token TEXT PRIMARY KEY NOT NULL,\n provider_key TEXT NOT NULL REFERENCES budget_providers(provider_key),\n owner TEXT NOT NULL CHECK(length(owner) BETWEEN 1 AND 256),\n admitted_at INTEGER NOT NULL CHECK(admitted_at BETWEEN 0 AND 9007199254740991),\n released INTEGER NOT NULL DEFAULT 0 CHECK(released IN (0, 1))\n) STRICT;\nCREATE INDEX budget_reservations_provider_time ON budget_reservations(provider_key, admitted_at);\n${CLOCK_AUDIT_TABLE}\n${PRUNING_SCHEMA}\nPRAGMA application_id = ${APPLICATION_ID};\nPRAGMA user_version = 1;\n`;\n\n/** Publish a complete database atomically; an existing empty file is corruption,\n * never evidence that this caller is authorized to reset the ledger. A losing\n * first-open contender adopts the winner's fully initialized file. */\nfunction publishNewDatabase(path: string): void {\n const temporary = `${path}.${randomUUID()}.initializing`;\n closeSync(openSync(temporary, 'wx', 0o600));\n let candidate: DatabaseSync | undefined;\n try {\n candidate = new DatabaseSync(temporary);\n candidate.exec(`PRAGMA synchronous = FULL; BEGIN IMMEDIATE; ${SCHEMA} COMMIT;`);\n candidate.close(); candidate = undefined;\n try { linkSync(temporary, path); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }\n const directory = openSync(dirname(path), 'r');\n try { fsyncSync(directory); } finally { closeSync(directory); }\n } finally {\n candidate?.close();\n unlinkSync(temporary);\n }\n}\n\n/** SQLite owns locking and crash recovery. There is no age-based lock takeover. */\nexport class BudgetDatabase {\n readonly db: DatabaseSync;\n readonly path: string;\n readonly identity: { dev: bigint; ino: bigint };\n #configured = false;\n #pruningReady = false;\n readonly #busyTimeoutMs: number;\n\n constructor(path: string, busyTimeoutMs: number) {\n this.path = path;\n this.#busyTimeoutMs = busyTimeoutMs;\n try { lstatSync(path); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n publishNewDatabase(path);\n }\n const stat = lstatSync(path, { bigint: true });\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Budget database must be a regular file');\n this.identity = { dev: stat.dev, ino: stat.ino };\n this.db = new DatabaseSync(path);\n try {\n this.#configure();\n this.db.exec('BEGIN IMMEDIATE');\n try {\n this.verify();\n installPruningTracking(this.db);\n this.db.exec('COMMIT'); this.#pruningReady = true;\n } catch (error) { this.db.exec('ROLLBACK'); throw error; }\n } catch (error) {\n // A competing writer is temporary, not corruption. Keep this connection and its original\n // inode; every operation still verifies the complete ledger before admitting anything.\n const code = error instanceof Error && 'errcode' in error ? error.errcode : undefined;\n if (typeof code !== 'number' || ![5, 6].includes(code & 255)) { this.db.close(); throw error; }\n }\n }\n\n #configure(): void {\n this.db.exec(`PRAGMA busy_timeout = ${this.#busyTimeoutMs}; PRAGMA foreign_keys = ON; PRAGMA synchronous = FULL;`);\n this.#configured = true;\n }\n\n verify(): void {\n const current = lstatSync(this.path, { bigint: true });\n if (!current.isFile() || current.isSymbolicLink()\n || current.dev !== this.identity.dev || current.ino !== this.identity.ino) {\n throw new Error('Budget database was replaced or removed');\n }\n if (this.db.prepare('PRAGMA application_id').get()?.application_id !== APPLICATION_ID\n || this.db.prepare('PRAGMA user_version').get()?.user_version !== 1) {\n throw new Error('Unrecognized budget database version');\n }\n const check = this.db.prepare('PRAGMA quick_check(1)').get();\n if (check?.quick_check !== 'ok' || this.db.prepare('PRAGMA foreign_key_check').get() !== undefined) {\n throw new Error('Budget database integrity check failed');\n }\n }\n\n /** Called inside this pinned connection's verified transaction. No mutable budget rows are hashed. */\n storageDigest(): string {\n const path = realpathSync(this.path);\n this.verify();\n return createHash('sha256').update(JSON.stringify(['oar-host-ledger', 1, APPLICATION_ID, path,\n String(this.identity.dev), String(this.identity.ino)])).digest('hex');\n }\n\n transaction<T>(work: (db: DatabaseSync) => T): T {\n if (!this.#configured) this.#configure();\n this.db.exec('BEGIN IMMEDIATE');\n try {\n this.verify();\n if (!this.#pruningReady) installPruningTracking(this.db);\n const result = work(this.db);\n this.db.exec('COMMIT'); this.#pruningReady = true;\n return result;\n } catch (error) {\n try { this.db.exec('ROLLBACK'); } catch { /* Never turn uncertain storage into an admission. */ }\n throw error;\n }\n }\n\n close(): void { this.db.close(); }\n}\n","import { createHash } from 'node:crypto';\nimport { lstatSync } from 'node:fs';\nimport { DatabaseSync } from 'node:sqlite';\nimport { absolutePath, identifier, integer } from './validation.ts';\n\nexport interface LegacyMigrationSource { databasePath: string; ownerPrefix: string }\nexport interface LegacyMigrationOptions extends LegacyMigrationSource {\n expectedDigest: string;\n /** Trusted operator acknowledgement; the ledger cannot prove process termination. */\n sourceStoppedConfirmed: true;\n}\ninterface LegacyProvider { providerKey: string; pausedUntil: number; observedAt: number; prunedThrough: number }\ninterface LegacyReservation { token: string; providerKey: string; owner: string; admittedAt: number; released: number }\nexport interface LegacySnapshot {\n databasePath: string; sourceDigest: string; identity: { dev: number; ino: number };\n providers: LegacyProvider[]; reservations: LegacyReservation[];\n}\nexport const legacyKey = (path: string, prefix: string) => createHash('sha256').update(JSON.stringify([path, prefix])).digest('hex');\nexport const legacyToken = (key: string, token: string) => `legacy:${createHash('sha256').update(JSON.stringify([key, token])).digest('hex')}`;\nexport const LEGACY_MIGRATIONS = `CREATE TABLE IF NOT EXISTS budget_legacy_migrations (\n migration_key TEXT PRIMARY KEY, source_digest TEXT NOT NULL, imported_at INTEGER NOT NULL\n) STRICT;\nCREATE TABLE IF NOT EXISTS budget_legacy_imported_tokens (token TEXT PRIMARY KEY NOT NULL) STRICT;`;\n\n/** Read-only snapshot of the version-1 budget protocol, never a migration or source rewrite. */\nexport function readLegacySnapshot(databasePath: string): LegacySnapshot {\n absolutePath(databasePath);\n const before = lstatSync(databasePath);\n if (!before.isFile() || before.isSymbolicLink() || before.size > 64 * 1024 * 1024) throw new Error('Legacy ledger must be a bounded regular file');\n const db = new DatabaseSync(databasePath, { readOnly: true });\n try {\n db.exec('PRAGMA query_only = ON; PRAGMA busy_timeout = 1000; BEGIN;');\n if (db.prepare('PRAGMA application_id').get()?.application_id !== 0x4f415242\n || db.prepare('PRAGMA user_version').get()?.user_version !== 1\n || db.prepare('PRAGMA quick_check(1)').get()?.quick_check !== 'ok'\n || db.prepare('PRAGMA foreign_key_check').get() !== undefined) throw new Error('Unrecognized or corrupt legacy ledger');\n const hasPruning = !!db.prepare(\"SELECT 1 FROM sqlite_schema WHERE type='table' AND name='budget_pruning_state'\").get();\n const pruning = new Map(hasPruning ? db.prepare('SELECT provider_key,pruned_through FROM budget_pruning_state LIMIT 1001').all()\n .map(row => {\n if (!identifier(row.provider_key) || !integer(row.pruned_through)) throw new Error('Invalid legacy pruning state');\n return [row.provider_key, row.pruned_through] as const;\n }) : []);\n if (pruning.size > 1000) throw new Error('Legacy pruning count exceeds migration budget');\n const providers = db.prepare('SELECT * FROM budget_providers ORDER BY provider_key LIMIT 1001').all().map(row => {\n if (!identifier(row.provider_key) || !['max_concurrent', 'max_hour', 'max_day', 'paused_until', 'last_observed_at'].every(key => integer(row[key]))\n || !integer(row.cooldown_ms, 1)) throw new Error('Invalid legacy provider state');\n return { providerKey: row.provider_key, pausedUntil: Number(row.paused_until), observedAt: Number(row.last_observed_at),\n prunedThrough: pruning.get(row.provider_key) ?? Math.max(0, Number(row.last_observed_at) - 86_400_000) };\n });\n if (providers.length > 1000) throw new Error('Legacy provider count exceeds migration budget');\n const known = new Set(providers.map(row => row.providerKey));\n const reservations = db.prepare('SELECT * FROM budget_reservations ORDER BY token LIMIT 100001').all().map(row => {\n if (!identifier(row.token) || !identifier(row.provider_key) || !known.has(row.provider_key) || !identifier(row.owner)\n || !integer(row.admitted_at) || ![0, 1].includes(Number(row.released))) throw new Error('Invalid legacy reservation');\n return { token: row.token, providerKey: row.provider_key, owner: row.owner, admittedAt: Number(row.admitted_at), released: Number(row.released) };\n });\n if (reservations.length > 100000) throw new Error('Legacy reservation count exceeds migration budget');\n const after = lstatSync(databasePath);\n if (!after.isFile() || after.isSymbolicLink() || after.dev !== before.dev || after.ino !== before.ino) throw new Error('Legacy ledger replaced during inspection');\n const sourceDigest = createHash('sha256').update(JSON.stringify({ providers, reservations })).digest('hex');\n return { databasePath, sourceDigest, providers, reservations, identity: { dev: before.dev, ino: before.ino } };\n } finally { db.close(); }\n}\n\n/** Safe to display: contains counts and a digest, never bearer tokens or run owners. */\nexport function inspectLegacyLaunchBudget(databasePath: string) {\n const snapshot = readLegacySnapshot(databasePath);\n return { sourceDigest: snapshot.sourceDigest, providers: snapshot.providers.map(provider => {\n const rows = snapshot.reservations.filter(row => row.providerKey === provider.providerKey);\n return { providerKey: provider.providerKey, reservations: rows.length, active: rows.filter(row => !row.released).length };\n }) };\n}\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { HostConcurrency, HostLaunchBudgetLimits, HostLedgerOptions } from './host-types.ts';\nimport { absolutePath, busyTimeout, closedRecord, identifier, integer, record } from './validation.ts';\n\nexport function validateConcurrency(value: unknown): asserts value is HostConcurrency {\n if (!record(value) || !((closedRecord(value, ['mode']) && value.mode === 'unlimited')\n || (closedRecord(value, ['mode', 'maxConcurrent']) && value.mode === 'limited' && integer(value.maxConcurrent)))) {\n throw new TypeError('Concurrency requires explicit limited integer or unlimited mode');\n }\n}\nexport function hostLaunchLimits(concurrency: HostConcurrency): HostLaunchBudgetLimits {\n validateConcurrency(concurrency);\n return { concurrency: { ...concurrency }, maxLaunchesPerHour: 400, maxLaunchesPerDay: 800, quotaCooldownMs: 60_000 };\n}\nexport const HOST_LAUNCH_LIMITS: HostLaunchBudgetLimits = Object.freeze({\n ...hostLaunchLimits({ mode: 'limited', maxConcurrent: 3 }), concurrency: Object.freeze({ mode: 'limited', maxConcurrent: 3 }),\n});\nexport function hostLedgerPath(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string {\n if (env.OAR_HOST_LEDGER !== undefined) { absolutePath(env.OAR_HOST_LEDGER); return env.OAR_HOST_LEDGER; }\n const home = env.HOME || homedir();\n const root = platform === 'darwin' ? join(home, 'Library', 'Application Support')\n : platform === 'win32' ? (env.LOCALAPPDATA || join(home, 'AppData', 'Local'))\n : (env.XDG_STATE_HOME || join(home, '.local', 'state'));\n absolutePath(root);\n return join(root, 'open-agent-runtime', 'host', 'admission.sqlite');\n}\nexport function validateHostOptions(options: HostLedgerOptions) {\n const keys = ['databasePath', 'concurrency', 'providers', 'busyTimeoutMs'];\n if (!closedRecord(options, keys, keys) || Object.values(options).some(value => value === undefined) || (Object.hasOwn(options, 'providers') && Object.hasOwn(options, 'concurrency'))) {\n throw new TypeError('Provide either explicit providers or concurrency shorthand');\n }\n busyTimeout(options.busyTimeoutMs);\n const databasePath = options.databasePath === undefined ? hostLedgerPath() : options.databasePath;\n absolutePath(databasePath);\n const concurrency = Object.hasOwn(options, 'concurrency') ? options.concurrency : HOST_LAUNCH_LIMITS.concurrency;\n validateConcurrency(concurrency);\n const providers = Object.hasOwn(options, 'providers') ? options.providers : { claude: hostLaunchLimits(concurrency), codex: hostLaunchLimits(concurrency) };\n if (!record(providers)) throw new TypeError('Explicit providers must be a plain JSON record');\n const policies = new Map<string, HostLaunchBudgetLimits>();\n const fields = ['concurrency', 'maxLaunchesPerHour', 'maxLaunchesPerDay', 'quotaCooldownMs'];\n for (const key of Reflect.ownKeys(providers)) {\n const desc = Object.getOwnPropertyDescriptor(providers, key), value: unknown = desc?.value;\n if (!identifier(key) || !desc?.enumerable || !Object.hasOwn(desc, 'value') || !closedRecord(value, fields)\n || !integer(value.maxLaunchesPerHour) || !integer(value.maxLaunchesPerDay) || !integer(value.quotaCooldownMs, 1)) throw new TypeError('Invalid host provider policy');\n validateConcurrency(value.concurrency);\n policies.set(key, { concurrency: { ...value.concurrency }, maxLaunchesPerHour: value.maxLaunchesPerHour, maxLaunchesPerDay: value.maxLaunchesPerDay, quotaCooldownMs: value.quotaCooldownMs });\n }\n return { databasePath, policies, busyTimeoutMs: options.busyTimeoutMs === undefined ? 1000 : Number(options.busyTimeoutMs) };\n}\n","import type { DatabaseSync } from 'node:sqlite';\nimport type { LaunchPriority } from './host-types.ts';\nimport { identifier } from './validation.ts';\n\n/**\n * How long a waiter's declaration counts without being renewed. A waiting `acquire` renews it on\n * every attempt, and attempts are at most 30 seconds apart, so only a process that died or stalled\n * lets it lapse. A lapsed declaration gives up precedence; it never frees or grants a slot.\n */\nexport const WAITER_LEASE_MS = 90_000;\n\n/** Higher rank is served first. Stored as a number so a further level is an additive change. */\nconst RANK: Readonly<Record<LaunchPriority, number>> = Object.freeze({ low: 0, normal: 1 });\nconst TOP_RANK = RANK.normal;\n\n/**\n * Additive migration: one table created on first use inside the caller's transaction. The ledger\n * stays at `user_version` 1, so a process on an older build keeps sharing the same file. That\n * older process neither declares its waits nor yields to anyone.\n */\nexport const WAITERS_SCHEMA = `\nCREATE TABLE IF NOT EXISTS budget_waiters (\n waiter TEXT PRIMARY KEY NOT NULL CHECK(length(waiter) BETWEEN 1 AND 256),\n provider_key TEXT NOT NULL REFERENCES budget_providers(provider_key),\n priority INTEGER NOT NULL CHECK(priority BETWEEN 0 AND 255),\n seen_at INTEGER NOT NULL CHECK(seen_at BETWEEN 0 AND 9007199254740991)\n) STRICT;\nCREATE INDEX IF NOT EXISTS budget_waiters_provider ON budget_waiters(provider_key, priority);`;\n\n/** One admission attempt's place in line. `waiter` is present only while the caller will wait. */\nexport interface LaunchTurn {\n priority: LaunchPriority;\n waiter?: string;\n}\n\nexport function isLaunchPriority(value: unknown): value is LaunchPriority {\n return typeof value === 'string' && Object.hasOwn(RANK, value);\n}\n\nexport function validTurn(turn: LaunchTurn): boolean {\n return isLaunchPriority(turn.priority) && (turn.waiter === undefined || identifier(turn.waiter));\n}\n\n/** Records or renews this waiter's place and drops declarations whose lease lapsed. */\nexport function declareWaiter(db: DatabaseSync, providerKey: string, turn: LaunchTurn, now: number): void {\n if (turn.waiter === undefined) return;\n db.exec(WAITERS_SCHEMA);\n db.prepare('DELETE FROM budget_waiters WHERE seen_at <= ?').run(now - WAITER_LEASE_MS);\n db.prepare(`INSERT INTO budget_waiters(waiter, provider_key, priority, seen_at) VALUES (?, ?, ?, ?)\n ON CONFLICT(waiter) DO UPDATE SET provider_key = excluded.provider_key, priority = excluded.priority, seen_at = excluded.seen_at`)\n .run(turn.waiter, providerKey, RANK[turn.priority], now);\n}\n\n/** True when a launch of higher priority is currently waiting for a slot of this provider. */\nexport function isOutranked(db: DatabaseSync, providerKey: string, turn: LaunchTurn, now: number): boolean {\n const rank = RANK[turn.priority];\n // The top priority yields to nobody: default callers never read or create the table.\n if (rank >= TOP_RANK) return false;\n db.exec(WAITERS_SCHEMA);\n const ahead = db.prepare(`SELECT 1 AS found FROM budget_waiters\n WHERE provider_key = ? AND priority > ? AND seen_at > ? AND waiter <> ? LIMIT 1`)\n .get(providerKey, rank, now - WAITER_LEASE_MS, turn.waiter ?? '');\n return ahead !== undefined;\n}\n\n/** Withdraws a declaration. Returns whether one was actually recorded. */\nexport function forgetWaiter(db: DatabaseSync, waiter: string): boolean {\n db.exec(WAITERS_SCHEMA);\n return db.prepare('DELETE FROM budget_waiters WHERE waiter = ?').run(waiter).changes === 1;\n}\n","import { watch, type FSWatcher } from 'node:fs';\n\n/** Event hint only: callers always recheck SQLite. Arming precedes the admission attempt. */\nexport function armBell(path: string, signal: AbortSignal | undefined) {\n let rang = false, settled = false;\n let watcher: FSWatcher | undefined, timer: ReturnType<typeof setTimeout> | undefined;\n let resolve: (() => void) | undefined, reject: ((reason: unknown) => void) | undefined;\n let aborted = false;\n const cleanup = () => {\n watcher?.close(); watcher = undefined;\n clearTimeout(timer); timer = undefined;\n signal?.removeEventListener('abort', abort);\n };\n const finish = () => {\n if (settled) return;\n settled = true; cleanup();\n if (aborted) reject?.(signal?.reason); else resolve?.();\n };\n const abort = () => { aborted = true; rang = true; finish(); };\n try {\n watcher = watch(path, { persistent: false }, () => { rang = true; if (resolve) finish(); });\n watcher.on('error', () => { watcher?.close(); watcher = undefined; });\n } catch { /* A missing event cannot authorize admission; the bounded backstop remains. */ }\n signal?.addEventListener('abort', abort, { once: true });\n if (signal?.aborted) abort();\n return {\n cancel: finish,\n wait(ms: number): Promise<void> {\n if (aborted) return Promise.reject(signal?.reason);\n if (settled) return Promise.resolve();\n return new Promise<void>((yes, no) => {\n resolve = yes; reject = no;\n timer = setTimeout(finish, Math.max(1, Math.min(2_147_483_647, Math.ceil(ms))));\n if (rang) finish();\n });\n },\n };\n}\n","import type { BudgetFailure, LaunchAdmission, LaunchBudgetLimits, LaunchBudgetStatus, LaunchReservation } from './types.ts';\n\nexport type HostConcurrency = { mode: 'limited'; maxConcurrent: number } | { mode: 'unlimited' };\nexport interface ConcurrencyPolicy { revision: number; concurrency: HostConcurrency }\nexport interface ConcurrencyChange { expectedRevision: number; concurrency: HostConcurrency }\nexport type HostLaunchBudgetLimits = Omit<LaunchBudgetLimits, 'maxConcurrent'> & { concurrency: HostConcurrency };\nexport type HostLaunchBudgetStatus = Omit<LaunchBudgetStatus, 'limits'> & { limits: HostLaunchBudgetLimits };\nexport interface HostLedgerOptions {\n databasePath?: string;\n concurrency?: HostConcurrency;\n providers?: Readonly<Record<string, HostLaunchBudgetLimits>>;\n busyTimeoutMs?: number;\n}\nexport type HostLaunchAdmission = LaunchAdmission | { allowed: false; reason: 'wait-timeout' };\nexport type HostLaunchDenial = Extract<HostLaunchAdmission, { allowed: false }>;\n/** `low` is for canaries and evaluation runs: it never takes a slot a waiting `normal` launch is entitled to. */\nexport type LaunchPriority = 'normal' | 'low';\nexport interface AcquireOptions { maxWaitMs: number; signal?: AbortSignal; priority?: LaunchPriority }\nexport interface SlotOptions extends AcquireOptions { isQuotaError?: (error: unknown) => boolean }\n/** Trusted host inspection only. Tokens must never cross the worker/model boundary. */\nexport type HostOwnerReservation = Readonly<LaunchReservation & { released: boolean }>;\nexport interface HostOwnerLookupOptions { limit: number }\nexport interface HostOwnerLookup {\n reservations: readonly HostOwnerReservation[];\n truncated: boolean;\n}\n/** Measured local storage binding only; neither a lease nor permission to release work. */\nexport interface HostLedgerIdentity { readonly format: 1; readonly digest: string }\nexport interface HostRecoveryOptions {\n ownerPrefix: string;\n /** Exact previously inspected bearer tokens; never infer these from a prefix at recovery time. */\n tokens: readonly string[];\n acknowledgement: { workStopped: true; evidenceDigest: string };\n}\nexport class LaunchRefusedError extends Error {\n readonly admission: HostLaunchDenial;\n constructor(admission: HostLaunchDenial) {\n super(`Launch refused: ${admission.reason}`); this.name = 'LaunchRefusedError'; this.admission = admission;\n }\n}\n/** A failed durable release is a halt condition, including when the operation also failed. */\nexport class LaunchReleaseError extends Error {\n readonly failure: BudgetFailure;\n constructor(failure: BudgetFailure, cause?: unknown) {\n super(`Launch release failed: ${failure.reason}`, { cause }); this.name = 'LaunchReleaseError'; this.failure = failure;\n }\n}\n\n/** The observed provider quota error could not be durably recorded; callers must halt admission. */\nexport class LaunchQuotaRecordError extends Error {\n readonly failure: BudgetFailure;\n constructor(failure: BudgetFailure, cause?: unknown) {\n super(`Launch quota recording failed: ${failure.reason}`, { cause }); this.name = 'LaunchQuotaRecordError'; this.failure = failure;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AACA,SAAS,aAAAA,YAAW,aAAAC,YAAW,WAAW,YAAAC,WAAU,qBAAqB;AACzE,SAAS,WAAAC,gBAAe;AACxB,SAAS,mBAAmB;AAC5B,SAAS,cAAAC,mBAAkB;;;ACJ3B,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,aAAa;;;ACDtB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,mBAAmB,SAAS,cAAc;AAAA,IACvE;AAAA,EACF;AAAA,EACA,QAAc;AACZ,QAAI;AAAE,oBAAc,KAAK,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC,GAAG,EAAE,MAAM,IAAM,CAAC;AAAA,IAAG,QAAQ;AAAA,IAAyC;AAAA,EACtI;AACF;","names":["closeSync","lstatSync","openSync","dirname","randomUUID","randomUUID","createHash","lstatSync","DatabaseSync","createHash","lstatSync","DatabaseSync","randomUUID","dirname","closeSync","openSync","lstatSync","randomUUID"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// src/public/memory-types.ts
|
|
2
|
+
var MEMORY_DEFAULT_MAX_ITEMS = 2;
|
|
3
|
+
var MEMORY_MAX_ITEMS_CEILING = 8;
|
|
4
|
+
var MEMORY_DEFAULT_MAX_BYTES = 8 * 1024;
|
|
5
|
+
var MEMORY_MAX_BYTES_CEILING = 32 * 1024;
|
|
6
|
+
var MEMORY_DEFAULT_RECALL_TIMEOUT_MS = 2e3;
|
|
7
|
+
var MEMORY_DEFAULT_MAX_PROFILE_BYTES = 2 * 1024;
|
|
8
|
+
var MEMORY_MAX_PROFILE_BYTES_CEILING = 8 * 1024;
|
|
9
|
+
var MEMORY_CAPTURE_TIMEOUT_MS = 1e4;
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
MEMORY_DEFAULT_MAX_ITEMS,
|
|
13
|
+
MEMORY_MAX_ITEMS_CEILING,
|
|
14
|
+
MEMORY_DEFAULT_MAX_BYTES,
|
|
15
|
+
MEMORY_MAX_BYTES_CEILING,
|
|
16
|
+
MEMORY_DEFAULT_RECALL_TIMEOUT_MS,
|
|
17
|
+
MEMORY_DEFAULT_MAX_PROFILE_BYTES,
|
|
18
|
+
MEMORY_MAX_PROFILE_BYTES_CEILING,
|
|
19
|
+
MEMORY_CAPTURE_TIMEOUT_MS
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=chunk-HZFZX5A3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/public/memory-types.ts"],"sourcesContent":["import type { ModelInfo, ProviderId, TransportKind, Turn } from './types.js';\n\n/**\n * Per-agent memory: the public contract.\n *\n * Memory is an application resource. The SDK never stores, embeds or ranks\n * anything itself here: it asks the application's provider for a few recalled\n * items before a turn, carries them to the model as reference data (never as\n * instructions), and, only when asked, hands the completed turn back to the\n * provider afterwards. Every step is opt-in and fail-open: a provider that\n * fails or is slow never fails the turn, and the turn records what happened.\n *\n * The scope is chosen by the application and is never derived from anything\n * the model wrote. It has the same shape as the orchestration memory ports'\n * `MemoryScope`, so a port implementation can serve it directly.\n */\nexport interface AgentMemoryScope {\n readonly tenant: string;\n readonly namespace: string;\n readonly subject?: string;\n}\n\n/** What the provider is asked before one turn. */\nexport interface MemoryRecallRequest {\n readonly scope: AgentMemoryScope;\n /** The turn's user text (text items joined); never includes earlier recalled blocks. */\n readonly text: string;\n readonly provider: ProviderId;\n readonly transport: TransportKind;\n readonly cwd: string;\n /** Upper bound the SDK will carry; a provider may return fewer, never needs to return more. */\n readonly limit: number;\n /** Aborted when the recall deadline passes or the turn is cancelled. */\n readonly signal: AbortSignal;\n}\n\n/**\n * One recalled item. Its text is data the model may read, not an instruction it must follow.\n * The SDK drops (and counts in `omitted`) an item whose `id` or `source` is empty, longer than\n * 256 characters, or contains a line break, a control character or an invisible format\n * character (zero-width, bidi override, tag), and an `id` or `source` with any opening or closing\n * punctuation after NFKC normalization (Unicode `Ps`/`Pe`: square brackets and their fullwidth or\n * other look-alikes, parentheses, braces, and the square-bracket pieces U+23A1-U+23A6, U+23B4-U+23B5), since they sit between brackets on the SDK-owned item\n * header; whose `observedAt` is longer than 64 characters or is not a strict ISO-8601 date and\n * time with an offset (`YYYY-MM-DDTHH:MM[:SS[.fraction]]` then `Z` or `±HH:MM`); whose `text` is\n * empty, contains NUL or is only tag characters; or whose id repeats an earlier item's. A\n * `title` that breaks the `id` rules is left out and the item kept. Tag characters are removed\n * from the text, and `observedAt` is carried as `Date.prototype.toISOString()` gives it. The\n * exported `recallableMemory` applies exactly these rules.\n */\nexport interface RecalledMemory {\n readonly id: string;\n readonly text: string;\n readonly title?: string;\n /** Provenance label shown to the model and recorded on the turn, e.g. `sqlite-system-memory`. */\n readonly source: string;\n /** Strict ISO-8601 time the remembered fact was observed, when the provider knows it; carried in UTC. */\n readonly observedAt?: string;\n}\n\n/** What the provider receives after a completed turn, only when `MemoryOption.capture` is true. */\nexport interface MemoryCaptureRequest {\n readonly scope: AgentMemoryScope;\n /** The user text of the turn, without the recalled block the SDK prepended. */\n readonly input: string;\n readonly turn: Turn;\n /** ISO-8601 time the SDK delivered the completed turn; stable for a retried capture of the same request. */\n readonly completedAt: string;\n /** Aborted after `MEMORY_CAPTURE_TIMEOUT_MS`. */\n readonly signal: AbortSignal;\n}\n\n/**\n * An application's memory backend for agents. Every method is optional: a\n * read-only memory implements `recall`, a recorder implements `capture`.\n * `AgentOptions.memory` needs `recall`, `capture` or `profile` (a provider with\n * only `propose` is a TypeError there: it serves only the memory tools).\n * Implementations must be safe to share between agents and sessions; per-call\n * identity arrives in the request, never in the provider instance.\n */\nexport interface AgentMemoryProvider {\n /**\n * Stable label recorded on every turn note, e.g. `sqlite-system-memory` or `agentdb`. It is the\n * source on the `### Profile [source: <id>]` header, so `AgentOptions.memory` refuses an id that\n * breaks the item id rules (see `RecalledMemory`), brackets and other opening or closing punctuation included.\n */\n readonly id: string;\n recall?(request: MemoryRecallRequest): Promise<readonly RecalledMemory[]>;\n capture?(request: MemoryCaptureRequest): Promise<void>;\n /**\n * The scope's fixed profile: a short text the application maintains (who the user is, the\n * project's conventions). Carried on every turn before the recalled items, under its own\n * budget. Only the application writes it; nothing an agent does reaches it. Asked in parallel\n * with `recall`, under the same deadline and signal, and just as fail-open; undefined means the\n * scope has no profile. The exported `profileText` applies the SDK's rules to the text.\n */\n profile?(request: MemoryProfileRequest): Promise<string | undefined>;\n /**\n * Stores something the agent proposes to remember, through a memory tool. A proposal is a\n * candidate, never recallable until the application promotes it; the result names it. Throw a\n * `TypeError` to refuse a proposal as written (e.g. over the store's size bound): the tool\n * reports `INVALID_INPUT` with the SDK's own message; any other error is `PROVIDER_FAILED`.\n */\n propose?(request: MemoryProposeRequest): Promise<{ readonly id: string }>;\n}\n\n/** What the provider is asked for the scope's profile, once per turn. */\nexport interface MemoryProfileRequest {\n readonly scope: AgentMemoryScope;\n readonly provider: ProviderId;\n readonly transport: TransportKind;\n readonly cwd: string;\n readonly signal: AbortSignal;\n}\n\n/** A memory the agent proposes through a memory tool; untrusted model output. */\nexport interface MemoryProposeRequest {\n readonly scope: AgentMemoryScope;\n readonly text: string;\n readonly title?: string;\n /** Where the proposal came from, e.g. `memory-tool` or `mcp:<server name>`. */\n readonly origin: string;\n readonly signal: AbortSignal;\n}\n\n/** Defaults and ceilings of the memory option. */\nexport const MEMORY_DEFAULT_MAX_ITEMS = 2;\nexport const MEMORY_MAX_ITEMS_CEILING = 8;\nexport const MEMORY_DEFAULT_MAX_BYTES = 8 * 1024;\nexport const MEMORY_MAX_BYTES_CEILING = 32 * 1024;\nexport const MEMORY_DEFAULT_RECALL_TIMEOUT_MS = 2_000;\n/** Profile budget: UTF-8 bytes of the profile section as rendered (see `MemoryOption.maxProfileBytes`). */\nexport const MEMORY_DEFAULT_MAX_PROFILE_BYTES = 2 * 1024;\nexport const MEMORY_MAX_PROFILE_BYTES_CEILING = 8 * 1024;\n/** Bound on one background capture, and on how long `close()` waits for pending captures. */\nexport const MEMORY_CAPTURE_TIMEOUT_MS = 10_000;\n\n/**\n * Opt-in per-agent memory, set on `AgentOptions.memory` (or as a Runtime\n * default). Its absence changes nothing.\n */\nexport interface MemoryOption {\n readonly provider: AgentMemoryProvider;\n readonly scope: AgentMemoryScope;\n /** Recalled items carried per turn: default 2, at most 8. */\n readonly maxItems?: number;\n /**\n * UTF-8 bytes of the recalled items carried per turn, as rendered: every kept item's header,\n * title line and indented text lines count, datamarked (each whitespace run inside a line is\n * U+02C6, 2 bytes); only the block's fixed heading, preamble and end\n * marker do not. Default 8 KiB, at least 256, at most 32 KiB. Items are whole or left out.\n */\n readonly maxBytes?: number;\n /**\n * Recall deadline; on expiry the turn runs without memory. Default 2000 ms. A turn with its own\n * `timeoutMs` gives recall at most a quarter of it, and keeps the rest for itself.\n */\n readonly recallTimeoutMs?: number;\n /**\n * UTF-8 bytes of the profile carried per turn (only read when the provider implements `profile`),\n * as rendered: its `### Profile [source: <provider id>]` header, every indented line and the\n * blank line after them. Default 2 KiB (`MEMORY_DEFAULT_MAX_PROFILE_BYTES`), at least 64, at most\n * 8 KiB (`MEMORY_MAX_PROFILE_BYTES_CEILING`). It is a budget of its own: the profile never takes\n * room from `maxBytes`. A profile that does not fit is left out whole, never truncated (a cut\n * could keep half a rule). To carry no profile, use a provider without `profile`.\n */\n readonly maxProfileBytes?: number;\n /**\n * Hand each completed turn to `provider.capture`, in the background, after the result is\n * delivered. Default false: recall-only; true needs a provider with `capture` (a TypeError\n * otherwise). `Session.close()` and `Agent.close()` wait for pending captures, each bounded by\n * `MEMORY_CAPTURE_TIMEOUT_MS`; an exec fork's first-turn capture belongs to the child session.\n */\n readonly capture?: boolean;\n /**\n * Receives capture failures, which never fail the turn. Without it a failure is a process\n * warning (code `OAR_MEMORY_CAPTURE_FAILED`), at most one a minute per Agent memory. Recall\n * failures are on the turn itself.\n */\n readonly onCaptureError?: (error: unknown) => void;\n}\n\n/** What a Runtime-wide default needs to pick a stable scope for each Agent it builds. */\nexport interface MemoryScopeContext {\n readonly model: ModelInfo;\n /** The cwd the Agent was given, before readiness resolves it; undefined means process.cwd(). */\n readonly cwd?: string;\n}\n\n/** Runtime-wide default: every Agent of the Runtime gets memory unless it sets `memory: false`. */\nexport interface RuntimeMemoryDefault extends Omit<MemoryOption, 'scope'> {\n readonly scope: (context: MemoryScopeContext) => AgentMemoryScope;\n}\n\n/**\n * What happened to the scope's profile on one turn; on the turn note only when the provider\n * implements `profile`. `carried`: in the block, `bytes` as rendered (never more than\n * `maxProfileBytes`). `absent`: the provider returned undefined. `omitted`: usable but over\n * `maxProfileBytes`, left out whole. `failed`: it threw, timed out (it shares the recall deadline\n * and signal) or returned something that is not a usable text: not a string, empty or only\n * whitespace once tag characters are removed, or containing NUL. `omitted` and `failed` also add\n * a `MEMORY_PROFILE_UNAVAILABLE` warning; neither changes what recall does or how it is recorded.\n */\nexport type MemoryProfileNote =\n | { status: 'carried'; bytes: number }\n | { status: 'absent' }\n | { status: 'omitted'; reason: string; bytes?: number }\n | { status: 'failed'; reason: string };\n\n/**\n * What one turn did with memory; found in `Turn.providerMetadata.memory`, recorded before a\n * required log capture sees the turn, so the logged and the returned turn are the same. The\n * `profile` field is there only when the provider implements `profile`; when the profile is\n * carried the block exists even if no item was recalled.\n */\nexport type MemoryTurnNote =\n | {\n status: 'recalled';\n provider: string;\n /** The carried items; `bytes` is each one as rendered (header, title and indented text). */\n items: ReadonlyArray<{ id: string; source: string; bytes: number }>;\n /** Items the provider returned that were malformed, repeated, or did not fit the item or byte budget. */\n omitted: number;\n /** The items' rendered bytes together: never more than `maxBytes`. The profile is not counted here. */\n bytes: number;\n capture: boolean;\n profile?: MemoryProfileNote;\n }\n /** The provider returned no items, or has no `recall`. */\n | { status: 'empty'; provider: string; capture: boolean; profile?: MemoryProfileNote }\n /**\n * The turn ran without recalled items: the recall threw, timed out or returned something that\n * is not a list, or every returned item was malformed or over budget. Also a `MEMORY_UNAVAILABLE`\n * warning. A carried profile still reaches the turn. A turn cancelled while recall ran does not\n * run at all, so it has no note.\n */\n | { status: 'failed'; provider: string; reason: string; capture: boolean; profile?: MemoryProfileNote };\n"],"mappings":";AA8HO,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AACjC,IAAM,2BAA2B,IAAI;AACrC,IAAM,2BAA2B,KAAK;AACtC,IAAM,mCAAmC;AAEzC,IAAM,mCAAmC,IAAI;AAC7C,IAAM,mCAAmC,IAAI;AAE7C,IAAM,4BAA4B;","names":[]}
|