open-multi-agent-kit 1.2.3 → 1.2.4

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.
Files changed (80) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +2 -2
  3. package/dist/cli/help.d.ts.map +1 -1
  4. package/dist/cli/help.js +2 -0
  5. package/dist/cli/help.js.map +1 -1
  6. package/dist/commands/doctor-provider.d.ts.map +1 -1
  7. package/dist/commands/doctor-provider.js +2 -13
  8. package/dist/commands/doctor-provider.js.map +1 -1
  9. package/dist/commands/provider-adopt-cli.d.ts +24 -0
  10. package/dist/commands/provider-adopt-cli.d.ts.map +1 -0
  11. package/dist/commands/provider-adopt-cli.js +182 -0
  12. package/dist/commands/provider-adopt-cli.js.map +1 -0
  13. package/dist/commands/provider-adopt-status.d.ts +21 -0
  14. package/dist/commands/provider-adopt-status.d.ts.map +1 -0
  15. package/dist/commands/provider-adopt-status.js +84 -0
  16. package/dist/commands/provider-adopt-status.js.map +1 -0
  17. package/dist/commands/provider-known-apis.d.ts +2 -0
  18. package/dist/commands/provider-known-apis.d.ts.map +1 -0
  19. package/dist/commands/provider-known-apis.js +28 -0
  20. package/dist/commands/provider-known-apis.js.map +1 -0
  21. package/dist/commands/run-command.d.ts.map +1 -1
  22. package/dist/commands/run-command.js +4 -0
  23. package/dist/commands/run-command.js.map +1 -1
  24. package/dist/core/agent-session.d.ts.map +1 -1
  25. package/dist/core/agent-session.js +6 -0
  26. package/dist/core/agent-session.js.map +1 -1
  27. package/dist/core/auth-storage.d.ts +16 -16
  28. package/dist/core/auth-storage.d.ts.map +1 -1
  29. package/dist/core/auth-storage.js +94 -111
  30. package/dist/core/auth-storage.js.map +1 -1
  31. package/dist/core/compaction/compaction.d.ts.map +1 -1
  32. package/dist/core/compaction/compaction.js +13 -10
  33. package/dist/core/compaction/compaction.js.map +1 -1
  34. package/dist/core/compaction/inert-tail.d.ts +23 -0
  35. package/dist/core/compaction/inert-tail.d.ts.map +1 -0
  36. package/dist/core/compaction/inert-tail.js +108 -0
  37. package/dist/core/compaction/inert-tail.js.map +1 -0
  38. package/dist/core/compaction/provenance.d.ts +30 -0
  39. package/dist/core/compaction/provenance.d.ts.map +1 -0
  40. package/dist/core/compaction/provenance.js +59 -0
  41. package/dist/core/compaction/provenance.js.map +1 -0
  42. package/dist/core/compaction/transaction.d.ts.map +1 -1
  43. package/dist/core/compaction/transaction.js +4 -1
  44. package/dist/core/compaction/transaction.js.map +1 -1
  45. package/dist/core/external-credential-sources.d.ts +48 -0
  46. package/dist/core/external-credential-sources.d.ts.map +1 -0
  47. package/dist/core/external-credential-sources.js +176 -0
  48. package/dist/core/external-credential-sources.js.map +1 -0
  49. package/dist/core/model-registry.d.ts +11 -0
  50. package/dist/core/model-registry.d.ts.map +1 -1
  51. package/dist/core/model-registry.js +28 -14
  52. package/dist/core/model-registry.js.map +1 -1
  53. package/dist/core/oauth-account-import.d.ts +52 -0
  54. package/dist/core/oauth-account-import.d.ts.map +1 -0
  55. package/dist/core/oauth-account-import.js +125 -0
  56. package/dist/core/oauth-account-import.js.map +1 -0
  57. package/dist/core/oauth-credential.d.ts +22 -0
  58. package/dist/core/oauth-credential.d.ts.map +1 -0
  59. package/dist/core/oauth-credential.js +36 -0
  60. package/dist/core/oauth-credential.js.map +1 -0
  61. package/dist/core/session-compaction-service.d.ts +2 -2
  62. package/dist/core/session-compaction-service.d.ts.map +1 -1
  63. package/dist/core/session-compaction-service.js +20 -57
  64. package/dist/core/session-compaction-service.js.map +1 -1
  65. package/dist/core/verified-run/owned-execution.d.ts.map +1 -1
  66. package/dist/core/verified-run/owned-execution.js +13 -1
  67. package/dist/core/verified-run/owned-execution.js.map +1 -1
  68. package/docs/compaction.md +2 -0
  69. package/docs/extensions.md +1 -1
  70. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  71. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  72. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  73. package/examples/extensions/gondolin/package-lock.json +2 -2
  74. package/examples/extensions/gondolin/package.json +1 -1
  75. package/examples/extensions/sandbox/package-lock.json +2 -2
  76. package/examples/extensions/sandbox/package.json +1 -1
  77. package/examples/extensions/with-deps/package-lock.json +2 -2
  78. package/examples/extensions/with-deps/package.json +1 -1
  79. package/npm-shrinkwrap.json +18 -18
  80. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage.js","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACnF,OAAO,EACN,WAAW,EACX,YAAY,GAKZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AAEpD,SAAS,yBAAyB,CAAC,IAAqB,EAAmB;IAC1E,IAAI,CAAC,CAAC,wBAAwB,IAAI,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACrD,MAAM,EAAE,CAAC,wBAAwB,CAAC,EAAE,QAAQ,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;IAC/D,OAAO,IAAI,CAAC;AAAA,CACZ;AA2BD,MAAM,uBAAuB,GAAG,CAAC,WAAW,EAAE,OAAO,EAA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O,SAAS,CAAC;IAAA,CACjB;IAED;;OAEG;IACH,iBAAiB,GAAG;QACnB,OAAO,iBAAiB,EAAE,CAAC;IAAA,CAC3B;CACD","sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n *\n * Uses file locking to prevent race conditions when multiple OMK instances\n * try to refresh tokens simultaneously.\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport {\n\tfindEnvKeys,\n\tgetEnvApiKey,\n\ttype OAuthCredentials,\n\ttype OAuthLoginCallbacks,\n\ttype OAuthProviderId,\n\ttype OAuthProviderInterface,\n} from \"omk-ai\";\nimport { getOAuthApiKey, getOAuthProvider, getOAuthProviders } from \"omk-ai/oauth\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\nconst RETIRED_GROK_OAUTH_PROXY = \"grok-oauth-proxy\";\n\nfunction omitRetiredGrokOAuthProxy(data: AuthStorageData): AuthStorageData {\n\tif (!(RETIRED_GROK_OAUTH_PROXY in data)) return data;\n\tconst { [RETIRED_GROK_OAUTH_PROXY]: _retired, ...kept } = data;\n\treturn kept;\n}\n\nexport type ApiKeyCredential = {\n\ttype: \"api_key\";\n\tkey: string;\n};\n\nexport type OAuthCredential = {\n\ttype: \"oauth\";\n\t/** Complete account list when more than one subscription account is configured. */\n\taccounts?: OAuthCredentials[];\n\t/** Index of the account explicitly selected for this provider. */\n\tactiveAccount?: number;\n\t/** Legacy cursor accepted when migrating older auth.json files. */\n\tnextAccount?: number;\n} & OAuthCredentials;\n\nexport interface OAuthAccountSummary {\n\tindex: number;\n\tlabel: string;\n\tselected: boolean;\n}\n\nexport type AuthCredential = ApiKeyCredential | OAuthCredential;\n\nexport type AuthStorageData = Record<string, AuthCredential>;\n\nconst OAUTH_ACCOUNT_ID_FIELDS = [\"accountId\", \"email\", \"userId\", \"username\"] as const;\nconst OAUTH_ACCOUNT_LABEL_FIELDS = [\"email\", \"username\"] as const;\nconst OAUTH_ACCOUNT_LABEL_MAX_LENGTH = 96;\nconst UNSAFE_ACCOUNT_LABEL_PATTERN =\n\t/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u206f\\ufeff]/g;\n\nfunction sanitizeOAuthAccountLabel(value: string): string | undefined {\n\tconst sanitized = stripAnsi(value)\n\t\t.replace(/[\\t\\r\\n]+/g, \" \")\n\t\t.replace(UNSAFE_ACCOUNT_LABEL_PATTERN, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim()\n\t\t.slice(0, OAUTH_ACCOUNT_LABEL_MAX_LENGTH);\n\treturn sanitized || undefined;\n}\n\nfunction stripOAuthStorageMetadata(credential: OAuthCredential): OAuthCredentials {\n\tconst {\n\t\ttype: _type,\n\t\taccounts: _accounts,\n\t\tactiveAccount: _activeAccount,\n\t\tnextAccount: _nextAccount,\n\t\t...credentials\n\t} = credential;\n\treturn credentials;\n}\n\nfunction getOAuthAccounts(credential: OAuthCredential): OAuthCredentials[] {\n\tif (Array.isArray(credential.accounts) && credential.accounts.length > 0) {\n\t\treturn credential.accounts;\n\t}\n\treturn [stripOAuthStorageMetadata(credential)];\n}\n\nfunction normalizeOAuthAccountIndex(index: unknown, accountCount: number): number {\n\tif (accountCount <= 0 || typeof index !== \"number\" || !Number.isInteger(index)) {\n\t\treturn 0;\n\t}\n\treturn ((index % accountCount) + accountCount) % accountCount;\n}\n\nfunction getSelectedOAuthAccountIndex(credential: OAuthCredential, accountCount: number): number {\n\treturn normalizeOAuthAccountIndex(credential.activeAccount ?? credential.nextAccount, accountCount);\n}\n\nfunction createOAuthCredential(accounts: OAuthCredentials[], activeAccount = 0): OAuthCredential {\n\tconst selectedIndex = normalizeOAuthAccountIndex(activeAccount, accounts.length);\n\tconst selected = accounts[selectedIndex];\n\tif (!selected) {\n\t\tthrow new Error(\"OAuth credential must contain at least one account\");\n\t}\n\tif (accounts.length === 1) {\n\t\treturn { ...selected, type: \"oauth\" };\n\t}\n\treturn {\n\t\t...selected,\n\t\ttype: \"oauth\",\n\t\taccounts,\n\t\tactiveAccount: selectedIndex,\n\t};\n}\n\nfunction getOAuthAccountIdentity(credentials: OAuthCredentials): string | undefined {\n\tconst accountId = credentials.accountId;\n\tconst orgId = credentials.orgId;\n\tif (typeof accountId === \"string\" && accountId.trim() && typeof orgId === \"string\" && orgId.trim()) {\n\t\treturn `accountId:${accountId.trim().toLowerCase()}:orgId:${orgId.trim().toLowerCase()}`;\n\t}\n\tfor (const field of OAUTH_ACCOUNT_ID_FIELDS) {\n\t\tconst value = credentials[field];\n\t\tif (typeof value === \"string\" && value.trim()) {\n\t\t\treturn `${field}:${value.trim().toLowerCase()}`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction getOAuthAccountDisplayLabel(providerId: string, credentials: OAuthCredentials): string | undefined {\n\tfor (const field of OAUTH_ACCOUNT_LABEL_FIELDS) {\n\t\tconst value = credentials[field];\n\t\tif (typeof value === \"string\" && value.trim()) {\n\t\t\tconst label = sanitizeOAuthAccountLabel(value);\n\t\t\tif (!label) continue;\n\t\t\tconst orgName =\n\t\t\t\ttypeof credentials.orgName === \"string\" ? sanitizeOAuthAccountLabel(credentials.orgName) : undefined;\n\t\t\treturn sanitizeOAuthAccountLabel(orgName ? `${label} (${orgName})` : label);\n\t\t}\n\t}\n\ttry {\n\t\tconst label = getOAuthProvider(providerId)?.getAccountLabel?.(credentials);\n\t\treturn typeof label === \"string\" ? sanitizeOAuthAccountLabel(label) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction findMatchingOAuthAccount(accounts: OAuthCredentials[], credentials: OAuthCredentials): number {\n\tconst identity = getOAuthAccountIdentity(credentials);\n\tif (identity) {\n\t\tconst exactMatch = accounts.findIndex((account) => getOAuthAccountIdentity(account) === identity);\n\t\tif (exactMatch >= 0) return exactMatch;\n\t}\n\n\t// Let newly enriched credentials update older entries that predate email/org metadata.\n\tfor (const field of OAUTH_ACCOUNT_ID_FIELDS) {\n\t\tconst value = credentials[field];\n\t\tif (typeof value !== \"string\" || !value.trim()) continue;\n\t\tconst normalizedValue = value.trim().toLowerCase();\n\t\tconst orgId = typeof credentials.orgId === \"string\" ? credentials.orgId.trim().toLowerCase() : \"\";\n\t\tconst compatibleMatch = accounts.findIndex((account) => {\n\t\t\tconst existingValue = account[field];\n\t\t\tif (typeof existingValue !== \"string\" || existingValue.trim().toLowerCase() !== normalizedValue) return false;\n\t\t\tconst existingOrgId = typeof account.orgId === \"string\" ? account.orgId.trim().toLowerCase() : \"\";\n\t\t\treturn !orgId || !existingOrgId || orgId === existingOrgId;\n\t\t});\n\t\tif (compatibleMatch >= 0) return compatibleMatch;\n\t}\n\n\treturn accounts.findIndex((account) => account.refresh === credentials.refresh);\n}\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\";\n\tlabel?: string;\n};\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n\tprivate data: AuthStorageData = {};\n\tprivate runtimeOverrides: Map<string, string> = new Map();\n\tprivate fallbackResolver?: (provider: string) => string | undefined;\n\tprivate loadError: Error | null = null;\n\tprivate errors: Error[] = [];\n\tprivate storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\t/**\n\t * Set a runtime API key override (not persisted to disk).\n\t * Used for CLI --api-key flag.\n\t */\n\tsetRuntimeApiKey(provider: string, apiKey: string): void {\n\t\tthis.runtimeOverrides.set(provider, apiKey);\n\t}\n\n\t/**\n\t * Remove a runtime API key override.\n\t */\n\tremoveRuntimeApiKey(provider: string): void {\n\t\tthis.runtimeOverrides.delete(provider);\n\t}\n\n\t/**\n\t * Set a fallback resolver for API keys not found in auth.json or env vars.\n\t * Used for custom provider keys from models.json.\n\t */\n\tsetFallbackResolver(resolver: (provider: string) => string | undefined): void {\n\t\tthis.fallbackResolver = resolver;\n\t}\n\n\tprivate recordError(error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push(normalizedError);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\treturn omitRetiredGrokOAuthProxy(JSON.parse(content) as AuthStorageData);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthrow new Error(`Failed to parse auth storage: ${message}`);\n\t\t}\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.loadError = error as Error;\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\tprivate persistProviderChange(provider: string, credential: AuthCredential | undefined): void {\n\t\tif (this.loadError) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst merged: AuthStorageData = { ...currentData };\n\t\t\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) {\n\t\t\t\t\tdelete merged[provider];\n\t\t\t\t} else if (credential) {\n\t\t\t\t\tmerged[provider] = credential;\n\t\t\t\t} else {\n\t\t\t\t\tdelete merged[provider];\n\t\t\t\t}\n\t\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Get credential for a provider.\n\t */\n\tget(provider: string): AuthCredential | undefined {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) return undefined;\n\t\treturn this.data[provider] ?? undefined;\n\t}\n\n\t/**\n\t * Set credential for a provider.\n\t */\n\tset(provider: string, credential: AuthCredential): void {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) {\n\t\t\tdelete this.data[provider];\n\t\t\tthis.persistProviderChange(provider, undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.data[provider] = credential;\n\t\tthis.persistProviderChange(provider, credential);\n\t}\n\n\t/**\n\t * Remove credential for a provider.\n\t */\n\tremove(provider: string): void {\n\t\tdelete this.data[provider];\n\t\tthis.persistProviderChange(provider, undefined);\n\t}\n\n\t/**\n\t * List all providers with credentials.\n\t */\n\tlist(): string[] {\n\t\treturn Object.keys(this.data).filter((provider) => provider !== RETIRED_GROK_OAUTH_PROXY);\n\t}\n\n\t/**\n\t * Check if credentials exist for a provider in auth.json.\n\t */\n\thas(provider: string): boolean {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) return false;\n\t\treturn provider in this.data;\n\t}\n\n\t/**\n\t * Check if any form of auth is configured for a provider.\n\t * Unlike getApiKey(), this doesn't refresh OAuth tokens.\n\t */\n\thasAuth(provider: string): boolean {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) return false;\n\t\tif (this.runtimeOverrides.has(provider)) return true;\n\t\tif (this.data[provider]) return true;\n\t\tif (getEnvApiKey(provider)) return true;\n\t\tif (this.fallbackResolver?.(provider)) return true;\n\t\treturn false;\n\t}\n\n\t/** Return the number of stored OAuth accounts for a provider. */\n\tgetOAuthAccountCount(provider: string): number {\n\t\tconst credential = this.data[provider];\n\t\treturn credential?.type === \"oauth\" ? getOAuthAccounts(credential).length : 0;\n\t}\n\n\t/** Return safe, human-readable labels for every stored OAuth account. */\n\tlistOAuthAccounts(provider: string): OAuthAccountSummary[] {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"oauth\") return [];\n\t\tconst accounts = getOAuthAccounts(credential);\n\t\tconst selectedIndex = getSelectedOAuthAccountIndex(credential, accounts.length);\n\t\treturn accounts.map((account, index) => ({\n\t\t\tindex,\n\t\t\tlabel: getOAuthAccountDisplayLabel(provider, account) ?? `Account ${index + 1}`,\n\t\t\tselected: index === selectedIndex,\n\t\t}));\n\t}\n\n\t/** Return the human-readable label of the selected OAuth account. */\n\tgetOAuthAccountLabel(provider: string): string | undefined {\n\t\treturn this.listOAuthAccounts(provider).find((account) => account.selected)?.label;\n\t}\n\n\t/** Explicitly select and persist the OAuth account used by this provider. */\n\tselectOAuthAccount(provider: string, accountIndex: number): void {\n\t\tthis.storage.withLock((current) => {\n\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\tconst credential = currentData[provider];\n\t\t\tif (credential?.type !== \"oauth\") {\n\t\t\t\tthrow new Error(`No OAuth accounts configured for ${provider}`);\n\t\t\t}\n\t\t\tconst accounts = [...getOAuthAccounts(credential)];\n\t\t\tif (!Number.isInteger(accountIndex) || accountIndex < 0 || accountIndex >= accounts.length) {\n\t\t\t\tthrow new Error(`Invalid OAuth account index ${accountIndex} for ${provider}`);\n\t\t\t}\n\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t...currentData,\n\t\t\t\t[provider]: createOAuthCredential(accounts, accountIndex),\n\t\t\t};\n\t\t\tthis.data = merged;\n\t\t\tthis.loadError = null;\n\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\t}\n\n\t/**\n\t * Return the explicitly selected OAuth credentials without refreshing tokens.\n\t * Used by provider model customization hooks.\n\t */\n\tgetOAuthCredentials(provider: string): OAuthCredentials | undefined {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"oauth\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst accounts = getOAuthAccounts(credential);\n\t\treturn accounts[getSelectedOAuthAccountIndex(credential, accounts.length)];\n\t}\n\n\t/**\n\t * Return auth status without exposing credential values or refreshing tokens.\n\t */\n\tgetAuthStatus(provider: string): AuthStatus {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) {\n\t\t\treturn { configured: false };\n\t\t}\n\t\tif (this.data[provider]) {\n\t\t\treturn { configured: true, source: \"stored\" };\n\t\t}\n\n\t\tif (this.runtimeOverrides.has(provider)) {\n\t\t\treturn { configured: false, source: \"runtime\", label: \"--api-key\" };\n\t\t}\n\n\t\tconst envKeys = findEnvKeys(provider);\n\t\tif (envKeys?.[0]) {\n\t\t\treturn { configured: false, source: \"environment\", label: envKeys[0] };\n\t\t}\n\n\t\tif (this.fallbackResolver?.(provider)) {\n\t\t\treturn { configured: false, source: \"fallback\", label: \"custom provider config\" };\n\t\t}\n\n\t\treturn { configured: false };\n\t}\n\n\t/**\n\t * Get all credentials (for passing to getOAuthApiKey).\n\t */\n\tgetAll(): AuthStorageData {\n\t\treturn omitRetiredGrokOAuthProxy({ ...this.data });\n\t}\n\n\tdrainErrors(): Error[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\t/**\n\t * Login to an OAuth provider. Repeated logins append distinct accounts and\n\t * update an existing account when the provider exposes a stable identity.\n\t */\n\tasync login(providerId: OAuthProviderId, callbacks: OAuthLoginCallbacks): Promise<void> {\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) {\n\t\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t\t}\n\n\t\tconst credentials = await provider.login(callbacks);\n\t\tif (this.loadError) {\n\t\t\tthis.data[providerId] = { type: \"oauth\", ...credentials };\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst existing = currentData[providerId];\n\t\t\t\tlet credential: OAuthCredential;\n\n\t\t\t\tif (existing?.type === \"oauth\") {\n\t\t\t\t\tconst accounts = [...getOAuthAccounts(existing)];\n\t\t\t\t\tconst matchingIndex = findMatchingOAuthAccount(accounts, credentials);\n\t\t\t\t\tlet activeAccount: number;\n\t\t\t\t\tif (matchingIndex >= 0) {\n\t\t\t\t\t\taccounts[matchingIndex] = credentials;\n\t\t\t\t\t\tactiveAccount = matchingIndex;\n\t\t\t\t\t} else {\n\t\t\t\t\t\taccounts.push(credentials);\n\t\t\t\t\t\tactiveAccount = accounts.length - 1;\n\t\t\t\t\t}\n\t\t\t\t\tcredential = createOAuthCredential(accounts, activeAccount);\n\t\t\t\t} else {\n\t\t\t\t\tcredential = createOAuthCredential([credentials]);\n\t\t\t\t}\n\n\t\t\t\tconst merged: AuthStorageData = { ...currentData, [providerId]: credential };\n\t\t\t\tthis.data = merged;\n\t\t\t\tthis.loadError = null;\n\t\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Logout from a provider.\n\t */\n\tlogout(provider: string): void {\n\t\tthis.remove(provider);\n\t}\n\n\t/**\n\t * Resolve the explicitly selected account and refresh it under the storage lock.\n\t *\n\t * `minRemainingMs` lets a long operation demand headroom. An access token is\n\t * resolved once and then reused for the whole request, so a token that is\n\t * merely \"not expired yet\" can still expire mid-flight and come back as a\n\t * provider 401. Callers that run for minutes (compaction) ask for a margin.\n\t */\n\tprivate async resolveOAuthTokenWithLock(\n\t\tproviderId: OAuthProviderId,\n\t\tminRemainingMs = 0,\n\t\trejectedApiKey?: string,\n\t): Promise<{ apiKey: string; newCredentials: OAuthCredentials } | null> {\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.storage.withLockAsync(async (current) => {\n\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\tthis.data = currentData;\n\t\t\tthis.loadError = null;\n\n\t\t\tconst credential = currentData[providerId];\n\t\t\tif (credential?.type !== \"oauth\") {\n\t\t\t\treturn { result: null };\n\t\t\t}\n\n\t\t\tconst accounts = [...getOAuthAccounts(credential)];\n\t\t\tconst accountIndex = getSelectedOAuthAccountIndex(credential, accounts.length);\n\t\t\tconst account = accounts[accountIndex];\n\t\t\tif (!account) return { result: null };\n\n\t\t\tconst resolved = await this.resolveAccountToken(provider, providerId, account, minRemainingMs, rejectedApiKey);\n\t\t\tif (!resolved) return { result: null };\n\n\t\t\tif (resolved.newCredentials === account) {\n\t\t\t\treturn { result: resolved };\n\t\t\t}\n\n\t\t\tconst newCredentials = { ...account, ...resolved.newCredentials };\n\t\t\taccounts[accountIndex] = newCredentials;\n\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t...currentData,\n\t\t\t\t[providerId]: createOAuthCredential(accounts, accountIndex),\n\t\t\t};\n\t\t\tthis.data = merged;\n\t\t\treturn {\n\t\t\t\tresult: { ...resolved, newCredentials },\n\t\t\t\tnext: JSON.stringify(merged, null, 2),\n\t\t\t};\n\t\t});\n\t}\n\n\t/**\n\t * Force-refresh the selected account after the provider rejected `rejectedApiKey`.\n\t *\n\t * Local expiry is not the last word: ChatGPT/Codex answers `401 token_expired`\n\t * for a token whose JWT `exp` and our stored `expires` still lie days ahead\n\t * (server-side revocation, rotation from another login). Refreshing only on\n\t * the local clock would keep replaying the dead token until that date.\n\t *\n\t * Several omk processes share auth.json. If the stored token no longer equals\n\t * the rejected one, another process already rotated it and the current token\n\t * is returned without a second refresh, which would only burn the new refresh\n\t * token. A failed refresh propagates so the caller can ask for `/login`; the\n\t * credential is left in place for that login to replace.\n\t */\n\tasync refreshRejectedOAuthToken(providerId: OAuthProviderId, rejectedApiKey: string): Promise<string | undefined> {\n\t\treturn (await this.resolveOAuthTokenWithLock(providerId, 0, rejectedApiKey))?.apiKey;\n\t}\n\n\t/**\n\t * Token for one account, refreshing when it is expired or too close to it.\n\t *\n\t * Hard expiry must refresh, and a refresh failure there is fatal. A margin\n\t * miss is only a precaution: the token is still valid, so a failed proactive\n\t * refresh falls back to it instead of breaking a working session. A token the\n\t * provider already rejected (`rejectedApiKey`) is refreshed unconditionally,\n\t * and that failure is fatal too.\n\t */\n\tprivate async resolveAccountToken(\n\t\tprovider: OAuthProviderInterface,\n\t\tproviderId: OAuthProviderId,\n\t\taccount: OAuthCredentials,\n\t\tminRemainingMs: number,\n\t\trejectedApiKey?: string,\n\t): Promise<{ apiKey: string; newCredentials: OAuthCredentials } | null> {\n\t\tconst now = Date.now();\n\t\tif (now >= account.expires) {\n\t\t\treturn await getOAuthApiKey(providerId, { [providerId]: account });\n\t\t}\n\t\tif (rejectedApiKey !== undefined && provider.getApiKey(account) === rejectedApiKey) {\n\t\t\tconst refreshed = await provider.refreshToken(account);\n\t\t\treturn { apiKey: provider.getApiKey(refreshed), newCredentials: refreshed };\n\t\t}\n\t\tif (minRemainingMs > 0 && now + minRemainingMs >= account.expires) {\n\t\t\ttry {\n\t\t\t\tconst refreshed = await provider.refreshToken(account);\n\t\t\t\treturn { apiKey: provider.getApiKey(refreshed), newCredentials: refreshed };\n\t\t\t} catch {\n\t\t\t\t// Still valid right now; prefer a usable token over a hard failure.\n\t\t\t}\n\t\t}\n\t\treturn { apiKey: provider.getApiKey(account), newCredentials: account };\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Priority:\n\t * 1. Runtime override (CLI --api-key)\n\t * 2. API key from auth.json\n\t * 3. OAuth token from auth.json (auto-refreshed with locking)\n\t * 4. Environment variable\n\t * 5. Fallback resolver (models.json custom providers)\n\t */\n\tasync getApiKey(\n\t\tproviderId: string,\n\t\toptions?: { includeFallback?: boolean; minRemainingMs?: number },\n\t): Promise<string | undefined> {\n\t\t// Runtime override takes highest priority\n\t\tconst runtimeKey = this.runtimeOverrides.get(providerId);\n\t\tif (runtimeKey) {\n\t\t\treturn runtimeKey;\n\t\t}\n\n\t\tconst cred = this.data[providerId];\n\n\t\tif (cred?.type === \"api_key\") {\n\t\t\treturn resolveConfigValue(cred.key);\n\t\t}\n\n\t\tif (cred?.type === \"oauth\") {\n\t\t\ttry {\n\t\t\t\tconst result = await this.resolveOAuthTokenWithLock(providerId, options?.minRemainingMs ?? 0);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn result.apiKey;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.recordError(error);\n\t\t\t\t// Credentials are preserved so a later request or /login can recover.\n\t\t\t\tthis.reload();\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\t// Fall back to environment variable\n\t\tconst envKey = getEnvApiKey(providerId);\n\t\tif (envKey) return envKey;\n\n\t\t// Fall back to custom resolver (e.g., models.json custom providers)\n\t\tif (options?.includeFallback !== false) {\n\t\t\treturn this.fallbackResolver?.(providerId) ?? undefined;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get all registered OAuth providers\n\t */\n\tgetOAuthProviders() {\n\t\treturn getOAuthProviders();\n\t}\n}\n"]}
1
+ {"version":3,"file":"auth-storage.js","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACnF,OAAO,EACN,WAAW,EACX,YAAY,GAKZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACN,wBAAwB,EACxB,qBAAqB,EACrB,2BAA2B,EAC3B,uBAAuB,EAGvB,yBAAyB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,qBAAqB,EACrB,gBAAgB,EAChB,4BAA4B,GAE5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AAEpD,SAAS,yBAAyB,CAAC,IAAqB,EAAmB;IAC1E,IAAI,CAAC,CAAC,w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C;gBACJ,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,yBAAyB,CAAC,UAAU,EAAE,OAAO,EAAE,cAAc,IAAI,CAAC,CAAC,CAAC;gBAC9F,IAAI,MAAM,EAAE,CAAC;oBACZ,OAAO,MAAM,CAAC,MAAM,CAAC;gBACtB,CAAC;YACF,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;gBACxB,sEAAsE;gBACtE,IAAI,CAAC,MAAM,EAAE,CAAC;gBACd,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;QAED,gGAAgG;QAChG,2FAA2F;QAC3F,gGAA8F;QAC9F,0EAA0E;QAC1E,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACjC,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,oCAAoC;QACpC,MAAM,MAAM,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;QACxC,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;QAE1B,oEAAoE;QACpE,IAAI,OAAO,EAAE,eAAe,KAAK,KAAK,EAAE,CAAC;YACxC,OAAO,IAAI,CAAC,gBAAgB,EAAE,CAAC,UAAU,CAAC,IAAI,SAAS,CAAC;QACzD,CAAC;QAED,OAAO,SAAS,CAAC;IAAA,CACjB;IAED;;OAEG;IACH,iBAAiB,GAAG;QACnB,OAAO,iBAAiB,EAAE,CAAC;IAAA,CAC3B;CACD","sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n *\n * Uses file locking to prevent race conditions when multiple OMK instances\n * try to refresh tokens simultaneously.\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport {\n\tfindEnvKeys,\n\tgetEnvApiKey,\n\ttype OAuthCredentials,\n\ttype OAuthLoginCallbacks,\n\ttype OAuthProviderId,\n\ttype OAuthProviderInterface,\n} from \"omk-ai\";\nimport { getOAuthApiKey, getOAuthProvider, getOAuthProviders } from \"omk-ai/oauth\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport {\n\tfindMatchingOAuthAccount,\n\tfindOAuthAccountMatch,\n\tgetOAuthAccountDisplayLabel,\n\tmergeImportedCredential,\n\ttype OAuthAccountImport,\n\ttype OAuthAccountSummary,\n\tpreviewOAuthAccountImport,\n} from \"./oauth-account-import.ts\";\nimport {\n\tcreateOAuthCredential,\n\tgetOAuthAccounts,\n\tgetSelectedOAuthAccountIndex,\n\ttype OAuthCredential,\n} from \"./oauth-credential.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\nconst RETIRED_GROK_OAUTH_PROXY = \"grok-oauth-proxy\";\n\nfunction omitRetiredGrokOAuthProxy(data: AuthStorageData): AuthStorageData {\n\tif (!(RETIRED_GROK_OAUTH_PROXY in data)) return data;\n\tconst { [RETIRED_GROK_OAUTH_PROXY]: _retired, ...kept } = data;\n\treturn kept;\n}\n\nexport type ApiKeyCredential = {\n\ttype: \"api_key\";\n\tkey: string;\n};\n\nexport type { OAuthAccountImport, OAuthAccountSummary } from \"./oauth-account-import.ts\";\nexport type { OAuthCredential } from \"./oauth-credential.ts\";\n\nexport type AuthCredential = ApiKeyCredential | OAuthCredential;\n\nexport type AuthStorageData = Record<string, AuthCredential>;\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\";\n\tlabel?: string;\n};\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n\tprivate data: AuthStorageData = {};\n\tprivate runtimeOverrides: Map<string, string> = new Map();\n\tprivate fallbackResolver?: (provider: string) => string | undefined;\n\tprivate loadError: Error | null = null;\n\tprivate errors: Error[] = [];\n\tprivate storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\t/**\n\t * Set a runtime API key override (not persisted to disk).\n\t * Used for CLI --api-key flag.\n\t */\n\tsetRuntimeApiKey(provider: string, apiKey: string): void {\n\t\tthis.runtimeOverrides.set(provider, apiKey);\n\t}\n\n\t/**\n\t * Remove a runtime API key override.\n\t */\n\tremoveRuntimeApiKey(provider: string): void {\n\t\tthis.runtimeOverrides.delete(provider);\n\t}\n\n\t/**\n\t * Set a fallback resolver for API keys not found in auth.json or env vars.\n\t * Used for custom provider keys from models.json.\n\t */\n\tsetFallbackResolver(resolver: (provider: string) => string | undefined): void {\n\t\tthis.fallbackResolver = resolver;\n\t}\n\n\tprivate recordError(error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push(normalizedError);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\treturn omitRetiredGrokOAuthProxy(JSON.parse(content) as AuthStorageData);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthrow new Error(`Failed to parse auth storage: ${message}`);\n\t\t}\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.loadError = error as Error;\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\tprivate persistProviderChange(provider: string, credential: AuthCredential | undefined): void {\n\t\tif (this.loadError) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst merged: AuthStorageData = { ...currentData };\n\t\t\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) {\n\t\t\t\t\tdelete merged[provider];\n\t\t\t\t} else if (credential) {\n\t\t\t\t\tmerged[provider] = credential;\n\t\t\t\t} else {\n\t\t\t\t\tdelete merged[provider];\n\t\t\t\t}\n\t\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Get credential for a provider.\n\t */\n\tget(provider: string): AuthCredential | undefined {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) return undefined;\n\t\treturn this.data[provider] ?? undefined;\n\t}\n\n\t/**\n\t * Set credential for a provider.\n\t */\n\tset(provider: string, credential: AuthCredential): void {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) {\n\t\t\tdelete this.data[provider];\n\t\t\tthis.persistProviderChange(provider, undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.data[provider] = credential;\n\t\tthis.persistProviderChange(provider, credential);\n\t}\n\n\t/**\n\t * Remove credential for a provider.\n\t */\n\tremove(provider: string): void {\n\t\tdelete this.data[provider];\n\t\tthis.persistProviderChange(provider, undefined);\n\t}\n\n\t/**\n\t * List all providers with credentials.\n\t */\n\tlist(): string[] {\n\t\treturn Object.keys(this.data).filter((provider) => provider !== RETIRED_GROK_OAUTH_PROXY);\n\t}\n\n\t/**\n\t * Check if credentials exist for a provider in auth.json.\n\t */\n\thas(provider: string): boolean {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) return false;\n\t\treturn provider in this.data;\n\t}\n\n\t/**\n\t * Check if any form of auth is configured for a provider.\n\t * Unlike getApiKey(), this doesn't refresh OAuth tokens.\n\t */\n\thasAuth(provider: string): boolean {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) return false;\n\t\tif (this.runtimeOverrides.has(provider)) return true;\n\t\tif (this.data[provider]) return true;\n\t\tif (getEnvApiKey(provider)) return true;\n\t\tif (this.fallbackResolver?.(provider)) return true;\n\t\treturn false;\n\t}\n\n\t/** Return the number of stored OAuth accounts for a provider. */\n\tgetOAuthAccountCount(provider: string): number {\n\t\tconst credential = this.data[provider];\n\t\treturn credential?.type === \"oauth\" ? getOAuthAccounts(credential).length : 0;\n\t}\n\n\t/** Return safe, human-readable labels for every stored OAuth account. */\n\tlistOAuthAccounts(provider: string): OAuthAccountSummary[] {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"oauth\") return [];\n\t\tconst accounts = getOAuthAccounts(credential);\n\t\tconst selectedIndex = getSelectedOAuthAccountIndex(credential, accounts.length);\n\t\treturn accounts.map((account, index) => ({\n\t\t\tindex,\n\t\t\tlabel: getOAuthAccountDisplayLabel(provider, account) ?? `Account ${index + 1}`,\n\t\t\tselected: index === selectedIndex,\n\t\t}));\n\t}\n\n\t/** Return the human-readable label of the selected OAuth account. */\n\tgetOAuthAccountLabel(provider: string): string | undefined {\n\t\treturn this.listOAuthAccounts(provider).find((account) => account.selected)?.label;\n\t}\n\n\t/**\n\t * Explicitly select and persist the OAuth account used by this provider.\n\t */\n\tselectOAuthAccount(provider: string, accountIndex: number): void {\n\t\tthis.storage.withLock((current) => {\n\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\tconst credential = currentData[provider];\n\t\t\tif (credential?.type !== \"oauth\") {\n\t\t\t\tthrow new Error(`No OAuth accounts configured for ${provider}`);\n\t\t\t}\n\t\t\tconst accounts = [...getOAuthAccounts(credential)];\n\t\t\tif (!Number.isInteger(accountIndex) || accountIndex < 0 || accountIndex >= accounts.length) {\n\t\t\t\tthrow new Error(`Invalid OAuth account index ${accountIndex} for ${provider}`);\n\t\t\t}\n\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t...currentData,\n\t\t\t\t[provider]: createOAuthCredential(accounts, accountIndex),\n\t\t\t};\n\t\t\tthis.data = merged;\n\t\t\tthis.loadError = null;\n\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\t}\n\n\t/** Match, merge and write inside the storage lock (`omk provider adopt`). The active selection never moves. */\n\taddOAuthAccount(provider: string, credentials: OAuthCredentials): OAuthAccountImport {\n\t\tif (this.loadError) {\n\t\t\treturn { action: \"blocked\", reason: \"the credential store could not be read\" };\n\t\t}\n\n\t\ttry {\n\t\t\treturn this.storage.withLock<OAuthAccountImport>((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst existing = currentData[provider];\n\t\t\t\tconst accounts = existing?.type === \"oauth\" ? [...getOAuthAccounts(existing)] : [];\n\t\t\t\tconst activeIndex =\n\t\t\t\t\texisting?.type === \"oauth\" ? getSelectedOAuthAccountIndex(existing, accounts.length) : 0;\n\t\t\t\tconst matchIndex = findOAuthAccountMatch(accounts, credentials);\n\n\t\t\t\tif (matchIndex >= 0) {\n\t\t\t\t\tconst current_ = accounts[matchIndex];\n\t\t\t\t\tif (current_ && typeof current_.expires === \"number\" && current_.expires > Date.now()) {\n\t\t\t\t\t\tthis.data = currentData;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\taction: \"unchanged\",\n\t\t\t\t\t\t\t\taccountIndex: matchIndex,\n\t\t\t\t\t\t\t\treason: \"the stored account is still valid\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\taccounts[matchIndex] = mergeImportedCredential(current_, credentials);\n\t\t\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t\t\t...currentData,\n\t\t\t\t\t\t[provider]: createOAuthCredential(accounts, accounts.length === 1 ? 0 : activeIndex),\n\t\t\t\t\t};\n\t\t\t\t\tthis.data = merged;\n\t\t\t\t\tthis.loadError = null;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tresult: { action: \"updated\", accountIndex: matchIndex },\n\t\t\t\t\t\tnext: JSON.stringify(merged, null, 2),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\taccounts.push(credentials);\n\t\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t\t...currentData,\n\t\t\t\t\t[provider]: createOAuthCredential(accounts, accounts.length === 1 ? 0 : activeIndex),\n\t\t\t\t};\n\t\t\t\tthis.data = merged;\n\t\t\t\tthis.loadError = null;\n\t\t\t\treturn {\n\t\t\t\t\tresult: { action: \"imported\", accountIndex: accounts.length - 1 },\n\t\t\t\t\tnext: JSON.stringify(merged, null, 2),\n\t\t\t\t};\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t\treturn {\n\t\t\t\taction: \"blocked\",\n\t\t\t\treason: `the credential store could not be written: ${error instanceof Error ? error.message : error}`,\n\t\t\t};\n\t\t}\n\t}\n\n\t/** Predict what `addOAuthAccount` would do, without writing. */\n\tpreviewOAuthAccountImport(provider: string, credentials: OAuthCredentials): OAuthAccountImport {\n\t\tconst existing = this.data[provider];\n\t\treturn previewOAuthAccountImport({\n\t\t\tloadError: this.loadError !== null,\n\t\t\texisting,\n\t\t\taccounts: existing?.type === \"oauth\" ? getOAuthAccounts(existing) : [],\n\t\t\tcredentials,\n\t\t});\n\t}\n\n\t/**\n\t * Return the explicitly selected OAuth credentials without refreshing tokens.\n\t * Used by provider model customization hooks.\n\t */\n\tgetOAuthCredentials(provider: string): OAuthCredentials | undefined {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"oauth\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst accounts = getOAuthAccounts(credential);\n\t\treturn accounts[getSelectedOAuthAccountIndex(credential, accounts.length)];\n\t}\n\n\t/**\n\t * Return auth status without exposing credential values or refreshing tokens.\n\t */\n\tgetAuthStatus(provider: string): AuthStatus {\n\t\tif (provider === RETIRED_GROK_OAUTH_PROXY) {\n\t\t\treturn { configured: false };\n\t\t}\n\t\tif (this.data[provider]) {\n\t\t\treturn { configured: true, source: \"stored\" };\n\t\t}\n\n\t\tif (this.runtimeOverrides.has(provider)) {\n\t\t\treturn { configured: false, source: \"runtime\", label: \"--api-key\" };\n\t\t}\n\n\t\tconst envKeys = findEnvKeys(provider);\n\t\tif (envKeys?.[0]) {\n\t\t\treturn { configured: false, source: \"environment\", label: envKeys[0] };\n\t\t}\n\n\t\tif (this.fallbackResolver?.(provider)) {\n\t\t\treturn { configured: false, source: \"fallback\", label: \"custom provider config\" };\n\t\t}\n\n\t\treturn { configured: false };\n\t}\n\n\t/**\n\t * Get all credentials (for passing to getOAuthApiKey).\n\t */\n\tgetAll(): AuthStorageData {\n\t\treturn omitRetiredGrokOAuthProxy({ ...this.data });\n\t}\n\n\tdrainErrors(): Error[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\t/**\n\t * True when the credential store could not be read (for example, lock contention with another\n\t * session). Callers must not substitute a different credential source while this is set.\n\t */\n\thasLoadError(): boolean {\n\t\treturn this.loadError !== null;\n\t}\n\n\t/**\n\t * Login to an OAuth provider. Repeated logins append distinct accounts and\n\t * update an existing account when the provider exposes a stable identity.\n\t */\n\tasync login(providerId: OAuthProviderId, callbacks: OAuthLoginCallbacks): Promise<void> {\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) {\n\t\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t\t}\n\n\t\tconst credentials = await provider.login(callbacks);\n\t\tif (this.loadError) {\n\t\t\tthis.data[providerId] = { type: \"oauth\", ...credentials };\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst existing = currentData[providerId];\n\t\t\t\tlet credential: OAuthCredential;\n\n\t\t\t\tif (existing?.type === \"oauth\") {\n\t\t\t\t\tconst accounts = [...getOAuthAccounts(existing)];\n\t\t\t\t\tconst matchingIndex = findMatchingOAuthAccount(accounts, credentials);\n\t\t\t\t\tlet activeAccount: number;\n\t\t\t\t\tif (matchingIndex >= 0) {\n\t\t\t\t\t\taccounts[matchingIndex] = credentials;\n\t\t\t\t\t\tactiveAccount = matchingIndex;\n\t\t\t\t\t} else {\n\t\t\t\t\t\taccounts.push(credentials);\n\t\t\t\t\t\tactiveAccount = accounts.length - 1;\n\t\t\t\t\t}\n\t\t\t\t\tcredential = createOAuthCredential(accounts, activeAccount);\n\t\t\t\t} else {\n\t\t\t\t\tcredential = createOAuthCredential([credentials]);\n\t\t\t\t}\n\n\t\t\t\tconst merged: AuthStorageData = { ...currentData, [providerId]: credential };\n\t\t\t\tthis.data = merged;\n\t\t\t\tthis.loadError = null;\n\t\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Logout from a provider.\n\t */\n\tlogout(provider: string): void {\n\t\tthis.remove(provider);\n\t}\n\n\t/**\n\t * Resolve the explicitly selected account and refresh it under the storage lock.\n\t *\n\t * `minRemainingMs` lets a long operation demand headroom. An access token is\n\t * resolved once and then reused for the whole request, so a token that is\n\t * merely \"not expired yet\" can still expire mid-flight and come back as a\n\t * provider 401. Callers that run for minutes (compaction) ask for a margin.\n\t */\n\tprivate async resolveOAuthTokenWithLock(\n\t\tproviderId: OAuthProviderId,\n\t\tminRemainingMs = 0,\n\t\trejectedApiKey?: string,\n\t): Promise<{ apiKey: string; newCredentials: OAuthCredentials } | null> {\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) return null;\n\n\t\treturn this.storage.withLockAsync(async (current) => {\n\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\tthis.data = currentData;\n\t\t\tthis.loadError = null;\n\n\t\t\tconst credential = currentData[providerId];\n\t\t\tif (credential?.type !== \"oauth\") {\n\t\t\t\treturn { result: null };\n\t\t\t}\n\n\t\t\tconst accounts = [...getOAuthAccounts(credential)];\n\t\t\tconst accountIndex = getSelectedOAuthAccountIndex(credential, accounts.length);\n\t\t\tconst account = accounts[accountIndex];\n\t\t\tif (!account) return { result: null };\n\n\t\t\tconst resolved = await this.resolveAccountToken(provider, providerId, account, minRemainingMs, rejectedApiKey);\n\t\t\tif (!resolved) return { result: null };\n\n\t\t\tif (resolved.newCredentials === account) {\n\t\t\t\treturn { result: resolved };\n\t\t\t}\n\n\t\t\tconst newCredentials = { ...account, ...resolved.newCredentials };\n\t\t\taccounts[accountIndex] = newCredentials;\n\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t...currentData,\n\t\t\t\t[providerId]: createOAuthCredential(accounts, accountIndex),\n\t\t\t};\n\t\t\tthis.data = merged;\n\t\t\treturn {\n\t\t\t\tresult: { ...resolved, newCredentials },\n\t\t\t\tnext: JSON.stringify(merged, null, 2),\n\t\t\t};\n\t\t});\n\t}\n\n\t/**\n\t * Force-refresh the selected account after the provider rejected `rejectedApiKey`.\n\t *\n\t * Local expiry is not the last word: ChatGPT/Codex answers `401 token_expired`\n\t * for a token whose JWT `exp` and our stored `expires` still lie days ahead\n\t * (server-side revocation, rotation from another login). Refreshing only on\n\t * the local clock would keep replaying the dead token until that date.\n\t *\n\t * Several omk processes share auth.json. If the stored token no longer equals\n\t * the rejected one, another process already rotated it and the current token\n\t * is returned without a second refresh, which would only burn the new refresh\n\t * token. A failed refresh propagates so the caller can ask for `/login`; the\n\t * credential is left in place for that login to replace.\n\t */\n\tasync refreshRejectedOAuthToken(providerId: OAuthProviderId, rejectedApiKey: string): Promise<string | undefined> {\n\t\treturn (await this.resolveOAuthTokenWithLock(providerId, 0, rejectedApiKey))?.apiKey;\n\t}\n\n\t/**\n\t * Token for one account, refreshing when it is expired or too close to it.\n\t *\n\t * Hard expiry must refresh, and a refresh failure there is fatal. A margin\n\t * miss is only a precaution: the token is still valid, so a failed proactive\n\t * refresh falls back to it instead of breaking a working session. A token the\n\t * provider already rejected (`rejectedApiKey`) is refreshed unconditionally,\n\t * and that failure is fatal too.\n\t */\n\tprivate async resolveAccountToken(\n\t\tprovider: OAuthProviderInterface,\n\t\tproviderId: OAuthProviderId,\n\t\taccount: OAuthCredentials,\n\t\tminRemainingMs: number,\n\t\trejectedApiKey?: string,\n\t): Promise<{ apiKey: string; newCredentials: OAuthCredentials } | null> {\n\t\tconst now = Date.now();\n\t\tif (now >= account.expires) {\n\t\t\treturn await getOAuthApiKey(providerId, { [providerId]: account });\n\t\t}\n\t\tif (rejectedApiKey !== undefined && provider.getApiKey(account) === rejectedApiKey) {\n\t\t\tconst refreshed = await provider.refreshToken(account);\n\t\t\treturn { apiKey: provider.getApiKey(refreshed), newCredentials: refreshed };\n\t\t}\n\t\tif (minRemainingMs > 0 && now + minRemainingMs >= account.expires) {\n\t\t\ttry {\n\t\t\t\tconst refreshed = await provider.refreshToken(account);\n\t\t\t\treturn { apiKey: provider.getApiKey(refreshed), newCredentials: refreshed };\n\t\t\t} catch {\n\t\t\t\t// Still valid right now; prefer a usable token over a hard failure.\n\t\t\t}\n\t\t}\n\t\treturn { apiKey: provider.getApiKey(account), newCredentials: account };\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Priority:\n\t * 1. Runtime override (CLI --api-key)\n\t * 2. API key from auth.json\n\t * 3. OAuth token from auth.json (auto-refreshed with locking)\n\t * 4. Environment variable\n\t * 5. Fallback resolver (models.json custom providers)\n\t */\n\tasync getApiKey(\n\t\tproviderId: string,\n\t\toptions?: { includeFallback?: boolean; minRemainingMs?: number },\n\t): Promise<string | undefined> {\n\t\t// Runtime override takes highest priority\n\t\tconst runtimeKey = this.runtimeOverrides.get(providerId);\n\t\tif (runtimeKey) {\n\t\t\treturn runtimeKey;\n\t\t}\n\n\t\t// Lock contention with another session leaves the credential map unread (reload() records the\n\t\t// failure and keeps the previous data). Retry the read here so one transient failure at startup\n\t\t// does not decide how this process authenticates for its whole lifetime.\n\t\tif (this.loadError) {\n\t\t\tthis.reload();\n\t\t}\n\n\t\tconst cred = this.data[providerId];\n\n\t\tif (cred?.type === \"api_key\") {\n\t\t\treturn resolveConfigValue(cred.key);\n\t\t}\n\n\t\tif (cred?.type === \"oauth\") {\n\t\t\ttry {\n\t\t\t\tconst result = await this.resolveOAuthTokenWithLock(providerId, options?.minRemainingMs ?? 0);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn result.apiKey;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.recordError(error);\n\t\t\t\t// Credentials are preserved so a later request or /login can recover.\n\t\t\t\tthis.reload();\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\t// A store that could not be read is not the same as a provider with no credential. Substituting\n\t\t// an environment key here replaced a stored OAuth credential with a stale OAuth token from\n\t\t// ANTHROPIC_API_KEY, and the provider answered 401 \"OAuth access token is invalid\" — an error\n\t\t// /login could never clear, because the stored credential was never used.\n\t\tif (this.loadError) {\n\t\t\tthis.recordError(this.loadError);\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Fall back to environment variable\n\t\tconst envKey = getEnvApiKey(providerId);\n\t\tif (envKey) return envKey;\n\n\t\t// Fall back to custom resolver (e.g., models.json custom providers)\n\t\tif (options?.includeFallback !== false) {\n\t\t\treturn this.fallbackResolver?.(providerId) ?? undefined;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get all registered OAuth providers\n\t */\n\tgetOAuthProviders() {\n\t\treturn getOAuthProviders();\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC3F,OAAO,EAAkB,KAAK,cAAc,EAAE,KAAK,WAAW,EAAsB,MAAM,QAAQ,CAAC;AACnG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,KAAK,sBAAsB,EAA+B,MAAM,qBAAqB,CAAC;AAE/F,OAAO,EACN,KAAK,uBAAuB,EAC5B,KAAK,2BAA2B,EAChC,KAAK,kBAAkB,EACvB,kCAAkC,EAClC,2BAA2B,EAC3B,8BAA8B,EAC9B,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CAAC,gBAAgB,CAAC,CAqB3B","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"omk-agent-core\";\nimport { uuidv7 } from \"omk-agent-core\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"omk-ai\";\nimport { completeSimple, type RetryCallbacks, type RetryPolicy, retryAssistantCall } from \"omk-ai\";\nimport type { CompactionSettings } from \"./compaction-headroom.ts\";\nimport { type CompactFailoverOptions, withCompactionModelFailover } from \"./model-failover.ts\";\n\nexport {\n\ttype CompactionHeadroomLimit,\n\ttype CompactionHeadroomThreshold,\n\ttype CompactionSettings,\n\tDEFAULT_COMPACTION_MAX_USAGE_RATIO,\n\tDEFAULT_COMPACTION_SETTINGS,\n\tgetCompactionHeadroomThreshold,\n\tshouldCompact,\n} from \"./compaction-headroom.ts\";\nexport type { CompactFailoverOptions } from \"./model-failover.ts\";\n\nimport { convertToLlm } from \"../messages.ts\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.ts\";\nimport {\n\tapplyCompactionKnowledgeTriage,\n\tbuildCompactionRuleHistory,\n\ttype CompactionRuleHistory,\n\ttype PreservedRuleRecord,\n} from \"./knowledge-triage.ts\";\nimport {\n\tcomputeFileLists,\n\textractCompactionFileOperations,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tgetMessageFromEntryForCompaction,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n\t/** Deterministically extracted, source-bound user rules carried outside LLM rewriting. */\n\tpreservedRules?: PreservedRuleRecord[];\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/** Estimate context tokens after adding messages that have not been sent yet. */\nexport function estimateProjectedContextTokens(\n\tmessages: AgentMessage[],\n\tpendingMessages: AgentMessage[],\n): ContextUsageEstimate {\n\treturn estimateContextTokens([...messages, ...pendingMessages]);\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// branch_summary and custom_message are user-role messages, valid cut points\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\t// branch_summary and custom_message are user-role messages, can start a turn\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\n\t\t// Estimate this message's size\n\t\tconst messageTokens = estimateTokens(entry.message);\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tlet matched = false;\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tmatched = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!matched) {\n\t\t\t\t// The budget-breaking entry is not itself cuttable (e.g. a huge\n\t\t\t\t// trailing tool result): fall back to its issuing assistant\n\t\t\t\t// message so compaction still makes progress and the call\n\t\t\t\t// stays with its result as one tail turn.\n\t\t\t\tfor (let j = i; j >= startIndex; j--) {\n\t\t\t\t\tconst candidate = entries[j];\n\t\t\t\t\tif (candidate.type === \"message\" && candidate.message.role === \"assistant\") {\n\t\t\t\t\t\tcutIndex = j;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at session header or compaction boundaries\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\t// Stop if we hit any message\n\t\t\tbreak;\n\t\t}\n\t\t// Include this non-message entry (bash, settings change, etc.)\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\n/**\n * Shared choke point for every compaction/branch-summary summarization call. Wraps the\n * single LLM call in {@link retryAssistantCall} so transient stream drops (e.g.\n * `terminated`, socket close) honor the configured retry policy instead of failing\n * the whole compaction on the first attempt. Deterministic errors and aborts return\n * immediately (see {@link retryAssistantCall}).\n */\nexport async function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\t// Summaries are standalone requests, so isolate routing and avoid cache writes that cannot be reused.\n\tconst requestOptions: SimpleStreamOptions = {\n\t\t...options,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t};\n\tconst produce = async (): Promise<AssistantMessage> =>\n\t\tstreamFn\n\t\t\t? (await streamFn(model, context, requestOptions)).result()\n\t\t\t: completeSimple(model, context, requestOptions);\n\treturn retryAssistantCall(produce, retry, requestOptions.signal, callbacks);\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn textContent;\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** Source-verified rule history from the prior default compaction. */\n\tpreviousRuleHistory?: CompactionRuleHistory;\n\t/** Exact session entries covered by this compaction's rule extraction. */\n\tcurrentRuleEntries?: readonly SessionEntry[];\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet previousRuleHistory: CompactionRuleHistory | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tpreviousRuleHistory = buildCompactionRuleHistory(prevCompaction, pathEntries);\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractCompactionFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\tconst currentRuleEntries = [\n\t\t...pathEntries.slice(boundaryStart, historyEnd),\n\t\t...(cutPoint.isSplitTurn ? pathEntries.slice(cutPoint.turnStartIndex, cutPoint.firstKeptEntryIndex) : []),\n\t];\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tpreviousRuleHistory,\n\t\tcurrentRuleEntries,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * When {@link failoverModels} is provided and the primary model fails with a\n * quota/billing exhaustion error (same-model retry is useless until reset),\n * the whole summarization is retried once with each eligible candidate in order.\n * Candidates use their own credentials; unresolved cross-provider auth is skipped.\n * Terminal candidate failures advance the chain. Other failures surface with\n * the candidate identity instead of being attributed to the primary model.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tfailoverModels?: readonly Model<any>[],\n\toptions?: CompactFailoverOptions,\n): Promise<CompactionResult> {\n\treturn withCompactionModelFailover({\n\t\tmodel,\n\t\tauth: { apiKey, headers },\n\t\tsignal,\n\t\tcandidates: failoverModels,\n\t\toptions,\n\t\trun: (candidate, auth) =>\n\t\t\tcompactWithModel(\n\t\t\t\tpreparation,\n\t\t\t\tcandidate,\n\t\t\t\tauth.apiKey,\n\t\t\t\tauth.headers,\n\t\t\t\tcustomInstructions,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t),\n\t});\n}\n\n/** Single-model compaction attempt (no failover). Implementation of {@link compact}. */\nasync function compactWithModel(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tpreviousRuleHistory,\n\t\tcurrentRuleEntries,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries (can be parallel if both needed) and merge into one\n\tlet summary: string;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\t// Generate both summaries in parallel\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? generateSummary(\n\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t\tretry,\n\t\t\t\t\t\tcallbacks,\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve(\"No prior history.\"),\n\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\tturnPrefixMessages,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t),\n\t\t]);\n\t\t// Merge into single summary\n\t\tsummary = `${historyResult}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult}`;\n\t} else {\n\t\t// Just generate history summary\n\t\tsummary = await generateSummary(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t);\n\t}\n\n\tconst triage = applyCompactionKnowledgeTriage({\n\t\tgeneratedSummary: summary,\n\t\tcurrentMessages: [...messagesToSummarize, ...turnPrefixMessages],\n\t\tcurrentEntries: currentRuleEntries,\n\t\tpreviousRules: previousRuleHistory?.rules,\n\t\tpreviousSummary,\n\t\tpreviousEntries: previousRuleHistory?.entries,\n\t});\n\tsummary = triage.summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles, preservedRules: [...triage.preservedRules] } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel),\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\treturn response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC3F,OAAO,EAAkB,KAAK,cAAc,EAAE,KAAK,WAAW,EAAsB,MAAM,QAAQ,CAAC;AACnG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,KAAK,sBAAsB,EAA+B,MAAM,qBAAqB,CAAC;AAE/F,OAAO,EACN,KAAK,uBAAuB,EAC5B,KAAK,2BAA2B,EAChC,KAAK,kBAAkB,EACvB,kCAAkC,EAClC,2BAA2B,EAC3B,8BAA8B,EAC9B,aAAa,GACb,MAAM,0BAA0B,CAAC;AAClC,YAAY,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAGlE,OAAO,EAA6C,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAGN,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAIN,KAAK,cAAc,EAKnB,MAAM,YAAY,CAAC;AAMpB,kEAAkE;AAClE,MAAM,WAAW,iBAAiB;IACjC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,0FAA0F;IAC1F,cAAc,CAAC,EAAE,mBAAmB,EAAE,CAAC;CACvC;AAMD,8EAA8E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EAAE,SAAS,YAAY,EAAE,CAAC;IAC7C,yDAAyD;IACzD,OAAO,EAAE,cAAc,CAAC;IACxB,8CAA8C;IAC9C,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,wBAAgB,iBAAiB,CAChC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,GAC1B,qBAAqB,GAAG,SAAS,CAgFnC;AAqBD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,OAAO,CAC5B,WAAW,EAAE,qBAAqB,EAClC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,kBAAkB,CAAC,EAAE,MAAM,EAC3B,MAAM,CAAC,EAAE,WAAW,EACpB,aAAa,CAAC,EAAE,aAAa,EAC7B,QAAQ,CAAC,EAAE,QAAQ,EACnB,KAAK,CAAC,EAAE,WAAW,EACnB,SAAS,CAAC,EAAE,cAAc,EAC1B,cAAc,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,EACtC,OAAO,CAAC,EAAE,sBAAsB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAqB3B","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"omk-agent-core\";\nimport { uuidv7 } from \"omk-agent-core\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"omk-ai\";\nimport { completeSimple, type RetryCallbacks, type RetryPolicy, retryAssistantCall } from \"omk-ai\";\nimport type { CompactionSettings } from \"./compaction-headroom.ts\";\nimport { type CompactFailoverOptions, withCompactionModelFailover } from \"./model-failover.ts\";\n\nexport {\n\ttype CompactionHeadroomLimit,\n\ttype CompactionHeadroomThreshold,\n\ttype CompactionSettings,\n\tDEFAULT_COMPACTION_MAX_USAGE_RATIO,\n\tDEFAULT_COMPACTION_SETTINGS,\n\tgetCompactionHeadroomThreshold,\n\tshouldCompact,\n} from \"./compaction-headroom.ts\";\nexport type { CompactFailoverOptions } from \"./model-failover.ts\";\n\nimport { convertToLlm } from \"../messages.ts\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.ts\";\nimport {\n\tapplyCompactionKnowledgeTriage,\n\tbuildCompactionRuleHistory,\n\ttype CompactionRuleHistory,\n\ttype PreservedRuleRecord,\n} from \"./knowledge-triage.ts\";\nimport {\n\tcomputeFileLists,\n\textractCompactionFileOperations,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tgetMessageFromEntryForCompaction,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n\t/** Deterministically extracted, source-bound user rules carried outside LLM rewriting. */\n\tpreservedRules?: PreservedRuleRecord[];\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/** Estimate context tokens after adding messages that have not been sent yet. */\nexport function estimateProjectedContextTokens(\n\tmessages: AgentMessage[],\n\tpendingMessages: AgentMessage[],\n): ContextUsageEstimate {\n\treturn estimateContextTokens([...messages, ...pendingMessages]);\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// branch_summary and custom_message are user-role messages, valid cut points\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\t// branch_summary and custom_message are user-role messages, can start a turn\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\n\t\t// Estimate this message's size\n\t\tconst messageTokens = estimateTokens(entry.message);\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tlet matched = false;\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tmatched = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!matched) {\n\t\t\t\t// The budget-breaking entry is not itself cuttable (e.g. a huge\n\t\t\t\t// trailing tool result): fall back to its issuing assistant\n\t\t\t\t// message so compaction still makes progress and the call\n\t\t\t\t// stays with its result as one tail turn.\n\t\t\t\tfor (let j = i; j >= startIndex; j--) {\n\t\t\t\t\tconst candidate = entries[j];\n\t\t\t\t\tif (candidate.type === \"message\" && candidate.message.role === \"assistant\") {\n\t\t\t\t\t\tcutIndex = j;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at session header or compaction boundaries\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\t// Stop if we hit any message\n\t\t\tbreak;\n\t\t}\n\t\t// Include this non-message entry (bash, settings change, etc.)\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\n/**\n * Shared choke point for every compaction/branch-summary summarization call. Wraps the\n * single LLM call in {@link retryAssistantCall} so transient stream drops (e.g.\n * `terminated`, socket close) honor the configured retry policy instead of failing\n * the whole compaction on the first attempt. Deterministic errors and aborts return\n * immediately (see {@link retryAssistantCall}).\n */\nexport async function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\t// Summaries are standalone requests, so isolate routing and avoid cache writes that cannot be reused.\n\tconst requestOptions: SimpleStreamOptions = {\n\t\t...options,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t};\n\tconst produce = async (): Promise<AssistantMessage> =>\n\t\tstreamFn\n\t\t\t? (await streamFn(model, context, requestOptions)).result()\n\t\t\t: completeSimple(model, context, requestOptions);\n\treturn retryAssistantCall(produce, retry, requestOptions.signal, callbacks);\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\treturn summaryTextOrThrow(response, \"Summarization failed\");\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** Source-verified rule history from the prior default compaction. */\n\tpreviousRuleHistory?: CompactionRuleHistory;\n\t/** Exact session entries covered by this compaction's rule extraction. */\n\tcurrentRuleEntries?: readonly SessionEntry[];\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet previousRuleHistory: CompactionRuleHistory | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tpreviousRuleHistory = buildCompactionRuleHistory(prevCompaction, pathEntries);\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractCompactionFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\tconst currentRuleEntries = [\n\t\t...pathEntries.slice(boundaryStart, historyEnd),\n\t\t...(cutPoint.isSplitTurn ? pathEntries.slice(cutPoint.turnStartIndex, cutPoint.firstKeptEntryIndex) : []),\n\t];\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tpreviousRuleHistory,\n\t\tcurrentRuleEntries,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * When {@link failoverModels} is provided and the primary model fails with a\n * quota/billing exhaustion error (same-model retry is useless until reset),\n * the whole summarization is retried once with each eligible candidate in order.\n * Candidates use their own credentials; unresolved cross-provider auth is skipped.\n * Terminal candidate failures advance the chain. Other failures surface with\n * the candidate identity instead of being attributed to the primary model.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tfailoverModels?: readonly Model<any>[],\n\toptions?: CompactFailoverOptions,\n): Promise<CompactionResult> {\n\treturn withCompactionModelFailover({\n\t\tmodel,\n\t\tauth: { apiKey, headers },\n\t\tsignal,\n\t\tcandidates: failoverModels,\n\t\toptions,\n\t\trun: (candidate, auth) =>\n\t\t\tcompactWithModel(\n\t\t\t\tpreparation,\n\t\t\t\tcandidate,\n\t\t\t\tauth.apiKey,\n\t\t\t\tauth.headers,\n\t\t\t\tcustomInstructions,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t),\n\t});\n}\n\n/** Single-model compaction attempt (no failover). Implementation of {@link compact}. */\nasync function compactWithModel(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tpreviousRuleHistory,\n\t\tcurrentRuleEntries,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries (can be parallel if both needed) and merge into one\n\tlet summary: string;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\t// Generate both summaries in parallel\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? generateSummary(\n\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t\tretry,\n\t\t\t\t\t\tcallbacks,\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve(\"No prior history.\"),\n\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\tturnPrefixMessages,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t),\n\t\t]);\n\t\t// Merge into single summary\n\t\tsummary = `${historyResult}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult}`;\n\t} else {\n\t\t// Just generate history summary\n\t\tsummary = await generateSummary(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t);\n\t}\n\n\tconst triage = applyCompactionKnowledgeTriage({\n\t\tgeneratedSummary: summary,\n\t\tcurrentMessages: [...messagesToSummarize, ...turnPrefixMessages],\n\t\tcurrentEntries: currentRuleEntries,\n\t\tpreviousRules: previousRuleHistory?.rules,\n\t\tpreviousSummary,\n\t\tpreviousEntries: previousRuleHistory?.entries,\n\t});\n\tsummary = triage.summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles, preservedRules: [...triage.preservedRules] } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel),\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\treturn summaryTextOrThrow(response, \"Turn prefix summarization failed\");\n}\n\n/** Summary text of a response. A length stop that wrote no text is a failure, not an empty summary. */\nfunction summaryTextOrThrow(response: AssistantMessage, failure: string): string {\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`${failure}: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\tconst text = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\tif (response.stopReason === \"length\" && text.trim().length === 0) {\n\t\t// Thinking can spend the whole cap; appending file lists to nothing would commit\n\t\t// a \"summary\" that silently drops the conversation.\n\t\tthrow new Error(`${failure}: the model reached its output limit before writing a summary`);\n\t}\n\treturn text;\n}\n"]}
@@ -433,14 +433,7 @@ export async function generateSummary(currentMessages, model, reserveTokens, api
433
433
  ];
434
434
  const completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);
435
435
  const response = await completeSummarization(model, { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages }, completionOptions, streamFn, retry, callbacks);
436
- if (response.stopReason === "error") {
437
- throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
438
- }
439
- const textContent = response.content
440
- .filter((c) => c.type === "text")
441
- .map((c) => c.text)
442
- .join("\n");
443
- return textContent;
436
+ return summaryTextOrThrow(response, "Summarization failed");
444
437
  }
445
438
  export function prepareCompaction(pathEntries, settings) {
446
439
  if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
@@ -613,12 +606,22 @@ async function generateTurnPrefixSummary(messages, model, reserveTokens, apiKey,
613
606
  },
614
607
  ];
615
608
  const response = await completeSummarization(model, { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages }, createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel), streamFn, retry, callbacks);
609
+ return summaryTextOrThrow(response, "Turn prefix summarization failed");
610
+ }
611
+ /** Summary text of a response. A length stop that wrote no text is a failure, not an empty summary. */
612
+ function summaryTextOrThrow(response, failure) {
616
613
  if (response.stopReason === "error") {
617
- throw new Error(`Turn prefix summarization failed: ${response.errorMessage || "Unknown error"}`);
614
+ throw new Error(`${failure}: ${response.errorMessage || "Unknown error"}`);
618
615
  }
619
- return response.content
616
+ const text = response.content
620
617
  .filter((c) => c.type === "text")
621
618
  .map((c) => c.text)
622
619
  .join("\n");
620
+ if (response.stopReason === "length" && text.trim().length === 0) {
621
+ // Thinking can spend the whole cap; appending file lists to nothing would commit
622
+ // a "summary" that silently drops the conversation.
623
+ throw new Error(`${failure}: the model reached its output limit before writing a summary`);
624
+ }
625
+ return text;
623
626
  }
624
627
  //# sourceMappingURL=compaction.js.map