codexuse-cli 3.9.9 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -16
- package/dist/index.js +8069 -4664
- package/dist/index.js.map +1 -1
- package/package.json +5 -11
- package/dist/server/NodeSqliteClient-Cx2_VxdP.mjs +0 -139
- package/dist/server/SqlError-CoqftVSq.mjs +0 -28
- package/dist/server/SqliteClient-CXjquy8x.mjs +0 -127
- package/dist/server/index.mjs +0 -88114
- package/dist/server/open-BWXrZXJl.mjs +0 -554
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js","../src/commands/accountPool.ts","../../../packages/contracts/src/settings/types.ts","../../../packages/runtime-app-state/src/app/state.ts","../../../packages/contracts/src/settings/chat-scrollback.ts","../../../packages/contracts/src/settings/commit-message-prompt.ts","../../../packages/contracts/src/settings/auto-roll.ts","../../../packages/runtime-app-state/src/storage/documents.ts","../../../packages/runtime-app-state/src/app/runtimeSettings.ts","../../../packages/runtime-profiles/src/license/service.ts","../../../packages/runtime-codex/src/codex/settings.ts","../../../packages/runtime-profiles/src/license/secret.ts","../../../packages/contracts/src/license/offer-config.ts","../../../packages/runtime-profiles/src/profiles/profile-manager.ts","../../../packages/contracts/src/profiles/identity.ts","../../../packages/runtime-codex/src/codex/rpc.ts","../../../packages/runtime-codex/src/codex/cli.ts","../../../packages/runtime-codex/src/codex/command.ts","../../../packages/shared/src/core/logger.ts","../src/app/help.ts","../src/platform/args.ts","../src/commands/codex.ts","../../../packages/runtime-profiles/src/profiles/rate-limit-notifier.ts","../src/platform/codexCli.ts","../src/commands/daemon.ts","../../../packages/shared/src/core/internal-js-runtime.ts","../src/commands/license.ts","../../../packages/runtime-profiles/src/license/guard.ts","../../../packages/runtime-codex/src/codex/officialAppRestart.ts","../src/commands/profile.ts","../../../packages/runtime-profiles/src/cloud-sync/service.ts","../../../packages/contracts/src/cloud-sync/types.ts","../../../packages/shared/src/core/type-guards.ts","../../../packages/runtime-profiles/src/cloud-sync/client.ts","../../../packages/runtime-codex/src/codex/config.ts","../../../packages/runtime-codex/src/codex/config-metadata.ts","../../../packages/runtime-codex/src/codex/config-io.ts","../../../packages/runtime-codex/src/codex/home.ts","../../../packages/runtime-codex/src/codex/config-presets.ts","../../../packages/shared/src/core/errors.ts","../src/commands/sync.ts","../../../packages/runtime-app-state/src/storage/migrations/v1.ts","../../../packages/contracts/src/settings/legacy-localstorage-keys.ts","../src/platform/storage.ts","../src/app/main.ts","../src/index.ts"],"sourcesContent":["'use strict'\nconst ParserEND = 0x110000\nclass ParserError extends Error {\n /* istanbul ignore next */\n constructor (msg, filename, linenumber) {\n super('[ParserError] ' + msg, filename, linenumber)\n this.name = 'ParserError'\n this.code = 'ParserError'\n if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError)\n }\n}\nclass State {\n constructor (parser) {\n this.parser = parser\n this.buf = ''\n this.returned = null\n this.result = null\n this.resultTable = null\n this.resultArr = null\n }\n}\nclass Parser {\n constructor () {\n this.pos = 0\n this.col = 0\n this.line = 0\n this.obj = {}\n this.ctx = this.obj\n this.stack = []\n this._buf = ''\n this.char = null\n this.ii = 0\n this.state = new State(this.parseStart)\n }\n\n parse (str) {\n /* istanbul ignore next */\n if (str.length === 0 || str.length == null) return\n\n this._buf = String(str)\n this.ii = -1\n this.char = -1\n let getNext\n while (getNext === false || this.nextChar()) {\n getNext = this.runOne()\n }\n this._buf = null\n }\n nextChar () {\n if (this.char === 0x0A) {\n ++this.line\n this.col = -1\n }\n ++this.ii\n this.char = this._buf.codePointAt(this.ii)\n ++this.pos\n ++this.col\n return this.haveBuffer()\n }\n haveBuffer () {\n return this.ii < this._buf.length\n }\n runOne () {\n return this.state.parser.call(this, this.state.returned)\n }\n finish () {\n this.char = ParserEND\n let last\n do {\n last = this.state.parser\n this.runOne()\n } while (this.state.parser !== last)\n\n this.ctx = null\n this.state = null\n this._buf = null\n\n return this.obj\n }\n next (fn) {\n /* istanbul ignore next */\n if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn))\n this.state.parser = fn\n }\n goto (fn) {\n this.next(fn)\n return this.runOne()\n }\n call (fn, returnWith) {\n if (returnWith) this.next(returnWith)\n this.stack.push(this.state)\n this.state = new State(fn)\n }\n callNow (fn, returnWith) {\n this.call(fn, returnWith)\n return this.runOne()\n }\n return (value) {\n /* istanbul ignore next */\n if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'))\n if (value === undefined) value = this.state.buf\n this.state = this.stack.pop()\n this.state.returned = value\n }\n returnNow (value) {\n this.return(value)\n return this.runOne()\n }\n consume () {\n /* istanbul ignore next */\n if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'))\n this.state.buf += this._buf[this.ii]\n }\n error (err) {\n err.line = this.line\n err.col = this.col\n err.pos = this.pos\n return err\n }\n /* istanbul ignore next */\n parseStart () {\n throw new ParserError('Must declare a parseStart method')\n }\n}\nParser.END = ParserEND\nParser.Error = ParserError\nmodule.exports = Parser\n","'use strict'\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nmodule.exports = (d, num) => {\n num = String(num)\n while (num.length < d) num = '0' + num\n return num\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass FloatingDateTime extends Date {\n constructor (value) {\n super(value + 'Z')\n this.isFloating = true\n }\n toISOString () {\n const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n return `${date}T${time}`\n }\n}\n\nmodule.exports = value => {\n const date = new FloatingDateTime(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\nconst DateTime = global.Date\n\nclass Date extends DateTime {\n constructor (value) {\n super(value)\n this.isDate = true\n }\n toISOString () {\n return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass Time extends Date {\n constructor (value) {\n super(`0000-01-01T${value}Z`)\n this.isTime = true\n }\n toISOString () {\n return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Time(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\n/* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */\nmodule.exports = makeParserClass(require('./parser.js'))\nmodule.exports.makeParserClass = makeParserClass\n\nclass TomlError extends Error {\n constructor (msg) {\n super(msg)\n this.name = 'TomlError'\n /* istanbul ignore next */\n if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError)\n this.fromTOML = true\n this.wrapped = null\n }\n}\nTomlError.wrap = err => {\n const terr = new TomlError(err.message)\n terr.code = err.code\n terr.wrapped = err\n return terr\n}\nmodule.exports.TomlError = TomlError\n\nconst createDateTime = require('./create-datetime.js')\nconst createDateTimeFloat = require('./create-datetime-float.js')\nconst createDate = require('./create-date.js')\nconst createTime = require('./create-time.js')\n\nconst CTRL_I = 0x09\nconst CTRL_J = 0x0A\nconst CTRL_M = 0x0D\nconst CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL\nconst CHAR_SP = 0x20\nconst CHAR_QUOT = 0x22\nconst CHAR_NUM = 0x23\nconst CHAR_APOS = 0x27\nconst CHAR_PLUS = 0x2B\nconst CHAR_COMMA = 0x2C\nconst CHAR_HYPHEN = 0x2D\nconst CHAR_PERIOD = 0x2E\nconst CHAR_0 = 0x30\nconst CHAR_1 = 0x31\nconst CHAR_7 = 0x37\nconst CHAR_9 = 0x39\nconst CHAR_COLON = 0x3A\nconst CHAR_EQUALS = 0x3D\nconst CHAR_A = 0x41\nconst CHAR_E = 0x45\nconst CHAR_F = 0x46\nconst CHAR_T = 0x54\nconst CHAR_U = 0x55\nconst CHAR_Z = 0x5A\nconst CHAR_LOWBAR = 0x5F\nconst CHAR_a = 0x61\nconst CHAR_b = 0x62\nconst CHAR_e = 0x65\nconst CHAR_f = 0x66\nconst CHAR_i = 0x69\nconst CHAR_l = 0x6C\nconst CHAR_n = 0x6E\nconst CHAR_o = 0x6F\nconst CHAR_r = 0x72\nconst CHAR_s = 0x73\nconst CHAR_t = 0x74\nconst CHAR_u = 0x75\nconst CHAR_x = 0x78\nconst CHAR_z = 0x7A\nconst CHAR_LCUB = 0x7B\nconst CHAR_RCUB = 0x7D\nconst CHAR_LSQB = 0x5B\nconst CHAR_BSOL = 0x5C\nconst CHAR_RSQB = 0x5D\nconst CHAR_DEL = 0x7F\nconst SURROGATE_FIRST = 0xD800\nconst SURROGATE_LAST = 0xDFFF\n\nconst escapes = {\n [CHAR_b]: '\\u0008',\n [CHAR_t]: '\\u0009',\n [CHAR_n]: '\\u000A',\n [CHAR_f]: '\\u000C',\n [CHAR_r]: '\\u000D',\n [CHAR_QUOT]: '\\u0022',\n [CHAR_BSOL]: '\\u005C'\n}\n\nfunction isDigit (cp) {\n return cp >= CHAR_0 && cp <= CHAR_9\n}\nfunction isHexit (cp) {\n return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9)\n}\nfunction isBit (cp) {\n return cp === CHAR_1 || cp === CHAR_0\n}\nfunction isOctit (cp) {\n return (cp >= CHAR_0 && cp <= CHAR_7)\n}\nfunction isAlphaNumQuoteHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_APOS\n || cp === CHAR_QUOT\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nfunction isAlphaNumHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nconst _type = Symbol('type')\nconst _declared = Symbol('declared')\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst defineProperty = Object.defineProperty\nconst descriptor = {configurable: true, enumerable: true, writable: true, value: undefined}\n\nfunction hasKey (obj, key) {\n if (hasOwnProperty.call(obj, key)) return true\n if (key === '__proto__') defineProperty(obj, '__proto__', descriptor)\n return false\n}\n\nconst INLINE_TABLE = Symbol('inline-table')\nfunction InlineTable () {\n return Object.defineProperties({}, {\n [_type]: {value: INLINE_TABLE}\n })\n}\nfunction isInlineTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_TABLE\n}\n\nconst TABLE = Symbol('table')\nfunction Table () {\n return Object.defineProperties({}, {\n [_type]: {value: TABLE},\n [_declared]: {value: false, writable: true}\n })\n}\nfunction isTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === TABLE\n}\n\nconst _contentType = Symbol('content-type')\nconst INLINE_LIST = Symbol('inline-list')\nfunction InlineList (type) {\n return Object.defineProperties([], {\n [_type]: {value: INLINE_LIST},\n [_contentType]: {value: type}\n })\n}\nfunction isInlineList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_LIST\n}\n\nconst LIST = Symbol('list')\nfunction List () {\n return Object.defineProperties([], {\n [_type]: {value: LIST}\n })\n}\nfunction isList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === LIST\n}\n\n// in an eval, to let bundlers not slurp in a util proxy\nlet _custom\ntry {\n const utilInspect = eval(\"require('util').inspect\")\n _custom = utilInspect.custom\n} catch (_) {\n /* eval require not available in transpiled bundle */\n}\n/* istanbul ignore next */\nconst _inspect = _custom || 'inspect'\n\nclass BoxedBigInt {\n constructor (value) {\n try {\n this.value = global.BigInt.asIntN(64, value)\n } catch (_) {\n /* istanbul ignore next */\n this.value = null\n }\n Object.defineProperty(this, _type, {value: INTEGER})\n }\n isNaN () {\n return this.value === null\n }\n /* istanbul ignore next */\n toString () {\n return String(this.value)\n }\n /* istanbul ignore next */\n [_inspect] () {\n return `[BigInt: ${this.toString()}]}`\n }\n valueOf () {\n return this.value\n }\n}\n\nconst INTEGER = Symbol('integer')\nfunction Integer (value) {\n let num = Number(value)\n // -0 is a float thing, not an int thing\n if (Object.is(num, -0)) num = 0\n /* istanbul ignore else */\n if (global.BigInt && !Number.isSafeInteger(num)) {\n return new BoxedBigInt(value)\n } else {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(num), {\n isNaN: {value: function () { return isNaN(this) }},\n [_type]: {value: INTEGER},\n [_inspect]: {value: () => `[Integer: ${value}]`}\n })\n }\n}\nfunction isInteger (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INTEGER\n}\n\nconst FLOAT = Symbol('float')\nfunction Float (value) {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(value), {\n [_type]: {value: FLOAT},\n [_inspect]: {value: () => `[Float: ${value}]`}\n })\n}\nfunction isFloat (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === FLOAT\n}\n\nfunction tomlType (value) {\n const type = typeof value\n if (type === 'object') {\n /* istanbul ignore if */\n if (value === null) return 'null'\n if (value instanceof Date) return 'datetime'\n /* istanbul ignore else */\n if (_type in value) {\n switch (value[_type]) {\n case INLINE_TABLE: return 'inline-table'\n case INLINE_LIST: return 'inline-list'\n /* istanbul ignore next */\n case TABLE: return 'table'\n /* istanbul ignore next */\n case LIST: return 'list'\n case FLOAT: return 'float'\n case INTEGER: return 'integer'\n }\n }\n }\n return type\n}\n\nfunction makeParserClass (Parser) {\n class TOMLParser extends Parser {\n constructor () {\n super()\n this.ctx = this.obj = Table()\n }\n\n /* MATCH HELPER */\n atEndOfWord () {\n return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine()\n }\n atEndOfLine () {\n return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M\n }\n\n parseStart () {\n if (this.char === Parser.END) {\n return null\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseTableOrList)\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (isAlphaNumQuoteHyphen(this.char)) {\n return this.callNow(this.parseAssignStatement)\n } else {\n throw this.error(new TomlError(`Unknown character \"${this.char}\"`))\n }\n }\n\n // HELPER, this strips any whitespace and comments to the end of the line\n // then RETURNS. Last state in a production.\n parseWhitespaceToEOL () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.goto(this.parseComment)\n } else if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n } else {\n throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'))\n }\n }\n\n /* ASSIGNMENT: key = value */\n parseAssignStatement () {\n return this.callNow(this.parseAssign, this.recordAssignStatement)\n }\n recordAssignStatement (kv) {\n let target = this.ctx\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n // unbox our numbers\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseWhitespaceToEOL)\n }\n\n /* ASSSIGNMENT expression, key = value possibly inside an inline table */\n parseAssign () {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n recordAssignKeyword (key) {\n if (this.state.resultTable) {\n this.state.resultTable.push(key)\n } else {\n this.state.resultTable = [key]\n }\n return this.goto(this.parseAssignKeywordPreDot)\n }\n parseAssignKeywordPreDot () {\n if (this.char === CHAR_PERIOD) {\n return this.next(this.parseAssignKeywordPostDot)\n } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.goto(this.parseAssignEqual)\n }\n }\n parseAssignKeywordPostDot () {\n if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n }\n\n parseAssignEqual () {\n if (this.char === CHAR_EQUALS) {\n return this.next(this.parseAssignPreValue)\n } else {\n throw this.error(new TomlError('Invalid character, expected \"=\"'))\n }\n }\n parseAssignPreValue () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseValue, this.recordAssignValue)\n }\n }\n recordAssignValue (value) {\n return this.returnNow({key: this.state.resultTable, value: value})\n }\n\n /* COMMENTS: #...eol */\n parseComment () {\n do {\n if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n }\n } while (this.nextChar())\n }\n\n /* TABLES AND LISTS, [foo] and [[foo]] */\n parseTableOrList () {\n if (this.char === CHAR_LSQB) {\n this.next(this.parseList)\n } else {\n return this.goto(this.parseTable)\n }\n }\n\n /* TABLE [foo.bar.baz] */\n parseTable () {\n this.ctx = this.obj\n return this.goto(this.parseTableNext)\n }\n parseTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseTableMore)\n }\n }\n parseTableMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n } else {\n this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table()\n this.ctx[_declared] = true\n }\n return this.next(this.parseWhitespaceToEOL)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n return this.next(this.parseTableNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* LIST [[a.b.c]] */\n parseList () {\n this.ctx = this.obj\n return this.goto(this.parseListNext)\n }\n parseListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseListMore)\n }\n }\n parseListMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx[keyword] = List()\n }\n if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isList(this.ctx[keyword])) {\n const next = Table()\n this.ctx[keyword].push(next)\n this.ctx = next\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListEnd)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isInlineTable(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline table\"))\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n parseListEnd (keyword) {\n if (this.char === CHAR_RSQB) {\n return this.next(this.parseWhitespaceToEOL)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* VALUE string, number, boolean, inline list, inline object */\n parseValue () {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key without value'))\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseDoubleString)\n } if (this.char === CHAR_APOS) {\n return this.next(this.parseSingleString)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n return this.goto(this.parseNumberSign)\n } else if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseNumberOrDateTime)\n } else if (this.char === CHAR_t || this.char === CHAR_f) {\n return this.goto(this.parseBoolean)\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseInlineList, this.recordValue)\n } else if (this.char === CHAR_LCUB) {\n return this.call(this.parseInlineTable, this.recordValue)\n } else {\n throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'))\n }\n }\n recordValue (value) {\n return this.returnNow(value)\n }\n\n parseInf () {\n if (this.char === CHAR_n) {\n return this.next(this.parseInf2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n parseInf2 () {\n if (this.char === CHAR_f) {\n if (this.state.buf === '-') {\n return this.return(-Infinity)\n } else {\n return this.return(Infinity)\n }\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n\n parseNan () {\n if (this.char === CHAR_a) {\n return this.next(this.parseNan2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n parseNan2 () {\n if (this.char === CHAR_n) {\n return this.return(NaN)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n\n /* KEYS, barewords or basic, literal, or dotted */\n parseKeyword () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseBasicString)\n } else if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralString)\n } else {\n return this.goto(this.parseBareKey)\n }\n }\n\n /* KEYS: barewords */\n parseBareKey () {\n do {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key ended without value'))\n } else if (isAlphaNumHyphen(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 0) {\n throw this.error(new TomlError('Empty bare keys are not allowed'))\n } else {\n return this.returnNow()\n }\n } while (this.nextChar())\n }\n\n /* STRINGS, single quoted (literal) */\n parseSingleString () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiStringMaybe)\n } else {\n return this.goto(this.parseLiteralString)\n }\n }\n parseLiteralString () {\n do {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiStringMaybe () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseLiteralMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseLiteralMultiStringContent)\n } else {\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiStringContent () {\n do {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiEnd () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd2)\n } else {\n this.state.buf += \"'\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiEnd2 () {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else {\n this.state.buf += \"''\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n\n /* STRINGS double quoted */\n parseDoubleString () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiStringMaybe)\n } else {\n return this.goto(this.parseBasicString)\n }\n }\n parseBasicString () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseEscape, this.recordEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n recordEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseBasicString)\n }\n parseMultiStringMaybe () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseMultiStringContent)\n } else {\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiStringContent () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n errorControlCharInString () {\n let displayCode = '\\\\u00'\n if (this.char < 16) {\n displayCode += '0'\n }\n displayCode += this.char.toString(16)\n\n return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))\n }\n recordMultiEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseMultiStringContent)\n }\n parseMultiEnd () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd2)\n } else {\n this.state.buf += '\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEnd2 () {\n if (this.char === CHAR_QUOT) {\n return this.return()\n } else {\n this.state.buf += '\"\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEscape () {\n if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else if (this.char === CHAR_SP || this.char === CTRL_I) {\n return this.next(this.parsePreMultiTrim)\n } else {\n return this.goto(this.parseEscape)\n }\n }\n parsePreMultiTrim () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else {\n throw this.error(new TomlError(\"Can't escape whitespace\"))\n }\n }\n parseMultiTrim () {\n // explicitly whitespace here, END should follow the same path as chars\n if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else {\n return this.returnNow()\n }\n }\n parseEscape () {\n if (this.char in escapes) {\n return this.return(escapes[this.char])\n } else if (this.char === CHAR_u) {\n return this.call(this.parseSmallUnicode, this.parseUnicodeReturn)\n } else if (this.char === CHAR_U) {\n return this.call(this.parseLargeUnicode, this.parseUnicodeReturn)\n } else {\n throw this.error(new TomlError('Unknown escape character: ' + this.char))\n }\n }\n parseUnicodeReturn (char) {\n try {\n const codePoint = parseInt(char, 16)\n if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {\n throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'))\n }\n return this.returnNow(String.fromCodePoint(codePoint))\n } catch (err) {\n throw this.error(TomlError.wrap(err))\n }\n }\n parseSmallUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 4) return this.return()\n }\n }\n parseLargeUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 8) return this.return()\n }\n }\n\n /* NUMBERS */\n parseNumberSign () {\n this.consume()\n return this.next(this.parseMaybeSignedInfOrNan)\n }\n parseMaybeSignedInfOrNan () {\n if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else {\n return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart)\n }\n }\n parseNumberIntegerStart () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberIntegerExponentOrDecimal)\n } else {\n return this.goto(this.parseNumberInteger)\n }\n }\n parseNumberIntegerExponentOrDecimal () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseNumberInteger () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseNoUnder () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNoUnderHexOctBinLiteral () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNumberFloat () {\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n parseNumberExponentSign () {\n if (isDigit(this.char)) {\n return this.goto(this.parseNumberExponent)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.call(this.parseNoUnder, this.parseNumberExponent)\n } else {\n throw this.error(new TomlError('Unexpected character, expected -, + or digit'))\n }\n }\n parseNumberExponent () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n\n /* NUMBERS or DATETIMES */\n parseNumberOrDateTime () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberBaseOrDateTime)\n } else {\n return this.goto(this.parseNumberOrDateTimeOnly)\n }\n }\n parseNumberOrDateTimeOnly () {\n // note, if two zeros are in a row then it MUST be a date\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length > 4) this.next(this.parseNumberInteger)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseDateTimeOnly () {\n if (this.state.buf.length < 4) {\n if (isDigit(this.char)) {\n return this.consume()\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n throw this.error(new TomlError('Expected digit while parsing year part of a date'))\n }\n } else {\n if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else {\n throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'))\n }\n }\n }\n parseNumberBaseOrDateTime () {\n if (this.char === CHAR_b) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin)\n } else if (this.char === CHAR_o) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct)\n } else if (this.char === CHAR_x) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex)\n } else if (this.char === CHAR_PERIOD) {\n return this.goto(this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseDateTimeOnly)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseIntegerHex () {\n if (isHexit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerOct () {\n if (isOctit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerBin () {\n if (isBit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n\n /* DATETIME */\n parseDateTime () {\n // we enter here having just consumed the year and about to consume the hyphen\n if (this.state.buf.length < 4) {\n throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateMonth)\n }\n parseDateMonth () {\n if (this.char === CHAR_HYPHEN) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateDay)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseDateDay () {\n if (this.char === CHAR_T || this.char === CHAR_SP) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseStartTimeHour)\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result + '-' + this.state.buf))\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseStartTimeHour () {\n if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result))\n } else {\n return this.goto(this.parseTimeHour)\n }\n }\n parseTimeHour () {\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result += 'T' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeMin)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeZoneOrFraction)\n }\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n\n parseOnlyTimeHour () {\n /* istanbul ignore else */\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeMin)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n return this.next(this.parseOnlyTimeFractionMaybe)\n }\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeFractionMaybe () {\n this.state.result += ':' + this.state.buf\n if (this.char === CHAR_PERIOD) {\n this.state.buf = ''\n this.next(this.parseOnlyTimeFraction)\n } else {\n return this.return(createTime(this.state.result))\n }\n }\n parseOnlyTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.atEndOfWord()) {\n if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'))\n return this.returnNow(createTime(this.state.result + '.' + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n\n parseTimeZoneOrFraction () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n this.next(this.parseDateTimeFraction)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseDateTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 1) {\n throw this.error(new TomlError('Expected digit in milliseconds'))\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseTimeZoneHour () {\n if (isDigit(this.char)) {\n this.consume()\n // FIXME: No more regexps\n if (/\\d\\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n parseTimeZoneSep () {\n if (this.char === CHAR_COLON) {\n this.consume()\n this.next(this.parseTimeZoneMin)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected colon'))\n }\n }\n parseTimeZoneMin () {\n if (isDigit(this.char)) {\n this.consume()\n if (/\\d\\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n\n /* BOOLEAN */\n parseBoolean () {\n /* istanbul ignore else */\n if (this.char === CHAR_t) {\n this.consume()\n return this.next(this.parseTrue_r)\n } else if (this.char === CHAR_f) {\n this.consume()\n return this.next(this.parseFalse_a)\n }\n }\n parseTrue_r () {\n if (this.char === CHAR_r) {\n this.consume()\n return this.next(this.parseTrue_u)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_u () {\n if (this.char === CHAR_u) {\n this.consume()\n return this.next(this.parseTrue_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_e () {\n if (this.char === CHAR_e) {\n return this.return(true)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_a () {\n if (this.char === CHAR_a) {\n this.consume()\n return this.next(this.parseFalse_l)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_l () {\n if (this.char === CHAR_l) {\n this.consume()\n return this.next(this.parseFalse_s)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_s () {\n if (this.char === CHAR_s) {\n this.consume()\n return this.next(this.parseFalse_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_e () {\n if (this.char === CHAR_e) {\n return this.return(false)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n /* INLINE LISTS */\n parseInlineList () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_RSQB) {\n return this.return(this.state.resultArr || InlineList())\n } else {\n return this.callNow(this.parseValue, this.recordInlineListValue)\n }\n }\n recordInlineListValue (value) {\n if (this.state.resultArr) {\n const listType = this.state.resultArr[_contentType]\n const valueType = tomlType(value)\n if (listType !== valueType) {\n throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))\n }\n } else {\n this.state.resultArr = InlineList(tomlType(value))\n }\n if (isFloat(value) || isInteger(value)) {\n // unbox now that we've verified they're ok\n this.state.resultArr.push(value.valueOf())\n } else {\n this.state.resultArr.push(value)\n }\n return this.goto(this.parseInlineListNext)\n }\n parseInlineListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineList)\n } else if (this.char === CHAR_RSQB) {\n return this.goto(this.parseInlineList)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n\n /* INLINE TABLE */\n parseInlineTable () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_RCUB) {\n return this.return(this.state.resultTable || InlineTable())\n } else {\n if (!this.state.resultTable) this.state.resultTable = InlineTable()\n return this.callNow(this.parseAssign, this.recordInlineTableValue)\n }\n }\n recordInlineTableValue (kv) {\n let target = this.state.resultTable\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseInlineTableNext)\n }\n parseInlineTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineTable)\n } else if (this.char === CHAR_RCUB) {\n return this.goto(this.parseInlineTable)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n }\n return TOMLParser\n}\n","'use strict'\nmodule.exports = prettyError\n\nfunction prettyError (err, buf) {\n /* istanbul ignore if */\n if (err.pos == null || err.line == null) return err\n let msg = err.message\n msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\\n`\n\n /* istanbul ignore else */\n if (buf && buf.split) {\n const lines = buf.split(/\\n/)\n const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length\n let linePadding = ' '\n while (linePadding.length < lineNumWidth) linePadding += ' '\n for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {\n let lineNum = String(ii + 1)\n if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum\n if (err.line === ii) {\n msg += lineNum + '> ' + lines[ii] + '\\n'\n msg += linePadding + ' '\n for (let hh = 0; hh < err.col; ++hh) {\n msg += ' '\n }\n msg += '^\\n'\n } else {\n msg += lineNum + ': ' + lines[ii] + '\\n'\n }\n }\n }\n err.message = msg + '\\n'\n return err\n}\n","'use strict'\nmodule.exports = parseString\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseString (str) {\n if (global.Buffer && global.Buffer.isBuffer(str)) {\n str = str.toString('utf8')\n }\n const parser = new TOMLParser()\n try {\n parser.parse(str)\n return parser.finish()\n } catch (err) {\n throw prettyError(err, str)\n }\n}\n","'use strict'\nmodule.exports = parseAsync\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseAsync (str, opts) {\n if (!opts) opts = {}\n const index = 0\n const blocksize = opts.blocksize || 40960\n const parser = new TOMLParser()\n return new Promise((resolve, reject) => {\n setImmediate(parseAsyncNext, index, blocksize, resolve, reject)\n })\n function parseAsyncNext (index, blocksize, resolve, reject) {\n if (index >= str.length) {\n try {\n return resolve(parser.finish())\n } catch (err) {\n return reject(prettyError(err, str))\n }\n }\n try {\n parser.parse(str.slice(index, index + blocksize))\n setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject)\n } catch (err) {\n reject(prettyError(err, str))\n }\n }\n}\n","'use strict'\nmodule.exports = parseStream\n\nconst stream = require('stream')\nconst TOMLParser = require('./lib/toml-parser.js')\n\nfunction parseStream (stm) {\n if (stm) {\n return parseReadable(stm)\n } else {\n return parseTransform(stm)\n }\n}\n\nfunction parseReadable (stm) {\n const parser = new TOMLParser()\n stm.setEncoding('utf8')\n return new Promise((resolve, reject) => {\n let readable\n let ended = false\n let errored = false\n function finish () {\n ended = true\n if (readable) return\n try {\n resolve(parser.finish())\n } catch (err) {\n reject(err)\n }\n }\n function error (err) {\n errored = true\n reject(err)\n }\n stm.once('end', finish)\n stm.once('error', error)\n readNext()\n\n function readNext () {\n readable = true\n let data\n while ((data = stm.read()) !== null) {\n try {\n parser.parse(data)\n } catch (err) {\n return error(err)\n }\n }\n readable = false\n /* istanbul ignore if */\n if (ended) return finish()\n /* istanbul ignore if */\n if (errored) return\n stm.once('readable', readNext)\n }\n })\n}\n\nfunction parseTransform () {\n const parser = new TOMLParser()\n return new stream.Transform({\n objectMode: true,\n transform (chunk, encoding, cb) {\n try {\n parser.parse(chunk.toString(encoding))\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n },\n flush (cb) {\n try {\n this.push(parser.finish())\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n }\n })\n}\n","'use strict'\nmodule.exports = require('./parse-string.js')\nmodule.exports.async = require('./parse-async.js')\nmodule.exports.stream = require('./parse-stream.js')\nmodule.exports.prettyError = require('./parse-pretty-error.js')\n","'use strict'\nmodule.exports = stringify\nmodule.exports.value = stringifyInline\n\nfunction stringify (obj) {\n if (obj === null) throw typeError('null')\n if (obj === void (0)) throw typeError('undefined')\n if (typeof obj !== 'object') throw typeError(typeof obj)\n\n if (typeof obj.toJSON === 'function') obj = obj.toJSON()\n if (obj == null) return null\n const type = tomlType(obj)\n if (type !== 'table') throw typeError(type)\n return stringifyObject('', '', obj)\n}\n\nfunction typeError (type) {\n return new Error('Can only stringify objects, not ' + type)\n}\n\nfunction arrayOneTypeError () {\n return new Error(\"Array values can't have mixed types\")\n}\n\nfunction getInlineKeys (obj) {\n return Object.keys(obj).filter(key => isInline(obj[key]))\n}\nfunction getComplexKeys (obj) {\n return Object.keys(obj).filter(key => !isInline(obj[key]))\n}\n\nfunction toJSON (obj) {\n let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {}\n for (let prop of Object.keys(obj)) {\n if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) {\n nobj[prop] = obj[prop].toJSON()\n } else {\n nobj[prop] = obj[prop]\n }\n }\n return nobj\n}\n\nfunction stringifyObject (prefix, indent, obj) {\n obj = toJSON(obj)\n var inlineKeys\n var complexKeys\n inlineKeys = getInlineKeys(obj)\n complexKeys = getComplexKeys(obj)\n var result = []\n var inlineIndent = indent || ''\n inlineKeys.forEach(key => {\n var type = tomlType(obj[key])\n if (type !== 'undefined' && type !== 'null') {\n result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true))\n }\n })\n if (result.length > 0) result.push('')\n var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : ''\n complexKeys.forEach(key => {\n result.push(stringifyComplex(prefix, complexIndent, key, obj[key]))\n })\n return result.join('\\n')\n}\n\nfunction isInline (value) {\n switch (tomlType(value)) {\n case 'undefined':\n case 'null':\n case 'integer':\n case 'nan':\n case 'float':\n case 'boolean':\n case 'string':\n case 'datetime':\n return true\n case 'array':\n return value.length === 0 || tomlType(value[0]) !== 'table'\n case 'table':\n return Object.keys(value).length === 0\n /* istanbul ignore next */\n default:\n return false\n }\n}\n\nfunction tomlType (value) {\n if (value === undefined) {\n return 'undefined'\n } else if (value === null) {\n return 'null'\n /* eslint-disable valid-typeof */\n } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) {\n return 'integer'\n } else if (typeof value === 'number') {\n return 'float'\n } else if (typeof value === 'boolean') {\n return 'boolean'\n } else if (typeof value === 'string') {\n return 'string'\n } else if ('toISOString' in value) {\n return isNaN(value) ? 'undefined' : 'datetime'\n } else if (Array.isArray(value)) {\n return 'array'\n } else {\n return 'table'\n }\n}\n\nfunction stringifyKey (key) {\n var keyStr = String(key)\n if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {\n return keyStr\n } else {\n return stringifyBasicString(keyStr)\n }\n}\n\nfunction stringifyBasicString (str) {\n return '\"' + escapeString(str).replace(/\"/g, '\\\\\"') + '\"'\n}\n\nfunction stringifyLiteralString (str) {\n return \"'\" + str + \"'\"\n}\n\nfunction numpad (num, str) {\n while (str.length < num) str = '0' + str\n return str\n}\n\nfunction escapeString (str) {\n return str.replace(/\\\\/g, '\\\\\\\\')\n .replace(/[\\b]/g, '\\\\b')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\f/g, '\\\\f')\n .replace(/\\r/g, '\\\\r')\n /* eslint-disable no-control-regex */\n .replace(/([\\u0000-\\u001f\\u007f])/, c => '\\\\u' + numpad(4, c.codePointAt(0).toString(16)))\n /* eslint-enable no-control-regex */\n}\n\nfunction stringifyMultilineString (str) {\n let escaped = str.split(/\\n/).map(str => {\n return escapeString(str).replace(/\"(?=\"\")/g, '\\\\\"')\n }).join('\\n')\n if (escaped.slice(-1) === '\"') escaped += '\\\\\\n'\n return '\"\"\"\\n' + escaped + '\"\"\"'\n}\n\nfunction stringifyAnyInline (value, multilineOk) {\n let type = tomlType(value)\n if (type === 'string') {\n if (multilineOk && /\\n/.test(value)) {\n type = 'string-multiline'\n } else if (!/[\\b\\t\\n\\f\\r']/.test(value) && /\"/.test(value)) {\n type = 'string-literal'\n }\n }\n return stringifyInline(value, type)\n}\n\nfunction stringifyInline (value, type) {\n /* istanbul ignore if */\n if (!type) type = tomlType(value)\n switch (type) {\n case 'string-multiline':\n return stringifyMultilineString(value)\n case 'string':\n return stringifyBasicString(value)\n case 'string-literal':\n return stringifyLiteralString(value)\n case 'integer':\n return stringifyInteger(value)\n case 'float':\n return stringifyFloat(value)\n case 'boolean':\n return stringifyBoolean(value)\n case 'datetime':\n return stringifyDatetime(value)\n case 'array':\n return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan'))\n case 'table':\n return stringifyInlineTable(value)\n /* istanbul ignore next */\n default:\n throw typeError(type)\n }\n}\n\nfunction stringifyInteger (value) {\n /* eslint-disable security/detect-unsafe-regex */\n return String(value).replace(/\\B(?=(\\d{3})+(?!\\d))/g, '_')\n}\n\nfunction stringifyFloat (value) {\n if (value === Infinity) {\n return 'inf'\n } else if (value === -Infinity) {\n return '-inf'\n } else if (Object.is(value, NaN)) {\n return 'nan'\n } else if (Object.is(value, -0)) {\n return '-0.0'\n }\n var chunks = String(value).split('.')\n var int = chunks[0]\n var dec = chunks[1] || 0\n return stringifyInteger(int) + '.' + dec\n}\n\nfunction stringifyBoolean (value) {\n return String(value)\n}\n\nfunction stringifyDatetime (value) {\n return value.toISOString()\n}\n\nfunction isNumber (type) {\n return type === 'float' || type === 'integer'\n}\nfunction arrayType (values) {\n var contentType = tomlType(values[0])\n if (values.every(_ => tomlType(_) === contentType)) return contentType\n // mixed integer/float, emit as floats\n if (values.every(_ => isNumber(tomlType(_)))) return 'float'\n return 'mixed'\n}\nfunction validateArray (values) {\n const type = arrayType(values)\n if (type === 'mixed') {\n throw arrayOneTypeError()\n }\n return type\n}\n\nfunction stringifyInlineArray (values) {\n values = toJSON(values)\n const type = validateArray(values)\n var result = '['\n var stringified = values.map(_ => stringifyInline(_, type))\n if (stringified.join(', ').length > 60 || /\\n/.test(stringified)) {\n result += '\\n ' + stringified.join(',\\n ') + '\\n'\n } else {\n result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '')\n }\n return result + ']'\n}\n\nfunction stringifyInlineTable (value) {\n value = toJSON(value)\n var result = []\n Object.keys(value).forEach(key => {\n result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false))\n })\n return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}'\n}\n\nfunction stringifyComplex (prefix, indent, key, value) {\n var valueType = tomlType(value)\n /* istanbul ignore else */\n if (valueType === 'array') {\n return stringifyArrayOfTables(prefix, indent, key, value)\n } else if (valueType === 'table') {\n return stringifyComplexTable(prefix, indent, key, value)\n } else {\n throw typeError(valueType)\n }\n}\n\nfunction stringifyArrayOfTables (prefix, indent, key, values) {\n values = toJSON(values)\n validateArray(values)\n var firstValueType = tomlType(values[0])\n /* istanbul ignore if */\n if (firstValueType !== 'table') throw typeError(firstValueType)\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n values.forEach(table => {\n if (result.length > 0) result += '\\n'\n result += indent + '[[' + fullKey + ']]\\n'\n result += stringifyObject(fullKey + '.', indent, table)\n })\n return result\n}\n\nfunction stringifyComplexTable (prefix, indent, key, value) {\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n if (getInlineKeys(value).length > 0) {\n result += indent + '[' + fullKey + ']\\n'\n }\n return result + stringifyObject(fullKey + '.', indent, value)\n}\n","'use strict'\nexports.parse = require('./parse.js')\nexports.stringify = require('./stringify.js')\n","import { createHash, randomBytes, randomUUID } from \"node:crypto\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport type {\n AccountPoolApiKeyCreateResult,\n AccountPoolApiKeyView,\n AccountPoolRoutingStrategy,\n AccountPoolSessionStatus,\n AccountPoolSessionView,\n} from \"@codexuse/contracts/account-pool/types\";\nimport {\n DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS,\n DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS,\n DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS,\n} from \"@codexuse/contracts/settings/types\";\nimport { getUserDataDir } from \"@codexuse/runtime-app-state/app/state\";\nimport { readAppSettings, writeAppSettings } from \"@codexuse/runtime-app-state/app/runtimeSettings\";\nimport { readDocument, updateDocument } from \"@codexuse/runtime-app-state/storage/documents\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { printHelp } from \"../app/help\";\nimport { hasFlag, parseIntegerFlag, parseStringFlag, stripFlags } from \"../platform/args\";\n\ntype JsonRecord = Record<string, unknown>;\ntype AccountPoolRuntime = \"desktop\" | \"daemon\";\n\ntype AccountPoolSettings = {\n accountPoolEnabled: boolean;\n accountPoolRoutingStrategy: AccountPoolRoutingStrategy;\n accountPoolProfilePool: string[];\n accountPoolExposedModels: string[];\n accountPoolExposedReasoningEfforts: string[];\n accountPoolExposedFastModeReasoningEfforts: string[];\n};\n\ntype AccountPoolApiKeyRecord = {\n id: string;\n tokenHash: string;\n tokenPreview: string;\n createdAt: string;\n lastUsedAt: string | null;\n revokedAt: string | null;\n};\n\ntype AccountPoolSessionRecord = {\n id: string;\n affinityKind: AccountPoolSessionView[\"affinityKind\"];\n affinityKey: string | null;\n activeSegmentId: string;\n segmentIds: string[];\n model: string | null;\n status: AccountPoolSessionStatus;\n lastError: string | null;\n createdAt: string;\n lastUsedAt: string;\n expiresAt: string | null;\n lastResponseId: string | null;\n responseIds: string[];\n rolloverCount: number;\n lastRolloverReason: string | null;\n};\n\ntype AccountPoolSegmentRecord = {\n id: string;\n sessionId: string;\n profileName: string;\n createdAt: string;\n lastUsedAt: string;\n};\n\ntype AccountPoolResponseIndexRecord = {\n sessionId: string;\n segmentId: string;\n createdAt: string;\n};\n\ntype AccountPoolStore = {\n version: number;\n roundRobinCursor: number;\n apiKeysById: Record<string, AccountPoolApiKeyRecord>;\n sessionsById: Record<string, AccountPoolSessionRecord>;\n segmentsById: Record<string, AccountPoolSegmentRecord>;\n responseIndex: Record<string, AccountPoolResponseIndexRecord>;\n};\n\ntype AccountPoolRuntimeSummary = {\n runtime: AccountPoolRuntime;\n stateDir: string;\n baseUrl: string | null;\n enabled: boolean;\n hasProLicense: boolean;\n routingStrategy: AccountPoolRoutingStrategy;\n activeApiKeyCount: number;\n activeSessionCount: number;\n};\n\ntype LegacyBrokerSessionRecord = {\n id: string;\n affinityKind: \"broker_session\" | \"prompt_cache\" | \"ephemeral\";\n affinityKey: string | null;\n profileName: string;\n threadId: string;\n model: string | null;\n status: AccountPoolSessionStatus;\n lastError: string | null;\n createdAt: string;\n lastUsedAt: string;\n expiresAt: string | null;\n lastResponseId: string | null;\n responseIds: string[];\n};\n\ntype LegacyBrokerStore = {\n version: number;\n roundRobinCursor: number;\n apiKeysById: Record<string, AccountPoolApiKeyRecord>;\n sessionsById: Record<string, LegacyBrokerSessionRecord>;\n responseIndex: Record<string, string>;\n};\n\nconst ACCOUNT_POOL_DOCUMENT = \"desktop.account-pool.v2\";\nconst LEGACY_BROKER_DOCUMENT = \"desktop.broker.v1\";\nconst ACCOUNT_POOL_PRO_REQUIRED_MESSAGE = \"Accounts Pool requires a Pro license.\";\nconst DEFAULT_DAEMON_STATE_DIR = path.join(os.homedir(), \".codexuse\", \"t3-daemon\");\nconst ACCOUNT_POOL_STORE_VERSION = 3;\nconst MAX_RESPONSE_IDS_PER_SESSION = 64;\nconst MODEL_SLUG_ALIASES = {\n \"5.5\": \"gpt-5.5\",\n \"5.4\": \"gpt-5.4\",\n \"5.3\": \"gpt-5.3-codex\",\n \"gpt-5.3\": \"gpt-5.3-codex\",\n \"5.3-spark\": \"gpt-5.3-codex-spark\",\n \"gpt-5.3-spark\": \"gpt-5.3-codex-spark\",\n} as const;\n\nfunction asRecord(value: unknown): JsonRecord {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as JsonRecord) : {};\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction asNumber(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction normalizeIsoString(value: unknown): string | null {\n const normalized = asString(value);\n if (!normalized) {\n return null;\n }\n const parsed = Date.parse(normalized);\n return Number.isNaN(parsed) ? null : new Date(parsed).toISOString();\n}\n\nfunction normalizeStringArray(value: unknown): string[] {\n const input = Array.isArray(value) ? value : [];\n const result: string[] = [];\n const seen = new Set<string>();\n for (const entry of input) {\n const normalized = asString(entry);\n if (!normalized || seen.has(normalized)) {\n continue;\n }\n seen.add(normalized);\n result.push(normalized);\n }\n return result;\n}\n\nfunction normalizeReasoningEffort(value: unknown): string | null {\n const normalized = asString(value)?.toLowerCase() ?? null;\n return normalized && normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeRoutingStrategy(value: unknown): AccountPoolRoutingStrategy {\n return value === \"round_robin\" ? \"round_robin\" : \"least_used\";\n}\n\nfunction normalizeCodexModelSlug(value: string | null | undefined): string | null {\n const trimmed = value?.trim();\n if (!trimmed) {\n return null;\n }\n return MODEL_SLUG_ALIASES[trimmed as keyof typeof MODEL_SLUG_ALIASES] ?? trimmed;\n}\n\nfunction formatRoutingStrategy(value: AccountPoolRoutingStrategy): string {\n return value === \"round_robin\" ? \"round-robin\" : \"least-used\";\n}\n\nfunction parseRoutingStrategy(value: string | null | undefined): AccountPoolRoutingStrategy | null {\n const normalized = value?.trim().toLowerCase();\n if (!normalized) {\n return null;\n }\n if (normalized === \"round-robin\" || normalized === \"round_robin\" || normalized === \"roundrobin\") {\n return \"round_robin\";\n }\n if (normalized === \"least-used\" || normalized === \"least_used\" || normalized === \"leastused\") {\n return \"least_used\";\n }\n return null;\n}\n\nfunction normalizeAccountPoolExposedModels(\n value: unknown,\n fallbackToDefault: boolean,\n): string[] {\n const result: string[] = [];\n const seen = new Set<string>();\n const input = Array.isArray(value) ? value : [];\n for (const entry of input) {\n const raw = asString(entry);\n const normalized = normalizeCodexModelSlug(raw) ?? raw;\n if (!normalized || seen.has(normalized)) {\n continue;\n }\n seen.add(normalized);\n result.push(normalized);\n }\n if (result.length > 0) {\n return result;\n }\n return fallbackToDefault ? [...DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS] : [];\n}\n\nfunction normalizeAccountPoolReasoningEfforts(\n value: unknown,\n fallback: readonly string[] | null,\n): string[] {\n const input = Array.isArray(value) ? value : [];\n const result: string[] = [];\n const seen = new Set<string>();\n for (const entry of input) {\n const normalized = normalizeReasoningEffort(entry);\n if (!normalized || seen.has(normalized)) {\n continue;\n }\n seen.add(normalized);\n result.push(normalized);\n }\n if (result.length > 0 || Array.isArray(value)) {\n return result;\n }\n return fallback ? [...fallback] : [];\n}\n\nfunction normalizeAccountPoolSettings(settings: JsonRecord): AccountPoolSettings {\n const accountPoolProfilePool = normalizeStringArray(settings.accountPoolProfilePool);\n return {\n accountPoolEnabled: settings.accountPoolEnabled === true || settings.brokerEnabled === true,\n accountPoolRoutingStrategy: normalizeRoutingStrategy(\n settings.accountPoolRoutingStrategy ?? settings.brokerRoutingStrategy,\n ),\n accountPoolProfilePool:\n accountPoolProfilePool.length > 0\n ? accountPoolProfilePool\n : normalizeStringArray(settings.brokerProfilePool),\n accountPoolExposedModels: normalizeAccountPoolExposedModels(\n settings.accountPoolExposedModels,\n true,\n ),\n accountPoolExposedReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n settings.accountPoolExposedReasoningEfforts,\n DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS,\n ),\n accountPoolExposedFastModeReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n settings.accountPoolExposedFastModeReasoningEfforts,\n DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS,\n ),\n };\n}\n\nfunction applyAccountPoolSettings(\n settings: JsonRecord,\n nextAccountPoolSettings: AccountPoolSettings,\n): JsonRecord {\n const next: JsonRecord = {\n ...settings,\n accountPoolEnabled: nextAccountPoolSettings.accountPoolEnabled,\n accountPoolRoutingStrategy: nextAccountPoolSettings.accountPoolRoutingStrategy,\n accountPoolProfilePool: nextAccountPoolSettings.accountPoolProfilePool.slice(),\n accountPoolExposedModels: nextAccountPoolSettings.accountPoolExposedModels.slice(),\n accountPoolExposedReasoningEfforts: nextAccountPoolSettings.accountPoolExposedReasoningEfforts.slice(),\n accountPoolExposedFastModeReasoningEfforts:\n nextAccountPoolSettings.accountPoolExposedFastModeReasoningEfforts.slice(),\n };\n delete next.brokerEnabled;\n delete next.brokerRoutingStrategy;\n delete next.brokerProfilePool;\n return next;\n}\n\nfunction printAccountPoolHelp(version: string): void {\n console.log(`CodexUse CLI v${version}\n\nUsage:\n codexuse account-pool status [--runtime=desktop|daemon] [--state-dir=/abs/path] [--port=NNNN]\n codexuse account-pool quickstart [--runtime=desktop|daemon] [--state-dir=/abs/path] [--port=NNNN]\n codexuse account-pool enable\n codexuse account-pool disable\n codexuse account-pool routing <least-used|round-robin>\n\n codexuse account-pool profiles list\n codexuse account-pool profiles set <name> [more...]\n codexuse account-pool profiles add <name> [more...]\n codexuse account-pool profiles remove <name> [more...]\n codexuse account-pool profiles reset\n\n codexuse account-pool models list\n codexuse account-pool models add <model> [more...]\n codexuse account-pool models remove <model> [more...]\n codexuse account-pool models reset\n\n codexuse account-pool reasoning list\n codexuse account-pool reasoning add <effort> [more...]\n codexuse account-pool reasoning remove <effort> [more...]\n codexuse account-pool reasoning reset\n\n codexuse account-pool fast-mode list\n codexuse account-pool fast-mode add <effort> [more...]\n codexuse account-pool fast-mode remove <effort> [more...]\n codexuse account-pool fast-mode reset\n\n codexuse account-pool keys list [--runtime=desktop|daemon] [--state-dir=/abs/path]\n codexuse account-pool keys create [--runtime=desktop|daemon] [--state-dir=/abs/path]\n codexuse account-pool keys revoke <id> [--runtime=desktop|daemon] [--state-dir=/abs/path]\n\n codexuse account-pool sessions list [--runtime=desktop|daemon] [--state-dir=/abs/path]\n\nNotes:\n - Settings are shared with the desktop app.\n - Keys and sessions are runtime-specific: desktop and daemon each keep their own pool store.\n - Session inspection is read-only here on purpose; pooled sessions are live runtime state.\n - Use --runtime=daemon plus --state-dir or --port when you want to inspect a headless daemon.\n`);\n}\n\nfunction normalizeSessionStatus(value: unknown): AccountPoolSessionStatus {\n return value === \"running\" || value === \"error\" || value === \"rollover_pending\"\n ? value\n : \"idle\";\n}\n\nfunction normalizeApiKeyRecord(id: string, value: unknown): AccountPoolApiKeyRecord | null {\n const record = asRecord(value);\n const tokenHash = asString(record.tokenHash);\n const tokenPreview = asString(record.tokenPreview);\n const createdAt = normalizeIsoString(record.createdAt);\n if (!tokenHash || !tokenPreview || !createdAt) {\n return null;\n }\n return {\n id,\n tokenHash,\n tokenPreview,\n createdAt,\n lastUsedAt: normalizeIsoString(record.lastUsedAt),\n revokedAt: normalizeIsoString(record.revokedAt),\n };\n}\n\nfunction normalizeLegacySessionRecord(id: string, value: unknown): LegacyBrokerSessionRecord | null {\n const record = asRecord(value);\n const profileName = asString(record.profileName);\n const createdAt = normalizeIsoString(record.createdAt);\n const lastUsedAt = normalizeIsoString(record.lastUsedAt);\n if (!profileName || !createdAt || !lastUsedAt) {\n return null;\n }\n const affinityKind =\n record.affinityKind === \"broker_session\" || record.affinityKind === \"prompt_cache\"\n ? record.affinityKind\n : \"ephemeral\";\n return {\n id,\n affinityKind,\n affinityKey: asString(record.affinityKey),\n profileName,\n threadId: asString(record.threadId) ?? id,\n model: asString(record.model),\n status: normalizeSessionStatus(record.status),\n lastError: asString(record.lastError),\n createdAt,\n lastUsedAt,\n expiresAt: normalizeIsoString(record.expiresAt),\n lastResponseId: asString(record.lastResponseId),\n responseIds: normalizeStringArray(record.responseIds).slice(0, MAX_RESPONSE_IDS_PER_SESSION),\n };\n}\n\nfunction normalizeLegacyStore(value: unknown): LegacyBrokerStore {\n const record = asRecord(value);\n const apiKeysById: Record<string, AccountPoolApiKeyRecord> = {};\n for (const [id, apiKeyValue] of Object.entries(asRecord(record.apiKeysById))) {\n const normalized = normalizeApiKeyRecord(id, apiKeyValue);\n if (normalized) {\n apiKeysById[id] = normalized;\n }\n }\n const sessionsById: Record<string, LegacyBrokerSessionRecord> = {};\n for (const [id, sessionValue] of Object.entries(asRecord(record.sessionsById))) {\n const normalized = normalizeLegacySessionRecord(id, sessionValue);\n if (normalized) {\n sessionsById[id] = normalized;\n }\n }\n const responseIndex: Record<string, string> = {};\n for (const [responseId, sessionId] of Object.entries(asRecord(record.responseIndex))) {\n const normalizedSessionId = asString(sessionId);\n if (normalizedSessionId) {\n responseIndex[responseId] = normalizedSessionId;\n }\n }\n return {\n version: asNumber(record.version) ?? 1,\n roundRobinCursor: asNumber(record.roundRobinCursor) ?? 0,\n apiKeysById,\n sessionsById,\n responseIndex,\n };\n}\n\nfunction normalizeSessionRecord(id: string, value: unknown): AccountPoolSessionRecord | null {\n const record = asRecord(value);\n const activeSegmentId = asString(record.activeSegmentId);\n const createdAt = normalizeIsoString(record.createdAt);\n const lastUsedAt = normalizeIsoString(record.lastUsedAt);\n if (!activeSegmentId || !createdAt || !lastUsedAt) {\n return null;\n }\n const affinityKind =\n record.affinityKind === \"pool_session\" || record.affinityKind === \"prompt_cache\"\n ? record.affinityKind\n : \"ephemeral\";\n return {\n id,\n affinityKind,\n affinityKey: asString(record.affinityKey),\n activeSegmentId,\n segmentIds: normalizeStringArray(record.segmentIds),\n model: asString(record.model),\n status: normalizeSessionStatus(record.status),\n lastError: asString(record.lastError),\n createdAt,\n lastUsedAt,\n expiresAt: normalizeIsoString(record.expiresAt),\n lastResponseId: asString(record.lastResponseId),\n responseIds: normalizeStringArray(record.responseIds).slice(0, MAX_RESPONSE_IDS_PER_SESSION),\n rolloverCount: asNumber(record.rolloverCount) ?? 0,\n lastRolloverReason: asString(record.lastRolloverReason),\n };\n}\n\nfunction normalizeSegmentRecord(id: string, value: unknown): AccountPoolSegmentRecord | null {\n const record = asRecord(value);\n const sessionId = asString(record.sessionId);\n const profileName = asString(record.profileName);\n const createdAt = normalizeIsoString(record.createdAt);\n const lastUsedAt = normalizeIsoString(record.lastUsedAt);\n if (!sessionId || !profileName || !createdAt || !lastUsedAt) {\n return null;\n }\n return {\n id,\n sessionId,\n profileName,\n createdAt,\n lastUsedAt,\n };\n}\n\nfunction normalizeResponseIndexRecord(value: unknown): AccountPoolResponseIndexRecord | null {\n const record = asRecord(value);\n const sessionId = asString(record.sessionId);\n const segmentId = asString(record.segmentId);\n const createdAt = normalizeIsoString(record.createdAt) ?? new Date(0).toISOString();\n if (!sessionId || !segmentId) {\n return null;\n }\n return { sessionId, segmentId, createdAt };\n}\n\nfunction normalizeAccountPoolStore(value: unknown): AccountPoolStore {\n const record = asRecord(value);\n const apiKeysById: Record<string, AccountPoolApiKeyRecord> = {};\n for (const [id, apiKeyValue] of Object.entries(asRecord(record.apiKeysById))) {\n const normalized = normalizeApiKeyRecord(id, apiKeyValue);\n if (normalized) {\n apiKeysById[id] = normalized;\n }\n }\n const sessionsById: Record<string, AccountPoolSessionRecord> = {};\n for (const [id, sessionValue] of Object.entries(asRecord(record.sessionsById))) {\n const normalized = normalizeSessionRecord(id, sessionValue);\n if (normalized) {\n sessionsById[id] = normalized;\n }\n }\n const segmentsById: Record<string, AccountPoolSegmentRecord> = {};\n for (const [id, segmentValue] of Object.entries(asRecord(record.segmentsById))) {\n const normalized = normalizeSegmentRecord(id, segmentValue);\n if (normalized) {\n segmentsById[id] = normalized;\n }\n }\n const responseIndex: Record<string, AccountPoolResponseIndexRecord> = {};\n for (const [responseId, responseValue] of Object.entries(asRecord(record.responseIndex))) {\n const normalized = normalizeResponseIndexRecord(responseValue);\n if (normalized) {\n responseIndex[responseId] = normalized;\n }\n }\n return {\n version: asNumber(record.version) ?? ACCOUNT_POOL_STORE_VERSION,\n roundRobinCursor: asNumber(record.roundRobinCursor) ?? 0,\n apiKeysById,\n sessionsById,\n segmentsById,\n responseIndex,\n };\n}\n\nfunction createDefaultStore(): AccountPoolStore {\n return {\n version: ACCOUNT_POOL_STORE_VERSION,\n roundRobinCursor: 0,\n apiKeysById: {},\n sessionsById: {},\n segmentsById: {},\n responseIndex: {},\n };\n}\n\nfunction migrateLegacyStore(legacyStore: LegacyBrokerStore): AccountPoolStore {\n const store = createDefaultStore();\n store.roundRobinCursor = legacyStore.roundRobinCursor;\n store.apiKeysById = { ...legacyStore.apiKeysById };\n for (const session of Object.values(legacyStore.sessionsById)) {\n const segmentId = `segment_${session.id}`;\n store.segmentsById[segmentId] = {\n id: segmentId,\n sessionId: session.id,\n profileName: session.profileName,\n createdAt: session.createdAt,\n lastUsedAt: session.lastUsedAt,\n };\n store.sessionsById[session.id] = {\n id: session.id,\n affinityKind: session.affinityKind === \"broker_session\" ? \"pool_session\" : session.affinityKind,\n affinityKey: session.affinityKey,\n activeSegmentId: segmentId,\n segmentIds: [segmentId],\n model: session.model,\n status: session.status,\n lastError: session.lastError,\n createdAt: session.createdAt,\n lastUsedAt: session.lastUsedAt,\n expiresAt: session.expiresAt,\n lastResponseId: session.lastResponseId,\n responseIds: session.responseIds.slice(0, MAX_RESPONSE_IDS_PER_SESSION),\n rolloverCount: 0,\n lastRolloverReason: null,\n };\n }\n for (const [responseId, sessionId] of Object.entries(legacyStore.responseIndex)) {\n const session = store.sessionsById[sessionId];\n if (!session) {\n continue;\n }\n store.responseIndex[responseId] = {\n sessionId,\n segmentId: session.activeSegmentId,\n createdAt: session.lastUsedAt,\n };\n }\n return store;\n}\n\nfunction deleteSessionFromStore(store: AccountPoolStore, sessionId: string): void {\n const session = store.sessionsById[sessionId];\n if (!session) {\n return;\n }\n for (const segmentId of session.segmentIds) {\n delete store.segmentsById[segmentId];\n }\n for (const [responseId, response] of Object.entries(store.responseIndex)) {\n if (response.sessionId === sessionId) {\n delete store.responseIndex[responseId];\n }\n }\n delete store.sessionsById[sessionId];\n}\n\nfunction pruneStore(store: AccountPoolStore): AccountPoolStore {\n const now = Date.now();\n for (const [sessionId, session] of Object.entries(store.sessionsById)) {\n const expiresAtMs = session.expiresAt ? Date.parse(session.expiresAt) : Number.NaN;\n if (Number.isFinite(expiresAtMs) && expiresAtMs < now) {\n deleteSessionFromStore(store, sessionId);\n }\n }\n for (const [segmentId, segment] of Object.entries(store.segmentsById)) {\n if (!store.sessionsById[segment.sessionId]) {\n delete store.segmentsById[segmentId];\n }\n }\n for (const [responseId, response] of Object.entries(store.responseIndex)) {\n if (!store.sessionsById[response.sessionId] || !store.segmentsById[response.segmentId]) {\n delete store.responseIndex[responseId];\n }\n }\n return store;\n}\n\nfunction resolveAccountPoolDbPath(stateDir: string): string {\n return path.join(stateDir, \"state.sqlite\");\n}\n\nasync function readLegacyStore(dbPath: string): Promise<LegacyBrokerStore | null> {\n return readDocument<LegacyBrokerStore>(dbPath, LEGACY_BROKER_DOCUMENT, normalizeLegacyStore);\n}\n\nasync function readStore(stateDir: string): Promise<AccountPoolStore> {\n const dbPath = resolveAccountPoolDbPath(stateDir);\n const store = await readDocument<AccountPoolStore>(\n dbPath,\n ACCOUNT_POOL_DOCUMENT,\n normalizeAccountPoolStore,\n );\n if (store) {\n return pruneStore(store);\n }\n const legacyStore = await readLegacyStore(dbPath);\n if (!legacyStore) {\n return createDefaultStore();\n }\n return pruneStore(migrateLegacyStore(legacyStore));\n}\n\nasync function updateStore(\n stateDir: string,\n mutate: (store: AccountPoolStore) => void,\n): Promise<AccountPoolStore> {\n const dbPath = resolveAccountPoolDbPath(stateDir);\n const legacyStore = await readLegacyStore(dbPath);\n return updateDocument<AccountPoolStore>({\n dbPath,\n namespace: ACCOUNT_POOL_DOCUMENT,\n normalize: normalizeAccountPoolStore,\n fallback: () => (legacyStore ? migrateLegacyStore(legacyStore) : createDefaultStore()),\n transform: (current) => {\n const next = pruneStore(current);\n mutate(next);\n return pruneStore(next);\n },\n });\n}\n\nfunction accountPoolApiKeyView(record: AccountPoolApiKeyRecord): AccountPoolApiKeyView {\n return {\n id: record.id,\n tokenPreview: record.tokenPreview,\n createdAt: record.createdAt,\n lastUsedAt: record.lastUsedAt,\n revokedAt: record.revokedAt,\n };\n}\n\nasync function listApiKeys(stateDir: string): Promise<AccountPoolApiKeyView[]> {\n const store = await readStore(stateDir);\n return Object.values(store.apiKeysById)\n .filter((key) => key.revokedAt === null)\n .sort((left, right) => right.createdAt.localeCompare(left.createdAt))\n .map(accountPoolApiKeyView);\n}\n\nfunction hashToken(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nasync function createApiKey(stateDir: string): Promise<AccountPoolApiKeyCreateResult> {\n const plaintextToken = `cux_pool_${randomBytes(24).toString(\"hex\")}`;\n const now = new Date().toISOString();\n const keyRecord: AccountPoolApiKeyRecord = {\n id: randomUUID(),\n tokenHash: hashToken(plaintextToken),\n tokenPreview: `${plaintextToken.slice(0, 8)}...${plaintextToken.slice(-6)}`,\n createdAt: now,\n lastUsedAt: null,\n revokedAt: null,\n };\n await updateStore(stateDir, (store) => {\n store.apiKeysById[keyRecord.id] = keyRecord;\n });\n return {\n key: accountPoolApiKeyView(keyRecord),\n plaintextToken,\n };\n}\n\nasync function revokeApiKey(stateDir: string, id: string): Promise<boolean> {\n let revoked = false;\n await updateStore(stateDir, (store) => {\n const existing = store.apiKeysById[id];\n if (!existing || existing.revokedAt !== null) {\n return;\n }\n existing.revokedAt = new Date().toISOString();\n revoked = true;\n });\n return revoked;\n}\n\nasync function listSessions(stateDir: string): Promise<AccountPoolSessionView[]> {\n const store = await readStore(stateDir);\n return Object.values(store.sessionsById)\n .sort((left, right) => right.lastUsedAt.localeCompare(left.lastUsedAt))\n .flatMap((session) => {\n const activeSegment = store.segmentsById[session.activeSegmentId];\n if (!activeSegment) {\n return [];\n }\n return [{\n id: session.id,\n affinityKind: session.affinityKind,\n affinityKey: session.affinityKey,\n activeProfileName: activeSegment.profileName,\n model: session.model,\n status: session.status,\n lastError: session.lastError,\n createdAt: session.createdAt,\n lastUsedAt: session.lastUsedAt,\n expiresAt: session.expiresAt,\n lastResponseId: session.lastResponseId,\n responseCount: session.responseIds.length,\n segmentCount: session.segmentIds.length,\n rolloverCount: session.rolloverCount,\n lastRolloverReason: session.lastRolloverReason,\n }];\n });\n}\n\nfunction resolveRuntimeStateDir(\n runtime: AccountPoolRuntime,\n explicitStateDir: string | null,\n): string {\n if (explicitStateDir) {\n return path.resolve(explicitStateDir);\n }\n if (runtime === \"daemon\") {\n return DEFAULT_DAEMON_STATE_DIR;\n }\n return path.join(getUserDataDir(), \"t3-projects\");\n}\n\nfunction resolveStateDir(flags: string[]): { runtime: AccountPoolRuntime; stateDir: string } {\n const runtimeFlag = parseStringFlag(flags, \"--runtime\")?.trim().toLowerCase();\n const runtime: AccountPoolRuntime = runtimeFlag === \"daemon\" ? \"daemon\" : \"desktop\";\n const explicitStateDir =\n parseStringFlag(flags, \"--state-dir\")\n ?? parseStringFlag(flags, \"--state\")\n ?? null;\n return {\n runtime,\n stateDir: resolveRuntimeStateDir(runtime, explicitStateDir),\n };\n}\n\nfunction resolveBaseUrlFromPort(runtime: AccountPoolRuntime, port: number | null): string | null {\n if (runtime === \"desktop\") {\n return null;\n }\n if (port === null) {\n return null;\n }\n if (!Number.isFinite(port) || port < 1 || port > 65535) {\n throw new Error(\"Daemon port must be an integer between 1 and 65535.\");\n }\n return `http://127.0.0.1:${port}`;\n}\n\nfunction resolveBaseUrl(runtime: AccountPoolRuntime, flags: string[]): string | null {\n return resolveBaseUrlFromPort(runtime, parseIntegerFlag(flags, \"--port\"));\n}\n\nexport async function readAccountPoolRuntimeSummary(input: {\n runtime?: AccountPoolRuntime;\n stateDir?: string | null;\n port?: number | null;\n} = {}): Promise<AccountPoolRuntimeSummary> {\n const runtime = input.runtime ?? \"desktop\";\n const stateDir = resolveRuntimeStateDir(runtime, input.stateDir ?? null);\n const [license, { normalized }, apiKeys, sessions] = await Promise.all([\n licenseService.getStatus().catch(() => null),\n readSettingsSnapshot(),\n listApiKeys(stateDir),\n listSessions(stateDir),\n ]);\n return {\n runtime,\n stateDir,\n baseUrl: resolveBaseUrlFromPort(runtime, input.port ?? null),\n enabled: normalized.accountPoolEnabled,\n hasProLicense: license?.isPro === true,\n routingStrategy: normalized.accountPoolRoutingStrategy,\n activeApiKeyCount: apiKeys.length,\n activeSessionCount: sessions.length,\n };\n}\n\nasync function readSettingsSnapshot(): Promise<{\n raw: JsonRecord;\n normalized: AccountPoolSettings;\n}> {\n const raw = asRecord(await readAppSettings());\n return {\n raw,\n normalized: normalizeAccountPoolSettings(raw),\n };\n}\n\nasync function updateSettings(\n transform: (current: AccountPoolSettings) => AccountPoolSettings,\n): Promise<{\n settings: AccountPoolSettings;\n forcedDisabledByLicense: boolean;\n}> {\n const { raw, normalized } = await readSettingsSnapshot();\n const nextSettings = transform(normalized);\n const license = await licenseService.getStatus().catch(() => null);\n const forcedDisabledByLicense = !license?.isPro && nextSettings.accountPoolEnabled === true;\n const sanitizedSettings: AccountPoolSettings = {\n ...nextSettings,\n accountPoolEnabled: forcedDisabledByLicense ? false : nextSettings.accountPoolEnabled,\n accountPoolRoutingStrategy: normalizeRoutingStrategy(nextSettings.accountPoolRoutingStrategy),\n accountPoolProfilePool: normalizeStringArray(nextSettings.accountPoolProfilePool),\n accountPoolExposedModels: normalizeAccountPoolExposedModels(\n nextSettings.accountPoolExposedModels,\n true,\n ),\n accountPoolExposedReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n nextSettings.accountPoolExposedReasoningEfforts,\n null,\n ),\n accountPoolExposedFastModeReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n nextSettings.accountPoolExposedFastModeReasoningEfforts,\n null,\n ),\n };\n await writeAppSettings(applyAccountPoolSettings(raw, sanitizedSettings));\n return {\n settings: sanitizedSettings,\n forcedDisabledByLicense,\n };\n}\n\nasync function requireProAccess(): Promise<void> {\n const license = await licenseService.getStatus();\n if (!license.isPro) {\n throw new Error(ACCOUNT_POOL_PRO_REQUIRED_MESSAGE);\n }\n}\n\nasync function listSavedProfiles() {\n const manager = new ProfileManager();\n return manager.listProfiles();\n}\n\nfunction printStringList(label: string, values: string[]): void {\n console.log(`${label}: ${values.length > 0 ? values.join(\", \") : \"(none)\"}`);\n}\n\nfunction printSessionRow(session: AccountPoolSessionView): void {\n const fields = [\n `id=${session.id}`,\n `profile=${session.activeProfileName}`,\n `status=${session.status}`,\n `model=${session.model ?? \"-\"}`,\n `responses=${session.responseCount}`,\n `segments=${session.segmentCount}`,\n ];\n if (session.lastResponseId) {\n fields.push(`lastResponse=${session.lastResponseId}`);\n }\n if (session.lastRolloverReason) {\n fields.push(`rollover=${session.lastRolloverReason}`);\n }\n console.log(fields.join(\" \"));\n}\n\nfunction printApiKeyRow(apiKey: AccountPoolApiKeyView): void {\n const fields = [\n `id=${apiKey.id}`,\n `preview=${apiKey.tokenPreview}`,\n `created=${apiKey.createdAt}`,\n ];\n if (apiKey.lastUsedAt) {\n fields.push(`lastUsed=${apiKey.lastUsedAt}`);\n }\n console.log(fields.join(\" \"));\n}\n\nfunction getArrayValues(params: string[], startIndex: number): string[] {\n return params.slice(startIndex).map((value) => value.trim()).filter(Boolean);\n}\n\nasync function handleStatus(flags: string[]): Promise<void> {\n const license = await licenseService.getStatus().catch(() => null);\n const { raw, normalized } = await readSettingsSnapshot();\n const { runtime, stateDir } = resolveStateDir(flags);\n const baseUrl = resolveBaseUrl(runtime, flags);\n const [profiles, apiKeys, sessions] = await Promise.all([\n listSavedProfiles(),\n listApiKeys(stateDir),\n listSessions(stateDir),\n ]);\n const explicitSelection = normalized.accountPoolProfilePool;\n const selectedProfiles =\n explicitSelection.length > 0\n ? explicitSelection\n : profiles.map((profile) => profile.name);\n const missingSelectedProfiles = explicitSelection.filter(\n (profileName) => !profiles.some((profile) => profile.name === profileName),\n );\n\n console.log(`License: ${license ? `${license.tier} (${license.state})` : \"unknown\"}`);\n console.log(`Enabled: ${normalized.accountPoolEnabled ? \"yes\" : \"no\"}`);\n console.log(`Runtime: ${runtime}`);\n console.log(`State dir: ${stateDir}`);\n console.log(`Routing: ${formatRoutingStrategy(normalized.accountPoolRoutingStrategy)}`);\n console.log(`Public API ready: ${normalized.accountPoolEnabled && license?.isPro === true && apiKeys.length > 0 ? \"yes\" : \"no\"}`);\n console.log(`API keys: ${apiKeys.length}`);\n console.log(`Sessions: ${sessions.length}`);\n console.log(`Selection mode: ${explicitSelection.length > 0 ? \"explicit\" : \"all saved profiles\"}`);\n if (baseUrl) {\n console.log(`Base URL: ${baseUrl}`);\n } else {\n console.log(\n runtime === \"desktop\"\n ? \"Base URL: check the running desktop app for the current Accounts Pool URL.\"\n : \"Base URL: daemon port not specified here; use the URL printed by `codexuse daemon start` or pass --port=NNNN.\",\n );\n }\n printStringList(\"Selected profiles\", selectedProfiles);\n if (missingSelectedProfiles.length > 0) {\n printStringList(\"Missing configured profiles\", missingSelectedProfiles);\n }\n printStringList(\"Published models\", normalized.accountPoolExposedModels);\n printStringList(\"Reasoning aliases\", normalized.accountPoolExposedReasoningEfforts);\n printStringList(\"Fast-mode aliases\", normalized.accountPoolExposedFastModeReasoningEfforts);\n if (raw.accountPoolEnabled !== true && raw.brokerEnabled === true) {\n console.log(\"Legacy broker setting detected: runtime is reading it through the new Accounts Pool surface.\");\n }\n if (normalized.accountPoolEnabled && license?.isPro !== true) {\n console.log(ACCOUNT_POOL_PRO_REQUIRED_MESSAGE);\n }\n}\n\nasync function handleEnable(): Promise<void> {\n await requireProAccess();\n const result = await updateSettings((current) => ({\n ...current,\n accountPoolEnabled: true,\n }));\n console.log(result.settings.accountPoolEnabled ? \"Accounts Pool enabled.\" : \"Accounts Pool is disabled.\");\n}\n\nasync function handleDisable(): Promise<void> {\n const result = await updateSettings((current) => ({\n ...current,\n accountPoolEnabled: false,\n }));\n console.log(result.settings.accountPoolEnabled ? \"Accounts Pool is enabled.\" : \"Accounts Pool disabled.\");\n}\n\nasync function handleRouting(params: string[]): Promise<void> {\n const value = parseRoutingStrategy(params[1]);\n if (!value) {\n throw new Error(\"Routing strategy must be `least-used` or `round-robin`.\");\n }\n const result = await updateSettings((current) => ({\n ...current,\n accountPoolRoutingStrategy: value,\n }));\n console.log(`Accounts Pool routing set to ${formatRoutingStrategy(result.settings.accountPoolRoutingStrategy)}.`);\n}\n\nasync function handleProfiles(params: string[]): Promise<void> {\n const action = params[1];\n const profiles = await listSavedProfiles();\n const availableProfileNames = profiles.map((profile) => profile.name);\n const availableSet = new Set(availableProfileNames);\n const { normalized } = await readSettingsSnapshot();\n\n if (!action || action === \"list\") {\n const explicitSelection = normalized.accountPoolProfilePool;\n if (explicitSelection.length === 0) {\n console.log(\"Selection: all saved profiles\");\n } else {\n printStringList(\"Explicitly selected profiles\", explicitSelection);\n }\n for (const profile of profiles) {\n const selected = explicitSelection.length === 0 || explicitSelection.includes(profile.name);\n const invalidSuffix = profile.isValid ? \"\" : \" [needs re-auth]\";\n console.log(`${selected ? \"*\" : \"-\"} ${profile.name}${invalidSuffix}`);\n }\n const missing = explicitSelection.filter((name) => !availableSet.has(name));\n if (missing.length > 0) {\n printStringList(\"Missing configured profiles\", missing);\n }\n return;\n }\n\n const names = getArrayValues(params, 2);\n if ((action === \"set\" || action === \"add\" || action === \"remove\") && names.length === 0) {\n throw new Error(`Profile names are required for \\`${action}\\`.`);\n }\n for (const name of names) {\n if (!availableSet.has(name)) {\n throw new Error(`Unknown profile: ${name}`);\n }\n }\n\n const result = await updateSettings((current) => {\n const currentSelection =\n current.accountPoolProfilePool.length > 0\n ? current.accountPoolProfilePool.slice()\n : availableProfileNames.slice();\n let nextSelection = currentSelection;\n switch (action) {\n case \"set\":\n nextSelection = names.slice();\n break;\n case \"add\":\n nextSelection = Array.from(new Set([...currentSelection, ...names]));\n break;\n case \"remove\":\n nextSelection = currentSelection.filter((name) => !names.includes(name));\n break;\n case \"reset\":\n nextSelection = [];\n break;\n default:\n throw new Error(\"Unknown profiles action.\");\n }\n return {\n ...current,\n accountPoolProfilePool:\n action === \"reset\" || nextSelection.length === availableProfileNames.length\n ? []\n : nextSelection,\n };\n });\n\n if (result.settings.accountPoolProfilePool.length === 0) {\n console.log(\"Accounts Pool now uses all saved profiles.\");\n return;\n }\n printStringList(\"Accounts Pool selected profiles\", result.settings.accountPoolProfilePool);\n}\n\ntype ArraySettingKey =\n | \"accountPoolExposedModels\"\n | \"accountPoolExposedReasoningEfforts\"\n | \"accountPoolExposedFastModeReasoningEfforts\";\n\nasync function handleArraySetting(input: {\n label: string;\n actionName: string;\n params: string[];\n key: ArraySettingKey;\n defaultValues: readonly string[];\n normalizeValue: (value: string) => string | null;\n}): Promise<void> {\n const action = input.params[1];\n const { normalized } = await readSettingsSnapshot();\n const currentValues = normalized[input.key];\n\n if (!action || action === \"list\") {\n printStringList(input.label, currentValues);\n return;\n }\n\n const rawValues = getArrayValues(input.params, 2);\n if ((action === \"add\" || action === \"remove\") && rawValues.length === 0) {\n throw new Error(`Values are required for \\`${input.actionName} ${action}\\`.`);\n }\n const normalizedValues = rawValues.map(input.normalizeValue).filter((value): value is string => Boolean(value));\n if ((action === \"add\" || action === \"remove\") && normalizedValues.length === 0) {\n throw new Error(\"No valid values were provided.\");\n }\n\n const result = await updateSettings((current) => {\n const existing = current[input.key];\n switch (action) {\n case \"add\":\n return {\n ...current,\n [input.key]: Array.from(new Set([...existing, ...normalizedValues])),\n };\n case \"remove\":\n return {\n ...current,\n [input.key]: existing.filter((value) => !normalizedValues.includes(value)),\n };\n case \"reset\":\n return {\n ...current,\n [input.key]: [...input.defaultValues],\n };\n default:\n throw new Error(`Unknown ${input.actionName} action.`);\n }\n });\n\n printStringList(input.label, result.settings[input.key]);\n}\n\nasync function handleKeys(params: string[], flags: string[]): Promise<void> {\n const action = params[1];\n const { runtime, stateDir } = resolveStateDir(flags);\n const baseUrl = resolveBaseUrl(runtime, flags);\n\n if (!action || action === \"list\") {\n const apiKeys = await listApiKeys(stateDir);\n if (apiKeys.length === 0) {\n console.log(\"No active Accounts Pool API keys.\");\n return;\n }\n for (const apiKey of apiKeys) {\n printApiKeyRow(apiKey);\n }\n return;\n }\n\n switch (action) {\n case \"create\": {\n await requireProAccess();\n const created = await createApiKey(stateDir);\n console.log(`Created key: ${created.key.id}`);\n console.log(`Preview: ${created.key.tokenPreview}`);\n console.log(`Token: ${created.plaintextToken}`);\n console.log(`Runtime: ${runtime}`);\n console.log(`State dir: ${stateDir}`);\n if (baseUrl) {\n console.log(`Base URL: ${baseUrl}`);\n } else if (runtime === \"desktop\") {\n console.log(\"Base URL: use the current Accounts Pool URL shown by the running desktop app.\");\n } else if (runtime === \"daemon\") {\n console.log(\"Base URL: pass --port=NNNN here or use the URL printed by `codexuse daemon start`.\");\n }\n console.log(\"This key only works for the selected runtime state dir.\");\n console.log(\"Store this token now. The plaintext value is only shown once.\");\n return;\n }\n case \"revoke\": {\n const id = params[2]?.trim();\n if (!id) {\n throw new Error(\"API key id is required.\");\n }\n const removed = await revokeApiKey(stateDir, id);\n if (!removed) {\n throw new Error(`No Accounts Pool API key found for id ${id}.`);\n }\n console.log(`Revoked key: ${id}`);\n return;\n }\n default:\n throw new Error(\"Unknown keys action.\");\n }\n}\n\nasync function handleSessions(params: string[], flags: string[]): Promise<void> {\n const action = params[1];\n if (action && action !== \"list\") {\n throw new Error(\"Only `sessions list` is supported here. Session mutation stays runtime-owned.\");\n }\n const { stateDir } = resolveStateDir(flags);\n const sessions = await listSessions(stateDir);\n if (sessions.length === 0) {\n console.log(\"No pooled sessions in this runtime store.\");\n return;\n }\n for (const session of sessions) {\n printSessionRow(session);\n }\n console.log(\"Session mutation is intentionally not exposed here; pooled sessions belong to the live runtime owner.\");\n}\n\nasync function handleQuickstart(flags: string[]): Promise<void> {\n const { runtime, stateDir } = resolveStateDir(flags);\n const port = parseIntegerFlag(flags, \"--port\");\n const summary = await readAccountPoolRuntimeSummary({ runtime, stateDir, port });\n const baseUrl = summary.baseUrl ?? \"http://127.0.0.1:<port>\";\n console.log(\"Accounts Pool quickstart\");\n console.log(`Runtime: ${summary.runtime}`);\n console.log(`Enabled: ${summary.enabled ? \"yes\" : \"no\"}`);\n console.log(`Pro: ${summary.hasProLicense ? \"yes\" : \"no\"}`);\n console.log(`API keys: ${summary.activeApiKeyCount}`);\n console.log(`Base URL: ${baseUrl}`);\n console.log(\"\");\n console.log(\"1. Enable pool:\");\n console.log(\" codexuse account-pool enable\");\n console.log(\"2. Create key:\");\n console.log(` codexuse account-pool keys create --runtime=${summary.runtime}`);\n console.log(\"3. Use OpenAI-compatible settings:\");\n console.log(` Base URL: ${baseUrl}/v1`);\n console.log(\" API key: cux_pool_...\");\n console.log(\"4. Smoke:\");\n console.log(` curl ${baseUrl}/v1/models -H 'Authorization: Bearer cux_pool_...'`);\n}\n\nexport async function handleAccountPoolCommand(args: string[], version: string): Promise<void> {\n const flags = args.filter((arg) => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printAccountPoolHelp(version);\n return;\n }\n\n switch (sub) {\n case \"status\":\n await handleStatus(flags);\n return;\n case \"quickstart\":\n await handleQuickstart(flags);\n return;\n case \"enable\":\n await handleEnable();\n return;\n case \"disable\":\n await handleDisable();\n return;\n case \"routing\":\n await handleRouting(params);\n return;\n case \"profiles\":\n await handleProfiles(params);\n return;\n case \"models\":\n await handleArraySetting({\n label: \"Published models\",\n actionName: \"models\",\n params,\n key: \"accountPoolExposedModels\",\n defaultValues: DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS,\n normalizeValue: (value) => normalizeCodexModelSlug(value) ?? asString(value),\n });\n return;\n case \"reasoning\":\n await handleArraySetting({\n label: \"Reasoning aliases\",\n actionName: \"reasoning\",\n params,\n key: \"accountPoolExposedReasoningEfforts\",\n defaultValues: DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS,\n normalizeValue: (value) => normalizeReasoningEffort(value),\n });\n return;\n case \"fast-mode\":\n await handleArraySetting({\n label: \"Fast-mode aliases\",\n actionName: \"fast-mode\",\n params,\n key: \"accountPoolExposedFastModeReasoningEfforts\",\n defaultValues: DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS,\n normalizeValue: (value) => normalizeReasoningEffort(value),\n });\n return;\n case \"keys\":\n await handleKeys(params, flags);\n return;\n case \"sessions\":\n await handleSessions(params, flags);\n return;\n default:\n printHelp(version);\n return;\n }\n}\n","export type AccessMode = \"read-only\" | \"current\" | \"full-access\";\nexport type ComposerSendIntent = \"default\" | \"queue\" | \"steer\";\n\nexport type SendMessageResult = {\n status: \"sent\" | \"blocked\" | \"steer_failed\";\n};\n\nexport type ProjectsTimestampFormat = \"locale\" | \"12-hour\" | \"24-hour\";\nexport type ProjectsDefaultThreadEnvMode = \"local\" | \"worktree\";\nexport type AccountPoolRoutingStrategy = \"round_robin\" | \"least_used\";\nexport type RateLimitPercentMode = \"remaining\" | \"used\";\nexport type ProjectsSidebarThreadPreviewCount = number;\n\nexport const MIN_PROJECTS_SIDEBAR_THREAD_PREVIEW_COUNT = 1;\nexport const MAX_PROJECTS_SIDEBAR_THREAD_PREVIEW_COUNT = 15;\nexport const DEFAULT_PROJECTS_SIDEBAR_THREAD_PREVIEW_COUNT: ProjectsSidebarThreadPreviewCount = 6;\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS = [\n \"gpt-5.5\",\n \"gpt-5.4\",\n \"gpt-5.4-mini\",\n \"gpt-5.4-nano\",\n] as const;\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS = [\n \"none\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n] as const;\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS = [\n \"xhigh\",\n] as const;\n\nconst ACCOUNT_POOL_REASONING_VARIANT_MARKER = \"__reasoning_\";\n\nexport function buildAccountPoolVariantModelId(input: {\n modelId: string;\n reasoningEffort: string;\n fastMode?: boolean;\n}): string {\n return [\n input.modelId.trim(),\n input.reasoningEffort.trim().toLowerCase(),\n ...(input.fastMode ? [\"fast\"] : []),\n ].join(\"-\");\n}\n\nexport function buildLegacyAccountPoolReasoningVariantModelId(\n modelId: string,\n reasoningEffort: string,\n): string {\n return `${modelId.trim()}${ACCOUNT_POOL_REASONING_VARIANT_MARKER}${reasoningEffort.trim().toLowerCase()}`;\n}\n\nexport function parseAccountPoolReasoningVariantModelId(\n modelId: string,\n): { modelId: string; reasoningEffort: string } | null {\n const trimmed = modelId.trim();\n const markerIndex = trimmed.lastIndexOf(ACCOUNT_POOL_REASONING_VARIANT_MARKER);\n if (markerIndex <= 0) {\n return null;\n }\n\n const baseModelId = trimmed.slice(0, markerIndex).trim();\n const reasoningEffort = trimmed\n .slice(markerIndex + ACCOUNT_POOL_REASONING_VARIANT_MARKER.length)\n .trim()\n .toLowerCase();\n if (!baseModelId || !reasoningEffort) {\n return null;\n }\n\n return {\n modelId: baseModelId,\n reasoningEffort,\n };\n}\n\nexport type AppSettings = {\n codexBin: string | null;\n codexArgs: string | null;\n codexHome: string | null;\n automaticAppUpdateChecksEnabled: boolean;\n keepAppRunningAfterWindowClose: boolean;\n rateLimitPercentMode: RateLimitPercentMode;\n telegramBridgeEnabled: boolean;\n telegramBotToken: string | null;\n telegramAllowedChatIds: string[];\n defaultAccessMode: AccessMode;\n reviewDeliveryMode: \"inline\" | \"detached\";\n composerModelShortcut: string | null;\n composerAccessShortcut: string | null;\n composerReasoningShortcut: string | null;\n composerCollaborationShortcut: string | null;\n interruptShortcut: string | null;\n newAgentShortcut: string | null;\n newWorktreeAgentShortcut: string | null;\n newCloneAgentShortcut: string | null;\n archiveThreadShortcut: string | null;\n toggleProjectsSidebarShortcut: string | null;\n toggleGitSidebarShortcut: string | null;\n branchSwitcherShortcut: string | null;\n toggleDebugPanelShortcut: string | null;\n toggleTerminalShortcut: string | null;\n cycleAgentNextShortcut: string | null;\n cycleAgentPrevShortcut: string | null;\n cycleWorkspaceNextShortcut: string | null;\n cycleWorkspacePrevShortcut: string | null;\n lastComposerModelId: string | null;\n lastComposerReasoningEffort: string | null;\n projectsTimestampFormat: ProjectsTimestampFormat;\n projectsDefaultThreadEnvMode: ProjectsDefaultThreadEnvMode;\n projectsAssistantStreamingEnabled: boolean;\n projectsConfirmThreadDelete: boolean;\n projectsAddProjectBaseDirectory: string | null;\n projectsCustomCodexModels: string[];\n projectsSidebarThreadPreviewCount: ProjectsSidebarThreadPreviewCount;\n accountPoolEnabled: boolean;\n accountPoolRoutingStrategy: AccountPoolRoutingStrategy;\n accountPoolProfilePool: string[];\n accountPoolExposedModels: string[];\n accountPoolExposedReasoningEfforts: string[];\n accountPoolExposedFastModeReasoningEfforts: string[];\n};\n\nexport type CodexFeatureStage =\n | \"under_development\"\n | \"beta\"\n | \"stable\"\n | \"deprecated\"\n | \"removed\";\n\nexport type CodexFeature = {\n name: string;\n stage: CodexFeatureStage;\n enabled: boolean;\n defaultEnabled: boolean;\n displayName: string | null;\n description: string | null;\n announcement: string | null;\n};\n\nexport type TelegramBridgeStreamMode = \"draft\" | \"message\" | \"none\";\n\nexport type TelegramBridgeStatus = {\n state: \"stopped\" | \"running\" | \"error\";\n running: boolean;\n botUsername: string | null;\n allowedChats: number;\n activeChats: number;\n streamMode: TelegramBridgeStreamMode;\n lastError: string | null;\n startedAtMs: number | null;\n};\n\nexport type TelegramBridgeTokenTestResult = {\n ok: boolean;\n username: string | null;\n error: string | null;\n};\n\nexport type CodexDoctorResult = {\n ok: boolean;\n codexBin: string | null;\n version: string | null;\n appServerOk: boolean;\n authStatus: \"authenticated\" | \"unauthenticated\" | \"unknown\";\n authMessage: string | null;\n accountLabel: string | null;\n details: string | null;\n path: string | null;\n nodeOk: boolean;\n nodeVersion: string | null;\n nodeDetails: string | null;\n};\n\nexport type CodexModelReasoningEffortOption = {\n reasoningEffort: string;\n description: string;\n};\n\nexport type CodexConnectedModelOption = {\n id: string;\n model: string;\n displayName: string;\n description: string;\n supportedReasoningEfforts: CodexModelReasoningEffortOption[];\n defaultReasoningEffort: string | null;\n isDefault: boolean;\n};\n\nexport type CodexRuntimeInspection = {\n doctor: CodexDoctorResult;\n models: CodexConnectedModelOption[];\n modelsError: string | null;\n};\n\nexport type CodexUpdateMethod =\n | \"brew_formula\"\n | \"brew_cask\"\n | \"npm\"\n | \"unknown\";\n\nexport type CodexUpdateResult = {\n ok: boolean;\n method: CodexUpdateMethod;\n package: string | null;\n beforeVersion: string | null;\n afterVersion: string | null;\n upgraded: boolean;\n output: string | null;\n details: string | null;\n};\n","import { promises as fs } from \"node:fs\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport type {\n ProfileData,\n ProfileMetadata,\n} from \"@codexuse/contracts/profiles/types\";\nimport type { AutoRollActivityEntry } from \"@codexuse/contracts/desktop/ipc-types\";\nimport {\n CHAT_SCROLLBACK_DEFAULT,\n normalizeChatHistoryScrollbackItems,\n} from \"@codexuse/contracts/settings/chat-scrollback\";\nimport {\n DEFAULT_COMMIT_MESSAGE_PROMPT,\n normalizeCommitMessagePrompt,\n} from \"@codexuse/contracts/settings/commit-message-prompt\";\nimport { normalizeAutoRollSettings } from \"@codexuse/contracts/settings/auto-roll\";\nimport {\n readDocument,\n resolveAppStorageDbPath,\n updateDocument,\n writeDocument,\n} from \"@codexuse/runtime-app-state/storage/documents\";\n\nconst LEGACY_APP_STATE_FILE = \"app-state.json\";\nconst APP_STATE_DOCUMENT = \"desktop.app-state\";\nconst APP_NAME = \"codexuse-desktop\";\n\nexport type LicenseStatusCode = \"inactive\" | \"active\" | \"grace\" | \"error\";\nexport type ReasoningEffort =\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"none\";\n\nexport type ProfileRecordState = {\n name: string;\n displayName: string | null;\n data: ProfileData;\n metadata?: ProfileMetadata;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n email: string | null;\n authMethod: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n};\n\nexport type ProfileDashboardState = {\n customGroupsByAccountKey: Record<string, string>;\n};\n\nexport type OfficialCodexState = {\n lastProfileSwitchAt: number | null;\n lastProfileSwitchProfileKey: string | null;\n lastVerifiedLaunchAt: number | null;\n lastVerifiedLaunchProfileKey: string | null;\n lastObservedPid: number | null;\n lastRestartStatus: string | null;\n lastRestartReason: string | null;\n activity: AutoRollActivityEntry[];\n instancesByProfileName: Record<string, OfficialCodexManagedInstanceState>;\n pendingRestartDebt: OfficialCodexRestartDebtState | null;\n};\n\nexport type OfficialCodexManagedInstanceState = {\n profileName: string;\n profileKey: string | null;\n profileHome: string | null;\n appPath: string | null;\n bundleId: string | null;\n pid: number | null;\n appServerPid: number | null;\n launchedAt: number | null;\n lastVerifiedAt: number | null;\n lastStatus: string | null;\n lastError: string | null;\n};\n\nexport type OfficialCodexRestartDebtState = {\n targetProfileName: string;\n targetProfileKey: string | null;\n sourceProfileName: string | null;\n sourceProfileKey: string | null;\n decisionId: string | null;\n attempts: number;\n lastReason: string | null;\n};\n\nexport type SkillsInstallState = {\n id: string;\n repo?: string | null;\n repoPath?: string | null;\n sourceLabel?: string | null;\n sourceType?: \"official\" | \"community\" | \"local\";\n viewUrl?: string | null;\n createdAt?: string | null;\n};\n\nexport type SyncState = {\n lastPushAt: string | null;\n lastPullAt: string | null;\n lastError: string | null;\n remoteUpdatedAt: string | null;\n};\n\nexport type AnalyticsState = {\n anonymousId: string | null;\n enabled: boolean;\n lastFlushAt: string | null;\n lastError: string | null;\n};\n\nexport type AppUiState = {\n themeMode: \"light\" | \"dark\" | null;\n layout: {\n sidebarCollapsed: boolean | null;\n };\n profiles: {\n viewMode: \"cards\" | \"compact\" | null;\n sortBy: string | null;\n groupBy: string | null;\n planFilter: string | null;\n healthFilter: string | null;\n customGroupFilter: string | null;\n toolbarOpen: boolean | null;\n collapsedSections: Record<string, boolean>;\n };\n onboarding: {\n welcomeCompleted: boolean;\n welcomeCompletedAt: number | null;\n welcomeResumeStep: 2 | null;\n milestones: {\n firstProfileAdded: boolean;\n secondProfileAdded: boolean;\n };\n sessionCount: number;\n nudgeCooldowns: Record<string, number>;\n nudgeDismissCount: Record<string, number>;\n proUnlockedCelebrated: boolean;\n };\n projectThreadSelections: Record<string, string | null>;\n duplicateWarningDismissedKey: string | null;\n pendingLicenseActivation: boolean;\n};\n\nexport type AppState = {\n schemaVersion: 1;\n autoRoll: {\n enabled: boolean;\n rearmRemainingThreshold: number;\n switchRemainingThreshold: number;\n restartOfficialCodexOnAutoRoll: boolean;\n launchOfficialCodexWhenClosedOnAutoRoll: boolean;\n priorityOrder: string[];\n lowRemainingNotificationEnabled: boolean;\n lowRemainingNotificationThreshold: number;\n };\n officialCodex: OfficialCodexState;\n app: {\n lastAppVersion: string | null;\n pendingUpdateVersion: string | null;\n lastProfileName: string | null;\n };\n license: {\n licenseKey: string | null;\n purchaseEmail: string | null;\n lastVerifiedAt: string | null;\n nextCheckAt: string | null;\n lastVerificationError: string | null;\n status: LicenseStatusCode;\n signature: string | null;\n };\n preferences: {\n excludeFolders: string[];\n enableTaskCompleteBeep: boolean;\n preventSleepDuringTasks: boolean;\n chatHistoryScrollbackItems: number | null;\n systemNotificationsEnabled: boolean;\n subagentSystemNotificationsEnabled: boolean;\n folderHistory: Array<{ path: string; name: string; lastVisited: number }>;\n pinnedPaths: string[];\n };\n runtimeSettings: Record<string, unknown>;\n ui: AppUiState;\n profileDashboard: ProfileDashboardState;\n workspaceSettingsByPath: Record<\n string,\n {\n systemPrompt?: string;\n runScript?: string;\n buildScript?: string;\n openIdeCommand?: string;\n }\n >;\n conversationCategoriesByCwd: Record<\n string,\n Array<{ id: string; name: string }>\n >;\n conversationCategoryAssignmentsByCwd: Record<string, Record<string, string>>;\n git: {\n commitMessagePrompt: string;\n };\n skills: {\n sources: Array<{\n id: string;\n repo: string;\n label: string;\n branch?: string | null;\n url?: string | null;\n official?: boolean;\n compatibilityNote?: string | null;\n priority?: number;\n }>;\n installsBySlug: Record<string, SkillsInstallState>;\n };\n sync: SyncState;\n analytics: AnalyticsState;\n profilesByName: Record<string, ProfileRecordState>;\n migration: {\n status: \"pending\" | \"pending_local_storage\" | \"complete\";\n startedAt: string | null;\n completedAt: string | null;\n localStorageImportedAt: string | null;\n lastError?: string | null;\n };\n};\n\nexport type AppStatePatch = DeepPartial<AppState>;\ntype AppStateUpdateMode = \"replace\" | \"patch\";\ntype AppStateUpdateOptions = {\n allowBeforeMigrationComplete?: boolean;\n mode?: AppStateUpdateMode;\n};\ntype AppStateUpdateTransform = (current: AppState) => AppState | AppStatePatch;\n\ntype DeepPartial<T> = {\n [K in keyof T]?: T[K] extends Array<infer U>\n ? U[]\n : T[K] extends object\n ? DeepPartial<T[K]>\n : T[K];\n};\n\nlet configuredUserDataDir: string | null = null;\nlet appStateCache: AppState | null = null;\nlet writeLock: Promise<void> = Promise.resolve();\nconst writeLockContext = new AsyncLocalStorage<boolean>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction resolveDefaultUserDataDir(): string {\n const home = process.env.HOME || process.env.USERPROFILE || os.homedir();\n if (!home) {\n throw new Error(\"Unable to resolve home directory for app state.\");\n }\n\n if (process.platform === \"darwin\") {\n return path.join(home, \"Library\", \"Application Support\", APP_NAME);\n }\n if (process.platform === \"win32\") {\n const appData = process.env.APPDATA;\n if (appData) {\n return path.join(appData, APP_NAME);\n }\n return path.join(home, \"AppData\", \"Roaming\", APP_NAME);\n }\n return path.join(home, \".config\", APP_NAME);\n}\n\nexport function getUserDataDir(): string {\n return configuredUserDataDir ?? resolveDefaultUserDataDir();\n}\n\nexport function resolveLegacyAppStatePath(): string {\n return path.join(getUserDataDir(), LEGACY_APP_STATE_FILE);\n}\n\nfunction resolveStorageDbPath(): string {\n return resolveAppStorageDbPath(getUserDataDir());\n}\n\nfunction createDefaultAppState(): AppState {\n return {\n schemaVersion: 1,\n autoRoll: {\n enabled: false,\n rearmRemainingThreshold: 15,\n switchRemainingThreshold: 5,\n restartOfficialCodexOnAutoRoll: false,\n launchOfficialCodexWhenClosedOnAutoRoll: false,\n priorityOrder: [],\n lowRemainingNotificationEnabled: false,\n lowRemainingNotificationThreshold: 1,\n },\n officialCodex: {\n lastProfileSwitchAt: null,\n lastProfileSwitchProfileKey: null,\n lastVerifiedLaunchAt: null,\n lastVerifiedLaunchProfileKey: null,\n lastObservedPid: null,\n lastRestartStatus: null,\n lastRestartReason: null,\n activity: [],\n instancesByProfileName: {},\n pendingRestartDebt: null,\n },\n app: {\n lastAppVersion: null,\n pendingUpdateVersion: null,\n lastProfileName: null,\n },\n license: {\n licenseKey: null,\n purchaseEmail: null,\n lastVerifiedAt: null,\n nextCheckAt: null,\n lastVerificationError: null,\n status: \"inactive\",\n signature: null,\n },\n preferences: {\n excludeFolders: [],\n enableTaskCompleteBeep: true,\n preventSleepDuringTasks: true,\n chatHistoryScrollbackItems: CHAT_SCROLLBACK_DEFAULT,\n systemNotificationsEnabled: true,\n subagentSystemNotificationsEnabled: true,\n folderHistory: [],\n pinnedPaths: [],\n },\n runtimeSettings: {},\n ui: {\n themeMode: null,\n layout: {\n sidebarCollapsed: null,\n },\n profiles: {\n viewMode: null,\n sortBy: null,\n groupBy: null,\n planFilter: null,\n healthFilter: null,\n customGroupFilter: null,\n toolbarOpen: null,\n collapsedSections: {},\n },\n onboarding: {\n welcomeCompleted: false,\n welcomeCompletedAt: null,\n welcomeResumeStep: null,\n milestones: {\n firstProfileAdded: false,\n secondProfileAdded: false,\n },\n sessionCount: 0,\n nudgeCooldowns: {},\n nudgeDismissCount: {},\n proUnlockedCelebrated: false,\n },\n projectThreadSelections: {},\n duplicateWarningDismissedKey: null,\n pendingLicenseActivation: false,\n },\n profileDashboard: {\n customGroupsByAccountKey: {},\n },\n workspaceSettingsByPath: {},\n conversationCategoriesByCwd: {},\n conversationCategoryAssignmentsByCwd: {},\n git: {\n commitMessagePrompt: DEFAULT_COMMIT_MESSAGE_PROMPT,\n },\n skills: {\n sources: [],\n installsBySlug: {},\n },\n sync: {\n lastPushAt: null,\n lastPullAt: null,\n lastError: null,\n remoteUpdatedAt: null,\n },\n analytics: {\n anonymousId: null,\n enabled: true,\n lastFlushAt: null,\n lastError: null,\n },\n profilesByName: {},\n migration: {\n status: \"pending\",\n startedAt: null,\n completedAt: null,\n localStorageImportedAt: null,\n lastError: null,\n },\n };\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction asBooleanOrNull(value: unknown): boolean | null {\n return typeof value === \"boolean\" ? value : null;\n}\n\nfunction normalizeAppState(raw: unknown): AppState {\n const defaults = createDefaultAppState();\n if (!isRecord(raw)) {\n return defaults;\n }\n\n const rawAutoRoll = isRecord(raw.autoRoll) ? raw.autoRoll : undefined;\n const next = deepMerge(defaults, raw as AppStatePatch);\n const merged = clone(next);\n\n merged.schemaVersion = 1;\n merged.autoRoll = normalizeAutoRollSettings(rawAutoRoll);\n if (!isRecord(merged.officialCodex)) {\n merged.officialCodex = clone(defaults.officialCodex);\n }\n merged.officialCodex.lastProfileSwitchAt = asNumberOrNull(\n merged.officialCodex.lastProfileSwitchAt,\n );\n merged.officialCodex.lastProfileSwitchProfileKey = asString(\n merged.officialCodex.lastProfileSwitchProfileKey,\n );\n merged.officialCodex.lastVerifiedLaunchAt = asNumberOrNull(\n merged.officialCodex.lastVerifiedLaunchAt,\n );\n merged.officialCodex.lastVerifiedLaunchProfileKey = asString(\n merged.officialCodex.lastVerifiedLaunchProfileKey,\n );\n merged.officialCodex.lastObservedPid = asNumberOrNull(\n merged.officialCodex.lastObservedPid,\n );\n merged.officialCodex.lastRestartStatus = asString(\n merged.officialCodex.lastRestartStatus,\n );\n merged.officialCodex.lastRestartReason = asString(\n merged.officialCodex.lastRestartReason,\n );\n merged.officialCodex.activity = Array.isArray(merged.officialCodex.activity)\n ? merged.officialCodex.activity\n .filter((entry): entry is AutoRollActivityEntry => isRecord(entry))\n .map((entry) => ({\n id: asString(entry.id) ?? \"\",\n at: asString(entry.at) ?? new Date(0).toISOString(),\n kind:\n entry.kind === \"auto-roll-eval\" ||\n entry.kind === \"profile-switch\" ||\n entry.kind === \"auth-verified\" ||\n entry.kind === \"official-codex-restart\" ||\n entry.kind === \"reset-window-activation\" ||\n entry.kind === \"low-remaining-alert\"\n ? entry.kind\n : \"auto-roll-eval\",\n status: asString(entry.status) ?? \"unknown\",\n reason: asString(entry.reason),\n decisionId: asString(entry.decisionId),\n profileName: asString(entry.profileName),\n sourceProfileName: asString(entry.sourceProfileName),\n targetProfileName: asString(entry.targetProfileName),\n remainingPercent: asNumberOrNull(entry.remainingPercent),\n threshold: asNumberOrNull(entry.threshold),\n snapshotAgeMs: asNumberOrNull(entry.snapshotAgeMs),\n snapshotSource: asString(entry.snapshotSource),\n phase: asString(entry.phase),\n pid: asNumberOrNull(entry.pid),\n profileKeyHash: asString(entry.profileKeyHash),\n switchVerified: asBooleanOrNull(entry.switchVerified),\n restartRequested: asBooleanOrNull(entry.restartRequested),\n restartResult: asString(entry.restartResult),\n observedProfileName: asString(entry.observedProfileName),\n observedProfileKeyHash: asString(entry.observedProfileKeyHash),\n observedProfileMatchSource: asString(\n entry.observedProfileMatchSource,\n ) as AutoRollActivityEntry[\"observedProfileMatchSource\"] | null,\n }))\n .filter((entry) => entry.id && entry.at)\n .slice(-50)\n : [];\n if (!isRecord(merged.officialCodex.instancesByProfileName)) {\n merged.officialCodex.instancesByProfileName = {};\n } else {\n const nextInstances: Record<string, OfficialCodexManagedInstanceState> = {};\n for (const [key, value] of Object.entries(\n merged.officialCodex.instancesByProfileName,\n )) {\n if (!isRecord(value)) {\n continue;\n }\n const profileName = asString(value.profileName) ?? asString(key);\n if (!profileName) {\n continue;\n }\n nextInstances[profileName] = {\n profileName,\n profileKey: asString(value.profileKey),\n profileHome: asString(value.profileHome),\n appPath: asString(value.appPath),\n bundleId: asString(value.bundleId),\n pid: asNumberOrNull(value.pid),\n appServerPid: asNumberOrNull(value.appServerPid),\n launchedAt: asNumberOrNull(value.launchedAt),\n lastVerifiedAt: asNumberOrNull(value.lastVerifiedAt),\n lastStatus: asString(value.lastStatus),\n lastError: asString(value.lastError),\n };\n }\n merged.officialCodex.instancesByProfileName = nextInstances;\n }\n if (isRecord(merged.officialCodex.pendingRestartDebt)) {\n const debt = merged.officialCodex.pendingRestartDebt;\n const targetProfileName = asString(debt.targetProfileName);\n merged.officialCodex.pendingRestartDebt = targetProfileName\n ? {\n targetProfileName,\n targetProfileKey: asString(debt.targetProfileKey),\n sourceProfileName: asString(debt.sourceProfileName),\n sourceProfileKey: asString(debt.sourceProfileKey),\n decisionId: asString(debt.decisionId),\n attempts: asNumberOrNull(debt.attempts) ?? 0,\n lastReason: asString(debt.lastReason),\n }\n : null;\n } else {\n merged.officialCodex.pendingRestartDebt = null;\n }\n merged.app.lastAppVersion = asString(merged.app.lastAppVersion);\n merged.app.pendingUpdateVersion = asString(merged.app.pendingUpdateVersion);\n merged.app.lastProfileName = asString(merged.app.lastProfileName);\n {\n const allowedAppKeys = new Set(Object.keys(defaults.app));\n for (const key of Object.keys(merged.app as Record<string, unknown>)) {\n if (!allowedAppKeys.has(key)) {\n delete (merged.app as Record<string, unknown>)[key];\n }\n }\n }\n\n merged.license.licenseKey = asString(merged.license.licenseKey);\n merged.license.purchaseEmail = asString(merged.license.purchaseEmail);\n merged.license.lastVerifiedAt = asString(merged.license.lastVerifiedAt);\n merged.license.nextCheckAt = asString(merged.license.nextCheckAt);\n merged.license.lastVerificationError = asString(\n merged.license.lastVerificationError,\n );\n merged.license.signature = asString(merged.license.signature);\n if (\n ![\"inactive\", \"active\", \"grace\", \"error\"].includes(merged.license.status)\n ) {\n merged.license.status = \"inactive\";\n }\n\n if (!Array.isArray(merged.preferences.excludeFolders)) {\n merged.preferences.excludeFolders = [];\n }\n if (typeof merged.preferences.enableTaskCompleteBeep !== \"boolean\") {\n merged.preferences.enableTaskCompleteBeep = true;\n }\n if (typeof merged.preferences.preventSleepDuringTasks !== \"boolean\") {\n merged.preferences.preventSleepDuringTasks = true;\n }\n merged.preferences.chatHistoryScrollbackItems =\n normalizeChatHistoryScrollbackItems(\n merged.preferences.chatHistoryScrollbackItems,\n );\n if (typeof merged.preferences.systemNotificationsEnabled !== \"boolean\") {\n merged.preferences.systemNotificationsEnabled = true;\n }\n if (\n typeof merged.preferences.subagentSystemNotificationsEnabled !== \"boolean\"\n ) {\n merged.preferences.subagentSystemNotificationsEnabled = true;\n }\n if (!Array.isArray(merged.preferences.folderHistory)) {\n merged.preferences.folderHistory = [];\n }\n if (!Array.isArray(merged.preferences.pinnedPaths)) {\n merged.preferences.pinnedPaths = [];\n }\n {\n const allowedPreferenceKeys = new Set(Object.keys(defaults.preferences));\n for (const key of Object.keys(\n merged.preferences as Record<string, unknown>,\n )) {\n if (!allowedPreferenceKeys.has(key)) {\n delete (merged.preferences as Record<string, unknown>)[key];\n }\n }\n }\n\n if (!isRecord(merged.runtimeSettings)) {\n merged.runtimeSettings = {};\n }\n if (!isRecord(merged.ui)) {\n merged.ui = clone(defaults.ui);\n }\n merged.ui.themeMode =\n merged.ui.themeMode === \"light\" || merged.ui.themeMode === \"dark\"\n ? merged.ui.themeMode\n : null;\n if (!isRecord(merged.ui.layout)) {\n merged.ui.layout = clone(defaults.ui.layout);\n }\n if (typeof merged.ui.layout.sidebarCollapsed !== \"boolean\") {\n merged.ui.layout.sidebarCollapsed = null;\n }\n if (!isRecord(merged.ui.profiles)) {\n merged.ui.profiles = clone(defaults.ui.profiles);\n }\n merged.ui.profiles.viewMode =\n merged.ui.profiles.viewMode === \"cards\" ||\n merged.ui.profiles.viewMode === \"compact\"\n ? merged.ui.profiles.viewMode\n : null;\n merged.ui.profiles.sortBy = asString(merged.ui.profiles.sortBy);\n merged.ui.profiles.groupBy = asString(merged.ui.profiles.groupBy);\n merged.ui.profiles.planFilter = asString(merged.ui.profiles.planFilter);\n merged.ui.profiles.healthFilter = asString(merged.ui.profiles.healthFilter);\n merged.ui.profiles.customGroupFilter = asString(\n merged.ui.profiles.customGroupFilter,\n );\n if (typeof merged.ui.profiles.toolbarOpen !== \"boolean\") {\n merged.ui.profiles.toolbarOpen = null;\n }\n if (!isRecord(merged.ui.profiles.collapsedSections)) {\n merged.ui.profiles.collapsedSections = {};\n } else {\n merged.ui.profiles.collapsedSections = Object.fromEntries(\n Object.entries(merged.ui.profiles.collapsedSections).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || typeof value !== \"boolean\") {\n return [];\n }\n return [[normalizedKey, value]];\n },\n ),\n );\n }\n if (!isRecord(merged.ui.onboarding)) {\n merged.ui.onboarding = clone(defaults.ui.onboarding);\n }\n if (typeof merged.ui.onboarding.welcomeCompleted !== \"boolean\") {\n merged.ui.onboarding.welcomeCompleted = false;\n }\n if (!Number.isFinite(merged.ui.onboarding.welcomeCompletedAt)) {\n merged.ui.onboarding.welcomeCompletedAt = null;\n }\n merged.ui.onboarding.welcomeResumeStep =\n merged.ui.onboarding.welcomeResumeStep === 2 ? 2 : null;\n if (!isRecord(merged.ui.onboarding.milestones)) {\n merged.ui.onboarding.milestones = clone(defaults.ui.onboarding.milestones);\n }\n if (typeof merged.ui.onboarding.milestones.firstProfileAdded !== \"boolean\") {\n merged.ui.onboarding.milestones.firstProfileAdded = false;\n }\n if (typeof merged.ui.onboarding.milestones.secondProfileAdded !== \"boolean\") {\n merged.ui.onboarding.milestones.secondProfileAdded = false;\n }\n if (!Number.isFinite(merged.ui.onboarding.sessionCount)) {\n merged.ui.onboarding.sessionCount = 0;\n }\n if (!isRecord(merged.ui.onboarding.nudgeCooldowns)) {\n merged.ui.onboarding.nudgeCooldowns = {};\n } else {\n merged.ui.onboarding.nudgeCooldowns = Object.fromEntries(\n Object.entries(merged.ui.onboarding.nudgeCooldowns).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || !Number.isFinite(value)) {\n return [];\n }\n return [[normalizedKey, Number(value)]];\n },\n ),\n );\n }\n if (!isRecord(merged.ui.onboarding.nudgeDismissCount)) {\n merged.ui.onboarding.nudgeDismissCount = {};\n } else {\n merged.ui.onboarding.nudgeDismissCount = Object.fromEntries(\n Object.entries(merged.ui.onboarding.nudgeDismissCount).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || !Number.isFinite(value)) {\n return [];\n }\n return [[normalizedKey, Number(value)]];\n },\n ),\n );\n }\n if (typeof merged.ui.onboarding.proUnlockedCelebrated !== \"boolean\") {\n merged.ui.onboarding.proUnlockedCelebrated = false;\n }\n if (!isRecord(merged.ui.projectThreadSelections)) {\n merged.ui.projectThreadSelections = {};\n } else {\n merged.ui.projectThreadSelections = Object.fromEntries(\n Object.entries(merged.ui.projectThreadSelections).flatMap(\n ([projectId, threadId]) => {\n const normalizedProjectId = asString(projectId);\n if (!normalizedProjectId) {\n return [];\n }\n const normalizedThreadId =\n typeof threadId === \"string\" && threadId.trim().length > 0\n ? threadId.trim()\n : null;\n return [[normalizedProjectId, normalizedThreadId]];\n },\n ),\n );\n }\n merged.ui.duplicateWarningDismissedKey = asString(\n merged.ui.duplicateWarningDismissedKey,\n );\n if (typeof merged.ui.pendingLicenseActivation !== \"boolean\") {\n merged.ui.pendingLicenseActivation = false;\n }\n {\n const allowedUiKeys = new Set(Object.keys(defaults.ui));\n for (const key of Object.keys(merged.ui as Record<string, unknown>)) {\n if (!allowedUiKeys.has(key)) {\n delete (merged.ui as Record<string, unknown>)[key];\n }\n }\n }\n if (!isRecord(merged.profileDashboard)) {\n merged.profileDashboard = clone(defaults.profileDashboard);\n }\n if (!isRecord(merged.profileDashboard.customGroupsByAccountKey)) {\n merged.profileDashboard.customGroupsByAccountKey = {};\n } else {\n merged.profileDashboard.customGroupsByAccountKey = Object.fromEntries(\n Object.entries(merged.profileDashboard.customGroupsByAccountKey).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n const normalizedValue = asString(value);\n if (!normalizedKey || !normalizedValue) {\n return [];\n }\n return [[normalizedKey, normalizedValue]];\n },\n ),\n );\n }\n {\n const allowedProfileDashboardKeys = new Set(\n Object.keys(defaults.profileDashboard),\n );\n for (const key of Object.keys(\n merged.profileDashboard as Record<string, unknown>,\n )) {\n if (!allowedProfileDashboardKeys.has(key)) {\n delete (merged.profileDashboard as Record<string, unknown>)[key];\n }\n }\n }\n\n const legacyProjectSettingsByPath = isRecord(\n (raw as Record<string, unknown>).projectSettingsByPath,\n )\n ? ((raw as Record<string, unknown>)\n .projectSettingsByPath as AppState[\"workspaceSettingsByPath\"])\n : null;\n if (!isRecord(merged.workspaceSettingsByPath)) {\n merged.workspaceSettingsByPath = {};\n }\n if (legacyProjectSettingsByPath) {\n merged.workspaceSettingsByPath = {\n ...legacyProjectSettingsByPath,\n ...merged.workspaceSettingsByPath,\n };\n }\n delete (merged as Record<string, unknown>).projectSettingsByPath;\n if (!isRecord(merged.conversationCategoriesByCwd)) {\n merged.conversationCategoriesByCwd = {};\n }\n if (!isRecord(merged.conversationCategoryAssignmentsByCwd)) {\n merged.conversationCategoryAssignmentsByCwd = {};\n }\n if (!isRecord(merged.git)) {\n merged.git = clone(defaults.git);\n }\n merged.git.commitMessagePrompt =\n normalizeCommitMessagePrompt(merged.git.commitMessagePrompt) ??\n DEFAULT_COMMIT_MESSAGE_PROMPT;\n {\n const allowedGitKeys = new Set(Object.keys(defaults.git));\n for (const key of Object.keys(merged.git as Record<string, unknown>)) {\n if (!allowedGitKeys.has(key)) {\n delete (merged.git as Record<string, unknown>)[key];\n }\n }\n }\n\n if (!isRecord(merged.skills)) {\n merged.skills = clone(defaults.skills);\n }\n if (!Array.isArray(merged.skills.sources)) {\n merged.skills.sources = [];\n }\n if (!isRecord(merged.skills.installsBySlug)) {\n merged.skills.installsBySlug = {};\n }\n\n if (!isRecord(merged.sync)) {\n merged.sync = clone(defaults.sync);\n }\n merged.sync.lastPushAt = asString(merged.sync.lastPushAt);\n merged.sync.lastPullAt = asString(merged.sync.lastPullAt);\n merged.sync.lastError = asString(merged.sync.lastError);\n merged.sync.remoteUpdatedAt = asString(merged.sync.remoteUpdatedAt);\n\n if (!isRecord(merged.analytics)) {\n merged.analytics = isRecord((merged as { telemetry?: unknown }).telemetry)\n ? clone((merged as unknown as { telemetry: AnalyticsState }).telemetry)\n : clone(defaults.analytics);\n }\n merged.analytics.anonymousId = asString(merged.analytics.anonymousId);\n if (!merged.analytics.anonymousId) {\n const legacyInstallId = asString(\n (merged as { telemetry?: { installId?: unknown } }).telemetry?.installId,\n );\n merged.analytics.anonymousId = legacyInstallId;\n }\n if (typeof merged.analytics.enabled !== \"boolean\") {\n merged.analytics.enabled = true;\n }\n merged.analytics.lastFlushAt = asString(merged.analytics.lastFlushAt);\n merged.analytics.lastError = asString(merged.analytics.lastError);\n\n if (\"telemetry\" in merged) {\n delete (merged as Record<string, unknown>).telemetry;\n }\n\n if (!isRecord(merged.profilesByName)) {\n merged.profilesByName = {};\n }\n\n if (!isRecord(merged.migration)) {\n merged.migration = clone(defaults.migration);\n }\n if (\n ![\"pending\", \"pending_local_storage\", \"complete\"].includes(\n merged.migration.status,\n )\n ) {\n merged.migration.status = \"pending\";\n }\n merged.migration.startedAt = asString(merged.migration.startedAt);\n merged.migration.completedAt = asString(merged.migration.completedAt);\n merged.migration.localStorageImportedAt = asString(\n merged.migration.localStorageImportedAt,\n );\n merged.migration.lastError = asString(merged.migration.lastError);\n\n return merged;\n}\n\nfunction deepMerge<T>(base: T, patch: DeepPartial<T>): T {\n if (!isRecord(base) || !isRecord(patch)) {\n return clone((patch as T) ?? base);\n }\n\n const next: Record<string, unknown> = {\n ...(base as Record<string, unknown>),\n };\n for (const [key, patchValue] of Object.entries(patch)) {\n if (patchValue === undefined) {\n continue;\n }\n\n const currentValue = next[key];\n if (Array.isArray(patchValue)) {\n next[key] = clone(patchValue);\n continue;\n }\n\n if (isRecord(currentValue) && isRecord(patchValue)) {\n next[key] = deepMerge(\n currentValue,\n patchValue as DeepPartial<typeof currentValue>,\n );\n continue;\n }\n\n next[key] = clone(patchValue);\n }\n\n return next as T;\n}\n\nasync function readLegacyAppStateFromDisk(): Promise<AppState | null> {\n const filePath = resolveLegacyAppStatePath();\n try {\n const raw = await fs.readFile(filePath, \"utf8\");\n return normalizeAppState(JSON.parse(raw) as unknown);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n}\n\nasync function readAppStateFromStorage(): Promise<AppState | null> {\n return readDocument(\n resolveStorageDbPath(),\n APP_STATE_DOCUMENT,\n normalizeAppState,\n );\n}\n\nasync function writeAppStateToStorage(state: AppState): Promise<AppState> {\n return writeDocument(\n resolveStorageDbPath(),\n APP_STATE_DOCUMENT,\n normalizeAppState(state),\n );\n}\n\nasync function ensureInitialized(): Promise<AppState> {\n if (appStateCache) {\n return appStateCache;\n }\n\n const loaded =\n (await readAppStateFromStorage()) ?? (await readLegacyAppStateFromDisk());\n const normalized = loaded ?? normalizeAppState(null);\n appStateCache = await writeAppStateToStorage(normalized);\n return clone(appStateCache);\n}\n\nasync function withWriteLock<T>(task: () => Promise<T>): Promise<T> {\n if (writeLockContext.getStore()) {\n return task();\n }\n\n const previous = writeLock;\n let release: (() => void) | undefined;\n writeLock = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n try {\n return await writeLockContext.run(true, task);\n } finally {\n if (release) {\n release();\n }\n }\n}\n\nexport async function initializeAppState(\n userDataDir: string,\n): Promise<AppState> {\n configuredUserDataDir = userDataDir;\n const state = await ensureInitialized();\n return clone(state);\n}\n\nexport async function getAppState(): Promise<AppState> {\n const state = await ensureInitialized();\n return clone(state);\n}\n\nexport async function refreshAppStateCache(): Promise<AppState> {\n const current =\n (await readAppStateFromStorage()) ?? (await ensureInitialized());\n appStateCache = current;\n return clone(current);\n}\n\nexport async function updateAppState(\n transform: AppStateUpdateTransform,\n options: AppStateUpdateOptions = {},\n): Promise<AppState> {\n const mode = options.mode ?? \"patch\";\n const allowBeforeMigrationComplete =\n options.allowBeforeMigrationComplete === true;\n\n return withWriteLock(async () => {\n const nextState = await updateDocument<AppState>({\n dbPath: resolveStorageDbPath(),\n namespace: APP_STATE_DOCUMENT,\n normalize: normalizeAppState,\n fallback: createDefaultAppState,\n transform: (current) => {\n if (\n !allowBeforeMigrationComplete &&\n current.migration.status !== \"complete\"\n ) {\n throw new Error(\"Storage migration is not complete yet.\");\n }\n\n const transformed = transform(clone(current));\n return mode === \"replace\"\n ? normalizeAppState(transformed)\n : normalizeAppState(deepMerge(current, transformed as AppStatePatch));\n },\n });\n appStateCache = nextState;\n return clone(nextState);\n });\n}\n\nexport async function patchAppState(patch: AppStatePatch): Promise<AppState> {\n return updateAppState(() => patch, {\n mode: \"patch\",\n allowBeforeMigrationComplete: false,\n });\n}\n","export const CHAT_SCROLLBACK_DEFAULT = 200;\nexport const CHAT_SCROLLBACK_MIN = 50;\nexport const CHAT_SCROLLBACK_MAX = 5000;\nexport const CHAT_SCROLLBACK_PRESETS = [200, 500, 1000, 2000, 5000] as const;\n\nexport function clampChatScrollbackItems(value: number): number {\n if (!Number.isFinite(value)) {\n return CHAT_SCROLLBACK_DEFAULT;\n }\n const rounded = Math.round(value);\n return Math.max(CHAT_SCROLLBACK_MIN, Math.min(CHAT_SCROLLBACK_MAX, rounded));\n}\n\nexport function isChatScrollbackPreset(value: number): boolean {\n return (CHAT_SCROLLBACK_PRESETS as readonly number[]).includes(value);\n}\n\nexport function normalizeChatHistoryScrollbackItems(value: unknown): number | null {\n if (value === null) {\n return null;\n }\n\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return clampChatScrollbackItems(value);\n }\n\n if (typeof value === \"string\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return clampChatScrollbackItems(parsed);\n }\n }\n\n return CHAT_SCROLLBACK_DEFAULT;\n}\n","export const DEFAULT_COMMIT_MESSAGE_PROMPT = `Generate a concise git commit message for the following changes. Follow conventional commit format (e.g., feat:, fix:, refactor:, docs:, etc.). Keep the summary line under 72 characters. Only output the commit message, nothing else.\n\nChanges:\n{diff}`;\n\nconst DIFF_PLACEHOLDER = \"{diff}\";\n\nfunction normalizeLineEndings(value: string): string {\n return value.replace(/\\r\\n/g, \"\\n\");\n}\n\nexport function normalizeCommitMessagePrompt(value: string | null | undefined): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = normalizeLineEndings(value).trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function buildCommitMessagePrompt(\n diff: string,\n template?: string | null,\n): string {\n const normalizedDiff = normalizeLineEndings(diff).trim();\n if (!normalizedDiff) {\n return \"\";\n }\n\n const normalizedTemplate = normalizeCommitMessagePrompt(template);\n const base = normalizedTemplate ?? DEFAULT_COMMIT_MESSAGE_PROMPT;\n\n if (base.includes(DIFF_PLACEHOLDER)) {\n return base.split(DIFF_PLACEHOLDER).join(normalizedDiff);\n }\n\n return `${base}\\n\\nChanges:\\n${normalizedDiff}`;\n}\n","export type { AutoRollSettings } from \"./auto-roll-types.ts\";\nimport type { AutoRollSettings } from \"./auto-roll-types.ts\";\n\nexport const DEFAULT_AUTO_ROLL_ENABLED = false;\nexport const DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD = 15;\nexport const DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD = 5;\nexport const DEFAULT_RESTART_OFFICIAL_CODEX_ON_AUTO_ROLL = false;\nexport const DEFAULT_LAUNCH_OFFICIAL_CODEX_WHEN_CLOSED_ON_AUTO_ROLL = false;\nexport const DEFAULT_AUTO_ROLL_PRIORITY_ORDER: string[] = [];\nexport const DEFAULT_LOW_REMAINING_NOTIFICATION_ENABLED = false;\nexport const DEFAULT_LOW_REMAINING_NOTIFICATION_THRESHOLD = 1;\nexport const AUTO_ROLL_SWITCH_REMAINING_MIN = 0;\nexport const AUTO_ROLL_SWITCH_REMAINING_MAX = 50;\nexport const AUTO_ROLL_REARM_REMAINING_MAX = 100;\nexport const LOW_REMAINING_NOTIFICATION_MIN = 1;\nexport const LOW_REMAINING_NOTIFICATION_MAX = 50;\n\ntype AutoRollSettingsInput = Partial<AutoRollSettings> & {\n warningThreshold?: unknown;\n switchThreshold?: unknown;\n};\n\nfunction clampNumber(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\nfunction resolveFiniteNumber(value: unknown, fallback: number): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction legacyUsedThresholdToRemaining(value: unknown, fallbackUsed: number): number {\n const used = clampNumber(resolveFiniteNumber(value, fallbackUsed), 0, 100);\n return 100 - used;\n}\n\nexport function sanitizeAutoRollSwitchRemainingThreshold(value: unknown): number {\n const numeric = resolveFiniteNumber(\n value,\n DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD,\n );\n return clampNumber(\n numeric,\n AUTO_ROLL_SWITCH_REMAINING_MIN,\n AUTO_ROLL_SWITCH_REMAINING_MAX,\n );\n}\n\nexport function sanitizeAutoRollRearmRemainingThreshold(\n value: unknown,\n switchRemainingThreshold: number,\n): number {\n const sanitizedSwitch = sanitizeAutoRollSwitchRemainingThreshold(\n switchRemainingThreshold,\n );\n const numeric = resolveFiniteNumber(\n value,\n DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD,\n );\n return clampNumber(\n numeric,\n sanitizedSwitch + 1,\n AUTO_ROLL_REARM_REMAINING_MAX,\n );\n}\n\nexport function sanitizeAutoRollThresholds(\n rearmRemainingThreshold: unknown,\n switchRemainingThreshold: unknown,\n): Pick<AutoRollSettings, \"rearmRemainingThreshold\" | \"switchRemainingThreshold\"> {\n const sanitizedSwitch = sanitizeAutoRollSwitchRemainingThreshold(\n switchRemainingThreshold,\n );\n const sanitizedRearm = sanitizeAutoRollRearmRemainingThreshold(\n rearmRemainingThreshold,\n sanitizedSwitch,\n );\n return {\n rearmRemainingThreshold: sanitizedRearm,\n switchRemainingThreshold: sanitizedSwitch,\n };\n}\n\nexport function sanitizeAutoRollPriorityOrder(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [...DEFAULT_AUTO_ROLL_PRIORITY_ORDER];\n }\n\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const item of value) {\n if (typeof item !== \"string\") {\n continue;\n }\n const trimmed = item.trim();\n if (!trimmed || seen.has(trimmed)) {\n continue;\n }\n seen.add(trimmed);\n normalized.push(trimmed);\n }\n return normalized;\n}\n\nexport function sanitizeLowRemainingNotificationThreshold(value: number): number {\n const numeric = resolveFiniteNumber(value, DEFAULT_LOW_REMAINING_NOTIFICATION_THRESHOLD);\n return clampNumber(\n numeric,\n LOW_REMAINING_NOTIFICATION_MIN,\n LOW_REMAINING_NOTIFICATION_MAX,\n );\n}\n\nexport function normalizeAutoRollSettings(\n raw?: AutoRollSettingsInput | null,\n): AutoRollSettings {\n const enabled = typeof raw?.enabled === \"boolean\" ? raw.enabled : DEFAULT_AUTO_ROLL_ENABLED;\n const rawSwitchRemaining =\n typeof raw?.switchRemainingThreshold === \"number\"\n ? raw.switchRemainingThreshold\n : legacyUsedThresholdToRemaining(raw?.switchThreshold, 95);\n const rawRearmRemaining =\n typeof raw?.rearmRemainingThreshold === \"number\"\n ? raw.rearmRemainingThreshold\n : legacyUsedThresholdToRemaining(raw?.warningThreshold, 85);\n\n const {\n rearmRemainingThreshold: normalizedRearm,\n switchRemainingThreshold: normalizedSwitch,\n } = sanitizeAutoRollThresholds(rawRearmRemaining, rawSwitchRemaining);\n\n return {\n enabled,\n rearmRemainingThreshold: normalizedRearm,\n switchRemainingThreshold: normalizedSwitch,\n restartOfficialCodexOnAutoRoll:\n raw?.restartOfficialCodexOnAutoRoll === true\n ? true\n : DEFAULT_RESTART_OFFICIAL_CODEX_ON_AUTO_ROLL,\n launchOfficialCodexWhenClosedOnAutoRoll:\n raw?.launchOfficialCodexWhenClosedOnAutoRoll === true\n ? true\n : DEFAULT_LAUNCH_OFFICIAL_CODEX_WHEN_CLOSED_ON_AUTO_ROLL,\n priorityOrder: sanitizeAutoRollPriorityOrder(raw?.priorityOrder),\n lowRemainingNotificationEnabled:\n raw?.lowRemainingNotificationEnabled === true\n ? true\n : DEFAULT_LOW_REMAINING_NOTIFICATION_ENABLED,\n lowRemainingNotificationThreshold: sanitizeLowRemainingNotificationThreshold(\n typeof raw?.lowRemainingNotificationThreshold === \"number\"\n ? raw.lowRemainingNotificationThreshold\n : Number.NaN,\n ),\n };\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nconst APP_STORAGE_TABLE = \"app_storage_documents\";\nconst APP_STORAGE_DB_DIR = \"t3-projects\";\nconst APP_STORAGE_DB_NAME = \"state.sqlite\";\nconst SQLITE_BUSY_TIMEOUT_MS = 5_000;\nconst SQLITE_BUSY_MAX_ATTEMPTS = 3;\nconst SQLITE_BUSY_RETRY_DELAY_MS = 100;\nconst writeQueueByDbPath = new Map<string, Promise<void>>();\n\ntype StatementLike = {\n get: (...params: any[]) => any;\n all: (...params: any[]) => any[];\n run: (...params: any[]) => any;\n finalize?: () => void;\n};\n\ntype DatabaseLike = {\n exec: (sql: string) => unknown;\n prepare: (sql: string) => StatementLike;\n close: () => unknown;\n};\n\nconst initializedDbPaths = new Set<string>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction safeParseJson<T>(raw: string | null | undefined): T | null {\n if (typeof raw !== \"string\" || raw.trim().length === 0) {\n return null;\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isSqliteBusyError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n\n const sqliteError = error as {\n code?: unknown;\n errno?: unknown;\n message?: unknown;\n };\n const message =\n typeof sqliteError.message === \"string\" ? sqliteError.message.toLowerCase() : \"\";\n\n return sqliteError.code === \"SQLITE_BUSY\" ||\n sqliteError.errno === 5 ||\n message.includes(\"sqlite_busy\") ||\n message.includes(\"database is locked\");\n}\n\nfunction beginImmediate(db: DatabaseLike): void {\n db.exec(\"BEGIN IMMEDIATE\");\n}\n\nfunction commit(db: DatabaseLike): void {\n db.exec(\"COMMIT\");\n}\n\nfunction rollback(db: DatabaseLike): void {\n try {\n db.exec(\"ROLLBACK\");\n } catch {\n // Ignore rollback failures after a failed transaction.\n }\n}\n\nfunction useStatement<T>(\n db: DatabaseLike,\n sql: string,\n task: (statement: StatementLike) => T,\n): T {\n const statement = db.prepare(sql);\n try {\n return task(statement);\n } finally {\n statement.finalize?.();\n }\n}\n\nasync function withWriteQueue<T>(dbPath: string, task: () => Promise<T>): Promise<T> {\n const previous = writeQueueByDbPath.get(dbPath) ?? Promise.resolve();\n let release: (() => void) | undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n writeQueueByDbPath.set(dbPath, current);\n\n await previous;\n try {\n return await task();\n } finally {\n release?.();\n if (writeQueueByDbPath.get(dbPath) === current) {\n writeQueueByDbPath.delete(dbPath);\n }\n }\n}\n\nfunction applyConnectionPragmas(db: DatabaseLike): void {\n // These PRAGMAs are connection-scoped, so every opened handle must set them.\n db.exec(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS};`);\n db.exec(\"PRAGMA journal_mode = WAL;\");\n db.exec(\"PRAGMA foreign_keys = ON;\");\n}\n\nfunction ensureSchema(db: DatabaseLike, dbPath: string): void {\n if (initializedDbPaths.has(dbPath)) {\n return;\n }\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS ${APP_STORAGE_TABLE} (\n namespace TEXT PRIMARY KEY,\n value_json TEXT NOT NULL,\n updated_at TEXT NOT NULL\n )\n `);\n initializedDbPaths.add(dbPath);\n}\n\nasync function openDatabase(dbPath: string): Promise<DatabaseLike> {\n await fs.mkdir(path.dirname(dbPath), { recursive: true });\n\n if (process.versions.bun !== undefined) {\n const sqlite = await (Function(\"return import('bun:sqlite')\")() as Promise<any>);\n const database = new sqlite.Database(dbPath);\n return {\n exec: database.exec.bind(database),\n prepare: database.prepare.bind(database),\n close: database.close.bind(database),\n };\n }\n\n // Keep the builtin import opaque so the CLI CJS bundle does not rewrite it to bare \"sqlite\".\n const sqlite = await (Function(\"return import('node:sqlite')\")() as Promise<any>);\n const database = new sqlite.DatabaseSync(dbPath);\n return {\n exec: database.exec.bind(database),\n prepare: database.prepare.bind(database),\n close: database.close.bind(database),\n };\n}\n\nasync function withDatabase<T>(dbPath: string, task: (db: DatabaseLike) => T): Promise<T> {\n for (let attempt = 1; attempt <= SQLITE_BUSY_MAX_ATTEMPTS; attempt += 1) {\n const db = await openDatabase(dbPath);\n try {\n applyConnectionPragmas(db);\n ensureSchema(db, dbPath);\n return task(db);\n } catch (error) {\n if (!isSqliteBusyError(error) || attempt >= SQLITE_BUSY_MAX_ATTEMPTS) {\n throw error;\n }\n } finally {\n db.close();\n }\n\n await sleep(SQLITE_BUSY_RETRY_DELAY_MS * attempt);\n }\n\n throw new Error(\"App storage database remained busy after retrying.\");\n}\n\nexport function resolveAppStorageDbPath(userDataDir: string): string {\n return path.join(userDataDir, APP_STORAGE_DB_DIR, APP_STORAGE_DB_NAME);\n}\n\nexport async function readDocument<T>(\n dbPath: string,\n namespace: string,\n normalize: (value: unknown) => T,\n): Promise<T | null> {\n return withDatabase(dbPath, (db) => {\n const row = useStatement(\n db,\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n (statement) => statement.get(namespace),\n );\n const parsed = isRecord(row) ? safeParseJson<T>(row.valueJson as string | null) : null;\n if (parsed === null) {\n return null;\n }\n return normalize(parsed);\n });\n}\n\nexport async function writeDocument<T>(\n dbPath: string,\n namespace: string,\n value: T,\n): Promise<T> {\n return withWriteQueue(\n dbPath,\n async () =>\n withDatabase(dbPath, (db) => {\n const normalizedValue = clone(value);\n beginImmediate(db);\n try {\n useStatement(\n db,\n `\n INSERT INTO ${APP_STORAGE_TABLE} (namespace, value_json, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(namespace)\n DO UPDATE SET\n value_json = excluded.value_json,\n updated_at = excluded.updated_at\n `,\n (statement) =>\n statement.run(namespace, JSON.stringify(normalizedValue), new Date().toISOString()),\n );\n commit(db);\n return normalizedValue;\n } catch (error) {\n rollback(db);\n throw error;\n }\n }),\n );\n}\n\nexport async function updateDocument<T>(input: {\n dbPath: string;\n namespace: string;\n normalize: (value: unknown) => T;\n fallback: () => T;\n transform: (current: T) => T;\n}): Promise<T> {\n return withWriteQueue(\n input.dbPath,\n async () =>\n withDatabase(input.dbPath, (db) => {\n beginImmediate(db);\n try {\n const row = useStatement(\n db,\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n (statement) => statement.get(input.namespace),\n );\n const current = isRecord(row)\n ? input.normalize(\n safeParseJson(row.valueJson as string | null) ?? input.fallback(),\n )\n : input.fallback();\n const next = input.normalize(input.transform(clone(current)));\n useStatement(\n db,\n `\n INSERT INTO ${APP_STORAGE_TABLE} (namespace, value_json, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(namespace)\n DO UPDATE SET\n value_json = excluded.value_json,\n updated_at = excluded.updated_at\n `,\n (statement) =>\n statement.run(input.namespace, JSON.stringify(next), new Date().toISOString()),\n );\n commit(db);\n return clone(next);\n } catch (error) {\n rollback(db);\n throw error;\n }\n }),\n );\n}\n\nexport async function deleteDocument(dbPath: string, namespace: string): Promise<void> {\n await withWriteQueue(\n dbPath,\n async () =>\n withDatabase(dbPath, (db) => {\n beginImmediate(db);\n try {\n useStatement(\n db,\n `DELETE FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n (statement) => statement.run(namespace),\n );\n commit(db);\n } catch (error) {\n rollback(db);\n throw error;\n }\n }),\n );\n}\n","import {\n getAppState,\n updateAppState,\n} from \"./state\";\n\ntype JsonRecord = Record<string, unknown>;\nconst CUSTOMER_DEFAULTS_MIGRATION_KEY = \"customerRateLimitBackgroundDefaultsApplied\";\n\nconst LEGACY_APP_SETTINGS_KEYS = new Set([\n \"backendMode\",\n \"theme\",\n \"commitMessageModelId\",\n \"usageShowRemaining\",\n \"remoteBackendProvider\",\n \"remoteBackendHost\",\n \"remoteBackendToken\",\n \"remoteBackends\",\n \"activeRemoteBackendId\",\n \"keepDaemonRunningAfterAppClose\",\n]);\n\nfunction asRecord(value: unknown): JsonRecord {\n return value && typeof value === \"object\" ? (value as JsonRecord) : {};\n}\n\nfunction stripLegacyAppSettingsKeys(settings: JsonRecord): JsonRecord {\n let changed = false;\n const next: JsonRecord = { ...settings };\n for (const key of LEGACY_APP_SETTINGS_KEYS) {\n if (!(key in next)) {\n continue;\n }\n changed = true;\n delete next[key];\n }\n return changed ? next : settings;\n}\n\nfunction withCurrentRuntimeDefaults(\n settings: JsonRecord,\n options: { migrateLegacyDefaults: boolean },\n): { settings: JsonRecord; changed: boolean } {\n let changed = false;\n const next: JsonRecord = { ...settings };\n const migrationApplied = next[CUSTOMER_DEFAULTS_MIGRATION_KEY] === true;\n\n if (options.migrateLegacyDefaults && !migrationApplied) {\n if (!(\"keepAppRunningAfterWindowClose\" in next)) {\n next.keepAppRunningAfterWindowClose = true;\n changed = true;\n }\n } else if (!(\"keepAppRunningAfterWindowClose\" in next)) {\n next.keepAppRunningAfterWindowClose = true;\n changed = true;\n }\n\n if (\n next.rateLimitPercentMode !== \"remaining\" &&\n next.rateLimitPercentMode !== \"used\"\n ) {\n next.rateLimitPercentMode = \"remaining\";\n changed = true;\n }\n\n if (!migrationApplied) {\n next[CUSTOMER_DEFAULTS_MIGRATION_KEY] = true;\n changed = true;\n }\n\n return { settings: changed ? next : settings, changed };\n}\n\nexport async function readAppSettings(): Promise<JsonRecord> {\n const appState = await getAppState();\n const stripped = stripLegacyAppSettingsKeys(asRecord(appState.runtimeSettings));\n const next = withCurrentRuntimeDefaults(stripped, {\n migrateLegacyDefaults: true,\n });\n if (next.changed) {\n await updateAppState(\n (current) => ({\n ...current,\n runtimeSettings: next.settings,\n }),\n {\n mode: \"replace\",\n allowBeforeMigrationComplete: false,\n },\n );\n }\n return next.settings;\n}\n\nexport async function writeAppSettings(\n settings: JsonRecord,\n onUpdated?: (settings: JsonRecord) => void | Promise<void>,\n): Promise<JsonRecord> {\n const nextSettings = withCurrentRuntimeDefaults(\n stripLegacyAppSettingsKeys(asRecord(settings)),\n {\n migrateLegacyDefaults: false,\n },\n ).settings;\n await updateAppState(\n (current) => ({\n ...current,\n runtimeSettings: nextSettings,\n }),\n {\n mode: \"replace\",\n allowBeforeMigrationComplete: false,\n },\n );\n if (onUpdated) {\n try {\n await onUpdated(nextSettings);\n } catch (error) {\n console.warn(\"Failed to apply runtime settings update hook:\", error);\n }\n }\n return nextSettings;\n}\n","import crypto from 'node:crypto';\nimport { persistLicense, getStoredLicense, type StoredLicense } from '@codexuse/runtime-codex/codex/settings';\nimport { getLicenseSecret } from '@codexuse/runtime-profiles/license/secret';\nimport { getActiveOffer, buildCheckoutUrl } from '@codexuse/contracts/license/offer-config';\nimport type { LicenseState, LicenseStatus, LicenseTier } from '@codexuse/contracts/license/types';\n\nconst offer = getActiveOffer();\nconst PRODUCT_PERMALINK = offer.productPermalink;\nconst PRODUCT_ID = '3_CcyVEXt2FOMiEpPx8xzw==';\nconst PRODUCT_URL = buildCheckoutUrl(offer);\nconst CHECKOUT_URL = buildCheckoutUrl(offer, { directCheckout: true });\nconst LICENSE_PRICE_DISPLAY = offer.isActive ? offer.salePriceDisplay : offer.basePriceDisplay;\nconst BASE_PRICE_DISPLAY = offer.basePriceDisplay;\nconst PROMO_CODE = offer.couponCode;\nconst PROMO_PERCENT = offer.discountPercent;\nconst PROMO_ACTIVE = offer.isActive;\nconst LICENSE_MAX_USES = 5;\nconst FREE_PROFILE_LIMIT = 2;\nconst LICENSE_REFRESH_INTERVAL_MS = 5 * 60 * 1000;\nconst MAX_NEXT_CHECK_MS = 60 * 60 * 1000;\nconst GRACE_MAX_AGE_MS = 3 * 60 * 60 * 1000;\n\ninterface GumroadLicenseResponse {\n success: boolean;\n message?: string;\n uses?: number;\n purchase?: {\n id: string;\n email: string;\n product_id?: string;\n product_permalink?: string;\n refunded?: boolean;\n chargebacked?: boolean;\n subscription_cancelled?: boolean;\n subscription_failed?: boolean;\n license_disabled?: boolean;\n variants?: string;\n };\n license_disabled?: boolean;\n}\n\ntype VerificationMode = 'activation' | 'refresh';\n\nclass LicenseError extends Error {\n readonly code: 'network' | 'invalid' | 'revoked';\n\n constructor(message: string, code: 'network' | 'invalid' | 'revoked') {\n super(message);\n this.name = 'LicenseError';\n this.code = code;\n }\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nfunction maskLicenseKey(key: string | null | undefined): string | null {\n if (!key || typeof key !== 'string') {\n return null;\n }\n\n const trimmed = key.trim();\n if (trimmed.length <= 4) {\n return '••••';\n }\n\n const visible = trimmed.slice(-4);\n return `••••${visible}`;\n}\n\nfunction resolveProfilesRemaining(limit: number | null, currentProfiles: number): number | null {\n if (typeof limit !== 'number') {\n return null;\n }\n return Math.max(0, limit - currentProfiles);\n}\n\nfunction determineTierFromStored(stored: StoredLicense | null): LicenseTier {\n if (!stored || !stored.licenseKey) {\n return 'free';\n }\n\n if (stored.status === 'inactive') {\n return 'free';\n }\n\n return 'pro';\n}\n\nfunction licenseSignaturePayload(license: StoredLicense): string {\n const payload = {\n licenseKey: license.licenseKey ?? null,\n purchaseEmail: license.purchaseEmail ?? null,\n lastVerifiedAt: license.lastVerifiedAt ?? null,\n nextCheckAt: license.nextCheckAt ?? null,\n lastVerificationError: license.lastVerificationError ?? null,\n status: license.status ?? null,\n };\n return JSON.stringify(payload);\n}\n\nfunction signLicense(license: StoredLicense, secret: string): string {\n return crypto.createHmac('sha256', secret).update(licenseSignaturePayload(license)).digest('hex');\n}\n\nfunction withSignature(license: StoredLicense, secret: string): StoredLicense {\n return {\n ...license,\n signature: signLicense(license, secret),\n };\n}\n\nfunction isSignatureValid(license: StoredLicense, secret: string): boolean {\n if (!license.signature) {\n return false;\n }\n const expected = signLicense(license, secret);\n return expected === license.signature;\n}\n\nasync function requestGumroadVerify(licenseKey: string, mode: VerificationMode): Promise<GumroadLicenseResponse> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 10_000);\n\n try {\n const body = new URLSearchParams({\n product_permalink: PRODUCT_PERMALINK,\n product_id: PRODUCT_ID,\n license_key: licenseKey,\n increment_uses_count: mode === 'activation' ? 'true' : 'false',\n });\n\n const response = await fetch('https://api.gumroad.com/v2/licenses/verify', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body,\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => null);\n const message = errorText\n ? `License verification failed (${response.status}): ${errorText}`\n : `License verification failed (${response.status}).`;\n throw new LicenseError(message, 'network');\n }\n\n const json = (await response.json()) as GumroadLicenseResponse;\n return json;\n } catch (error) {\n if (error instanceof LicenseError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === 'AbortError') {\n throw new LicenseError('License verification timed out.', 'network');\n }\n\n throw new LicenseError(\n error instanceof Error ? error.message : 'Unable to reach Gumroad for license verification.',\n 'network',\n );\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction normalizeVerificationResult(response: GumroadLicenseResponse): { email: string | null } {\n if (!response.success) {\n const message = response.message ?? 'License key is invalid.';\n throw new LicenseError(message, 'invalid');\n }\n\n if (!response.purchase) {\n throw new LicenseError('License verification response was incomplete.', 'network');\n }\n\n if (response.purchase.chargebacked || response.purchase.refunded || response.license_disabled) {\n throw new LicenseError('This license has been revoked or refunded.', 'revoked');\n }\n\n if (response.purchase.subscription_cancelled || response.purchase.subscription_failed) {\n throw new LicenseError('This license subscription is no longer active.', 'revoked');\n }\n\n const email = response.purchase.email ?? null;\n return { email };\n}\n\nfunction ensureWithinUseLimit(response: GumroadLicenseResponse): void {\n if (!response.success) {\n return;\n }\n\n if (typeof response.uses !== 'number') {\n return;\n }\n\n if (response.uses > LICENSE_MAX_USES) {\n throw new LicenseError(\n `This license has reached the activation limit (${LICENSE_MAX_USES}). Contact support to move it to another device.`,\n 'invalid',\n );\n }\n}\n\nfunction toLicenseStatus(stored: StoredLicense | null, overrides: Partial<LicenseStatus> = {}): LicenseStatus {\n const tier = determineTierFromStored(stored);\n const isPro = tier === 'pro';\n\n const state: LicenseState =\n stored && stored.status\n ? stored.status\n : isPro\n ? 'active'\n : 'inactive';\n\n const base: LicenseStatus = {\n tier,\n state,\n isPro,\n profileLimit: isPro ? null : FREE_PROFILE_LIMIT,\n profilesRemaining: null,\n purchaseEmail: stored?.purchaseEmail ?? null,\n maskedLicenseKey: maskLicenseKey(stored?.licenseKey),\n lastVerifiedAt: stored?.lastVerifiedAt ?? null,\n nextCheckAt: stored?.nextCheckAt ?? null,\n message: null,\n error: stored?.lastVerificationError ?? null,\n productUrl: PRODUCT_URL,\n checkoutUrl: CHECKOUT_URL,\n productId: PRODUCT_ID,\n productPermalink: PRODUCT_PERMALINK,\n priceDisplay: LICENSE_PRICE_DISPLAY,\n basePriceDisplay: BASE_PRICE_DISPLAY,\n promoCode: PROMO_ACTIVE ? PROMO_CODE : null,\n promoPercent: PROMO_ACTIVE ? PROMO_PERCENT : null,\n maxDevices: LICENSE_MAX_USES,\n };\n\n return { ...base, ...overrides };\n}\n\nfunction parseTimestamp(value: string | null | undefined): number | null {\n if (typeof value !== 'string' || value.trim() === '') {\n return null;\n }\n\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\nclass LicenseService {\n private refreshPromise: Promise<void> | null = null;\n private verificationPromise: Promise<LicenseStatus> | null = null;\n\n async getCachedStatus(): Promise<LicenseStatus> {\n return this.getStatus({ allowStale: true, refreshInBackground: true });\n }\n\n async getStatus(options: {\n forceRefresh?: boolean;\n allowStale?: boolean;\n refreshInBackground?: boolean;\n } = {}): Promise<LicenseStatus> {\n const forceRefresh = Boolean(options.forceRefresh);\n const allowStale = Boolean(options.allowStale);\n const refreshInBackground = Boolean(options.refreshInBackground);\n const secret = await getLicenseSecret();\n const stored = await getStoredLicense();\n\n if (!stored?.licenseKey) {\n return toLicenseStatus(null);\n }\n\n const now = Date.now();\n const nextCheckTs = parseTimestamp(stored.nextCheckAt);\n const lastVerifiedTs = parseTimestamp(stored.lastVerifiedAt);\n const graceStale =\n (stored.status === 'grace' || stored.status === 'error') &&\n (lastVerifiedTs === null || lastVerifiedTs + GRACE_MAX_AGE_MS < now);\n\n let workingStored: StoredLicense = { ...stored };\n const signatureValid = isSignatureValid(workingStored, secret);\n\n let cappedNextCheckTs = nextCheckTs;\n\n if (nextCheckTs !== null && nextCheckTs > now + MAX_NEXT_CHECK_MS) {\n cappedNextCheckTs = now;\n const updated = {\n ...workingStored,\n nextCheckAt: new Date(cappedNextCheckTs).toISOString(),\n };\n const signed = withSignature(updated, secret);\n workingStored = signed;\n await persistLicense(signed);\n }\n\n const tampered = Boolean(workingStored.licenseKey) && !signatureValid;\n\n const cached = tampered\n ? toLicenseStatus(null, {\n state: 'verifying',\n message: 'License data changed, rechecking.',\n error: 'Untrusted license data.',\n })\n : toLicenseStatus(workingStored);\n\n const shouldRefresh =\n forceRefresh || graceStale || tampered || cappedNextCheckTs === null || cappedNextCheckTs <= now;\n\n if (!shouldRefresh || allowStale) {\n // Startup/bootstrap callers should render from durable cached state and\n // let the online recheck happen off the critical path.\n if (allowStale && shouldRefresh && refreshInBackground) {\n this.refreshStatusInBackground({ force: forceRefresh });\n }\n return cached;\n }\n\n if (this.verificationPromise && !forceRefresh) {\n return this.verificationPromise;\n }\n\n const verify = async (): Promise<LicenseStatus> => {\n try {\n const result = await requestGumroadVerify(workingStored.licenseKey!, 'refresh');\n ensureWithinUseLimit(result);\n const normalized = normalizeVerificationResult(result);\n const updated: StoredLicense = {\n licenseKey: workingStored.licenseKey,\n purchaseEmail: normalized.email,\n lastVerifiedAt: nowIso(),\n nextCheckAt: new Date(Date.now() + LICENSE_REFRESH_INTERVAL_MS).toISOString(),\n status: 'active',\n lastVerificationError: null,\n };\n\n const signed = withSignature(updated, secret);\n\n await persistLicense(signed);\n return toLicenseStatus(signed);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'License verification failed.';\n\n if (error instanceof LicenseError && error.code === 'network') {\n const fallbackStored: StoredLicense = withSignature(\n {\n ...workingStored,\n status: tampered ? 'inactive' : workingStored.status === 'inactive' ? 'inactive' : 'grace',\n lastVerificationError: message,\n nextCheckAt: new Date(Date.now() + LICENSE_REFRESH_INTERVAL_MS).toISOString(),\n },\n secret,\n );\n await persistLicense(fallbackStored);\n const fallback = toLicenseStatus(fallbackStored, {\n state: fallbackStored.status ?? 'grace',\n error: message,\n });\n return fallback;\n }\n\n const fallbackStored: StoredLicense = withSignature({\n licenseKey: workingStored.licenseKey,\n purchaseEmail: workingStored.purchaseEmail ?? null,\n lastVerifiedAt: workingStored.lastVerifiedAt ?? null,\n nextCheckAt: null,\n status: 'inactive',\n lastVerificationError: message,\n }, secret);\n await persistLicense(fallbackStored);\n return toLicenseStatus(fallbackStored, { error: message });\n }\n };\n\n this.verificationPromise = verify();\n try {\n return await this.verificationPromise;\n } finally {\n this.verificationPromise = null;\n }\n }\n\n async activate(licenseKey: string): Promise<LicenseStatus> {\n const trimmed = licenseKey.trim();\n if (!trimmed) {\n throw new Error('License key is required.');\n }\n\n const secret = await getLicenseSecret();\n const digest = crypto.createHash('sha256').update(trimmed).digest('hex');\n\n const result = await requestGumroadVerify(trimmed, 'activation');\n ensureWithinUseLimit(result);\n const normalized = normalizeVerificationResult(result);\n const stored: StoredLicense = {\n licenseKey: trimmed,\n purchaseEmail: normalized.email,\n lastVerifiedAt: nowIso(),\n nextCheckAt: new Date(Date.now() + LICENSE_REFRESH_INTERVAL_MS).toISOString(),\n status: 'active',\n lastVerificationError: null,\n };\n\n const signed = withSignature(stored, secret);\n\n await persistLicense(signed);\n return toLicenseStatus(signed, {\n message: `License verified (${digest.slice(0, 8)}).`,\n });\n }\n\n applyProfileCount(status: LicenseStatus, profileCount: number): LicenseStatus {\n const profilesRemaining = resolveProfilesRemaining(status.profileLimit, profileCount);\n return {\n ...status,\n profilesRemaining,\n };\n }\n\n refreshStatusInBackground(options: { force?: boolean } = {}): void {\n if (this.refreshPromise) {\n return;\n }\n\n const forceRefresh = Boolean(options.force);\n this.refreshPromise = (async () => {\n try {\n await this.getStatus({ forceRefresh });\n } catch (error) {\n console.warn('Background license refresh failed:', error);\n } finally {\n this.refreshPromise = null;\n }\n })();\n }\n}\n\nexport const licenseService = new LicenseService();\nexport { FREE_PROFILE_LIMIT };\n\nfunction isExplicitInvalidation(message: string | null | undefined): boolean {\n if (!message) {\n return false;\n }\n const normalized = message.toLowerCase();\n return (\n normalized.includes('revoked') ||\n normalized.includes('refunded') ||\n normalized.includes('invalid') ||\n normalized.includes('no longer active')\n );\n}\n\n/**\n * Determines when it is safe to enforce profile limits (e.g., pruning).\n * We skip enforcement when the license state is uncertain (grace/error/verifying)\n * and only enforce limits for true free/unlicensed states or explicit revocations.\n */\nexport function shouldEnforceProfileLimit(status: LicenseStatus): boolean {\n if (status.isPro) {\n return false;\n }\n\n if (status.state === 'grace' || status.state === 'verifying' || status.state === 'error') {\n return false;\n }\n\n if (isExplicitInvalidation(status.error)) {\n return true;\n }\n\n return status.state === 'inactive';\n}\n","import { normalizeAutoRollSettings, type AutoRollSettings } from \"@codexuse/contracts/settings/auto-roll\";\nimport { getAppState, patchAppState } from \"@codexuse/runtime-app-state/app/state\";\n\ntype LicenseStatusCode = \"inactive\" | \"active\" | \"grace\" | \"error\";\n\ninterface StoredLicense {\n licenseKey?: string | null;\n purchaseEmail?: string | null;\n lastVerifiedAt?: string | null;\n nextCheckAt?: string | null;\n lastVerificationError?: string | null;\n status?: LicenseStatusCode;\n signature?: string | null;\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction parseAutoRoll(raw: unknown): AutoRollSettings | null {\n if (!raw) {\n return null;\n }\n try {\n return normalizeAutoRollSettings(raw as Partial<AutoRollSettings>);\n } catch {\n return null;\n }\n}\n\nfunction parseStoredLicense(raw?: unknown): StoredLicense | null {\n if (!isRecord(raw)) {\n return null;\n }\n\n const statusCandidate = asString(raw.status);\n const status = [\"inactive\", \"active\", \"grace\", \"error\"].includes(statusCandidate ?? \"\")\n ? (statusCandidate as LicenseStatusCode)\n : undefined;\n\n const license: StoredLicense = {\n licenseKey: asString(raw.licenseKey ?? raw.license_key),\n purchaseEmail: asString(raw.purchaseEmail ?? raw.purchase_email),\n lastVerifiedAt: asString(raw.lastVerifiedAt ?? raw.last_verified_at),\n nextCheckAt: asString(raw.nextCheckAt ?? raw.next_check_at),\n lastVerificationError: asString(raw.lastVerificationError ?? raw.last_verification_error),\n status,\n signature: asString(raw.signature),\n };\n\n const hasValue = Boolean(\n license.licenseKey ||\n license.purchaseEmail ||\n license.lastVerifiedAt ||\n license.nextCheckAt ||\n license.lastVerificationError ||\n license.status,\n );\n\n return hasValue ? license : null;\n}\n\nexport async function getLastProfileName(): Promise<string | null> {\n const state = await getAppState();\n return asString(state.app.lastProfileName);\n}\n\nexport async function persistLastProfileName(profileName: string | null): Promise<void> {\n await patchAppState({\n app: {\n lastProfileName: asString(profileName),\n },\n });\n}\n\nexport async function getStoredLicense(): Promise<StoredLicense | null> {\n const state = await getAppState();\n return parseStoredLicense(state.license);\n}\n\nexport async function persistLicense(license: StoredLicense | null): Promise<void> {\n const parsed = parseStoredLicense(license);\n await patchAppState({\n license: parsed\n ? {\n licenseKey: parsed.licenseKey ?? null,\n purchaseEmail: parsed.purchaseEmail ?? null,\n lastVerifiedAt: parsed.lastVerifiedAt ?? null,\n nextCheckAt: parsed.nextCheckAt ?? null,\n lastVerificationError: parsed.lastVerificationError ?? null,\n status: parsed.status ?? \"inactive\",\n signature: parsed.signature ?? null,\n }\n : {\n licenseKey: null,\n purchaseEmail: null,\n lastVerifiedAt: null,\n nextCheckAt: null,\n lastVerificationError: null,\n status: \"inactive\",\n signature: null,\n },\n });\n}\n\nexport async function getStoredAutoRollSettings(): Promise<AutoRollSettings | null> {\n const state = await getAppState();\n return normalizeAutoRollSettings(state.autoRoll);\n}\n\nexport async function persistAutoRollSettings(settings: AutoRollSettings | null): Promise<void> {\n const normalized = normalizeAutoRollSettings(settings ?? undefined);\n await patchAppState({\n autoRoll: {\n enabled: normalized.enabled,\n rearmRemainingThreshold: normalized.rearmRemainingThreshold,\n switchRemainingThreshold: normalized.switchRemainingThreshold,\n restartOfficialCodexOnAutoRoll: normalized.restartOfficialCodexOnAutoRoll,\n launchOfficialCodexWhenClosedOnAutoRoll:\n normalized.launchOfficialCodexWhenClosedOnAutoRoll,\n priorityOrder: normalized.priorityOrder,\n lowRemainingNotificationEnabled: normalized.lowRemainingNotificationEnabled,\n lowRemainingNotificationThreshold: normalized.lowRemainingNotificationThreshold,\n },\n });\n}\n\nexport async function getStoredAppVersion(): Promise<string | null> {\n const state = await getAppState();\n return asString(state.app.lastAppVersion);\n}\n\nexport async function persistAppVersion(version: string | null): Promise<void> {\n await patchAppState({\n app: {\n lastAppVersion: asString(version),\n },\n });\n}\n\nexport async function getPendingUpdateVersion(): Promise<string | null> {\n const state = await getAppState();\n return asString(state.app.pendingUpdateVersion);\n}\n\nexport async function persistPendingUpdateVersion(version: string | null): Promise<void> {\n await patchAppState({\n app: {\n pendingUpdateVersion: asString(version),\n },\n });\n}\n\nexport async function readCodexSettingsJsonRaw(): Promise<Record<string, unknown>> {\n const state = await getAppState();\n return {\n lastProfileName: state.app.lastProfileName,\n lastAppVersion: state.app.lastAppVersion,\n pendingUpdateVersion: state.app.pendingUpdateVersion,\n autoRoll: state.autoRoll,\n license: state.license,\n excludeFolders: state.preferences.excludeFolders,\n enableTaskCompleteBeep: state.preferences.enableTaskCompleteBeep,\n preventSleepDuringTasks: state.preferences.preventSleepDuringTasks,\n systemNotificationsEnabled: state.preferences.systemNotificationsEnabled,\n subagentSystemNotificationsEnabled:\n state.preferences.subagentSystemNotificationsEnabled,\n folderHistory: state.preferences.folderHistory,\n pinnedPaths: state.preferences.pinnedPaths,\n workspaceSettingsByPath: state.workspaceSettingsByPath,\n // Legacy compatibility for older consumers.\n projectSettingsByPath: state.workspaceSettingsByPath,\n categoriesByCwd: state.conversationCategoriesByCwd,\n conversationCategoryByCwd: state.conversationCategoryAssignmentsByCwd,\n git: state.git,\n sync: state.sync,\n };\n}\n\nexport async function writeCodexSettingsJsonRaw(payload: Record<string, unknown> | null | undefined): Promise<void> {\n if (!isRecord(payload)) {\n return;\n }\n\n const autoRoll = parseAutoRoll(payload.autoRoll ?? payload.auto_roll);\n const license = parseStoredLicense(payload.license);\n\n await patchAppState({\n app: {\n lastProfileName: asString(payload.lastProfileName ?? payload.last_profile_name),\n lastAppVersion: asString(payload.lastAppVersion ?? payload.last_app_version),\n pendingUpdateVersion: asString(payload.pendingUpdateVersion ?? payload.pending_update_version),\n },\n autoRoll: autoRoll\n ? {\n enabled: autoRoll.enabled,\n rearmRemainingThreshold: autoRoll.rearmRemainingThreshold,\n switchRemainingThreshold: autoRoll.switchRemainingThreshold,\n restartOfficialCodexOnAutoRoll: autoRoll.restartOfficialCodexOnAutoRoll,\n launchOfficialCodexWhenClosedOnAutoRoll:\n autoRoll.launchOfficialCodexWhenClosedOnAutoRoll,\n priorityOrder: autoRoll.priorityOrder,\n lowRemainingNotificationEnabled: autoRoll.lowRemainingNotificationEnabled,\n lowRemainingNotificationThreshold: autoRoll.lowRemainingNotificationThreshold,\n }\n : undefined,\n license: license\n ? {\n licenseKey: license.licenseKey ?? null,\n purchaseEmail: license.purchaseEmail ?? null,\n lastVerifiedAt: license.lastVerifiedAt ?? null,\n nextCheckAt: license.nextCheckAt ?? null,\n lastVerificationError: license.lastVerificationError ?? null,\n status: license.status ?? \"inactive\",\n signature: license.signature ?? null,\n }\n : undefined,\n preferences: {\n excludeFolders: Array.isArray(payload.excludeFolders)\n ? (payload.excludeFolders as string[])\n : undefined,\n enableTaskCompleteBeep:\n typeof payload.enableTaskCompleteBeep === \"boolean\"\n ? payload.enableTaskCompleteBeep\n : undefined,\n preventSleepDuringTasks:\n typeof payload.preventSleepDuringTasks === \"boolean\"\n ? payload.preventSleepDuringTasks\n : undefined,\n systemNotificationsEnabled:\n typeof payload.systemNotificationsEnabled === \"boolean\"\n ? payload.systemNotificationsEnabled\n : undefined,\n subagentSystemNotificationsEnabled:\n typeof payload.subagentSystemNotificationsEnabled === \"boolean\"\n ? payload.subagentSystemNotificationsEnabled\n : undefined,\n folderHistory: Array.isArray(payload.folderHistory)\n ? (payload.folderHistory as Array<{ path: string; name: string; lastVisited: number }>)\n : undefined,\n pinnedPaths: Array.isArray(payload.pinnedPaths)\n ? (payload.pinnedPaths as string[])\n : undefined,\n },\n workspaceSettingsByPath: isRecord(payload.workspaceSettingsByPath)\n ? (payload.workspaceSettingsByPath as Record<\n string,\n {\n systemPrompt?: string;\n runScript?: string;\n buildScript?: string;\n openIdeCommand?: string;\n }\n >)\n : isRecord(payload.projectSettingsByPath)\n ? (payload.projectSettingsByPath as Record<\n string,\n {\n systemPrompt?: string;\n runScript?: string;\n buildScript?: string;\n openIdeCommand?: string;\n }\n >)\n : undefined,\n conversationCategoriesByCwd: isRecord(payload.categoriesByCwd)\n ? (payload.categoriesByCwd as Record<string, Array<{ id: string; name: string }>>)\n : undefined,\n conversationCategoryAssignmentsByCwd: isRecord(payload.conversationCategoryByCwd)\n ? (payload.conversationCategoryByCwd as Record<string, Record<string, string>>)\n : undefined,\n git: isRecord(payload.git)\n ? (payload.git as { commitMessagePrompt: string })\n : undefined,\n sync: isRecord(payload.sync)\n ? (payload.sync as {\n lastPushAt: string | null;\n lastPullAt: string | null;\n lastError: string | null;\n remoteUpdatedAt: string | null;\n })\n : undefined,\n });\n}\n\nexport type { StoredLicense };\n","import { promises as fs } from \"node:fs\";\nimport crypto from \"node:crypto\";\nimport path from \"node:path\";\nimport {\n getUserDataDir,\n} from \"@codexuse/runtime-app-state/app/state\";\nimport {\n readDocument,\n resolveAppStorageDbPath,\n writeDocument,\n} from \"@codexuse/runtime-app-state/storage/documents\";\n\nconst LICENSE_SECRET_DOCUMENT = \"desktop.license-secret\";\nconst LEGACY_LICENSE_SECRET_FILE = \"license.secret\";\n\nasync function generateSecret(): Promise<string> {\n return crypto.randomBytes(32).toString(\"hex\");\n}\n\nfunction normalizeSecret(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\nasync function readLegacyLicenseSecret(): Promise<string> {\n const legacyPath = path.join(getUserDataDir(), LEGACY_LICENSE_SECRET_FILE);\n try {\n return normalizeSecret(await fs.readFile(legacyPath, \"utf8\"));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return \"\";\n }\n throw error;\n }\n}\n\nasync function persistLicenseSecret(dbPath: string, secret: string): Promise<string> {\n await writeDocument(dbPath, LICENSE_SECRET_DOCUMENT, secret);\n return secret;\n}\n\nexport async function getLicenseSecret(): Promise<string> {\n const dbPath = resolveAppStorageDbPath(getUserDataDir());\n const existing = await readDocument<string>(dbPath, LICENSE_SECRET_DOCUMENT, normalizeSecret);\n const normalizedExisting = normalizeSecret(existing);\n if (normalizedExisting.length > 0) {\n return normalizedExisting;\n }\n\n const legacySecret = await readLegacyLicenseSecret();\n if (legacySecret.length > 0) {\n return persistLicenseSecret(dbPath, legacySecret);\n }\n\n const secret = await generateSecret();\n return persistLicenseSecret(dbPath, secret);\n}\n","export interface OfferConfig {\n basePriceUsd: number;\n basePriceDisplay: string;\n couponCode: string | null;\n discountPercent: number;\n salePriceUsd: number;\n salePriceDisplay: string;\n isActive: boolean;\n campaign: string | null;\n productPermalink: string;\n checkoutBaseUrl: string;\n}\n\nexport interface CheckoutUrlOptions {\n source?: string;\n medium?: string;\n campaign?: string;\n directCheckout?: boolean;\n}\n\nexport function getActiveOffer(): OfferConfig {\n const basePriceUsd = 39;\n const discountPercent = 50;\n const salePriceUsd = basePriceUsd * (100 - discountPercent) / 100;\n\n return {\n basePriceUsd,\n basePriceDisplay: `$${basePriceUsd}`,\n couponCode: \"SPRING50\",\n discountPercent,\n salePriceUsd,\n salePriceDisplay: `$${salePriceUsd.toFixed(2)}`,\n isActive: true,\n campaign: \"spring-2026\",\n productPermalink: \"codex-use\",\n checkoutBaseUrl: \"https://hweihwang.gumroad.com/l/codex-use\",\n };\n}\n\nexport function buildCheckoutUrl(\n offer: OfferConfig,\n options?: CheckoutUrlOptions,\n): string {\n const base = offer.checkoutBaseUrl;\n const withCoupon = offer.isActive && offer.couponCode\n ? `${base}/${offer.couponCode}`\n : base;\n\n const url = new URL(withCoupon);\n\n if (options?.directCheckout) {\n url.searchParams.set(\"wanted\", \"true\");\n }\n\n if (!options?.source || !options?.medium) {\n return url.toString();\n }\n\n url.searchParams.set(\"utm_source\", options.source);\n url.searchParams.set(\"utm_medium\", options.medium);\n if (options.campaign) {\n url.searchParams.set(\"utm_campaign\", options.campaign);\n } else if (offer.campaign) {\n url.searchParams.set(\"utm_campaign\", offer.campaign);\n }\n\n return url.toString();\n}\n","import { createHash } from 'node:crypto';\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { join } from 'path';\nimport { parse, stringify } from '@iarna/toml';\nimport type {\n Profile,\n ProfileData,\n ActiveAuth,\n ProfileMetadata,\n OrganizationInfo,\n RateLimitSnapshot,\n SubscriptionInfo,\n TokenAlert,\n TokenIssue,\n TokenStatus,\n} from '@codexuse/contracts/profiles/types';\nimport {\n resolveLegacyProfileAccountKey,\n resolveProfileIdentityKey as resolveSharedProfileIdentityKey,\n} from '@codexuse/contracts/profiles/identity';\nimport type { ActiveCodexAuthStatus } from '@codexuse/contracts/profiles/view-types';\nimport {\n activateResetWindowViaRpc,\n fetchRateLimitsViaRpc,\n type CodexResetWindowActivationResult,\n} from '@codexuse/runtime-codex/codex/rpc';\nimport type { CloudSyncProfileRecord } from '@codexuse/contracts/cloud-sync/types';\nimport {\n getAppState,\n getUserDataDir,\n updateAppState,\n type ProfileDashboardState,\n type ProfileRecordState,\n} from '@codexuse/runtime-app-state/app/state';\nimport { logError, logInfo, logWarn } from '@codexuse/shared/core/logger';\n\nconst TOKEN_EXPIRING_SOON_WINDOW_MS = 15 * 60 * 1000;\nconst REFRESH_TOKEN_REDEEMED_SNIPPET = 'refresh token was already used';\nconst REFRESH_TOKEN_REDEEMED_REASON =\n 'Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.';\nconst AUTH_BACKUP_MISSING_MARKER = '__codexuse_missing_auth__';\nconst DEFAULT_WORKSPACE_ID = '__default__';\nlet globalAuthSwapLock: Promise<void> = Promise.resolve();\nconst profileOperationLocks = new Map<string, Promise<void>>();\n\nexport function detectRefreshTokenRedeemedMessage(output: string | Buffer | null | undefined): string | null {\n if (!output) {\n return null;\n }\n\n const text = output.toString();\n if (!text) {\n return null;\n }\n\n const normalized = text\n .toLowerCase()\n .replace(/\\s+/g, ' ');\n if (!normalized.includes(REFRESH_TOKEN_REDEEMED_SNIPPET)) {\n return null;\n }\n\n const trimmed = text.trim();\n return trimmed.length > 0 ? trimmed : REFRESH_TOKEN_REDEEMED_REASON;\n}\n\ntype ProfileRecord = {\n name: string;\n displayName: string | null;\n data: ProfileData;\n metadata?: ProfileMetadata;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n email: string | null;\n authMethod: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n};\n\nexport type ActiveAuthSnapshot = {\n fingerprint: string | null;\n email: string | null;\n accountId: string | null;\n userId: string | null;\n chatgptUserId: string | null;\n chatgptAccountUserId: string | null;\n workspaceId: string | null;\n};\n\nexport type PreparedProfileRuntime = {\n profileHome: string;\n env: NodeJS.ProcessEnv;\n};\n\nfunction resolveFallbackAccountKey(profileName: string): string {\n return `profile:${profileName}`;\n}\n\nexport class ProfileManager {\n private codexDir: string;\n private profileHomesRoot: string;\n private activeAuth: string;\n private activeAuthBackup: string;\n private lastActiveAuthErrorSignature: string | null;\n constructor() {\n const homeDir = process.env.HOME || process.env.USERPROFILE || '';\n this.codexDir = join(homeDir, '.codex');\n this.profileHomesRoot = join(getUserDataDir(), 'profile-homes');\n this.activeAuth = join(this.codexDir, 'auth.json');\n this.activeAuthBackup = `${this.activeAuth}.swap`;\n this.lastActiveAuthErrorSignature = null;\n }\n\n private computeExpiryIso(data: ProfileData | null | undefined): string | undefined {\n if (!data) {\n return undefined;\n }\n if (typeof data.expired === 'string' && data.expired.trim()) {\n const parsed = Date.parse(data.expired);\n if (!Number.isNaN(parsed)) {\n return new Date(parsed).toISOString();\n }\n }\n const expiresIn = typeof data.expires_in === 'number' && Number.isFinite(data.expires_in)\n ? data.expires_in\n : undefined;\n const issuedMs =\n typeof data.timestamp === 'number' && Number.isFinite(data.timestamp)\n ? data.timestamp\n : undefined;\n const issuedAt = issuedMs ? issuedMs : undefined;\n const baseMs = issuedAt ?? Date.now();\n if (expiresIn && expiresIn > 0) {\n return new Date(baseMs + expiresIn * 1000).toISOString();\n }\n return undefined;\n }\n\n private normalizeProfileName(name: string): string {\n if (typeof name !== 'string') {\n throw new Error('Profile name is required');\n }\n\n const trimmed = name.trim();\n if (!trimmed) {\n throw new Error('Profile name must not be empty.');\n }\n\n if (trimmed === '.' || trimmed === '..') {\n throw new Error(`Profile name '${name}' is not allowed.`);\n }\n\n if (/[\\\\/]/.test(trimmed)) {\n throw new Error(\"Profile name cannot contain path separators.\");\n }\n\n if (trimmed.includes('\\0')) {\n throw new Error('Profile name contains invalid characters.');\n }\n\n return trimmed;\n }\n\n private isNotFoundError(error: unknown): boolean {\n return Boolean(\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as NodeJS.ErrnoException).code === 'ENOENT',\n );\n }\n\n private toStateRecord(record: ProfileRecord): ProfileRecordState {\n return {\n name: record.name,\n displayName: record.displayName ?? null,\n data: record.data,\n metadata: record.metadata,\n accountId: record.accountId ?? null,\n workspaceId: record.workspaceId ?? null,\n workspaceName: record.workspaceName ?? null,\n email: record.email ?? null,\n authMethod: record.authMethod ?? null,\n createdAt: record.createdAt ?? null,\n updatedAt: record.updatedAt ?? null,\n };\n }\n\n private fromStateRecord(profileName: string, raw: ProfileRecordState): ProfileRecord | null {\n if (!raw || typeof raw !== 'object') {\n return null;\n }\n\n const dataRaw = raw.data;\n if (!dataRaw || typeof dataRaw !== 'object') {\n return null;\n }\n\n return {\n name: profileName,\n displayName: typeof raw.displayName === 'string' ? raw.displayName : null,\n data: dataRaw as ProfileData,\n metadata: raw.metadata,\n accountId: typeof raw.accountId === 'string' ? raw.accountId : null,\n workspaceId: typeof raw.workspaceId === 'string' ? raw.workspaceId : null,\n workspaceName: typeof raw.workspaceName === 'string' ? raw.workspaceName : null,\n email: typeof raw.email === 'string' ? raw.email : null,\n authMethod: typeof raw.authMethod === 'string' ? raw.authMethod : null,\n createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : null,\n updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : null,\n };\n }\n\n private async readProfilesStateMap(): Promise<Record<string, ProfileRecordState>> {\n const state = await getAppState();\n return { ...(state.profilesByName ?? {}) };\n }\n\n private async writeProfilesStateMap(nextMap: Record<string, ProfileRecordState>): Promise<void> {\n await updateAppState((state) => ({\n ...state,\n profilesByName: nextMap,\n }), { mode: 'replace' });\n }\n\n private async readProfileDashboardState(): Promise<ProfileDashboardState> {\n const state = await getAppState();\n return {\n customGroupsByAccountKey: { ...(state.profileDashboard?.customGroupsByAccountKey ?? {}) },\n };\n }\n\n private async writeProfileDashboardState(nextState: ProfileDashboardState): Promise<void> {\n await updateAppState((state) => ({\n ...state,\n profileDashboard: {\n ...state.profileDashboard,\n customGroupsByAccountKey: { ...nextState.customGroupsByAccountKey },\n },\n }), { mode: 'replace' });\n }\n\n private async readProfileRecord(profileName: string): Promise<ProfileRecord | null> {\n const map = await this.readProfilesStateMap();\n const raw = map[profileName];\n if (!raw) {\n return null;\n }\n return this.fromStateRecord(profileName, raw);\n }\n\n private async listProfileRecords(): Promise<ProfileRecord[]> {\n const map = await this.readProfilesStateMap();\n const records: ProfileRecord[] = [];\n for (const [profileName, raw] of Object.entries(map)) {\n const record = this.fromStateRecord(profileName, raw);\n if (record) {\n records.push(record);\n }\n }\n return records;\n }\n\n private async writeProfileRecord(record: ProfileRecord): Promise<void> {\n const map = await this.readProfilesStateMap();\n map[record.name] = this.toStateRecord(record);\n await this.writeProfilesStateMap(map);\n }\n\n private async deleteProfileRecord(name: string): Promise<void> {\n const map = await this.readProfilesStateMap();\n if (!Object.prototype.hasOwnProperty.call(map, name)) {\n return;\n }\n delete map[name];\n await this.writeProfilesStateMap(map);\n }\n\n private resolveAuthMethod(data: ProfileData | null | undefined): string {\n const raw = typeof data?.auth_method === 'string' ? data.auth_method.trim().toLowerCase() : '';\n return raw || 'codex-cli';\n }\n\n private async readActiveAuthFile(): Promise<ActiveAuth | null> {\n try {\n const raw = await fs.readFile(this.activeAuth, 'utf8');\n const trimmed = raw.trim();\n if (!trimmed) {\n return null;\n }\n return JSON.parse(trimmed) as ActiveAuth;\n } catch (error) {\n if (this.isNotFoundError(error)) {\n return null;\n }\n const message = error instanceof Error ? error.message : 'unknown error';\n const signature = typeof message === 'string' ? `${message}:${this.activeAuth}` : this.activeAuth;\n if (this.lastActiveAuthErrorSignature !== signature) {\n logWarn('Failed to read active auth file:', error);\n this.lastActiveAuthErrorSignature = signature;\n }\n return null;\n }\n }\n\n private emptyAuthSnapshot(fingerprint: string | null = null): ActiveAuthSnapshot {\n return {\n fingerprint,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n chatgptAccountUserId: null,\n workspaceId: null,\n };\n }\n\n private async captureAuthSnapshotAtPath(authPath: string): Promise<ActiveAuthSnapshot> {\n let raw: string;\n try {\n raw = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (this.isNotFoundError(error)) {\n return this.emptyAuthSnapshot();\n }\n const message = error instanceof Error ? error.message : 'unknown error';\n const signature = typeof message === 'string' ? `${message}:${authPath}` : authPath;\n if (this.lastActiveAuthErrorSignature !== signature) {\n logWarn('Failed to snapshot auth file:', error);\n this.lastActiveAuthErrorSignature = signature;\n }\n return this.emptyAuthSnapshot();\n }\n\n const trimmed = raw.trim();\n if (!trimmed) {\n return this.emptyAuthSnapshot();\n }\n\n const fingerprint = createHash('sha256').update(trimmed).digest('hex');\n\n try {\n const parsed = JSON.parse(trimmed) as ActiveAuth;\n const normalized = this.normalizeProfileData(parsed);\n const metadata = this.extractProfileMetadata(normalized);\n const workspace = this.resolveWorkspaceIdentity(normalized, metadata);\n return {\n fingerprint,\n email: this.resolveProfileEmail(normalized, metadata) ?? null,\n accountId: this.getAccountIdFromData(normalized) ?? null,\n userId: metadata?.userId ?? null,\n chatgptUserId: metadata?.chatgptUserId ?? null,\n chatgptAccountUserId: metadata?.chatgptAccountUserId ?? null,\n workspaceId: workspace.id ?? null,\n };\n } catch {\n return this.emptyAuthSnapshot(fingerprint);\n }\n }\n\n async captureAuthSnapshot(authPath?: string): Promise<ActiveAuthSnapshot> {\n const targetPath = authPath ?? this.activeAuth;\n if (targetPath === this.activeAuth) {\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n return this.captureAuthSnapshotAtPath(targetPath);\n });\n }\n\n await this.initialize();\n return this.captureAuthSnapshotAtPath(targetPath);\n }\n\n async captureActiveAuthSnapshot(): Promise<ActiveAuthSnapshot> {\n return this.captureAuthSnapshot(this.activeAuth);\n }\n\n /**\n * Decode a JWT payload into an object without validating the signature.\n */\n private decodeJwtPayload(token?: string | null): Record<string, unknown> | null {\n if (!token || typeof token !== 'string') {\n return null;\n }\n\n const segments = token.split('.');\n if (segments.length < 2) {\n return null;\n }\n\n try {\n const payload = Buffer.from(segments[1], 'base64url').toString('utf8');\n return JSON.parse(payload);\n } catch {\n return null;\n }\n }\n\n private toIsoStringFromSeconds(seconds?: number): string | undefined {\n if (typeof seconds !== 'number' || Number.isNaN(seconds)) {\n return undefined;\n }\n\n try {\n return new Date(seconds * 1000).toISOString();\n } catch {\n return undefined;\n }\n }\n\n private normalizeEmailCandidate(value: unknown): string | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (!trimmed || trimmed.includes(' ')) {\n return undefined;\n }\n\n const atIndex = trimmed.indexOf('@');\n if (atIndex <= 0 || atIndex === trimmed.length - 1) {\n return undefined;\n }\n\n const domain = trimmed.slice(atIndex + 1);\n if (!domain || !domain.includes('.')) {\n return undefined;\n }\n\n return trimmed;\n }\n\n private pickFirstEmail(candidates: Array<string | undefined>): string | undefined {\n for (const candidate of candidates) {\n const normalized = this.normalizeEmailCandidate(candidate);\n if (normalized) {\n return normalized;\n }\n }\n return undefined;\n }\n\n private findEmailInObject(value: unknown, seen = new Set<unknown>()): string | undefined {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n\n if (seen.has(value)) {\n return undefined;\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const entry of value) {\n const nested = this.findEmailInObject(entry, seen);\n if (nested) {\n return nested;\n }\n }\n return undefined;\n }\n\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (typeof entry === 'string') {\n const normalized = this.normalizeEmailCandidate(entry);\n const lowerKey = key.toLowerCase();\n const keyHintsAtEmail =\n lowerKey.includes('email') ||\n lowerKey.includes('contact') ||\n lowerKey.includes('username') ||\n lowerKey.includes('login');\n\n if (normalized && (keyHintsAtEmail || entry.includes('@'))) {\n return normalized;\n }\n }\n\n if (entry && typeof entry === 'object') {\n const nested = this.findEmailInObject(entry, seen);\n if (nested) {\n return nested;\n }\n }\n }\n\n return undefined;\n }\n\n private resolveProfileEmail(data: ProfileData, metadata?: ProfileMetadata): string | undefined {\n const direct = this.normalizeEmailCandidate(data.email);\n if (direct) {\n return direct;\n }\n\n if (metadata?.email) {\n return metadata.email;\n }\n\n return this.findEmailInObject(data);\n }\n\n private evaluateTokenStatus(data: ProfileData, metadata?: ProfileMetadata): TokenStatus {\n const expiresAt = metadata?.tokenExpiresAt ?? this.computeExpiryIso(data);\n const parsedExpiry = expiresAt ? Date.parse(expiresAt) : Number.NaN;\n const hasExpiry = !Number.isNaN(parsedExpiry);\n const tokenAlert = data.tokenAlert;\n\n if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {\n return {\n state: 'missing',\n reason: 'No authentication data saved for this profile.',\n expiresAt,\n issue: 'auth-missing',\n requiresUserAction: true,\n };\n }\n\n if (tokenAlert?.issue) {\n const reason = typeof tokenAlert.reason === 'string' && tokenAlert.reason.trim().length > 0\n ? tokenAlert.reason.trim()\n : tokenAlert.issue === 'refresh-redeemed'\n ? REFRESH_TOKEN_REDEEMED_REASON\n : 'Authentication needs attention. Re-login this profile.';\n const issue = (tokenAlert.issue as TokenIssue) ?? 'auth-missing';\n return {\n state: 'invalid',\n reason,\n expiresAt,\n issue,\n requiresUserAction: true,\n };\n }\n\n if (!data.access_token) {\n return {\n state: 'missing',\n reason: 'Access token is missing. Re-authenticate with Codex CLI.',\n expiresAt,\n issue: 'access-missing',\n requiresUserAction: true,\n };\n }\n\n if (!this.decodeJwtPayload(data.access_token)) {\n return {\n state: 'invalid',\n reason: 'Access token is corrupted or not a valid JWT.',\n expiresAt,\n issue: 'access-invalid',\n requiresUserAction: true,\n };\n }\n\n const refreshToken = typeof data.refresh_token === 'string' ? data.refresh_token.trim() : '';\n if (!refreshToken) {\n return {\n state: 'missing',\n reason: 'Refresh token is missing. Run Codex login again.',\n expiresAt,\n issue: 'refresh-missing',\n requiresUserAction: true,\n };\n }\n\n if (hasExpiry) {\n const diff = parsedExpiry - Date.now();\n if (diff <= 0) {\n return {\n state: 'expiring',\n reason: 'Access token expired.',\n expiresAt,\n accessTokenExpired: true,\n issue: 'access-expired',\n requiresUserAction: false,\n };\n }\n\n if (diff <= TOKEN_EXPIRING_SOON_WINDOW_MS) {\n return {\n state: 'expiring',\n reason: 'Access token expires soon.',\n expiresAt,\n issue: 'access-expiring',\n requiresUserAction: false,\n };\n }\n }\n\n return {\n state: 'ok',\n expiresAt,\n requiresUserAction: false,\n };\n }\n\n private extractProfileMetadata(data: ProfileData): ProfileMetadata | undefined {\n const idPayload = this.decodeJwtPayload(data.id_token) as Record<string, unknown> | null;\n const accessPayload = this.decodeJwtPayload(data.access_token) as Record<string, unknown> | null;\n\n if (!idPayload && !accessPayload) {\n return undefined;\n }\n\n const authInfo = (idPayload?.['https://api.openai.com/auth'] ??\n accessPayload?.['https://api.openai.com/auth']) as Record<string, unknown> | undefined;\n\n const profileInfo = accessPayload?.['https://api.openai.com/profile'] as Record<string, unknown> | undefined;\n\n const getNumber = (obj: Record<string, unknown> | null | undefined, key: string): number | undefined =>\n typeof obj?.[key] === 'number' ? (obj[key] as number) : undefined;\n\n const getString = (obj: Record<string, unknown> | undefined | null, key: string): string | undefined =>\n typeof obj?.[key] === 'string' ? (obj[key] as string) : undefined;\n\n const exp = getNumber(idPayload, 'exp') ?? getNumber(accessPayload, 'exp');\n const iat = getNumber(idPayload, 'iat') ?? getNumber(accessPayload, 'iat');\n const authTime = getNumber(idPayload, 'auth_time') ?? getNumber(accessPayload, 'auth_time');\n\n const organizationsRaw = Array.isArray(authInfo?.['organizations'])\n ? (authInfo?.['organizations'] as unknown[])\n : undefined;\n\n const organizations = organizationsRaw\n ? organizationsRaw\n .map((org): OrganizationInfo => {\n const record = org as Record<string, unknown> | undefined;\n return {\n id: getString(record, 'id'),\n title: getString(record, 'title'),\n role: getString(record, 'role'),\n isDefault: typeof record?.['is_default'] === 'boolean' ? (record?.['is_default'] as boolean) : undefined,\n };\n })\n .filter(\n org =>\n org.id ||\n org.title ||\n org.role ||\n typeof org.isDefault === 'boolean'\n )\n : undefined;\n\n const groups = Array.isArray(authInfo?.['groups'])\n ? (authInfo?.['groups'] as unknown[]).filter((group): group is string => typeof group === 'string')\n : undefined;\n\n const emailVerified =\n typeof profileInfo?.['email_verified'] === 'boolean'\n ? (profileInfo?.['email_verified'] as boolean)\n : typeof idPayload?.['email_verified'] === 'boolean'\n ? (idPayload?.['email_verified'] as boolean)\n : typeof accessPayload?.['email_verified'] === 'boolean'\n ? (accessPayload?.['email_verified'] as boolean)\n : undefined;\n\n const email =\n this.pickFirstEmail([\n getString(profileInfo, 'email'),\n getString(profileInfo, 'email_address'),\n getString(profileInfo, 'primary_email'),\n getString(profileInfo, 'default_email'),\n getString(profileInfo, 'contact_email'),\n ]) ??\n this.findEmailInObject(profileInfo) ??\n this.pickFirstEmail([\n getString(authInfo, 'user_email'),\n getString(authInfo, 'email'),\n getString(authInfo, 'userEmail'),\n getString(authInfo, 'chatgpt_user_email'),\n ]) ??\n this.findEmailInObject(authInfo) ??\n this.pickFirstEmail([\n getString(idPayload, 'email'),\n getString(idPayload, 'preferred_username'),\n getString(idPayload, 'username'),\n ]) ??\n this.findEmailInObject(idPayload) ??\n this.pickFirstEmail([\n getString(accessPayload, 'email'),\n ]) ??\n this.findEmailInObject(accessPayload);\n\n const subscription: SubscriptionInfo | undefined = authInfo\n ? {\n activeStart: getString(authInfo, 'chatgpt_subscription_active_start'),\n activeUntil: getString(authInfo, 'chatgpt_subscription_active_until'),\n lastChecked: getString(authInfo, 'chatgpt_subscription_last_checked'),\n }\n : undefined;\n\n const planType = getString(authInfo, 'chatgpt_plan_type');\n const chatgptUserId = getString(authInfo, 'chatgpt_user_id');\n const chatgptAccountUserId = getString(authInfo, 'chatgpt_account_user_id');\n const userId =\n getString(authInfo, 'user_id') ??\n chatgptAccountUserId ??\n getString(idPayload ?? undefined, 'sub') ??\n getString(accessPayload ?? undefined, 'sub');\n\n const metadata: ProfileMetadata = {\n email,\n planType,\n subscription,\n organizations,\n groups,\n userId,\n chatgptUserId,\n chatgptAccountUserId,\n emailVerified,\n tokenExpiresAt: this.toIsoStringFromSeconds(exp),\n tokenIssuedAt: this.toIsoStringFromSeconds(iat),\n tokenAuthTime: this.toIsoStringFromSeconds(authTime),\n };\n\n const hasMeaningfulData =\n Boolean(metadata.planType) ||\n Boolean(\n metadata.subscription &&\n (metadata.subscription.activeStart ||\n metadata.subscription.activeUntil ||\n metadata.subscription.lastChecked)\n ) ||\n Boolean(metadata.organizations && metadata.organizations.length > 0) ||\n Boolean(metadata.groups && metadata.groups.length > 0) ||\n Boolean(metadata.userId) ||\n Boolean(metadata.chatgptUserId) ||\n Boolean(metadata.chatgptAccountUserId) ||\n Boolean(metadata.email) ||\n typeof metadata.emailVerified === 'boolean' ||\n Boolean(metadata.tokenExpiresAt) ||\n Boolean(metadata.tokenIssuedAt) ||\n Boolean(metadata.tokenAuthTime);\n\n return hasMeaningfulData ? metadata : undefined;\n }\n\n /**\n * Initialize the profile manager and create necessary directories\n */\n async initialize(): Promise<void> {\n this.profileHomesRoot = join(getUserDataDir(), 'profile-homes');\n\n try {\n await fs.mkdir(this.codexDir, { recursive: true });\n } catch (error) {\n logError('Failed to ensure Codex directory exists:', error);\n throw new Error('Failed to initialize profile manager');\n }\n try {\n await fs.mkdir(this.profileHomesRoot, { recursive: true });\n } catch (error) {\n logError('Failed to ensure profile homes directory exists:', error);\n throw new Error('Failed to initialize profile manager');\n }\n\n await this.recoverActiveAuthBackup();\n }\n\n private enqueueAuthSwap<T>(task: () => Promise<T>): Promise<T> {\n const run = globalAuthSwapLock.then(task, task);\n globalAuthSwapLock = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private enqueueProfileOperation<T>(name: string, task: () => Promise<T>): Promise<T> {\n const key = this.normalizeProfileName(name);\n const previous = profileOperationLocks.get(key) ?? Promise.resolve();\n const run = previous.then(task, task);\n const tail = run.then(\n () => undefined,\n () => undefined,\n );\n profileOperationLocks.set(key, tail);\n void tail.finally(() => {\n if (profileOperationLocks.get(key) === tail) {\n profileOperationLocks.delete(key);\n }\n });\n return run;\n }\n\n private async recoverActiveAuthBackup(): Promise<void> {\n let backup: string;\n try {\n backup = await fs.readFile(this.activeAuthBackup, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn('Failed to inspect active auth backup:', error);\n }\n return;\n }\n\n try {\n if (backup === AUTH_BACKUP_MISSING_MARKER) {\n await fs.rm(this.activeAuth, { force: true });\n } else {\n try {\n await this.writeAtomic(this.activeAuth, backup);\n } catch (error) {\n logWarn('Failed to restore active auth from backup, falling back to direct write:', error);\n try {\n await fs.writeFile(this.activeAuth, backup, 'utf8');\n } catch (fallbackError) {\n logWarn('Direct write failed while restoring active auth backup:', fallbackError);\n }\n }\n }\n } catch (error) {\n logWarn('Failed to restore active auth from backup:', error);\n }\n\n try {\n await fs.rm(this.activeAuthBackup, { force: true });\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn('Failed to remove active auth backup:', error);\n }\n }\n }\n\n private async writeAtomic(filePath: string, contents: string): Promise<void> {\n const tempPath = `${filePath}.tmp`;\n const dir = path.dirname(filePath);\n await fs.mkdir(dir, { recursive: true });\n\n await fs.writeFile(tempPath, contents, 'utf8');\n try {\n await fs.rename(tempPath, filePath);\n } catch (error) {\n // Fall back to writing directly if rename fails for any reason.\n try {\n await fs.writeFile(filePath, contents, 'utf8');\n } catch (writeError) {\n // Surface the original error context to aid debugging.\n const original = error instanceof Error ? error.message : String(error);\n const fallback = writeError instanceof Error ? writeError.message : String(writeError);\n throw new Error(`Atomic write failed (rename: ${original}; direct write: ${fallback})`);\n }\n }\n // Best-effort cleanup of temp file if it still exists.\n try {\n await fs.rm(tempPath, { force: true });\n } catch {\n // ignore cleanup failures\n }\n }\n\n /**\n * Extract account_id from auth data (supports both formats)\n */\n private getAccountIdFromData(data: ProfileData | ActiveAuth): string | undefined {\n if ('account_id' in data && typeof data.account_id === 'string' && data.account_id.trim()) {\n return data.account_id.trim();\n }\n\n if ('tokens' in data && data.tokens && typeof data.tokens === 'object') {\n const accountId = (data.tokens as { account_id?: unknown }).account_id;\n if (typeof accountId === 'string' && accountId.trim()) {\n return accountId.trim();\n }\n }\n\n const email =\n 'email' in data && typeof (data as ProfileData).email === 'string'\n ? (data as ProfileData).email?.trim()\n : undefined;\n return email || undefined;\n }\n\n private resolveProfileIdentityKey(args: {\n name?: string | null;\n accountId?: string | null;\n workspaceId?: string | null;\n email?: string | null;\n metadata?: ProfileMetadata;\n }): string | null {\n return resolveSharedProfileIdentityKey(args);\n }\n\n private resolveLegacyAccountKey(args: {\n name?: string | null;\n accountId?: string | null;\n email?: string | null;\n metadata?: ProfileMetadata;\n }): string | null {\n return resolveLegacyProfileAccountKey(args);\n }\n\n private resolveProfileIdentityFromData(\n name: string | null | undefined,\n data: ProfileData | ActiveAuth,\n metadata?: ProfileMetadata,\n ): string | null {\n const resolvedMetadata = metadata ?? this.extractProfileMetadata(data);\n const workspace = this.resolveWorkspaceIdentity(data, resolvedMetadata);\n const email = this.resolveProfileEmail(data, resolvedMetadata) ?? null;\n return this.resolveProfileIdentityKey({\n name,\n accountId: this.getAccountIdFromData(data) ?? null,\n workspaceId: workspace.id ?? null,\n email,\n metadata: resolvedMetadata,\n });\n }\n\n private resolveProfileIdentityFromRecord(record: ProfileRecord): string {\n return (\n this.resolveProfileIdentityFromData(record.name, record.data, record.metadata) ??\n this.resolveLegacyAccountKey({\n name: record.name,\n accountId: record.accountId,\n email: record.email,\n metadata: record.metadata,\n }) ??\n resolveFallbackAccountKey(record.name)\n );\n }\n\n private describeActiveAuth(auth: ActiveAuth): {\n normalized: ProfileData;\n metadata?: ProfileMetadata;\n workspaceId: string;\n workspaceName: string | null;\n email: string | null;\n accountId: string | null;\n identityKey: string | null;\n hasTokenPayload: boolean;\n } {\n const normalized = this.normalizeProfileData(auth);\n if (typeof normalized.auth_method === 'string') {\n normalized.auth_method = normalized.auth_method.trim().toLowerCase();\n }\n normalized.auth_method = normalized.auth_method ?? 'codex-cli';\n\n const metadata = this.extractProfileMetadata(normalized);\n const workspace = this.resolveWorkspaceIdentity(normalized, metadata);\n const workspaceId = workspace.id || DEFAULT_WORKSPACE_ID;\n const workspaceName = workspace.name ?? null;\n normalized.workspace_id = normalized.workspace_id ?? workspaceId;\n if (workspaceName) {\n normalized.workspace_name = normalized.workspace_name ?? workspaceName;\n }\n\n const email = this.resolveProfileEmail(normalized, metadata) ?? null;\n if (email) {\n normalized.email = email;\n }\n\n const accountId = this.getAccountIdFromData(normalized) ?? null;\n const identityKey = this.resolveProfileIdentityFromData(null, normalized, metadata);\n const hasTokenPayload = Boolean(\n normalized.id_token ||\n normalized.access_token ||\n normalized.refresh_token ||\n accountId ||\n email,\n );\n\n return {\n normalized,\n metadata,\n workspaceId,\n workspaceName,\n email,\n accountId,\n identityKey,\n hasTokenPayload,\n };\n }\n\n private async findProfileForActiveAuth(\n identityKey: string,\n workspaceId: string,\n ): Promise<ProfileRecord | undefined> {\n return this.getProfileRowByIdentityAndWorkspace(identityKey, workspaceId, {\n preferAuthMethod: 'codex-cli',\n });\n }\n\n private async syncMatchedProfileFromActiveAuth(\n record: ProfileRecord,\n description: ReturnType<ProfileManager['describeActiveAuth']>,\n ): Promise<void> {\n if (!this.hasTokenChanges(record.data, description.normalized)) {\n return;\n }\n const { profile: merged, metadata } = this.mergeProfileRecords(record.data, description.normalized);\n delete merged.tokenAlert;\n await this.persistProfileRecord(record.name, merged, metadata);\n }\n\n private async assertActiveAuthMatchesRecord(record: ProfileRecord, message: string): Promise<void> {\n const activeAuth = await this.readActiveAuthFile();\n if (!activeAuth) {\n throw new Error('Active Codex auth is missing. Refresh profiles and try again.');\n }\n\n const activeDescription = this.describeActiveAuth(activeAuth);\n const targetIdentity = this.resolveProfileIdentityFromRecord(record);\n const targetWorkspaceId = this.normalizeWorkspaceId(record.workspaceId ?? record.data.workspace_id);\n if (\n activeDescription.identityKey !== targetIdentity ||\n this.normalizeWorkspaceId(activeDescription.workspaceId) !== targetWorkspaceId\n ) {\n throw new Error(message);\n }\n }\n\n private async writeActiveAuthForRecord(record: ProfileRecord): Promise<void> {\n const profileData = record.data;\n const targetIdentity = this.resolveProfileIdentityFromRecord(record);\n const targetWorkspaceId = this.normalizeWorkspaceId(record.workspaceId ?? profileData.workspace_id);\n const codexFormat = this.convertToCodexFormat(profileData);\n await this.writeAtomic(this.activeAuth, JSON.stringify(codexFormat, null, 2));\n\n const written = await this.readActiveAuthFile();\n if (!written) {\n throw new Error('Codex auth file was not written.');\n }\n const writtenDescription = this.describeActiveAuth(written);\n if (writtenDescription.identityKey !== targetIdentity) {\n throw new Error('Codex auth verification failed after profile switch.');\n }\n if (this.normalizeWorkspaceId(writtenDescription.workspaceId) !== targetWorkspaceId) {\n throw new Error('Codex auth workspace verification failed after profile switch.');\n }\n }\n\n private async syncActiveAuthFromProfileIfCurrent(name: string): Promise<void> {\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n return;\n }\n\n const activeAuth = await this.readActiveAuthFile();\n if (!activeAuth) {\n return;\n }\n\n const activeDescription = this.describeActiveAuth(activeAuth);\n const targetIdentity = this.resolveProfileIdentityFromRecord(record);\n const targetWorkspaceId = this.normalizeWorkspaceId(record.workspaceId ?? record.data.workspace_id);\n if (\n activeDescription.identityKey !== targetIdentity ||\n this.normalizeWorkspaceId(activeDescription.workspaceId) !== targetWorkspaceId\n ) {\n return;\n }\n\n await this.writeActiveAuthForRecord(record);\n }\n\n private async removeActiveAuthFiles(): Promise<void> {\n await fs.rm(this.activeAuth, { force: true });\n await fs.rm(this.activeAuthBackup, { force: true });\n await fs.rm(`${this.activeAuth}.tmp`, { force: true });\n }\n\n private resolveAutoImportedProfileName(email: string | null, existingRecords: ProfileRecord[]): string {\n const source = email ? email.split('@')[0] : 'codex-account';\n const base =\n source\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 48) || 'codex-account';\n const used = new Set(existingRecords.map(record => record.name));\n let candidate = this.normalizeProfileName(base);\n let suffix = 2;\n while (used.has(candidate)) {\n candidate = this.normalizeProfileName(`${base}-${suffix}`);\n suffix += 1;\n }\n return candidate;\n }\n\n private buildActiveCodexAuthStatus(\n state: ActiveCodexAuthStatus['state'],\n description?: ReturnType<ProfileManager['describeActiveAuth']>,\n options?: {\n profileName?: string | null;\n importedProfileName?: string | null;\n importBlockedReason?: string | null;\n },\n ): ActiveCodexAuthStatus {\n return {\n state,\n profileName: options?.profileName ?? null,\n email: description?.email ?? null,\n accountId: description?.accountId ?? null,\n workspaceId: description?.workspaceId ?? null,\n workspaceName: description?.workspaceName ?? null,\n importedProfileName: options?.importedProfileName ?? null,\n importBlockedReason: options?.importBlockedReason ?? null,\n };\n }\n\n private resolveWorkspaceIdentity(data: ProfileData | ActiveAuth, metadata?: ProfileMetadata): { id: string; name?: string } {\n const directId =\n 'workspace_id' in data && typeof data.workspace_id === 'string'\n ? data.workspace_id.trim()\n : undefined;\n const directName =\n 'workspace_name' in data && typeof data.workspace_name === 'string'\n ? data.workspace_name.trim()\n : undefined;\n\n if (directId) {\n return { id: directId, name: directName };\n }\n\n const organizations = metadata?.organizations;\n if (organizations && organizations.length > 0) {\n const preferred = organizations.find(org => org.isDefault) ?? organizations[0];\n if (preferred?.id) {\n return { id: preferred.id, name: preferred.title ?? directName };\n }\n }\n\n return { id: DEFAULT_WORKSPACE_ID, name: directName };\n }\n\n private async getProfileRowByName(name: string): Promise<ProfileRecord | undefined> {\n const normalized = this.normalizeProfileName(name);\n const record = await this.readProfileRecord(normalized);\n return record ?? undefined;\n }\n\n private async getProfileRowByIdentityAndWorkspace(\n identityKey: string,\n workspaceId: string,\n options?: { authMethod?: string | null; preferAuthMethod?: string | null },\n ): Promise<ProfileRecord | undefined> {\n const workspaceKey = workspaceId && workspaceId.trim().length > 0 ? workspaceId.trim() : DEFAULT_WORKSPACE_ID;\n const records = await this.listProfileRecords();\n const matches = records.filter(record => {\n if (this.resolveProfileIdentityFromRecord(record) !== identityKey) {\n return false;\n }\n const storedWorkspace = record.workspaceId ?? record.data.workspace_id ?? DEFAULT_WORKSPACE_ID;\n return (storedWorkspace && storedWorkspace.trim() ? storedWorkspace.trim() : DEFAULT_WORKSPACE_ID) === workspaceKey;\n });\n\n if (matches.length === 0) {\n return undefined;\n }\n\n const mustMatch = typeof options?.authMethod === 'string' ? options.authMethod.trim().toLowerCase() : null;\n if (mustMatch) {\n return matches.find(record => this.resolveAuthMethod(record.data) === mustMatch);\n }\n\n const prefer = typeof options?.preferAuthMethod === 'string' ? options.preferAuthMethod.trim().toLowerCase() : null;\n if (prefer) {\n return matches.find(record => this.resolveAuthMethod(record.data) === prefer) ?? matches[0];\n }\n\n return matches[0];\n }\n\n private normalizeWorkspaceId(value: string | null | undefined): string {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : DEFAULT_WORKSPACE_ID;\n }\n\n private async persistProfileRecord(\n name: string,\n data: ProfileData,\n metadata?: ProfileMetadata,\n options?: { displayName?: string | null },\n ): Promise<void> {\n const resolvedName = this.normalizeProfileName(name);\n const existingRecord = await this.readProfileRecord(resolvedName);\n if (typeof data.auth_method === 'string') {\n data.auth_method = data.auth_method.trim().toLowerCase();\n }\n if (!data.auth_method) {\n data.auth_method = 'codex-cli';\n }\n const resolvedMetadata = metadata ?? this.extractProfileMetadata(data) ?? existingRecord?.metadata;\n const workspace = this.resolveWorkspaceIdentity(data, resolvedMetadata);\n const workspaceId = workspace.id || DEFAULT_WORKSPACE_ID;\n const workspaceName = workspace.name ?? null;\n if (!data.workspace_id) {\n data.workspace_id = workspaceId;\n }\n if (!data.workspace_name && workspaceName) {\n data.workspace_name = workspaceName;\n }\n\n const now = new Date().toISOString();\n const accountId = this.getAccountIdFromData(data) ?? null;\n const resolvedEmail = this.resolveProfileEmail(data, resolvedMetadata) ?? data.email ?? null;\n if (resolvedEmail) {\n data.email = resolvedEmail;\n }\n const createdAt = data.created_at ?? existingRecord?.createdAt ?? now;\n data.created_at = createdAt;\n const updatedAt = data.updated_at ?? now;\n data.updated_at = updatedAt;\n\n const displayName =\n typeof options?.displayName === 'string' && options.displayName.trim().length > 0\n ? options.displayName.trim()\n : existingRecord?.displayName ?? resolvedName;\n\n const record: ProfileRecord = {\n name: resolvedName,\n displayName,\n data,\n metadata: resolvedMetadata,\n accountId,\n workspaceId: data.workspace_id ?? workspaceId,\n workspaceName: data.workspace_name ?? workspaceName,\n email: resolvedEmail ?? null,\n authMethod: typeof data.auth_method === 'string' ? data.auth_method : null,\n createdAt,\n updatedAt,\n };\n\n await fs.mkdir(this.getProfileHomePath(resolvedName), { recursive: true });\n await this.writeProfileRecord(record);\n }\n\n private buildProfileFromRow(row: ProfileRecord): Profile {\n const profile = this.buildProfileFromData(row.name, row.data, {\n displayName: row.displayName ?? undefined,\n email: row.email ?? undefined,\n createdAt: row.createdAt ?? undefined,\n authMethod: row.authMethod ?? undefined,\n accountId: row.accountId ?? undefined,\n workspaceId: row.workspaceId ?? undefined,\n workspaceName: row.workspaceName ?? undefined,\n metadata: row.metadata,\n });\n\n return profile;\n }\n\n private async deleteProfileRecordAndHome(record: ProfileRecord): Promise<void> {\n const profileName = this.normalizeProfileName(record.name);\n if (!record.accountId) {\n const dashboardState = await this.readProfileDashboardState();\n delete dashboardState.customGroupsByAccountKey[resolveFallbackAccountKey(profileName)];\n await this.writeProfileDashboardState(dashboardState);\n }\n try {\n await fs.rm(this.getProfileHomePath(profileName), { recursive: true, force: true });\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to remove profile home for '${profileName}':`, error);\n }\n }\n await this.deleteProfileRecord(profileName);\n }\n\n private buildProfileFromData(\n name: string,\n data: ProfileData,\n fallback?: {\n displayName?: string;\n email?: string;\n createdAt?: string;\n authMethod?: string;\n accountId?: string;\n projectId?: string;\n workspaceId?: string;\n workspaceName?: string;\n metadata?: ProfileMetadata;\n },\n ): Profile {\n const metadata = fallback?.metadata ?? this.extractProfileMetadata(data);\n const workspace = this.resolveWorkspaceIdentity(data, metadata);\n const workspaceId = workspace.id || fallback?.workspaceId || DEFAULT_WORKSPACE_ID;\n const workspaceName = workspace.name ?? fallback?.workspaceName ?? undefined;\n const email = this.resolveProfileEmail(data, metadata) ?? fallback?.email ?? undefined;\n const tokenStatus = this.evaluateTokenStatus(data, metadata);\n const accountId = this.getAccountIdFromData(data) ?? fallback?.accountId;\n const projectId =\n typeof data.project_id === 'string' && data.project_id.trim().length > 0\n ? data.project_id.trim()\n : fallback?.projectId;\n\n return {\n name,\n displayName: fallback?.displayName ?? name,\n isValid: Boolean(data && Object.keys(data).length > 0),\n accountId,\n projectId,\n workspaceId,\n workspaceName,\n email,\n createdAt: data.created_at ?? fallback?.createdAt ?? undefined,\n authMethod: typeof data.auth_method === 'string'\n ? data.auth_method.trim().toLowerCase()\n : fallback?.authMethod ?? undefined,\n metadata,\n tokenStatus,\n };\n }\n\n /**\n * Convert profile data to Codex's expected format\n */\n private convertToCodexFormat(data: ProfileData): ActiveAuth {\n // Check if data is already in Codex format\n if ('tokens' in data) {\n return data as ActiveAuth;\n }\n\n // Convert flat structure to nested Codex format.\n // Keep existing refresh metadata if present; never forge it.\n const lastRefresh = typeof data.last_refresh === 'string' ? data.last_refresh.trim() : '';\n let normalizedLastRefresh = lastRefresh.length > 0 ? lastRefresh : undefined;\n if (!normalizedLastRefresh) {\n const accessPayload = this.decodeJwtPayload(data.access_token);\n const tokenIssuedAt = typeof accessPayload?.iat === 'number'\n ? this.toIsoStringFromSeconds(accessPayload.iat)\n : undefined;\n if (tokenIssuedAt) {\n normalizedLastRefresh = tokenIssuedAt;\n }\n }\n if (!normalizedLastRefresh) {\n const createdAt = typeof data.created_at === 'string' ? data.created_at.trim() : '';\n if (createdAt) {\n normalizedLastRefresh = createdAt;\n }\n }\n const codexAuth: ActiveAuth = {\n OPENAI_API_KEY: null,\n tokens: {\n id_token: data.id_token,\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n account_id: data.account_id,\n ...(normalizedLastRefresh ? { last_refresh: normalizedLastRefresh } : {}),\n },\n };\n if (normalizedLastRefresh) {\n codexAuth.last_refresh = normalizedLastRefresh;\n }\n const email = typeof data.email === 'string' ? data.email.trim() : '';\n if (email) {\n codexAuth.email = email;\n }\n const workspaceId = typeof data.workspace_id === 'string' ? data.workspace_id.trim() : '';\n if (workspaceId) {\n codexAuth.workspace_id = workspaceId;\n }\n const workspaceName = typeof data.workspace_name === 'string' ? data.workspace_name.trim() : '';\n if (workspaceName) {\n codexAuth.workspace_name = workspaceName;\n }\n return codexAuth;\n }\n\n /**\n * Normalize Codex auth data to flat profile format\n */\n private normalizeProfileData(data: ActiveAuth): ProfileData {\n // If data is already in flat format, return as-is\n if ('id_token' in data) {\n return data as ProfileData;\n }\n\n // Convert nested Codex format to flat\n const tokens = data.tokens || {};\n const profile: ProfileData = {\n id_token: tokens.id_token,\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n account_id: tokens.account_id,\n };\n const tokenLastRefresh = typeof tokens.last_refresh === 'string' ? tokens.last_refresh.trim() : '';\n const rootLastRefresh = typeof data.last_refresh === 'string' ? data.last_refresh.trim() : '';\n const normalizedLastRefresh = tokenLastRefresh || rootLastRefresh;\n if (normalizedLastRefresh) {\n profile.last_refresh = normalizedLastRefresh;\n }\n\n const email = typeof data.email === 'string' ? data.email.trim() : '';\n if (email) {\n profile.email = email;\n }\n const workspaceId = typeof data.workspace_id === 'string' ? data.workspace_id.trim() : '';\n if (workspaceId) {\n profile.workspace_id = workspaceId;\n }\n const workspaceName = typeof data.workspace_name === 'string' ? data.workspace_name.trim() : '';\n if (workspaceName) {\n profile.workspace_name = workspaceName;\n }\n\n return profile;\n }\n\n private mergeProfileRecords(existing: ProfileData, incoming: ProfileData): {\n profile: ProfileData;\n metadata?: ProfileMetadata;\n } {\n const merged: ProfileData = {\n ...existing,\n ...incoming,\n created_at: existing.created_at ?? incoming.created_at ?? new Date().toISOString(),\n };\n\n if (typeof merged.auth_method === 'string') {\n merged.auth_method = merged.auth_method.trim().toLowerCase();\n }\n if (!merged.auth_method) {\n merged.auth_method = 'codex-cli';\n }\n\n const metadata = this.extractProfileMetadata(merged);\n const resolvedEmail = this.resolveProfileEmail(merged, metadata);\n\n if (resolvedEmail) {\n merged.email = resolvedEmail;\n }\n\n const workspace = this.resolveWorkspaceIdentity(merged, metadata);\n if (!merged.workspace_id) {\n merged.workspace_id = workspace.id || existing.workspace_id || DEFAULT_WORKSPACE_ID;\n }\n if (!merged.workspace_name) {\n merged.workspace_name = workspace.name ?? existing.workspace_name;\n }\n\n if (this.hasTokenChanges(existing, incoming)) {\n delete merged.tokenAlert;\n }\n\n return { profile: merged, metadata };\n }\n\n private hasTokenChanges(existing: ProfileData, incoming: ProfileData): boolean {\n const tokenKeys: Array<keyof ProfileData> = [\n 'id_token',\n 'access_token',\n 'refresh_token',\n 'last_refresh',\n 'account_id',\n 'workspace_id',\n ];\n\n return tokenKeys.some(key => {\n const nextValue = incoming[key];\n if (typeof nextValue !== 'string' || nextValue.length === 0) {\n return false;\n }\n return nextValue !== existing[key];\n });\n }\n\n async flagAuthIssue(\n name: string,\n issue: TokenIssue,\n reason?: string,\n options?: { observedAt?: string },\n ): Promise<void> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n logWarn(`Cannot flag auth issue '${issue}' for missing profile '${profileName}'.`);\n return;\n }\n\n const observedAt = options?.observedAt ? Date.parse(options.observedAt) : null;\n const updatedAt = record.updatedAt ? Date.parse(record.updatedAt) : null;\n if (observedAt !== null && updatedAt !== null && observedAt <= updatedAt) {\n return;\n }\n\n const data: ProfileData = record.data;\n\n const trimmedReason = typeof reason === 'string' && reason.trim().length > 0 ? reason.trim() : undefined;\n const normalized = trimmedReason?.toLowerCase() ?? '';\n const storedReason = issue === 'refresh-redeemed'\n ? (normalized.includes(REFRESH_TOKEN_REDEEMED_SNIPPET)\n ? REFRESH_TOKEN_REDEEMED_REASON\n : trimmedReason ?? REFRESH_TOKEN_REDEEMED_REASON)\n : trimmedReason;\n const alert: TokenAlert = {\n issue,\n reason: storedReason,\n recordedAt: new Date().toISOString(),\n };\n\n data.tokenAlert = alert;\n\n try {\n const metadata = this.extractProfileMetadata(data);\n await this.persistProfileRecord(profileName, data, metadata);\n } catch (error) {\n logError(`Failed to persist token alert for profile '${profileName}':`, error);\n }\n }\n\n async flagRefreshTokenRedeemed(name: string, reason?: string, options?: { observedAt?: string }): Promise<void> {\n await this.flagAuthIssue(name, 'refresh-redeemed', reason, options);\n }\n\n private async syncProfileTokensFromActiveAuth(\n profileName: string,\n baselineProfile: ProfileData,\n authPath?: string,\n ): Promise<void> {\n const targetPath = authPath ?? this.activeAuth;\n try {\n const authRaw = await fs.readFile(targetPath, 'utf8');\n await this.syncProfileTokensFromAuthContent(profileName, baselineProfile, authRaw);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read Codex auth for '${profileName}' while syncing tokens:`, error);\n }\n }\n }\n\n private async syncProfileTokensFromAuthContent(\n profileName: string,\n baselineProfile: ProfileData,\n authContent: string,\n ): Promise<void> {\n let activeAuth: ActiveAuth;\n try {\n activeAuth = JSON.parse(authContent) as ActiveAuth;\n } catch (error) {\n logWarn(`Failed to parse Codex auth while syncing tokens for '${profileName}':`, error);\n return;\n }\n\n const normalized = this.normalizeProfileData(activeAuth);\n const metadata = this.extractProfileMetadata(normalized);\n const workspace = this.resolveWorkspaceIdentity(normalized, metadata);\n normalized.workspace_id = normalized.workspace_id ?? workspace.id ?? DEFAULT_WORKSPACE_ID;\n if (workspace.name) {\n normalized.workspace_name = normalized.workspace_name ?? workspace.name;\n }\n const hasTokens =\n typeof normalized.id_token === 'string' ||\n typeof normalized.access_token === 'string' ||\n typeof normalized.refresh_token === 'string';\n\n if (!hasTokens) {\n return;\n }\n\n let existing = baselineProfile;\n const latestRow = await this.getProfileRowByName(profileName);\n if (latestRow) {\n existing = latestRow.data;\n }\n\n const existingMetadata = this.extractProfileMetadata(existing);\n const existingWorkspace = this.resolveWorkspaceIdentity(existing, existingMetadata);\n existing.workspace_id = existing.workspace_id ?? existingWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (existingWorkspace.name) {\n existing.workspace_name = existing.workspace_name ?? existingWorkspace.name;\n }\n const existingIdentity = this.resolveProfileIdentityFromData(profileName, existing, existingMetadata);\n const nextIdentity = this.resolveProfileIdentityFromData(profileName, normalized, metadata);\n\n if (existingIdentity && nextIdentity && existingIdentity !== nextIdentity) {\n logInfo(\n `Skipped syncing tokens for profile '${profileName}' because Codex auth switched to a different OpenAI identity.`,\n );\n return;\n }\n if (this.normalizeWorkspaceId(existing.workspace_id) !== this.normalizeWorkspaceId(normalized.workspace_id)) {\n logInfo(\n `Skipped syncing tokens for profile '${profileName}' because Codex auth switched to a different workspace.`,\n );\n return;\n }\n\n if (!this.hasTokenChanges(existing, normalized)) {\n return;\n }\n\n const { profile: merged, metadata: mergedMetadata } = this.mergeProfileRecords(existing, normalized);\n\n try {\n await this.persistProfileRecord(profileName, merged, mergedMetadata);\n } catch (error) {\n logError(`Failed to persist refreshed tokens for profile '${profileName}':`, error);\n }\n }\n\n private async copyCodexConfig(targetCodexHome: string): Promise<void> {\n const candidates = ['config.toml', 'config.json', 'config.yaml', 'config.yml'];\n for (const file of candidates) {\n const source = join(this.codexDir, file);\n const destination = join(targetCodexHome, file);\n try {\n await fs.copyFile(source, destination);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to copy Codex config '${file}' to profile home:`, error);\n }\n }\n }\n }\n\n private getProfileHomePath(profileName: string): string {\n return join(this.profileHomesRoot, profileName);\n }\n\n private ensureTrailingNewline(content: string): string {\n return content.endsWith('\\n') ? content : `${content}\\n`;\n }\n\n private async sanitizeProfileConfig(profileHome: string): Promise<void> {\n const configPath = join(profileHome, 'config.toml');\n let raw: string;\n try {\n raw = await fs.readFile(configPath, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read config for profile home '${profileHome}':`, error);\n }\n return;\n }\n\n let parsed: Record<string, unknown>;\n try {\n parsed = parse(raw) as Record<string, unknown>;\n } catch (error) {\n logWarn(`Failed to parse config.toml for profile home '${profileHome}':`, error);\n return;\n }\n\n if (!Object.prototype.hasOwnProperty.call(parsed, 'model_reasoning_effort')) {\n return;\n }\n\n delete parsed['model_reasoning_effort'];\n const sanitized = this.ensureTrailingNewline(\n stringify(parsed as Parameters<typeof stringify>[0]),\n );\n try {\n await fs.writeFile(configPath, sanitized, 'utf8');\n } catch (error) {\n logWarn(`Failed to write sanitized config.toml for profile home '${profileHome}':`, error);\n }\n }\n\n private async prepareProfileHome(profileName: string, authData: ActiveAuth): Promise<string> {\n const profileHome = this.getProfileHomePath(profileName);\n await fs.mkdir(profileHome, { recursive: true });\n const authPath = join(profileHome, 'auth.json');\n await this.writeAtomic(authPath, JSON.stringify(authData, null, 2));\n await this.copyCodexConfig(profileHome);\n await this.sanitizeProfileConfig(profileHome);\n return profileHome;\n }\n\n /**\n * List all available profiles\n */\n async profileExists(name: string): Promise<boolean> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n return Boolean(await this.getProfileRowByName(profileName));\n }\n\n async listProfiles(): Promise<Profile[]> {\n await this.initialize();\n try {\n const records = await this.listProfileRecords();\n return records\n .map(record => this.buildProfileFromRow(record))\n .filter(profile => !profile.authMethod || profile.authMethod === 'codex-cli')\n .sort((a, b) => {\n const aLabel = a.displayName ?? a.name;\n const bLabel = b.displayName ?? b.name;\n const base = aLabel.localeCompare(bLabel);\n return base !== 0 ? base : a.name.localeCompare(b.name);\n });\n } catch (error) {\n logError('Error reading profiles from disk:', error);\n return [];\n }\n }\n\n private async runWithPreparedProfileHome<T>(\n name: string,\n action: (env: NodeJS.ProcessEnv) => Promise<T>,\n options: { syncFromActiveAuthBeforeAction?: boolean } = {},\n ): Promise<T> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n let profileData: ProfileData = record.data;\n if (options.syncFromActiveAuthBeforeAction !== false) {\n await this.syncProfileTokensFromActiveAuth(profileName, profileData);\n const updatedRecord = await this.getProfileRowByName(profileName);\n if (updatedRecord) {\n profileData = updatedRecord.data;\n }\n }\n\n if (profileData.auth_method && profileData.auth_method !== 'codex-cli') {\n throw new Error('Unsupported auth method. Codex CLI profiles only.');\n }\n\n const codexFormat = this.convertToCodexFormat(profileData);\n const profileHome = await this.prepareProfileHome(profileName, codexFormat);\n const authPath = path.join(profileHome, 'auth.json');\n\n const envOverrides: NodeJS.ProcessEnv = {\n ...process.env,\n HOME: profileHome,\n USERPROFILE: profileHome,\n CODEX_HOME: profileHome,\n };\n\n try {\n return await action(envOverrides);\n } finally {\n let finalAuthContent: string | null = null;\n try {\n finalAuthContent = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read isolated auth for '${profileName}' after action:`, error);\n }\n }\n\n try {\n if (finalAuthContent) {\n await this.syncProfileTokensFromAuthContent(profileName, profileData, finalAuthContent);\n } else {\n await this.syncProfileTokensFromActiveAuth(profileName, profileData, authPath);\n }\n } catch (error) {\n logWarn(`Failed to sync refreshed tokens for profile '${profileName}':`, error);\n }\n }\n }\n\n async prepareProfileRuntime(name: string): Promise<PreparedProfileRuntime> {\n return this.enqueueProfileOperation(name, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n let profileData: ProfileData = record.data;\n await this.syncProfileTokensFromActiveAuth(profileName, profileData);\n const updatedRecord = await this.getProfileRowByName(profileName);\n if (updatedRecord) {\n profileData = updatedRecord.data;\n }\n\n if (profileData.auth_method && profileData.auth_method !== 'codex-cli') {\n throw new Error('Unsupported auth method. Codex CLI profiles only.');\n }\n\n const codexFormat = this.convertToCodexFormat(profileData);\n const profileHome = await this.prepareProfileHome(profileName, codexFormat);\n return {\n profileHome,\n env: {\n ...process.env,\n HOME: profileHome,\n USERPROFILE: profileHome,\n CODEX_HOME: profileHome,\n },\n };\n }),\n );\n }\n\n async syncProfileRuntime(name: string, profileHome?: string): Promise<void> {\n return this.enqueueProfileOperation(name, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const authPath = path.join(profileHome ?? this.getProfileHomePath(profileName), 'auth.json');\n let finalAuthContent: string | null = null;\n try {\n finalAuthContent = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read isolated auth for '${profileName}' while syncing runtime:`, error);\n }\n }\n\n if (finalAuthContent) {\n await this.syncProfileTokensFromAuthContent(profileName, record.data, finalAuthContent);\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n return;\n }\n\n await this.syncProfileTokensFromActiveAuth(profileName, record.data, authPath);\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n }),\n );\n }\n\n /**\n * Create a new profile by running codex login\n */\n private async readAuthFileForImport(authPath: string, actionLabel: string): Promise<ActiveAuth> {\n let authRaw: string;\n try {\n authRaw = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (this.isNotFoundError(error)) {\n throw new Error(`Codex CLI did not produce an auth file. Complete the login before ${actionLabel}.`);\n }\n logError(`Failed to read Codex auth file during ${actionLabel}:`, error);\n throw new Error('Failed to read Codex auth file. Complete the login and try again.');\n }\n\n try {\n return JSON.parse(authRaw) as ActiveAuth;\n } catch (error) {\n logError(`Failed to parse Codex auth file during ${actionLabel}:`, error);\n throw new Error('Failed to parse Codex auth file. Complete the login and try again.');\n }\n }\n\n private async persistNewProfileFromAuth(profileName: string, authData: ActiveAuth): Promise<Profile | null> {\n const description = this.describeActiveAuth(authData);\n const normalizedProfile = description.normalized;\n normalizedProfile.created_at = normalizedProfile.created_at ?? new Date().toISOString();\n\n await this.persistProfileRecord(profileName, normalizedProfile, description.metadata);\n const stored = await this.getProfileRowByName(profileName);\n return stored ? this.buildProfileFromRow(stored) : null;\n }\n\n async createProfile(name: string): Promise<Profile | null> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n\n if (await this.getProfileRowByName(profileName)) {\n throw new Error(`Profile '${profileName}' already exists!`);\n }\n\n try {\n const authData = await this.readAuthFileForImport(this.activeAuth, 'profile creation');\n return await this.persistNewProfileFromAuth(profileName, authData);\n } catch (error) {\n logError('Error creating profile:', error);\n throw new Error('Failed to create profile. Make sure Codex CLI is installed and you are logged in.');\n }\n }),\n );\n }\n\n async createProfileFromAuthFile(name: string, authPath: string): Promise<Profile | null> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, async () => {\n await this.initialize();\n\n if (await this.getProfileRowByName(profileName)) {\n throw new Error(`Profile '${profileName}' already exists!`);\n }\n\n try {\n const authData = await this.readAuthFileForImport(authPath, 'profile creation');\n return await this.persistNewProfileFromAuth(profileName, authData);\n } catch (error) {\n logError('Error creating profile:', error);\n throw new Error('Failed to create profile. Make sure Codex CLI is installed and you are logged in.');\n }\n });\n }\n\n private async refreshProfileAuthWithData(\n profileName: string,\n record: ProfileRecord,\n activeAuth: ActiveAuth,\n ): Promise<Profile> {\n const existing: ProfileData = record.data;\n const normalized = this.normalizeProfileData(activeAuth);\n const existingMetadata = record.metadata ?? this.extractProfileMetadata(existing);\n const currentWorkspace = this.resolveWorkspaceIdentity(existing, existingMetadata);\n existing.workspace_id = existing.workspace_id ?? currentWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (currentWorkspace.name) {\n existing.workspace_name = existing.workspace_name ?? currentWorkspace.name;\n }\n\n const normalizedMetadata = this.extractProfileMetadata(normalized);\n const normalizedWorkspace = this.resolveWorkspaceIdentity(normalized, normalizedMetadata);\n normalized.workspace_id = normalized.workspace_id ?? normalizedWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (normalizedWorkspace.name) {\n normalized.workspace_name = normalized.workspace_name ?? normalizedWorkspace.name;\n }\n const existingIdentity = this.resolveProfileIdentityFromData(profileName, existing, existingMetadata);\n const newIdentity = this.resolveProfileIdentityFromData(profileName, normalized, normalizedMetadata);\n\n if (existingIdentity && newIdentity && existingIdentity !== newIdentity) {\n throw new Error(\n `Active Codex login is for a different OpenAI identity than profile '${profileName}'. Create a new profile for that login instead.`,\n );\n }\n\n if (existingIdentity && normalized.workspace_id) {\n const targetWorkspaceId = normalized.workspace_id;\n const currentWorkspaceId = currentWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (targetWorkspaceId !== currentWorkspaceId) {\n const duplicate = await this.getProfileRowByIdentityAndWorkspace(existingIdentity, targetWorkspaceId, {\n authMethod: this.resolveAuthMethod(existing),\n });\n if (duplicate && duplicate.name !== profileName) {\n throw new Error(\n `Account is already saved as profile '${duplicate.name}'. Switch to or delete that profile before creating another.`,\n );\n }\n }\n }\n\n const { profile: merged, metadata } = this.mergeProfileRecords(existing, normalized);\n delete merged.tokenAlert;\n\n await this.persistProfileRecord(profileName, merged, metadata);\n const updated = await this.getProfileRowByName(profileName);\n if (!updated) {\n throw new Error('Failed to persist refreshed profile data.');\n }\n\n const profile = this.buildProfileFromRow(updated);\n if (metadata) {\n profile.metadata = metadata;\n profile.tokenStatus = this.evaluateTokenStatus(merged, metadata);\n }\n return profile;\n }\n\n /**\n * Switch to a different profile\n */\n async switchToProfile(name: string): Promise<boolean> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n try {\n await this.writeActiveAuthForRecord(record);\n return true;\n } catch (error) {\n logError('Error switching profile:', error);\n throw new Error('Failed to switch profile');\n }\n }),\n );\n }\n\n async refreshProfileAuth(name: string): Promise<Profile> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const activeAuth = await this.readAuthFileForImport(this.activeAuth, 'profile refresh');\n return this.refreshProfileAuthWithData(profileName, record, activeAuth);\n }),\n );\n }\n\n async refreshProfileAuthFromFile(name: string, authPath: string): Promise<Profile> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const activeAuth = await this.readAuthFileForImport(authPath, 'profile refresh');\n const profile = await this.refreshProfileAuthWithData(profileName, record, activeAuth);\n await this.enqueueAuthSwap(async () => {\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n });\n return profile;\n });\n }\n\n /**\n * Execute an action with a profile's auth injected.\n * Creates an isolated CODEX_HOME with the profile's auth/config, invokes the action\n * with env overrides, then syncs any refreshed tokens back to the profile.\n */\n async runWithProfileAuth<T>(\n name: string,\n action: (env: NodeJS.ProcessEnv) => Promise<T>,\n ): Promise<T> {\n return this.enqueueProfileOperation(name, () =>\n this.enqueueAuthSwap(async () => {\n try {\n return await this.runWithPreparedProfileHome(name, action, {\n syncFromActiveAuthBeforeAction: true,\n });\n } finally {\n await this.syncActiveAuthFromProfileIfCurrent(name);\n }\n }),\n );\n }\n\n async readLiveRateLimits(\n name: string,\n options: { codexPath?: string } = {},\n ): Promise<RateLimitSnapshot | null> {\n const profileName = this.normalizeProfileName(name);\n try {\n return await this.enqueueProfileOperation(profileName, () =>\n this.runWithPreparedProfileHome(\n profileName,\n env => fetchRateLimitsViaRpc(env, { codexPath: options.codexPath }),\n { syncFromActiveAuthBeforeAction: false },\n ),\n );\n } finally {\n await this.enqueueAuthSwap(async () => {\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n }).catch(error => {\n logWarn(`Failed to sync active auth after rate-limit probe for '${profileName}':`, error);\n });\n }\n }\n\n async activateResetWindow(\n name: string,\n options: { codexPath?: string } = {},\n ): Promise<CodexResetWindowActivationResult> {\n const profileName = this.normalizeProfileName(name);\n try {\n return await this.enqueueProfileOperation(profileName, () =>\n this.runWithPreparedProfileHome(\n profileName,\n env => activateResetWindowViaRpc(env, { codexPath: options.codexPath }),\n { syncFromActiveAuthBeforeAction: false },\n ),\n );\n } finally {\n await this.enqueueAuthSwap(async () => {\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n }).catch(error => {\n logWarn(`Failed to sync active auth after reset-window activation for '${profileName}':`, error);\n });\n }\n }\n\n /**\n * Rename a profile\n */\n async renameProfile(oldName: string, newName: string): Promise<boolean> {\n await this.initialize();\n const sourceName = this.normalizeProfileName(oldName);\n const targetName = this.normalizeProfileName(newName);\n\n const existing = await this.getProfileRowByName(sourceName);\n if (!existing) {\n throw new Error(`Profile '${sourceName}' not found!`);\n }\n\n if (await this.getProfileRowByName(targetName)) {\n throw new Error(`Profile '${targetName}' already exists!`);\n }\n\n const oldHome = this.getProfileHomePath(sourceName);\n const newHome = this.getProfileHomePath(targetName);\n try {\n await fs.mkdir(this.profileHomesRoot, { recursive: true });\n await fs.rename(oldHome, newHome);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to move profile home from '${sourceName}' to '${targetName}':`, error);\n }\n }\n\n try {\n const updatedRecord: ProfileRecord = {\n ...existing,\n name: targetName,\n };\n await this.writeProfileRecord(updatedRecord);\n await this.deleteProfileRecord(sourceName);\n } catch (error) {\n logWarn(`Failed to rewrite profile record after renaming '${sourceName}' to '${targetName}':`, error);\n }\n\n return true;\n }\n\n async updateProfileDisplayName(name: string, displayName: string): Promise<boolean> {\n await this.initialize();\n\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const trimmed = typeof displayName === 'string' ? displayName.trim() : '';\n if (!trimmed) {\n throw new Error('Profile name must not be empty.');\n }\n\n const now = new Date().toISOString();\n record.displayName = trimmed;\n record.updatedAt = now;\n (record.data as ProfileData & { updated_at?: string }).updated_at = now;\n\n await this.writeProfileRecord(record);\n return true;\n }\n\n async getCustomGroupsByAccountKey(): Promise<Record<string, string>> {\n await this.initialize();\n const state = await this.readProfileDashboardState();\n return { ...state.customGroupsByAccountKey };\n }\n\n async updateCustomGroup(accountKey: string, groupName: string | null): Promise<Record<string, string>> {\n await this.initialize();\n\n const normalizedAccountKey = this.normalizeProfileName(accountKey);\n const normalizedGroupName =\n typeof groupName === 'string' && groupName.trim().length > 0\n ? groupName.trim()\n : null;\n const nextState = await this.readProfileDashboardState();\n\n if (normalizedGroupName) {\n nextState.customGroupsByAccountKey[normalizedAccountKey] = normalizedGroupName;\n } else {\n delete nextState.customGroupsByAccountKey[normalizedAccountKey];\n }\n\n await this.writeProfileDashboardState(nextState);\n return { ...nextState.customGroupsByAccountKey };\n }\n\n /**\n * Delete a profile\n */\n async deleteProfile(name: string): Promise<boolean> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n await this.deleteProfileRecordAndHome(record);\n return true;\n }\n\n async deleteActiveProfileAndSwitch(name: string, replacementName: string): Promise<boolean> {\n const profileName = this.normalizeProfileName(name);\n const nextProfileName = this.normalizeProfileName(replacementName);\n if (profileName === nextProfileName) {\n throw new Error('Replacement profile must be different from the deleted profile.');\n }\n\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n const replacement = await this.getProfileRowByName(nextProfileName);\n if (!replacement) {\n throw new Error(`Profile '${nextProfileName}' not found!`);\n }\n\n await this.assertActiveAuthMatchesRecord(\n record,\n 'Active Codex login changed before deletion. Refresh profiles and try again.',\n );\n await this.writeActiveAuthForRecord(replacement);\n await this.deleteProfileRecordAndHome(record);\n return true;\n });\n }\n\n async deleteActiveProfileAndAuth(name: string): Promise<boolean> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n await this.assertActiveAuthMatchesRecord(\n record,\n 'Active Codex login changed before deletion. Refresh profiles and try again.',\n );\n await this.removeActiveAuthFiles();\n await this.deleteProfileRecordAndHome(record);\n return true;\n });\n }\n\n /**\n * Delete every profile that does not appear in the allow-list.\n * Used to enforce plan limits when local storage was tampered with.\n */\n async deleteProfilesNotIn(allowedNames: Iterable<string>): Promise<string[]> {\n await this.initialize();\n const normalized = new Set<string>();\n for (const name of allowedNames) {\n try {\n normalized.add(this.normalizeProfileName(name));\n } catch {\n // Skip invalid names so we only retain well-formed entries.\n }\n }\n\n const records = await this.listProfileRecords();\n const deleteCandidates = records\n .map(record => {\n try {\n return this.normalizeProfileName(record.name);\n } catch {\n return null;\n }\n })\n .filter((name): name is string => typeof name === 'string')\n .filter(name => !normalized.has(name));\n\n if (deleteCandidates.length === 0) {\n return [];\n }\n\n const removed: string[] = [];\n for (const name of deleteCandidates) {\n try {\n await fs.rm(this.getProfileHomePath(name), { recursive: true, force: true });\n await this.deleteProfileRecord(name);\n removed.push(name);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to remove profile '${name}' during plan enforcement:`, error);\n }\n }\n }\n return removed;\n }\n\n async getActiveCodexAuthStatus(options: {\n autoImport?: boolean;\n canAutoImport?: boolean;\n importBlockedReason?: string | null;\n } = {}): Promise<ActiveCodexAuthStatus> {\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n const activeAuth = await this.readActiveAuthFile();\n if (!activeAuth) {\n return this.buildActiveCodexAuthStatus('missing');\n }\n\n const description = this.describeActiveAuth(activeAuth);\n if (!description.hasTokenPayload || !description.identityKey) {\n return this.buildActiveCodexAuthStatus('unknown', description);\n }\n\n const matching = await this.findProfileForActiveAuth(\n description.identityKey,\n description.workspaceId,\n );\n if (matching) {\n const normalized = this.normalizeProfileName(matching.name);\n await this.syncMatchedProfileFromActiveAuth(matching, description);\n return this.buildActiveCodexAuthStatus('matched', description, {\n profileName: normalized,\n });\n }\n\n if (!options.autoImport) {\n return this.buildActiveCodexAuthStatus('unmanaged', description);\n }\n\n if (options.canAutoImport === false) {\n return this.buildActiveCodexAuthStatus('unmanaged', description, {\n importBlockedReason:\n options.importBlockedReason ??\n 'Profile limit reached. Upgrade to CodexUse Pro or remove a profile before importing this Codex login.',\n });\n }\n\n const records = await this.listProfileRecords();\n const profileName = this.resolveAutoImportedProfileName(description.email, records);\n const profileData: ProfileData = {\n ...description.normalized,\n auth_method: 'codex-cli',\n created_at: description.normalized.created_at ?? new Date().toISOString(),\n };\n await this.persistProfileRecord(profileName, profileData, description.metadata, {\n displayName: description.email ?? profileName,\n });\n\n return this.buildActiveCodexAuthStatus('matched', description, {\n profileName,\n importedProfileName: profileName,\n });\n });\n }\n\n /**\n * Check if the real Codex auth file matches a saved profile.\n */\n async getCurrentProfile(): Promise<{ name: string | null; trusted: boolean }> {\n const status = await this.getActiveCodexAuthStatus({ autoImport: false });\n if (status.state === 'matched' && status.profileName) {\n return { name: status.profileName, trusted: true };\n }\n return { name: null, trusted: false };\n }\n\n /**\n * Export a profile to a portable format.\n * Sensitive tokens are included but should be handled securely.\n */\n async exportProfile(name: string): Promise<{\n name: string;\n displayName: string | null;\n email: string | null;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n authMethod: string | null;\n createdAt: string | null;\n metadata: ProfileMetadata | undefined;\n exportedAt: string;\n }> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n return {\n name: record.name,\n displayName: record.displayName,\n email: record.email,\n accountId: record.accountId,\n workspaceId: record.workspaceId,\n workspaceName: record.workspaceName,\n authMethod: record.authMethod,\n createdAt: record.createdAt,\n metadata: record.metadata,\n exportedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Export profiles for cloud sync (includes token-bearing auth data).\n */\n async exportProfilesForCloudSync(): Promise<CloudSyncProfileRecord[]> {\n await this.initialize();\n const records = await this.listProfileRecords();\n return records.map(record => ({\n name: record.name,\n displayName: record.displayName,\n data: record.data,\n metadata: record.metadata,\n accountId: record.accountId,\n workspaceId: record.workspaceId,\n workspaceName: record.workspaceName,\n email: record.email,\n authMethod: record.authMethod,\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n }));\n }\n\n /**\n * Replace local profiles with a full snapshot from cloud sync.\n */\n async replaceProfilesFromCloudSync(records: CloudSyncProfileRecord[]): Promise<{ imported: number; removed: number }> {\n await this.initialize();\n const now = new Date().toISOString();\n const normalized = new Map<string, ProfileRecord>();\n const existingMap = await this.readProfilesStateMap();\n const existingNames = new Set(Object.keys(existingMap));\n\n for (const candidate of records ?? []) {\n try {\n const name = this.normalizeProfileName(candidate?.name ?? '');\n const data =\n candidate && typeof candidate.data === 'object' && candidate.data !== null\n ? (candidate.data as ProfileData)\n : null;\n if (!data) {\n continue;\n }\n\n const metadata =\n candidate.metadata && typeof candidate.metadata === 'object'\n ? candidate.metadata\n : undefined;\n\n const record: ProfileRecord = {\n name,\n displayName: typeof candidate.displayName === 'string' ? candidate.displayName : null,\n data,\n metadata,\n accountId: typeof candidate.accountId === 'string' ? candidate.accountId : null,\n workspaceId: typeof candidate.workspaceId === 'string' ? candidate.workspaceId : null,\n workspaceName: typeof candidate.workspaceName === 'string' ? candidate.workspaceName : null,\n email: typeof candidate.email === 'string' ? candidate.email : null,\n authMethod: typeof candidate.authMethod === 'string' ? candidate.authMethod : this.resolveAuthMethod(data),\n createdAt: typeof candidate.createdAt === 'string' ? candidate.createdAt : now,\n updatedAt: typeof candidate.updatedAt === 'string' ? candidate.updatedAt : now,\n };\n\n normalized.set(name, record);\n } catch {\n // Ignore malformed record entries.\n }\n }\n\n const nextMap: Record<string, ProfileRecordState> = {};\n for (const record of normalized.values()) {\n nextMap[record.name] = this.toStateRecord(record);\n }\n await this.writeProfilesStateMap(nextMap);\n\n let removed = 0;\n\n for (const name of existingNames) {\n if (normalized.has(name)) {\n continue;\n }\n try {\n await fs.rm(this.getProfileHomePath(name), { recursive: true, force: true });\n removed += 1;\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to remove profile '${name}' during cloud sync replace:`, error);\n }\n }\n }\n\n return {\n imported: normalized.size,\n removed,\n };\n }\n}\n","import type { Profile, ProfileMetadata } from \"./types\";\n\ntype ProfileIdentityLike = {\n name?: string | null;\n accountId?: string | null;\n workspaceId?: string | null;\n email?: string | null;\n metadata?: Pick<\n ProfileMetadata,\n \"email\" | \"userId\" | \"chatgptUserId\" | \"chatgptAccountUserId\"\n > | null;\n};\n\nfunction normalizeValue(value?: string | null): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeEmail(value?: string | null): string | null {\n const normalized = normalizeValue(value);\n return normalized ? normalized.toLowerCase() : null;\n}\n\nfunction encodeIdentityPart(value: string): string {\n return encodeURIComponent(value);\n}\n\nexport function resolveLegacyProfileAccountKey(profile: ProfileIdentityLike): string | null {\n const accountId = normalizeValue(profile.accountId);\n if (accountId) {\n return accountId;\n }\n\n const email = normalizeValue(profile.email ?? profile.metadata?.email);\n if (email) {\n return email;\n }\n\n const profileName = normalizeValue(profile.name);\n return profileName ? `profile:${profileName}` : null;\n}\n\nexport function resolveProfileIdentityKey(profile: ProfileIdentityLike): string | null {\n const workspaceId = normalizeValue(profile.workspaceId);\n const accountUserId = normalizeValue(profile.metadata?.chatgptAccountUserId);\n if (accountUserId) {\n return `seat:${encodeIdentityPart(accountUserId)}`;\n }\n\n const userId =\n normalizeValue(profile.metadata?.userId) ??\n normalizeValue(profile.metadata?.chatgptUserId);\n if (workspaceId && userId) {\n return `workspace-user:${encodeIdentityPart(workspaceId)}|${encodeIdentityPart(userId)}`;\n }\n\n const accountId = normalizeValue(profile.accountId);\n if (accountId) {\n return accountId;\n }\n\n const email = normalizeEmail(profile.email ?? profile.metadata?.email);\n if (workspaceId && email) {\n return `workspace-email:${encodeIdentityPart(workspaceId)}|${encodeIdentityPart(email)}`;\n }\n if (userId) {\n return `user:${encodeIdentityPart(userId)}`;\n }\n if (email) {\n return `email:${encodeIdentityPart(email)}`;\n }\n\n return resolveLegacyProfileAccountKey(profile);\n}\n\nexport function resolveProfileIdentityKeyFromProfile(profile: Profile): string {\n return resolveProfileIdentityKey(profile) ?? `profile:${profile.name}`;\n}\n","import { spawn } from \"node:child_process\";\nimport readline from \"node:readline\";\nimport { promises as fs } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { requireCodexCli } from \"@codexuse/runtime-codex/codex/cli\";\nimport { buildCodexCommand } from \"@codexuse/runtime-codex/codex/command\";\nimport { logWarn } from \"@codexuse/shared/core/logger\";\nimport type {\n RateLimitSnapshot,\n RateLimitWindow,\n} from \"@codexuse/contracts/profiles/types\";\n\ntype RpcError = {\n code?: number;\n message?: string;\n data?: unknown;\n};\n\ntype RpcMessage = {\n id?: number | string | null;\n method?: string;\n params?: unknown;\n result?: unknown;\n error?: RpcError;\n};\n\ntype RpcRateLimitWindow = {\n usedPercent?: number;\n windowDurationMins?: number;\n resetsAt?: number;\n};\n\ntype RpcRateLimitSnapshot = {\n primary?: RpcRateLimitWindow | null;\n secondary?: RpcRateLimitWindow | null;\n};\n\nexport type CodexResetWindowActivationResult = {\n status: \"completed\" | \"failed\" | \"skipped\";\n reason: string | null;\n threadId?: string | null;\n turnId?: string | null;\n};\n\nconst RPC_TIMEOUT_MS = 10_000;\nconst ACTIVATION_TURN_TIMEOUT_MS = 90_000;\nconst ACTIVATION_PROMPT = \"Reply with exactly: ok.\";\nconst ACTIVATION_MODEL = \"gpt-5.1-codex-mini\";\nconst MAX_STDERR_CAPTURE_CHARS = 32_768;\nconst REFRESH_TOKEN_REDEEMED_SNIPPET = \"refresh token was already used\";\n\ntype AuthRecord = {\n last_refresh?: unknown;\n access_token?: unknown;\n tokens?: {\n last_refresh?: unknown;\n access_token?: unknown;\n };\n};\n\ntype RpcMessageReader = {\n read: (\n predicate: (message: RpcMessage) => boolean,\n timeoutMs: number,\n ) => Promise<RpcMessage>;\n dispose: () => void;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction asString(value: unknown): string {\n return typeof value === \"string\" ? value : value != null ? String(value) : \"\";\n}\n\nfunction createRpcMessageReader(rl: readline.Interface): RpcMessageReader {\n type Waiter = {\n predicate: (message: RpcMessage) => boolean;\n resolve: (message: RpcMessage) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n };\n\n const queue: RpcMessage[] = [];\n const waiters: Waiter[] = [];\n let closedError: Error | null = null;\n\n const rejectAll = (error: Error): void => {\n closedError = error;\n while (waiters.length > 0) {\n const waiter = waiters.shift()!;\n clearTimeout(waiter.timer);\n waiter.reject(error);\n }\n };\n\n const onLine = (line: string): void => {\n let parsed: RpcMessage;\n try {\n parsed = JSON.parse(line) as RpcMessage;\n } catch {\n rejectAll(new Error(\"codex RPC returned malformed JSON\"));\n return;\n }\n\n const waiterIndex = waiters.findIndex((waiter) => waiter.predicate(parsed));\n if (waiterIndex >= 0) {\n const [waiter] = waiters.splice(waiterIndex, 1);\n clearTimeout(waiter.timer);\n waiter.resolve(parsed);\n return;\n }\n queue.push(parsed);\n };\n\n const onClose = (): void => {\n rejectAll(new Error(\"codex RPC stream closed before response\"));\n };\n\n rl.on(\"line\", onLine);\n rl.on(\"close\", onClose);\n\n return {\n read(predicate, timeoutMs) {\n const queuedIndex = queue.findIndex(predicate);\n if (queuedIndex >= 0) {\n const [message] = queue.splice(queuedIndex, 1);\n return Promise.resolve(message);\n }\n if (closedError) {\n return Promise.reject(closedError);\n }\n return new Promise<RpcMessage>((resolve, reject) => {\n const waiter: Waiter = {\n predicate,\n resolve,\n reject,\n timer: setTimeout(\n () => {\n const index = waiters.indexOf(waiter);\n if (index >= 0) {\n waiters.splice(index, 1);\n }\n reject(new Error(\"codex RPC timed out\"));\n },\n Math.max(1, timeoutMs),\n ),\n };\n waiters.push(waiter);\n });\n },\n dispose() {\n rl.off(\"line\", onLine);\n rl.off(\"close\", onClose);\n while (waiters.length > 0) {\n const waiter = waiters.shift()!;\n clearTimeout(waiter.timer);\n }\n },\n };\n}\n\nfunction readThreadIdFromResult(result: unknown): string | null {\n if (!isRecord(result)) return null;\n const thread = isRecord(result.thread) ? result.thread : {};\n const value = asString(thread.id ?? result.threadId).trim();\n return value.length > 0 ? value : null;\n}\n\nfunction readTurnIdFromResult(result: unknown): string | null {\n if (!isRecord(result)) return null;\n const turn = isRecord(result.turn) ? result.turn : {};\n const value = asString(turn.id ?? result.turnId).trim();\n return value.length > 0 ? value : null;\n}\n\nfunction readTurnIdFromNotification(message: RpcMessage): string | null {\n if (!isRecord(message.params)) return null;\n const turn = isRecord(message.params.turn) ? message.params.turn : {};\n const value = asString(turn.id ?? message.params.turnId).trim();\n return value.length > 0 ? value : null;\n}\n\nfunction readTurnStatusFromNotification(message: RpcMessage): {\n status: string | null;\n reason: string | null;\n} {\n if (!isRecord(message.params)) {\n return { status: null, reason: null };\n }\n const turn = isRecord(message.params.turn) ? message.params.turn : {};\n const error = isRecord(turn.error) ? turn.error : null;\n return {\n status: asString(turn.status).trim() || null,\n reason: error ? asString(error.message).trim() || null : null,\n };\n}\n\nfunction readLegacyEventTurnId(message: RpcMessage): string | null {\n if (!isRecord(message.params)) return null;\n const msg = isRecord(message.params.msg) ? message.params.msg : {};\n const value = asString(message.params.id ?? msg.turn_id ?? msg.turnId).trim();\n return value.length > 0 ? value : null;\n}\n\nfunction parseTimestamp(value: unknown): number | null {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n return null;\n }\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\nfunction decodeJwtPayload(token: unknown): Record<string, unknown> | null {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n return null;\n }\n\n const segments = token.split(\".\");\n if (segments.length < 2) {\n return null;\n }\n\n try {\n const payloadRaw = Buffer.from(segments[1], \"base64url\").toString(\"utf8\");\n const payload = JSON.parse(payloadRaw);\n return payload && typeof payload === \"object\"\n ? (payload as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction extractJwtIssuedAtMs(token: unknown): number | null {\n const payload = decodeJwtPayload(token);\n if (!payload) {\n return null;\n }\n\n const issuedAt = payload[\"iat\"];\n if (typeof issuedAt !== \"number\" || !Number.isFinite(issuedAt)) {\n return null;\n }\n\n return issuedAt * 1000;\n}\n\nfunction parseAuthRecord(content: string): AuthRecord | null {\n try {\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === \"object\" ? (parsed as AuthRecord) : null;\n } catch {\n return null;\n }\n}\n\nfunction extractAuthRecencyMs(content: string): number | null {\n const parsed = parseAuthRecord(content);\n if (!parsed) {\n return null;\n }\n\n const rootLastRefresh = parseTimestamp(parsed.last_refresh);\n const nestedLastRefresh = parseTimestamp(parsed.tokens?.last_refresh);\n const rootAccessIssuedAt = extractJwtIssuedAtMs(parsed.access_token);\n const nestedAccessIssuedAt = extractJwtIssuedAtMs(\n parsed.tokens?.access_token,\n );\n const candidates = [\n rootLastRefresh,\n nestedLastRefresh,\n rootAccessIssuedAt,\n nestedAccessIssuedAt,\n ].filter(\n (value): value is number =>\n typeof value === \"number\" && Number.isFinite(value),\n );\n\n if (candidates.length === 0) {\n return null;\n }\n\n return Math.max(...candidates);\n}\n\nfunction shouldWriteBackAuth(\n initialSourceAuth: string | null,\n currentSourceAuth: string | null,\n updatedAuth: string,\n): boolean {\n if (updatedAuth.trim().length === 0) {\n return false;\n }\n\n if (!currentSourceAuth) {\n return true;\n }\n\n if (currentSourceAuth === updatedAuth) {\n return false;\n }\n\n if (currentSourceAuth === initialSourceAuth) {\n return true;\n }\n\n const currentRecency = extractAuthRecencyMs(currentSourceAuth);\n const updatedRecency = extractAuthRecencyMs(updatedAuth);\n\n if (\n typeof updatedRecency === \"number\" &&\n typeof currentRecency === \"number\"\n ) {\n return updatedRecency > currentRecency;\n }\n\n if (\n typeof updatedRecency === \"number\" &&\n typeof currentRecency !== \"number\"\n ) {\n return true;\n }\n\n return false;\n}\n\nfunction inferRefreshFailureHint(stderrOutput: string): string | null {\n if (!stderrOutput) {\n return null;\n }\n\n const normalized = stderrOutput.toLowerCase();\n if (normalized.includes(REFRESH_TOKEN_REDEEMED_SNIPPET)) {\n return REFRESH_TOKEN_REDEEMED_SNIPPET;\n }\n\n return null;\n}\n\nasync function sendPayload(\n child: ReturnType<typeof spawn>,\n payload: Record<string, unknown>,\n): Promise<void> {\n child.stdin?.write(JSON.stringify(payload));\n child.stdin?.write(\"\\n\");\n}\n\nfunction isRpcResponseForRequest(\n message: RpcMessage,\n requestId: number,\n): boolean {\n if (message.id !== requestId) {\n return false;\n }\n return (\n Object.prototype.hasOwnProperty.call(message, \"result\") ||\n Object.prototype.hasOwnProperty.call(message, \"error\")\n );\n}\n\nasync function readRpcResponseById(\n rl: readline.Interface,\n requestId: number,\n timeoutMs: number,\n): Promise<RpcMessage> {\n return new Promise<RpcMessage>((resolve, reject) => {\n const timer = setTimeout(\n () => {\n cleanup();\n reject(new Error(\"codex RPC timed out\"));\n },\n Math.max(1, timeoutMs),\n );\n\n const cleanup = () => {\n clearTimeout(timer);\n rl.off(\"line\", onLine);\n rl.off(\"close\", onClose);\n };\n\n const onClose = () => {\n cleanup();\n reject(new Error(\"codex RPC stream closed before response\"));\n };\n\n const onLine = (line: string) => {\n let parsed: RpcMessage;\n try {\n parsed = JSON.parse(line) as RpcMessage;\n } catch {\n cleanup();\n reject(new Error(\"codex RPC returned malformed JSON\"));\n return;\n }\n\n if (!isRpcResponseForRequest(parsed, requestId)) {\n return;\n }\n\n cleanup();\n resolve(parsed);\n };\n\n rl.on(\"line\", onLine);\n rl.on(\"close\", onClose);\n });\n}\n\nfunction formatRpcError(method: string, error: RpcError): string {\n const codeText =\n typeof error.code === \"number\" ? ` (code ${error.code})` : \"\";\n const message =\n typeof error.message === \"string\" && error.message.trim().length > 0\n ? error.message.trim()\n : \"Unknown RPC error\";\n return `${method} failed${codeText}: ${message}`;\n}\n\nfunction toWindow(\n rpc?: RpcRateLimitWindow | null,\n): RateLimitWindow | undefined {\n if (!rpc) return undefined;\n const usedPercent =\n typeof rpc.usedPercent === \"number\" && Number.isFinite(rpc.usedPercent)\n ? rpc.usedPercent\n : undefined;\n const windowMinutes =\n typeof rpc.windowDurationMins === \"number\" &&\n Number.isFinite(rpc.windowDurationMins)\n ? rpc.windowDurationMins\n : undefined;\n\n let resetsAt: string | undefined;\n let resetsInSeconds: number | undefined;\n if (typeof rpc.resetsAt === \"number\" && Number.isFinite(rpc.resetsAt)) {\n const ms =\n rpc.resetsAt > 10_000_000_000 ? rpc.resetsAt : rpc.resetsAt * 1000;\n resetsAt = new Date(ms).toISOString();\n resetsInSeconds = Math.max(0, Math.round((ms - Date.now()) / 1000));\n }\n\n if (\n typeof usedPercent === \"undefined\" &&\n typeof windowMinutes === \"undefined\" &&\n typeof resetsAt === \"undefined\"\n ) {\n return undefined;\n }\n\n const window: RateLimitWindow = {};\n if (typeof usedPercent === \"number\") {\n window.usedPercent = usedPercent;\n }\n if (typeof windowMinutes === \"number\") {\n window.windowMinutes = windowMinutes;\n }\n if (typeof resetsAt === \"string\") {\n window.resetsAt = resetsAt;\n }\n if (typeof resetsInSeconds === \"number\") {\n window.resetsInSeconds = resetsInSeconds;\n }\n return window;\n}\n\nfunction parseRateLimitSnapshotFromRpcMessage(\n message: RpcMessage,\n): RateLimitSnapshot | null {\n if (message.error) {\n throw new Error(formatRpcError(\"account/rateLimits/read\", message.error));\n }\n\n const result = message.result as\n | { rateLimits?: RpcRateLimitSnapshot }\n | undefined;\n const limits = result?.rateLimits;\n const primary = toWindow(limits?.primary ?? null);\n const secondary = toWindow(limits?.secondary ?? null);\n\n if (!primary && !secondary) {\n return null;\n }\n\n const snapshot: RateLimitSnapshot = {\n lastUpdated: new Date().toISOString(),\n source: \"codex-rpc\",\n };\n if (primary) {\n snapshot.primary = primary;\n }\n if (secondary) {\n snapshot.secondary = secondary;\n }\n return snapshot;\n}\n\nexport async function fetchRateLimitsViaRpc(\n envOverride?: NodeJS.ProcessEnv,\n options: { authPath?: string; codexPath?: string } = {},\n): Promise<RateLimitSnapshot | null> {\n const binaryPath = options.codexPath ?? (await requireCodexCli());\n const tempHome = await fs.mkdtemp(path.join(os.tmpdir(), \"codex-rpc-\"));\n const tempAuthPath = path.join(tempHome, \"auth.json\");\n let initialSourceAuth: string | null = null;\n\n const sourceAuthPath =\n options.authPath ??\n (envOverride?.CODEX_HOME\n ? path.join(envOverride.CODEX_HOME, \"auth.json\")\n : path.join(\n envOverride?.HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n os.homedir(),\n \".codex\",\n \"auth.json\",\n ));\n\n try {\n initialSourceAuth = await fs\n .readFile(sourceAuthPath, \"utf8\")\n .catch(() => null);\n if (!initialSourceAuth) {\n return null;\n }\n await fs.writeFile(tempAuthPath, initialSourceAuth, \"utf8\");\n } catch {\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n return null;\n }\n\n const childEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...(envOverride ?? {}),\n HOME: tempHome,\n USERPROFILE: tempHome,\n CODEX_HOME: tempHome,\n CODEX_TELEMETRY_LABEL: \"codex-rpc\",\n ELECTRON_RUN_AS_NODE: \"1\",\n };\n const command = buildCodexCommand(\n binaryPath,\n [\"-s\", \"read-only\", \"-a\", \"untrusted\", \"app-server\"],\n childEnv,\n );\n const child = spawn(command.command, command.args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: childEnv,\n shell: command.shell,\n });\n\n const rl = readline.createInterface({\n input: child.stdout!,\n crlfDelay: Infinity,\n });\n let stderrOutput = \"\";\n child.stderr?.on(\"data\", (chunk) => {\n if (stderrOutput.length >= MAX_STDERR_CAPTURE_CHARS) {\n return;\n }\n const text = chunk.toString(\"utf8\");\n const remaining = MAX_STDERR_CAPTURE_CHARS - stderrOutput.length;\n stderrOutput += text.slice(0, Math.max(0, remaining));\n });\n\n try {\n await sendPayload(child, {\n id: 1,\n method: \"initialize\",\n params: { clientInfo: { name: \"codexuse\", version: \"0.0.0\" } },\n });\n const initializeResponse = await readRpcResponseById(rl, 1, RPC_TIMEOUT_MS);\n if (initializeResponse.error) {\n throw new Error(formatRpcError(\"initialize\", initializeResponse.error));\n }\n\n await sendPayload(child, { method: \"initialized\", params: {} });\n\n await sendPayload(child, {\n id: 2,\n method: \"account/rateLimits/read\",\n params: {},\n });\n const message = await readRpcResponseById(rl, 2, RPC_TIMEOUT_MS);\n if (message.error) {\n const base = formatRpcError(\"account/rateLimits/read\", message.error);\n const hint = inferRefreshFailureHint(stderrOutput);\n if (hint && !base.toLowerCase().includes(hint)) {\n throw new Error(`${base}; ${hint}`);\n }\n throw new Error(base);\n }\n\n return parseRateLimitSnapshotFromRpcMessage(message);\n } finally {\n child.kill();\n rl.close();\n try {\n const updatedAuth = await fs.readFile(tempAuthPath, \"utf8\");\n if (updatedAuth.trim().length > 0) {\n const currentSourceAuth = await fs\n .readFile(sourceAuthPath, \"utf8\")\n .catch(() => null);\n if (\n shouldWriteBackAuth(initialSourceAuth, currentSourceAuth, updatedAuth)\n ) {\n await fs.writeFile(sourceAuthPath, updatedAuth, \"utf8\");\n } else if (\n currentSourceAuth &&\n currentSourceAuth !== updatedAuth &&\n currentSourceAuth !== initialSourceAuth\n ) {\n logWarn(\n \"Skipped stale auth sync-back after rate-limit probe; source auth changed in flight.\",\n {\n sourceAuthPath,\n currentRecencyMs: extractAuthRecencyMs(currentSourceAuth),\n updatedRecencyMs: extractAuthRecencyMs(updatedAuth),\n },\n );\n }\n }\n } catch {\n // Best effort: if auth sync-back fails, keep existing source auth.\n }\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n }\n}\n\nexport async function activateResetWindowViaRpc(\n envOverride?: NodeJS.ProcessEnv,\n options: { authPath?: string; codexPath?: string } = {},\n): Promise<CodexResetWindowActivationResult> {\n const binaryPath = options.codexPath ?? (await requireCodexCli());\n const tempHome = await fs.mkdtemp(\n path.join(os.tmpdir(), \"codex-activation-\"),\n );\n const tempAuthPath = path.join(tempHome, \"auth.json\");\n let initialSourceAuth: string | null = null;\n\n const sourceAuthPath =\n options.authPath ??\n (envOverride?.CODEX_HOME\n ? path.join(envOverride.CODEX_HOME, \"auth.json\")\n : path.join(\n envOverride?.HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n os.homedir(),\n \".codex\",\n \"auth.json\",\n ));\n\n try {\n initialSourceAuth = await fs\n .readFile(sourceAuthPath, \"utf8\")\n .catch(() => null);\n if (!initialSourceAuth) {\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n return { status: \"skipped\", reason: \"auth-missing\" };\n }\n await fs.writeFile(tempAuthPath, initialSourceAuth, \"utf8\");\n } catch {\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n return { status: \"skipped\", reason: \"auth-missing\" };\n }\n\n const childEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...(envOverride ?? {}),\n HOME: tempHome,\n USERPROFILE: tempHome,\n CODEX_HOME: tempHome,\n CODEX_TELEMETRY_LABEL: \"codex-reset-activation\",\n ELECTRON_RUN_AS_NODE: \"1\",\n };\n const command = buildCodexCommand(\n binaryPath,\n [\"-s\", \"read-only\", \"-a\", \"untrusted\", \"app-server\"],\n childEnv,\n );\n const child = spawn(command.command, command.args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: childEnv,\n shell: command.shell,\n });\n\n const rl = readline.createInterface({\n input: child.stdout!,\n crlfDelay: Infinity,\n });\n const reader = createRpcMessageReader(rl);\n let stderrOutput = \"\";\n child.stderr?.on(\"data\", (chunk) => {\n if (stderrOutput.length >= MAX_STDERR_CAPTURE_CHARS) {\n return;\n }\n const text = chunk.toString(\"utf8\");\n const remaining = MAX_STDERR_CAPTURE_CHARS - stderrOutput.length;\n stderrOutput += text.slice(0, Math.max(0, remaining));\n });\n\n try {\n await sendPayload(child, {\n id: 1,\n method: \"initialize\",\n params: { clientInfo: { name: \"codexuse\", version: \"0.0.0\" } },\n });\n const initializeResponse = await reader.read(\n (message) => isRpcResponseForRequest(message, 1),\n RPC_TIMEOUT_MS,\n );\n if (initializeResponse.error) {\n throw new Error(formatRpcError(\"initialize\", initializeResponse.error));\n }\n\n await sendPayload(child, { method: \"initialized\", params: {} });\n\n await sendPayload(child, {\n id: 2,\n method: \"thread/start\",\n params: {\n cwd: tempHome,\n model: ACTIVATION_MODEL,\n approvalPolicy: \"untrusted\",\n sandbox: \"read-only\",\n experimentalRawEvents: false,\n },\n });\n const threadResponse = await reader.read(\n (message) => isRpcResponseForRequest(message, 2),\n RPC_TIMEOUT_MS,\n );\n if (threadResponse.error) {\n throw new Error(formatRpcError(\"thread/start\", threadResponse.error));\n }\n const threadId = readThreadIdFromResult(threadResponse.result);\n if (!threadId) {\n throw new Error(\"thread/start response did not include a thread id.\");\n }\n\n await sendPayload(child, {\n id: 3,\n method: \"turn/start\",\n params: {\n threadId,\n model: ACTIVATION_MODEL,\n effort: \"low\",\n input: [\n {\n type: \"text\",\n text: ACTIVATION_PROMPT,\n text_elements: [],\n },\n ],\n },\n });\n const turnResponse = await reader.read(\n (message) => isRpcResponseForRequest(message, 3),\n RPC_TIMEOUT_MS,\n );\n if (turnResponse.error) {\n const base = formatRpcError(\"turn/start\", turnResponse.error);\n const hint = inferRefreshFailureHint(stderrOutput);\n if (hint && !base.toLowerCase().includes(hint)) {\n throw new Error(`${base}; ${hint}`);\n }\n throw new Error(base);\n }\n const turnId = readTurnIdFromResult(turnResponse.result);\n if (!turnId) {\n throw new Error(\"turn/start response did not include a turn id.\");\n }\n\n const completed = await reader.read(\n (message) =>\n (message.method === \"turn/completed\" &&\n readTurnIdFromNotification(message) === turnId) ||\n (message.method === \"codex/event/task_complete\" &&\n readLegacyEventTurnId(message) === turnId),\n ACTIVATION_TURN_TIMEOUT_MS,\n );\n const turnStatus = readTurnStatusFromNotification(completed);\n if (turnStatus.status === \"failed\") {\n return {\n status: \"failed\",\n reason: turnStatus.reason ?? \"turn-failed\",\n threadId,\n turnId,\n };\n }\n\n return { status: \"completed\", reason: null, threadId, turnId };\n } finally {\n child.kill();\n reader.dispose();\n rl.close();\n try {\n const updatedAuth = await fs.readFile(tempAuthPath, \"utf8\");\n if (updatedAuth.trim().length > 0) {\n const currentSourceAuth = await fs\n .readFile(sourceAuthPath, \"utf8\")\n .catch(() => null);\n if (\n shouldWriteBackAuth(initialSourceAuth, currentSourceAuth, updatedAuth)\n ) {\n await fs.writeFile(sourceAuthPath, updatedAuth, \"utf8\");\n } else if (\n currentSourceAuth &&\n currentSourceAuth !== updatedAuth &&\n currentSourceAuth !== initialSourceAuth\n ) {\n logWarn(\n \"Skipped stale auth sync-back after reset-window activation; source auth changed in flight.\",\n {\n sourceAuthPath,\n currentRecencyMs: extractAuthRecencyMs(currentSourceAuth),\n updatedRecencyMs: extractAuthRecencyMs(updatedAuth),\n },\n );\n }\n }\n } catch {\n // Best effort: if auth sync-back fails, keep existing source auth.\n }\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n }\n}\n","import { readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { CodexCliChannel, CodexCliInfoPayload, CodexCliStatusPayload } from \"@codexuse/contracts/desktop/ipc-types\";\n\ntype MutableStatus = CodexCliStatusPayload;\nconst STABLE_CHANNEL: CodexCliChannel = \"stable\";\nconst ENV_HINTS = [\"CODEX_BINARY\", \"CODEX_CLI_PATH\", \"CODEX_PATH\"] as const;\n\nlet cachedStatus: MutableStatus | null = null;\n\nfunction getPathHintEntries(): string[] {\n const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? \"\";\n const homeEntries = homeDir\n ? [\n path.join(homeDir, \".local\", \"bin\"),\n path.join(homeDir, \".fnm\", \"aliases\", \"default\", \"bin\"),\n path.join(homeDir, \".fnm\", \"current\", \"bin\"),\n path.join(homeDir, \".volta\", \"bin\"),\n path.join(homeDir, \".asdf\", \"shims\"),\n path.join(homeDir, \".bun\", \"bin\"),\n ]\n : [];\n const configuredHints = (process.env.CODEX_PATH_HINTS ?? \"\")\n .split(path.delimiter)\n .map(entry => entry.trim())\n .filter(Boolean);\n\n return [\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n ...homeEntries,\n ...configuredHints,\n ];\n}\n\nfunction fileExists(candidate: string | undefined | null): string | null {\n if (!candidate) {\n return null;\n }\n\n const normalized = path.resolve(candidate);\n\n try {\n const stats = statSync(normalized);\n if (stats.isFile()) {\n return normalized;\n }\n } catch {\n // ignore missing paths\n }\n\n return null;\n}\n\nfunction resolveCodexFromEnv(): string | null {\n for (const key of ENV_HINTS) {\n const value = process.env[key];\n if (!value) {\n continue;\n }\n const resolved = fileExists(value);\n if (resolved) {\n return resolved;\n }\n }\n return null;\n}\n\nfunction resolveCodexFromPath(): string | null {\n const pathValue = process.env.PATH ?? \"\";\n const entries = Array.from(\n new Set(\n [\n ...getPathHintEntries(),\n ...pathValue\n .split(path.delimiter)\n .map(entry => entry.trim())\n .filter(Boolean),\n ].filter(Boolean),\n ),\n );\n const names = process.platform === \"win32\"\n ? [\"codex.exe\", \"codex.cmd\", \"codex.bat\", \"codex\"]\n : [\"codex\"];\n\n for (const entry of entries) {\n for (const name of names) {\n const candidate = fileExists(path.join(entry, name));\n if (candidate) {\n return candidate;\n }\n }\n }\n return null;\n}\n\nfunction resolvePackageJsonPath(cliPath: string): string | null {\n const normalized = path.resolve(cliPath);\n const binDir = path.dirname(normalized);\n const packageDir = path.basename(binDir) === \"bin\" ? path.dirname(binDir) : path.dirname(normalized);\n const pkgPath = path.join(packageDir, \"package.json\");\n return fileExists(pkgPath);\n}\n\nfunction readCodexCliVersion(cliPath: string): string | null {\n const packageJsonPath = resolvePackageJsonPath(cliPath);\n if (!packageJsonPath) {\n return null;\n }\n try {\n const raw = readFileSync(packageJsonPath, \"utf8\");\n const parsed = JSON.parse(raw) as { version?: unknown };\n if (typeof parsed?.version !== \"string\") {\n return null;\n }\n const normalized = parsed.version.trim();\n return normalized.length > 0 ? normalized : null;\n } catch {\n return null;\n }\n}\n\nfunction buildUnavailableStatus(reason?: string): MutableStatus {\n return {\n available: false,\n path: null,\n reason: reason ?? \"Codex CLI not found. Install @openai/codex on this machine or set CODEX_BINARY.\",\n source: null,\n channel: STABLE_CHANNEL,\n };\n}\n\nfunction evaluateExternalStatus(): MutableStatus {\n const envPath = resolveCodexFromEnv();\n if (envPath) {\n return {\n available: true,\n path: envPath,\n reason: null,\n source: \"env\",\n channel: STABLE_CHANNEL,\n };\n }\n\n const pathResolved = resolveCodexFromPath();\n if (pathResolved) {\n return {\n available: true,\n path: pathResolved,\n reason: null,\n source: \"path\",\n channel: STABLE_CHANNEL,\n };\n }\n\n return buildUnavailableStatus();\n}\n\nfunction evaluateCodexCliStatus(): MutableStatus {\n return evaluateExternalStatus();\n}\n\nexport async function refreshCodexStatus(): Promise<CodexCliStatusPayload> {\n cachedStatus = evaluateCodexCliStatus();\n return { ...cachedStatus };\n}\n\nasync function getCodexCliStatus(): Promise<CodexCliStatusPayload> {\n if (!cachedStatus) {\n return refreshCodexStatus();\n }\n return { ...cachedStatus };\n}\n\nexport async function getCodexCliInfo(): Promise<CodexCliInfoPayload> {\n const status = await getCodexCliStatus();\n const version =\n status.available && status.path\n ? readCodexCliVersion(status.path)\n : null;\n return { ...status, version };\n}\n\nexport class CodexCliMissingError extends Error {\n readonly status: CodexCliStatusPayload;\n\n constructor(status: CodexCliStatusPayload, message?: string) {\n super(message ?? status.reason ?? \"Codex CLI is not available\");\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"CodexCliMissingError\";\n this.status = { ...status };\n }\n}\n\nexport async function requireCodexCli(): Promise<string> {\n const status = await refreshCodexStatus();\n if (!status.available || !status.path) {\n throw new CodexCliMissingError(status);\n }\n return status.path;\n}\n","import { spawnSync } from \"node:child_process\";\nimport path from \"node:path\";\n\nlet cachedNodeRuntime: string | null = null;\n\nfunction isJavaScriptEntrypoint(binaryPath: string): boolean {\n const normalized = binaryPath.trim().toLowerCase();\n return (\n normalized.endsWith(\".js\") ||\n normalized.endsWith(\".mjs\") ||\n normalized.endsWith(\".cjs\")\n );\n}\n\nfunction resolveNodeRuntime(env?: NodeJS.ProcessEnv): string {\n const override =\n env?.CODEX_NODE_RUNTIME?.trim() ||\n env?.CODEX_NODE_BIN?.trim() ||\n env?.CODEX_NODE?.trim() ||\n process.env.CODEX_NODE_RUNTIME?.trim() ||\n process.env.CODEX_NODE_BIN?.trim() ||\n process.env.CODEX_NODE?.trim() ||\n null;\n if (override) {\n return override;\n }\n\n if (cachedNodeRuntime) {\n return cachedNodeRuntime;\n }\n\n const runtimeEnv: NodeJS.ProcessEnv = { ...process.env, ...env };\n const homeDir = runtimeEnv.HOME ?? runtimeEnv.USERPROFILE ?? \"\";\n const pathHints = (runtimeEnv.CODEX_PATH_HINTS ?? process.env.CODEX_PATH_HINTS ?? \"\")\n .split(path.delimiter)\n .map(entry => entry.trim())\n .filter(Boolean);\n const extraPathEntries = [\n \"/usr/local/bin\",\n \"/opt/homebrew/bin\",\n path.join(homeDir, \".local\", \"bin\"),\n path.join(homeDir, \".fnm\", \"aliases\", \"default\", \"bin\"),\n path.join(homeDir, \".fnm\", \"current\", \"bin\"),\n ...pathHints,\n ].filter(Boolean);\n const currentPath = runtimeEnv.PATH ?? \"\";\n runtimeEnv.PATH = Array.from(\n new Set([...extraPathEntries, ...currentPath.split(path.delimiter).filter(Boolean)]),\n ).join(path.delimiter);\n\n const candidates = Array.from(\n new Set(\n [\n runtimeEnv.CODEX_NODE_RUNTIME?.trim(),\n runtimeEnv.CODEX_NODE_BIN?.trim(),\n runtimeEnv.CODEX_NODE?.trim(),\n \"/opt/homebrew/bin/node\",\n \"/usr/local/bin/node\",\n \"node\",\n ].filter((candidate): candidate is string => typeof candidate === \"string\" && candidate.length > 0),\n ),\n );\n\n for (const candidate of candidates) {\n const probe = spawnSync(candidate, [\"-v\"], { env: runtimeEnv, stdio: \"ignore\" });\n if (!probe.error && probe.status === 0) {\n cachedNodeRuntime = candidate;\n return candidate;\n }\n }\n\n cachedNodeRuntime = process.execPath;\n return process.execPath;\n}\n\nexport function buildCodexCommand(\n binaryPath: string,\n args: ReadonlyArray<string>,\n env?: NodeJS.ProcessEnv,\n): {\n command: string;\n args: string[];\n shell: boolean;\n} {\n if (isJavaScriptEntrypoint(binaryPath)) {\n return {\n command: resolveNodeRuntime(env),\n args: [binaryPath, ...args],\n shell: false,\n };\n }\n\n return {\n command: binaryPath,\n args: [...args],\n shell: process.platform === \"win32\",\n };\n}\n","const isTestEnv =\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n process.env.VITEST === '1';\n\nfunction isMocked(fn: unknown): boolean {\n return Boolean(fn && typeof fn === 'function' && 'mock' in (fn as object));\n}\n\nexport function logWarn(...args: Parameters<typeof console.warn>): void {\n if (isTestEnv && !isMocked(console.warn)) {\n return;\n }\n console.warn(...args);\n}\n\nexport function logError(...args: Parameters<typeof console.error>): void {\n if (isTestEnv && !isMocked(console.error)) {\n return;\n }\n console.error(...args);\n}\n\nexport function logInfo(...args: Parameters<typeof console.info>): void {\n if (isTestEnv && !isMocked(console.info)) {\n return;\n }\n console.info(...args);\n}\n","export function printHelp(version: string): void {\n console.log(`CodexUse CLI v${version}\n\nUsage:\n codexuse doctor\n codexuse run --profile <name> -- <codex args>\n codexuse best [--dry-run] -- <codex args>\n\n codexuse account-pool status [--runtime=desktop|daemon] [--state-dir=/abs/path] [--port=NNNN]\n codexuse account-pool quickstart\n codexuse account-pool enable\n codexuse account-pool disable\n codexuse account-pool routing <least-used|round-robin>\n codexuse account-pool profiles list\n codexuse account-pool profiles set <name> [more...]\n codexuse account-pool models list\n codexuse account-pool keys list [--runtime=desktop|daemon]\n codexuse account-pool keys create [--runtime=desktop|daemon]\n codexuse account-pool sessions list [--runtime=desktop|daemon]\n\n codexuse profile list [--no-usage] [--compact]\n codexuse profile current\n codexuse profile add <name> [--skip-login] [--device-auth] [--login=browser|device]\n codexuse profile refresh <name> [--skip-login] [--device-auth] [--login=browser|device]\n codexuse profile switch <name> [--restart-codex]\n codexuse profile autoroll [--switch-left=0-50] [--threshold=50-100] [--dry-run] [--watch] [--interval=seconds] [--restart-codex|--no-restart-codex]\n codexuse profile delete <name>\n codexuse profile rename <old> <new>\n\n codexuse license status [--refresh]\n codexuse license activate <license-key>\n\n codexuse sync status\n codexuse sync pull\n codexuse sync push\n\n codexuse daemon start [--port=NNNN] [--telegram-bot-token=<token>] [--project-path=/abs/path]\n\nFlags:\n -h, --help Show help\n -v, --version Show version\n --no-usage Skip rate-limit usage fetch\n --compact Names only\n --device-auth Use device auth for Codex login\n --login=MODE Login mode: browser | device\n --switch-left=NN Auto-roll switch threshold by percent left (0-50)\n --threshold=NN Legacy auto-roll switch threshold by percent used (50-100)\n --watch Keep checking and auto-switch when threshold is reached\n --interval=SEC Watch interval in seconds (default: 30)\n --dry-run Print planned switch without changing active profile\n --restart-codex Restart official Codex after a profile switch\n --no-restart-codex Override saved auto-roll restart setting\n --profile=NAME Run Codex with one saved profile\n --runtime=NAME Accounts Pool runtime store: desktop | daemon\n --state-dir=PATH Override the runtime state dir for Accounts Pool inspection\n --port=NNNN Stable daemon/API port (or use with account-pool status for daemon base URL)\n --telegram-bot-token=TOKEN Enable Telegram remote control for daemon mode\n --project-path=PATH Optional path to bootstrap as the default Projects root in daemon mode\n\nNote: profile autoroll requires Pro.\n`);\n}\n","import type { CodexLoginMode } from \"./codexCli\";\n\nexport const DEFAULT_AUTOROLL_INTERVAL_SECONDS = 30;\n\nexport function hasFlag(args: string[], flag: string): boolean {\n return args.includes(flag);\n}\n\nexport function stripFlags(args: string[]): string[] {\n return args.filter(arg => !arg.startsWith(\"-\"));\n}\n\nexport function parseLoginMode(flags: string[]): CodexLoginMode | null {\n if (flags.includes(\"--device-auth\")) return \"device\";\n const explicit = flags.find(flag => flag.startsWith(\"--login=\"));\n if (!explicit) return null;\n const value = explicit.split(\"=\")[1];\n if (value === \"browser\" || value === \"device\") {\n return value;\n }\n return null;\n}\n\nexport function parseNumericFlag(flags: string[], name: string): number | null {\n const explicit = flags.find(flag => flag.startsWith(`${name}=`));\n if (!explicit) {\n return null;\n }\n const raw = explicit.slice(`${name}=`.length);\n const value = Number.parseFloat(raw);\n return Number.isFinite(value) ? value : Number.NaN;\n}\n\nexport function parseIntegerFlag(flags: string[], name: string): number | null {\n const explicit = flags.find(flag => flag.startsWith(`${name}=`));\n if (!explicit) {\n return null;\n }\n const raw = explicit.slice(`${name}=`.length);\n const value = Number.parseInt(raw, 10);\n return Number.isFinite(value) ? value : Number.NaN;\n}\n\nexport function parseStringFlag(flags: string[], name: string): string | null {\n const explicit = flags.find(flag => flag.startsWith(`${name}=`));\n if (!explicit) {\n return null;\n }\n const value = explicit.slice(`${name}=`.length).trim();\n return value.length > 0 ? value : \"\";\n}\n","import { spawn } from \"node:child_process\";\nimport { maxUsedPercent } from \"@codexuse/runtime-profiles/profiles/rate-limit-notifier\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport type { Profile, RateLimitSnapshot } from \"@codexuse/contracts/profiles/types\";\nimport { readAccountPoolRuntimeSummary } from \"./accountPool\";\nimport { hasFlag } from \"../platform/args\";\nimport {\n buildCodexCommand,\n resolveCodexBinary,\n} from \"../platform/codexCli\";\n\ntype SplitCommandArgs = {\n flags: string[];\n codexArgs: string[];\n};\n\ntype CommandResult = {\n code: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n};\n\ntype BestProfileCandidate = {\n profile: Profile;\n usedPercent: number | null;\n resetSeconds: number | null;\n};\n\nconst DOCTOR_TIMEOUT_MS = 8_000;\n\nfunction splitCommandArgs(args: string[]): SplitCommandArgs {\n const delimiterIndex = args.indexOf(\"--\");\n const flags = delimiterIndex >= 0 ? args.slice(0, delimiterIndex) : args.slice();\n const codexArgs = delimiterIndex >= 0 ? args.slice(delimiterIndex + 1) : [];\n return { flags, codexArgs };\n}\n\nfunction readOption(flags: string[], longName: string, shortName?: string): string | null {\n for (let index = 0; index < flags.length; index += 1) {\n const flag = flags[index];\n if (flag === longName) {\n const next = flags[index + 1];\n return next && !next.startsWith(\"-\") ? next : \"\";\n }\n if (flag.startsWith(`${longName}=`)) {\n return flag.slice(longName.length + 1).trim();\n }\n if (shortName && flag === shortName) {\n const next = flags[index + 1];\n return next && !next.startsWith(\"-\") ? next : \"\";\n }\n }\n return null;\n}\n\nfunction firstLine(value: string): string | null {\n const line = value.split(/\\r?\\n/).map((entry) => entry.trim()).find(Boolean);\n return line ?? null;\n}\n\nfunction formatUsagePercent(value: number | null): string {\n return typeof value === \"number\" && Number.isFinite(value)\n ? `${Math.round(value)}%`\n : \"unknown\";\n}\n\nfunction snapshotResetSeconds(snapshot: RateLimitSnapshot | null): number | null {\n const values = [\n snapshot?.primary?.resetsInSeconds,\n snapshot?.secondary?.resetsInSeconds,\n ].filter((value): value is number => typeof value === \"number\" && Number.isFinite(value));\n return values.length > 0 ? Math.min(...values) : null;\n}\n\nfunction fallbackUsedPercent(profile: Profile): number | null {\n const cached = maxUsedPercent(profile.rateLimit ?? null);\n return typeof cached === \"number\" && Number.isFinite(cached) ? cached : null;\n}\n\nfunction compareCandidates(left: BestProfileCandidate, right: BestProfileCandidate): number {\n const leftUsage = left.usedPercent ?? Number.POSITIVE_INFINITY;\n const rightUsage = right.usedPercent ?? Number.POSITIVE_INFINITY;\n if (leftUsage !== rightUsage) {\n return leftUsage - rightUsage;\n }\n const leftReset = left.resetSeconds ?? Number.POSITIVE_INFINITY;\n const rightReset = right.resetSeconds ?? Number.POSITIVE_INFINITY;\n if (leftReset !== rightReset) {\n return leftReset - rightReset;\n }\n return left.profile.name.localeCompare(right.profile.name);\n}\n\nasync function runCommand(\n codexPath: string,\n args: string[],\n timeoutMs: number,\n): Promise<CommandResult> {\n const command = buildCodexCommand(codexPath, args);\n return new Promise((resolve) => {\n const child = spawn(command.command, command.args, {\n env: process.env,\n shell: command.shell,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n let settled = false;\n let timedOut = false;\n let timer: NodeJS.Timeout;\n const finish = (code: number | null) => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n };\n timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n finish(null);\n }, timeoutMs);\n child.stdout?.on(\"data\", (chunk) => {\n stdout += String(chunk).slice(0, 20_000);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += String(chunk).slice(0, 20_000);\n });\n child.on(\"error\", () => finish(null));\n child.on(\"close\", (code) => finish(code));\n });\n}\n\nasync function selectBestProfile(\n manager: ProfileManager,\n profiles: Profile[],\n codexPath: string,\n): Promise<BestProfileCandidate | null> {\n const candidates: BestProfileCandidate[] = [];\n for (const profile of profiles) {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n continue;\n }\n try {\n const snapshot = await manager.readLiveRateLimits(profile.name, { codexPath });\n candidates.push({\n profile,\n usedPercent: typeof maxUsedPercent(snapshot) === \"number\"\n ? maxUsedPercent(snapshot)\n : fallbackUsedPercent(profile),\n resetSeconds: snapshotResetSeconds(snapshot),\n });\n } catch {\n candidates.push({\n profile,\n usedPercent: fallbackUsedPercent(profile),\n resetSeconds: snapshotResetSeconds(profile.rateLimit ?? null),\n });\n }\n }\n return candidates.sort(compareCandidates)[0] ?? null;\n}\n\nasync function runCodexWithProfile(\n manager: ProfileManager,\n profileName: string,\n codexArgs: string[],\n): Promise<void> {\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n throw new Error(\"Codex CLI not found. Install Codex CLI or set CODEX_BINARY.\");\n }\n const runtime = await manager.prepareProfileRuntime(profileName);\n const command = buildCodexCommand(codexPath, codexArgs);\n try {\n const child = spawn(command.command, command.args, {\n env: runtime.env,\n shell: command.shell,\n stdio: \"inherit\",\n });\n const exitCode = await new Promise<number>((resolve) => {\n child.on(\"close\", (code) => resolve(code ?? 0));\n });\n process.exitCode = exitCode;\n } finally {\n await manager.syncProfileRuntime(profileName, runtime.profileHome).catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Warning: failed to sync profile runtime for '${profileName}': ${message}`);\n });\n }\n}\n\nexport async function handleDoctorCommand(args: string[]): Promise<void> {\n if (hasFlag(args, \"--help\") || hasFlag(args, \"-h\")) {\n console.log(`Usage:\n codexuse doctor\n\nChecks Codex CLI, auth, saved profiles, license, and Accounts Pool readiness.`);\n return;\n }\n\n const manager = new ProfileManager();\n const codexPath = resolveCodexBinary();\n const [profiles, current, license, accountPool] = await Promise.all([\n manager.listProfiles(),\n manager.getCurrentProfile(),\n licenseService.getStatus().catch(() => null),\n readAccountPoolRuntimeSummary().catch(() => null),\n ]);\n\n console.log(\"CodexUse Doctor\");\n if (!codexPath) {\n console.log(\"Codex CLI: missing\");\n } else {\n const version = await runCommand(codexPath, [\"--version\"], DOCTOR_TIMEOUT_MS);\n const versionText = firstLine(version.stdout) ?? firstLine(version.stderr);\n console.log(`Codex CLI: ${version.code === 0 ? \"ok\" : \"check\"} (${codexPath})`);\n console.log(`Version: ${versionText ?? (version.timedOut ? \"timed out\" : \"unknown\")}`);\n\n const auth = await runCommand(codexPath, [\"login\", \"status\"], DOCTOR_TIMEOUT_MS);\n const authText = firstLine(auth.stdout) ?? firstLine(auth.stderr);\n console.log(`Auth: ${auth.code === 0 ? \"ok\" : \"check\"}${authText ? ` (${authText})` : \"\"}`);\n }\n\n console.log(`Profiles: ${profiles.length}`);\n console.log(`Active profile: ${current.name ?? \"none\"}${current.trusted ? \"\" : \" (untrusted)\"}`);\n console.log(`License: ${license ? `${license.tier} (${license.state})` : \"unknown\"}`);\n if (accountPool) {\n console.log(\n `Accounts Pool: ${accountPool.enabled ? \"on\" : \"off\"} | keys ${accountPool.activeApiKeyCount} | sessions ${accountPool.activeSessionCount}`,\n );\n } else {\n console.log(\"Accounts Pool: unknown\");\n }\n\n const fixes: string[] = [];\n if (!codexPath) {\n fixes.push(\"Install Codex CLI or set CODEX_BINARY.\");\n }\n if (profiles.length === 0) {\n fixes.push(\"Add first profile: codexuse profile add personal\");\n }\n if (profiles.length === 1) {\n fixes.push(\"Add second profile: codexuse profile add work\");\n }\n if (!current.name && profiles.length > 0) {\n fixes.push(`Switch active profile: codexuse profile switch ${profiles[0]?.name}`);\n }\n if (accountPool && (!accountPool.enabled || accountPool.activeApiKeyCount === 0)) {\n fixes.push(\"Pool quickstart: codexuse account-pool quickstart\");\n }\n\n if (fixes.length > 0) {\n console.log(\"Fixes:\");\n for (const fix of fixes) {\n console.log(`- ${fix}`);\n }\n return;\n }\n console.log(\"Ready.\");\n}\n\nexport async function handleRunCommand(args: string[]): Promise<void> {\n const { flags, codexArgs } = splitCommandArgs(args);\n if (hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n console.log(`Usage:\n codexuse run --profile <name> -- <codex args>\n\nRuns Codex under one saved CodexUse profile.`);\n return;\n }\n const profileName = readOption(flags, \"--profile\", \"-p\");\n if (!profileName) {\n throw new Error(\"Profile is required. Use --profile <name>.\");\n }\n const manager = new ProfileManager();\n await runCodexWithProfile(manager, profileName, codexArgs);\n}\n\nexport async function handleBestCommand(args: string[]): Promise<void> {\n const { flags, codexArgs } = splitCommandArgs(args);\n if (hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n console.log(`Usage:\n codexuse best -- <codex args>\n\nPicks the healthiest saved profile, then runs Codex. Auto-run requires Pro.`);\n return;\n }\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n throw new Error(\"Codex CLI not found. Install Codex CLI or set CODEX_BINARY.\");\n }\n const manager = new ProfileManager();\n const profiles = await manager.listProfiles();\n const best = await selectBestProfile(manager, profiles, codexPath);\n if (!best) {\n throw new Error(\"No valid saved profiles found. Add one with `codexuse profile add <name>`.\");\n }\n\n const dryRun = hasFlag(flags, \"--dry-run\");\n const license = await licenseService.getStatus();\n const summary = `${best.profile.name} (${formatUsagePercent(best.usedPercent)} used)`;\n if (!license.isPro) {\n console.log(`Best profile: ${summary}`);\n console.log(\"Auto-run is Pro. Free path:\");\n console.log(` codexuse run --profile ${best.profile.name} -- ${codexArgs.join(\" \")}`.trimEnd());\n return;\n }\n if (dryRun) {\n console.log(`Would run with profile: ${summary}`);\n return;\n }\n console.error(`CodexUse best -> ${summary}`);\n await runCodexWithProfile(manager, best.profile.name, codexArgs);\n}\n","import type { RateLimitSnapshot } from \"@codexuse/contracts/profiles/types\";\n\nexport function maxUsedPercent(snapshot: RateLimitSnapshot | null | undefined): number | null {\n if (!snapshot) {\n return null;\n }\n\n const candidates = [\n snapshot.primary?.usedPercent,\n snapshot.secondary?.usedPercent,\n ].filter((value): value is number => typeof value === \"number\" && Number.isFinite(value));\n\n if (candidates.length === 0) {\n return null;\n }\n\n return Math.max(...candidates);\n}\n","import { spawn } from \"node:child_process\";\nimport { statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nconst ENV_HINTS = [\"CODEX_BINARY\", \"CODEX_CLI_PATH\", \"CODEX_PATH\"] as const;\n\nexport type CodexLoginMode = \"browser\" | \"device\";\n\nfunction fileExists(candidate: string | null | undefined): string | null {\n if (!candidate) return null;\n const resolved = path.resolve(candidate);\n try {\n const stat = statSync(resolved);\n if (stat.isFile()) return resolved;\n } catch {\n return null;\n }\n return null;\n}\n\nfunction resolveFromEnv(): string | null {\n for (const key of ENV_HINTS) {\n const value = process.env[key];\n if (!value) continue;\n const resolved = fileExists(value);\n if (resolved) return resolved;\n }\n return null;\n}\n\nfunction resolveFromPath(): string | null {\n const pathValue = process.env.PATH ?? \"\";\n const entries = pathValue.split(path.delimiter).filter(Boolean);\n const names = process.platform === \"win32\"\n ? [\"codex.exe\", \"codex.cmd\", \"codex.bat\", \"codex\"]\n : [\"codex\"];\n\n for (const entry of entries) {\n for (const name of names) {\n const candidate = fileExists(path.join(entry, name));\n if (candidate) return candidate;\n }\n }\n\n return null;\n}\n\nexport function resolveCodexBinary(): string | null {\n return (\n resolveFromEnv() ||\n resolveFromPath()\n );\n}\n\nfunction requireCodexBinary(context?: string): string {\n const resolved = resolveCodexBinary();\n if (resolved) return resolved;\n const hint = \"Install Codex CLI (npm i -g @openai/codex) or set CODEX_BINARY.\";\n const message = context ? `${context} ${hint}` : hint;\n throw new Error(message);\n}\n\nexport function buildCodexCommand(codexPath: string, args: string[]): { command: string; args: string[]; shell: boolean } {\n const normalized = codexPath.toLowerCase();\n const isJs = normalized.endsWith(\".js\") || normalized.endsWith(\".mjs\") || normalized.endsWith(\".cjs\");\n if (isJs) {\n return { command: process.execPath, args: [codexPath, ...args], shell: false };\n }\n\n const useShell = process.platform === \"win32\";\n return { command: codexPath, args, shell: useShell };\n}\n\nfunction isHeadless(): boolean {\n if (process.env.CODEXUSE_HEADLESS === \"1\") return true;\n if (process.env.CI) return true;\n if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return true;\n if (process.platform === \"linux\") {\n if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return true;\n }\n return false;\n}\n\nexport function resolveLoginMode(preferred?: CodexLoginMode | null): CodexLoginMode {\n if (preferred === \"browser\" || preferred === \"device\") {\n return preferred;\n }\n const envMode = process.env.CODEXUSE_LOGIN_MODE;\n if (envMode === \"browser\" || envMode === \"device\") {\n return envMode;\n }\n return isHeadless() ? \"device\" : \"browser\";\n}\n\nexport async function runCodexLogin(mode?: CodexLoginMode | null): Promise<void> {\n const codexPath = requireCodexBinary(\"Codex CLI is required to login.\");\n const resolvedMode = resolveLoginMode(mode ?? null);\n const loginArgs = resolvedMode === \"device\"\n ? [\"login\", \"--device-auth\"]\n : [\"login\"];\n const { command, args, shell } = buildCodexCommand(codexPath, loginArgs);\n\n const child = spawn(command, args, {\n stdio: \"inherit\",\n env: process.env,\n shell,\n });\n\n const exitCode = await new Promise<number>((resolve) => {\n child.on(\"close\", (code) => resolve(code ?? 0));\n });\n\n if (exitCode !== 0) {\n throw new Error(`Codex CLI login failed (exit code ${exitCode}).`);\n }\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport net from \"node:net\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { resolveInternalBunRuntime } from \"@codexuse/shared/core/internal-js-runtime\";\nimport { readAccountPoolRuntimeSummary } from \"./accountPool\";\nimport { hasFlag, parseIntegerFlag, parseStringFlag, stripFlags } from \"../platform/args\";\n\ntype DaemonStartOptions = {\n projectPath: string | null;\n port: number | null;\n telegramBotToken: string | null;\n version: string;\n};\n\nfunction normalizeTelegramBotToken(value: string | undefined): string | null {\n const trimmed = value?.trim() ?? \"\";\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction printDaemonHelp(version: string): void {\n console.log(`CodexUse CLI v${version}\n\nUsage:\n codexuse daemon start [--port=NNNN] [--telegram-bot-token=<token>] [--project-path=/abs/path]\n\nNotes:\n - Runs the T3 Projects/chat server in headless mode.\n - The same daemon can serve Accounts Pool and Telegram remote control.\n - Requires Bun on PATH because the bundled Projects server runs on Bun.\n - Pass --port to keep a stable local API URL for Accounts Pool or other local clients.\n - Pass --telegram-bot-token or set CODEXUSE_TELEGRAM_BOT_TOKEN to enable Telegram remote control.\n - --project-path bootstraps that folder as the default project/thread.\n - Stop with Ctrl+C or SIGTERM.\n`);\n}\n\nfunction resolveServerEntry(): string {\n const candidates = [\n path.resolve(__dirname, \"server\", \"index.mjs\"),\n path.resolve(__dirname, \"../../../server/dist/index.mjs\"),\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return candidates[0];\n}\n\nfunction resolveStateDir(): string {\n return path.join(os.homedir(), \".codexuse\", \"t3-daemon\");\n}\n\nfunction reserveLoopbackPort(port = 0): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => {\n const address = server.address();\n const port = typeof address === \"object\" && address ? address.port : null;\n server.close((error) => {\n if (error) {\n reject(error);\n return;\n }\n if (typeof port !== \"number\") {\n reject(new Error(\"Failed to reserve a loopback port for the Projects server.\"));\n return;\n }\n resolve(port);\n });\n });\n });\n}\n\nasync function runDaemonStart(options: DaemonStartOptions): Promise<void> {\n const entry = resolveServerEntry();\n if (!fs.existsSync(entry)) {\n throw new Error(\n `Missing bundled T3 server build output at ${entry}. Rebuild the CLI package with \\`bun run build:cli\\`.`,\n );\n }\n\n if (options.port !== null && (!Number.isFinite(options.port) || options.port < 1 || options.port > 65535)) {\n throw new Error(\"Daemon port must be an integer between 1 and 65535.\");\n }\n\n const port = await reserveLoopbackPort(options.port ?? 0);\n const authToken = randomBytes(24).toString(\"hex\");\n const stateDir = resolveStateDir();\n const projectPath = options.projectPath ? path.resolve(options.projectPath) : null;\n const childCwd = projectPath ?? process.cwd();\n const telegramBotToken = options.telegramBotToken?.trim() || null;\n\n const runtime = resolveInternalBunRuntime({\n T3CODE_MODE: \"desktop\",\n T3CODE_HOST: \"127.0.0.1\",\n T3CODE_PORT: String(port),\n T3CODE_NO_BROWSER: \"1\",\n T3CODE_AUTH_TOKEN: authToken,\n T3CODE_STATE_DIR: stateDir,\n T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: projectPath ? \"1\" : \"0\",\n CODEXUSE_TELEGRAM_RUNTIME_OWNER: \"daemon\",\n ...(telegramBotToken\n ? {\n CODEXUSE_TELEGRAM_BOT_TOKEN: telegramBotToken,\n CODEXUSE_TELEGRAM_BRIDGE_ENABLED: \"1\",\n }\n : {}),\n });\n\n const child = spawn(runtime.bin, [entry], {\n cwd: childCwd,\n env: runtime.env,\n stdio: \"inherit\",\n });\n\n console.log(`Daemon started. Projects server listening on http://127.0.0.1:${port}`);\n console.log(`State dir: ${stateDir}`);\n if (projectPath) {\n console.log(`Bootstrapped project path: ${projectPath}`);\n }\n if (telegramBotToken) {\n console.log(\"Telegram remote control enabled for this daemon session.\");\n }\n const accountPool = await readAccountPoolRuntimeSummary({\n runtime: \"daemon\",\n stateDir,\n port,\n });\n if (accountPool.enabled && accountPool.hasProLicense) {\n console.log(`Accounts Pool base URL: ${accountPool.baseUrl ?? `http://127.0.0.1:${port}`}`);\n if (accountPool.activeApiKeyCount > 0) {\n console.log(`Accounts Pool active keys: ${accountPool.activeApiKeyCount}`);\n } else {\n console.log(\"Accounts Pool is enabled, but this daemon has no runtime key yet. Create one with `codexuse account-pool keys create --runtime=daemon`.\");\n }\n } else if (accountPool.enabled) {\n console.log(\"Accounts Pool is configured, but Pro is required before this daemon can serve it.\");\n } else {\n console.log(\"Accounts Pool is disabled for this daemon. Enable it with `codexuse account-pool enable`.\");\n }\n if (options.port === null) {\n console.log(\"Tip: pass --port=3773 (or another fixed port) if another local client should keep one stable base URL.\");\n }\n console.log(\"Running until SIGINT/SIGTERM...\");\n\n await waitForChild(child);\n}\n\nfunction waitForChild(child: ChildProcess): Promise<void> {\n return new Promise((resolve, reject) => {\n let stopping = false;\n\n const stop = (signal: NodeJS.Signals) => {\n if (stopping) {\n return;\n }\n stopping = true;\n child.kill(signal);\n };\n\n const onSigInt = () => stop(\"SIGINT\");\n const onSigTerm = () => stop(\"SIGTERM\");\n\n process.once(\"SIGINT\", onSigInt);\n process.once(\"SIGTERM\", onSigTerm);\n\n child.once(\"exit\", (code, signal) => {\n process.off(\"SIGINT\", onSigInt);\n process.off(\"SIGTERM\", onSigTerm);\n if (code === 0 || stopping) {\n resolve();\n return;\n }\n reject(\n new Error(\n `Projects server exited unexpectedly (code=${code ?? \"null\"}, signal=${signal ?? \"null\"}).`,\n ),\n );\n });\n\n child.once(\"error\", (error) => {\n process.off(\"SIGINT\", onSigInt);\n process.off(\"SIGTERM\", onSigTerm);\n reject(error);\n });\n });\n}\n\nexport async function handleDaemonCommand(args: string[], version: string): Promise<void> {\n const flags = args.filter((arg) => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printDaemonHelp(version);\n return;\n }\n\n switch (sub) {\n case \"start\": {\n const port = parseIntegerFlag(flags, \"--port\");\n const projectPath =\n parseStringFlag(flags, \"--project-path\")\n ?? parseStringFlag(flags, \"--project\")\n ?? null;\n const telegramBotToken =\n parseStringFlag(flags, \"--telegram-bot-token\")\n ?? normalizeTelegramBotToken(process.env.CODEXUSE_TELEGRAM_BOT_TOKEN)\n ?? null;\n\n await runDaemonStart({\n projectPath,\n port,\n telegramBotToken,\n version,\n });\n return;\n }\n default:\n printDaemonHelp(version);\n return;\n }\n}\n","import { spawnSync } from \"node:child_process\"\nimport path from \"node:path\"\n\nexport interface InternalJavaScriptRuntime {\n readonly bin: string\n readonly env: NodeJS.ProcessEnv\n}\n\nlet cachedBunBinary: string | null = null\n\nfunction hasBunRuntime(): boolean {\n return typeof process.versions.bun === \"string\" && process.versions.bun.length > 0\n}\n\nfunction hasElectronRuntime(): boolean {\n return typeof process.versions.electron === \"string\" && process.versions.electron.length > 0\n}\n\nfunction buildRuntimePath(env: NodeJS.ProcessEnv): string {\n const homeDir = env.HOME ?? env.USERPROFILE ?? \"\"\n const pathHints = (env.CODEX_PATH_HINTS ?? \"\")\n .split(path.delimiter)\n .map(entry => entry.trim())\n .filter(Boolean)\n const entries = [\n env.PATH ?? \"\",\n path.join(homeDir, \".bun\", \"bin\"),\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n path.join(homeDir, \".local\", \"bin\"),\n path.join(homeDir, \".fnm\", \"aliases\", \"default\", \"bin\"),\n path.join(homeDir, \".fnm\", \"current\", \"bin\"),\n ...pathHints,\n ]\n\n return Array.from(\n new Set(\n entries\n .flatMap(entry => entry.split(path.delimiter))\n .map(entry => entry.trim())\n .filter(Boolean),\n ),\n ).join(path.delimiter)\n}\n\nfunction resolveConfiguredRuntime(env: NodeJS.ProcessEnv): string | null {\n const candidates = [\n env.CODEXUSE_INTERNAL_JS_RUNTIME,\n env.CODEXUSE_INTERNAL_BUN_BIN,\n env.BUN_BIN,\n process.env.CODEXUSE_INTERNAL_JS_RUNTIME,\n process.env.CODEXUSE_INTERNAL_BUN_BIN,\n process.env.BUN_BIN,\n ]\n\n for (const candidate of candidates) {\n const normalized = candidate?.trim() ?? \"\"\n if (normalized.length > 0) {\n return normalized\n }\n }\n\n return null\n}\n\nfunction resolveConfiguredBunBinary(env: NodeJS.ProcessEnv): string | null {\n const candidates = [\n env.CODEXUSE_INTERNAL_BUN_BIN,\n env.BUN_BIN,\n process.env.CODEXUSE_INTERNAL_BUN_BIN,\n process.env.BUN_BIN,\n ]\n\n for (const candidate of candidates) {\n const normalized = candidate?.trim() ?? \"\"\n if (normalized.length > 0) {\n return normalized\n }\n }\n\n return null\n}\n\nfunction probeBunBinary(env: NodeJS.ProcessEnv): string | null {\n if (hasBunRuntime()) {\n return process.execPath\n }\n\n if (cachedBunBinary) {\n return cachedBunBinary\n }\n\n const homeDir = env.HOME ?? env.USERPROFILE ?? \"\"\n const candidates = Array.from(\n new Set(\n [\n env.CODEXUSE_INTERNAL_BUN_BIN?.trim(),\n env.BUN_BIN?.trim(),\n path.join(homeDir, \".bun\", \"bin\", \"bun\"),\n \"/opt/homebrew/bin/bun\",\n \"/usr/local/bin/bun\",\n \"bun\",\n ].filter((candidate): candidate is string => typeof candidate === \"string\" && candidate.length > 0),\n ),\n )\n\n for (const candidate of candidates) {\n const probe = spawnSync(candidate, [\"--version\"], {\n env,\n stdio: \"ignore\",\n })\n if (!probe.error && probe.status === 0) {\n cachedBunBinary = candidate\n return candidate\n }\n }\n\n return null\n}\n\nexport function resolveInternalBunRuntime(\n overrides: Partial<NodeJS.ProcessEnv> = {},\n): InternalJavaScriptRuntime {\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n ...overrides,\n }\n env.PATH = buildRuntimePath(env)\n\n const runtimeBin = hasBunRuntime()\n ? process.execPath\n : resolveConfiguredBunBinary(env) ?? probeBunBinary(env)\n\n if (!runtimeBin) {\n throw new Error(\n \"CodexUse desktop requires a Bun runtime to launch internal services. Install Bun or set CODEXUSE_INTERNAL_BUN_BIN.\",\n )\n }\n\n delete env.ELECTRON_RUN_AS_NODE\n\n return {\n bin: runtimeBin,\n env,\n }\n}\n\nexport function resolveInternalJavaScriptRuntime(\n overrides: Partial<NodeJS.ProcessEnv> = {},\n): InternalJavaScriptRuntime {\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n ...overrides,\n }\n env.PATH = buildRuntimePath(env)\n\n const configuredRuntime = resolveConfiguredRuntime(env)\n const preferredRuntime = configuredRuntime ?? probeBunBinary(env) ?? process.execPath\n const usesElectronHostFallback =\n hasElectronRuntime() &&\n !hasBunRuntime() &&\n path.resolve(preferredRuntime) === path.resolve(process.execPath)\n\n if (usesElectronHostFallback) {\n env.ELECTRON_RUN_AS_NODE = \"1\"\n } else {\n delete env.ELECTRON_RUN_AS_NODE\n }\n\n return {\n bin: preferredRuntime,\n env,\n }\n}\n","import { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { printHelp } from \"../app/help\";\nimport { hasFlag, stripFlags } from \"../platform/args\";\n\nexport async function handleLicense(args: string[], version: string): Promise<void> {\n const flags = args.filter(arg => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printHelp(version);\n return;\n }\n\n switch (sub) {\n case \"status\": {\n const forceRefresh = hasFlag(flags, \"--refresh\");\n const status = await licenseService.getStatus({ forceRefresh });\n console.log(`Tier: ${status.tier}`);\n console.log(`State: ${status.state}`);\n if (status.profileLimit !== null) {\n console.log(`Profile limit: ${status.profileLimit}`);\n }\n if (status.profilesRemaining !== null) {\n console.log(`Profiles remaining: ${status.profilesRemaining}`);\n }\n if (status.purchaseEmail) {\n console.log(`Email: ${status.purchaseEmail}`);\n }\n if (status.maskedLicenseKey) {\n console.log(`License: ${status.maskedLicenseKey}`);\n }\n if (status.message) {\n console.log(`Message: ${status.message}`);\n }\n if (status.error) {\n console.log(`Error: ${status.error}`);\n }\n return;\n }\n case \"activate\": {\n const key = params[1];\n if (!key) {\n throw new Error(\"License key is required.\");\n }\n const status = await licenseService.activate(key);\n console.log(status.message ?? \"License activated.\");\n return;\n }\n default:\n printHelp(version);\n }\n}\n","import { licenseService, shouldEnforceProfileLimit } from \"@codexuse/runtime-profiles/license/service\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\n\nconst PROJECT_LIMIT_MESSAGE =\n \"CodexUse Free supports up to 2 projects. Upgrade to CodexUse Pro for unlimited projects.\";\n\nexport async function assertProfileCreationAllowed(\n profileManager?: ProfileManager,\n): Promise<void> {\n const manager = profileManager ?? new ProfileManager();\n await manager.initialize();\n\n const license = await licenseService.getStatus();\n const profiles = await manager.listProfiles();\n const licenseWithCounts = licenseService.applyProfileCount(license, profiles.length);\n\n if (\n typeof licenseWithCounts.profileLimit === \"number\" &&\n licenseWithCounts.profilesRemaining !== null &&\n licenseWithCounts.profilesRemaining <= 0\n ) {\n throw new Error(\"CodexUse Free supports up to 2 profiles. Upgrade to CodexUse Pro for unlimited profiles.\");\n }\n}\n\ntype WorkspaceLike = {\n kind?: string | null;\n};\n\nfunction countMainProjects(workspaces: WorkspaceLike[]): number {\n return workspaces.filter((workspace) => (workspace.kind ?? \"main\") !== \"worktree\").length;\n}\n\nexport async function assertProjectCreationAllowed(\n workspaces: WorkspaceLike[],\n): Promise<void> {\n const license = await licenseService.getStatus();\n if (!shouldEnforceProfileLimit(license)) {\n return;\n }\n\n const mainProjectCount = countMainProjects(workspaces);\n if (mainProjectCount >= 2) {\n throw new Error(PROJECT_LIMIT_MESSAGE);\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport path from \"node:path\";\nimport type {\n AutoRollActivityEntry,\n AutoRollActivityKind,\n OfficialCodexInstancesPayload,\n OfficialCodexProfileActionPayload,\n OfficialCodexProfileInstancePayload,\n OfficialCodexRestartPayload,\n OfficialCodexSyncStatusPayload,\n OfficialCodexUnmanagedInstancePayload,\n} from \"@codexuse/contracts/desktop/ipc-types\";\nimport {\n getAppState,\n patchAppState,\n updateAppState,\n type OfficialCodexManagedInstanceState,\n} from \"@codexuse/runtime-app-state/app/state\";\n\nconst RESTART_COOLDOWN_MS = 60_000;\nconst COMMAND_TIMEOUT_MS = 3_000;\nconst EXIT_WAIT_MS = 10_000;\nconst LAUNCH_WAIT_MS = 15_000;\nconst POLL_INTERVAL_MS = 250;\nconst APP_DISCOVERY_CACHE_TTL_MS = 60_000;\nconst APP_DISCOVERY_MISS_CACHE_TTL_MS = 5_000;\nconst OFFICIAL_CODEX_ACTIVITY_LIMIT = 50;\n\ntype CommandResult = {\n code: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n};\n\ntype OfficialCodexAppCandidate = {\n appPath: string;\n bundleId: string;\n executableName: string;\n version: string | null;\n};\n\ntype OfficialCodexAppTarget = {\n candidate: OfficialCodexAppCandidate | null;\n runningPids: number[];\n mainPids: number[];\n};\n\ntype ProcessRow = {\n pid: number;\n ppid: number;\n startedAt: number | null;\n args: string;\n};\n\ntype OfficialCodexProfileLaunchOptions = {\n profileName: string;\n profileKey: string | null;\n profileHome: string;\n};\n\nexport type OfficialCodexRestartResult = OfficialCodexRestartPayload;\nexport type OfficialCodexRestartSource = \"manual\" | \"auto-roll\";\n\ntype OfficialCodexActivityInput = {\n kind: AutoRollActivityKind;\n status: string;\n reason?: string | null;\n decisionId?: string | null;\n profileName?: string | null;\n sourceProfileName?: string | null;\n targetProfileName?: string | null;\n remainingPercent?: number | null;\n threshold?: number | null;\n snapshotAgeMs?: number | null;\n snapshotSource?: string | null;\n phase?: string | null;\n pid?: number | null;\n profileKey?: string | null;\n profileKeyHash?: string | null;\n switchVerified?: boolean | null;\n restartRequested?: boolean | null;\n restartResult?: string | null;\n observedProfileName?: string | null;\n observedProfileKey?: string | null;\n observedProfileKeyHash?: string | null;\n observedProfileMatchSource?: AutoRollActivityEntry[\"observedProfileMatchSource\"];\n};\n\nlet restartPromise: Promise<OfficialCodexRestartResult> | null = null;\nlet lastRestartStartedAt = 0;\nlet profileActionLock: Promise<void> = Promise.resolve();\nlet appDiscoveryCache: {\n envPath: string | null;\n expiresAt: number;\n candidates: OfficialCodexAppCandidate[];\n} | null = null;\n\nfunction logOfficialCodexRestart(\n level: \"info\" | \"warn\" | \"error\",\n message: string,\n context?: Record<string, unknown>,\n): void {\n const logger =\n level === \"warn\" ? console.warn : level === \"error\" ? console.error : console.info;\n if (context && Object.keys(context).length > 0) {\n logger(`[official-codex-restart] ${message}`, context);\n return;\n }\n logger(`[official-codex-restart] ${message}`);\n}\n\nfunction hashProfileKey(profileKey?: string | null): string | null {\n if (!profileKey) {\n return null;\n }\n return createHash(\"sha256\").update(profileKey).digest(\"hex\").slice(0, 12);\n}\n\nexport async function recordOfficialCodexActivity(\n input: OfficialCodexActivityInput,\n): Promise<void> {\n const now = new Date();\n const entry: AutoRollActivityEntry = {\n id: `${now.getTime().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,\n at: now.toISOString(),\n kind: input.kind,\n status: input.status,\n reason: input.reason ?? null,\n decisionId: input.decisionId ?? null,\n profileName: input.profileName ?? null,\n sourceProfileName: input.sourceProfileName ?? null,\n targetProfileName: input.targetProfileName ?? null,\n remainingPercent: input.remainingPercent ?? null,\n threshold: input.threshold ?? null,\n snapshotAgeMs: input.snapshotAgeMs ?? null,\n snapshotSource: input.snapshotSource ?? null,\n phase: input.phase ?? null,\n pid: input.pid ?? null,\n profileKeyHash: input.profileKeyHash ?? hashProfileKey(input.profileKey),\n switchVerified: input.switchVerified ?? null,\n restartRequested: input.restartRequested ?? null,\n restartResult: input.restartResult ?? null,\n observedProfileName: input.observedProfileName ?? null,\n observedProfileKeyHash:\n input.observedProfileKeyHash ?? hashProfileKey(input.observedProfileKey),\n observedProfileMatchSource: input.observedProfileMatchSource ?? null,\n };\n try {\n await updateAppState((state) => ({\n officialCodex: {\n activity: [...state.officialCodex.activity, entry].slice(\n -OFFICIAL_CODEX_ACTIVITY_LIMIT,\n ),\n },\n }));\n } catch (error) {\n logOfficialCodexRestart(\"warn\", \"Failed to record official Codex activity.\", {\n kind: entry.kind,\n status: entry.status,\n profileKeyHash: entry.profileKeyHash,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nfunction runCommand(\n command: string,\n args: string[],\n timeoutMs = COMMAND_TIMEOUT_MS,\n): Promise<CommandResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, timeoutMs);\n\n child.stdout?.on(\"data\", (chunk) => {\n stdout += String(chunk);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += String(chunk);\n });\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n resolve({\n code: -1,\n stdout,\n stderr: error instanceof Error ? error.message : String(error),\n timedOut,\n });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\nfunction enqueueProfileAction<T>(work: () => Promise<T>): Promise<T> {\n const run = profileActionLock.then(work, work);\n profileActionLock = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n}\n\nasync function readProcessRows(): Promise<ProcessRow[]> {\n const result = await runCommand(\n \"/bin/ps\",\n [\"-axo\", \"pid=,ppid=,lstart=,args=\"],\n 2_000,\n );\n if (result.code !== 0) {\n return [];\n }\n\n return result.stdout.split(/\\r?\\n/).flatMap((line) => {\n const match = line.match(\n /^\\s*(\\d+)\\s+(\\d+)\\s+([A-Z][a-z]{2}\\s+[A-Z][a-z]{2}\\s+\\d+\\s+\\d+:\\d+:\\d+\\s+\\d{4})\\s+(.+)$/,\n );\n if (!match) {\n return [];\n }\n const pid = Number(match[1]);\n const ppid = Number(match[2]);\n const parsedStartedAt = Date.parse(match[3] ?? \"\");\n const startedAt = Number.isFinite(parsedStartedAt) ? parsedStartedAt : null;\n const args = match[4] ?? \"\";\n if (!Number.isInteger(pid) || !Number.isInteger(ppid) || !args) {\n return [];\n }\n return [{ pid, ppid, startedAt, args }];\n });\n}\n\nfunction getMainExecutablePath(candidate: OfficialCodexAppCandidate): string {\n return path.join(candidate.appPath, \"Contents\", \"MacOS\", candidate.executableName);\n}\n\nfunction isMainProcessRow(\n row: ProcessRow,\n candidate: OfficialCodexAppCandidate,\n): boolean {\n return row.args.includes(getMainExecutablePath(candidate));\n}\n\nfunction findAppServerPid(rows: ProcessRow[], mainPid: number): number | null {\n return (\n rows.find(\n (row) =>\n row.ppid === mainPid &&\n row.args.includes(\"/Contents/Resources/codex app-server\"),\n )?.pid ?? null\n );\n}\n\nasync function processMatchesProfileHome(\n pid: number,\n profileHome: string,\n): Promise<boolean> {\n const result = await runCommand(\n \"/bin/ps\",\n [\"eww\", \"-p\", String(pid), \"-o\", \"command=\"],\n 2_000,\n );\n if (result.code !== 0) {\n return false;\n }\n return (\n result.stdout.includes(`CODEX_HOME=${profileHome}`) ||\n result.stdout.includes(profileHome)\n );\n}\n\nasync function findAppServerPidForProfile(\n rows: ProcessRow[],\n mainPid: number,\n profileHome: string,\n): Promise<number | null> {\n const candidates = rows.filter(\n (row) =>\n row.ppid === mainPid &&\n row.args.includes(\"/Contents/Resources/codex app-server\"),\n );\n for (const row of candidates) {\n if (\n row.args.includes(profileHome) ||\n (await processMatchesProfileHome(row.pid, profileHome))\n ) {\n return row.pid;\n }\n }\n return null;\n}\n\nasync function describeUnmanagedProfileHint(\n appServerPid: number | null,\n): Promise<Pick<\n OfficialCodexUnmanagedInstancePayload,\n \"profileName\" | \"profileMatchSource\"\n>> {\n if (!appServerPid) {\n return {};\n }\n const result = await runCommand(\n \"/bin/ps\",\n [\"eww\", \"-p\", String(appServerPid), \"-o\", \"command=\"],\n 2_000,\n );\n if (result.code !== 0) {\n return {};\n }\n const telemetryMatch = result.stdout.match(\n /CODEX_TELEMETRY_LABEL=codexuse-profile-([^\\s]+)/,\n );\n if (telemetryMatch?.[1]) {\n const encodedProfileName = telemetryMatch[1];\n let profileName = encodedProfileName;\n try {\n profileName = decodeURIComponent(encodedProfileName);\n } catch {\n profileName = encodedProfileName;\n }\n return {\n profileName,\n profileMatchSource: \"telemetry-label\",\n };\n }\n const profileHomeMatch = result.stdout.match(/profile-homes\\/([^\\s]+)/);\n if (profileHomeMatch?.[1]) {\n return {\n profileName: profileHomeMatch[1],\n profileMatchSource: \"profile-home\",\n };\n }\n return {};\n}\n\nfunction getDescendantPids(rootPid: number, rows: ProcessRow[]): number[] {\n const descendants: number[] = [];\n const queue = [rootPid];\n const seen = new Set<number>();\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (seen.has(current)) {\n continue;\n }\n seen.add(current);\n for (const row of rows) {\n if (row.ppid !== current || seen.has(row.pid)) {\n continue;\n }\n descendants.push(row.pid);\n queue.push(row.pid);\n }\n }\n\n return descendants;\n}\n\nasync function waitForNewMainPid(\n candidate: OfficialCodexAppCandidate,\n previousPids: ReadonlySet<number>,\n): Promise<number | null> {\n const deadline = Date.now() + LAUNCH_WAIT_MS;\n while (Date.now() < deadline) {\n const rows = await readProcessRows();\n const pid =\n rows.find((row) => isMainProcessRow(row, candidate) && !previousPids.has(row.pid))\n ?.pid ?? null;\n if (pid !== null) {\n return pid;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return null;\n}\n\nasync function waitForMainPid(\n candidate: OfficialCodexAppCandidate,\n pid: number,\n timeoutMs: number,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const rows = await readProcessRows();\n if (rows.some((row) => row.pid === pid && isMainProcessRow(row, candidate))) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return false;\n}\n\nasync function waitForAppServerPid(\n mainPid: number,\n profileHome: string,\n): Promise<number | null> {\n const deadline = Date.now() + LAUNCH_WAIT_MS;\n while (Date.now() < deadline) {\n const pid = await findAppServerPidForProfile(\n await readProcessRows(),\n mainPid,\n profileHome,\n );\n if (pid !== null) {\n return pid;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return null;\n}\n\nasync function waitForMainPidExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const rows = await readProcessRows();\n if (!rows.some((row) => row.pid === pid)) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return false;\n}\n\nasync function focusMainPid(pid: number): Promise<boolean> {\n const result = await runCommand(\"/usr/bin/osascript\", [\n \"-e\",\n `tell application \"System Events\" to repeat with proc in (processes whose unix id is ${pid})`,\n \"-e\",\n \"set frontmost of proc to true\",\n \"-e\",\n \"end repeat\",\n ], 5_000);\n return result.code === 0;\n}\n\nfunction managedInstanceToPayload(\n instance: OfficialCodexManagedInstanceState,\n running: boolean,\n appServerPid: number | null = instance.appServerPid,\n startedAt: number | null = null,\n): OfficialCodexProfileInstancePayload {\n const runningStartedAt = startedAt ?? instance.launchedAt;\n return {\n profileName: instance.profileName,\n profileKey: instance.profileKey,\n appPath: instance.appPath,\n bundleId: instance.bundleId,\n pid: running ? instance.pid : null,\n appServerPid: running ? appServerPid : null,\n running,\n startedAt: running ? toIso(runningStartedAt) : null,\n uptimeMs:\n running && typeof runningStartedAt === \"number\"\n ? Math.max(0, Date.now() - runningStartedAt)\n : null,\n launchedAt: toIso(instance.launchedAt),\n lastVerifiedAt: toIso(instance.lastVerifiedAt),\n lastStatus: instance.lastStatus,\n lastError: instance.lastError,\n };\n}\n\nasync function patchManagedInstance(\n instance: OfficialCodexManagedInstanceState,\n): Promise<void> {\n await patchAppState({\n officialCodex: {\n instancesByProfileName: {\n [instance.profileName]: instance,\n },\n },\n });\n}\n\nasync function readManagedInstance(\n profileName: string,\n): Promise<OfficialCodexManagedInstanceState | null> {\n const state = await getAppState();\n return state.officialCodex.instancesByProfileName[profileName] ?? null;\n}\n\nasync function resolveInstanceRuntimeState(args: {\n instance: OfficialCodexManagedInstanceState;\n candidate: OfficialCodexAppCandidate;\n rows: ProcessRow[];\n}): Promise<{\n running: boolean;\n appServerPid: number | null;\n startedAt: number | null;\n}> {\n const pid = args.instance.pid;\n if (!pid) {\n return { running: false, appServerPid: null, startedAt: null };\n }\n const mainRow = args.rows.find((row) => row.pid === pid);\n if (!mainRow || !isMainProcessRow(mainRow, args.candidate)) {\n return { running: false, appServerPid: null, startedAt: null };\n }\n const appServerPid = args.instance.profileHome\n ? await findAppServerPidForProfile(args.rows, pid, args.instance.profileHome)\n : findAppServerPid(args.rows, pid);\n if (args.instance.profileHome && appServerPid === null) {\n return { running: false, appServerPid: null, startedAt: null };\n }\n return {\n running: true,\n appServerPid,\n startedAt: mainRow.startedAt,\n };\n}\n\nasync function openCodexWithProfileHome(\n candidate: OfficialCodexAppCandidate,\n profileHome: string,\n profileName: string,\n previousPids: ReadonlySet<number>,\n): Promise<{ opened: boolean; pid: number | null }> {\n const executablePath = getMainExecutablePath(candidate);\n if (!existsSync(executablePath)) {\n return { opened: false, pid: null };\n }\n const telemetryLabel = `codexuse-profile-${encodeURIComponent(profileName)}`;\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(executablePath, [], {\n detached: true,\n env: {\n ...process.env,\n CODEX_HOME: profileHome,\n CODEX_TELEMETRY_LABEL: telemetryLabel,\n },\n stdio: \"ignore\",\n });\n } catch {\n return { opened: false, pid: null };\n }\n\n const childPid = child.pid ?? null;\n child.unref();\n const spawnError = await new Promise<boolean>((resolve) => {\n let settled = false;\n const settle = (failed: boolean) => {\n if (settled) {\n return;\n }\n settled = true;\n resolve(failed);\n };\n child.once(\"error\", () => settle(true));\n setTimeout(() => settle(false), POLL_INTERVAL_MS);\n });\n if (spawnError) {\n return { opened: false, pid: null };\n }\n\n if (childPid !== null) {\n const verified = await waitForMainPid(candidate, childPid, 2_000);\n if (verified) {\n return { opened: true, pid: childPid };\n }\n }\n\n return {\n opened: true,\n pid: await waitForNewMainPid(candidate, previousPids),\n };\n}\n\nasync function readBundleString(\n appPath: string,\n key: \"CFBundleIdentifier\" | \"CFBundleExecutable\" | \"CFBundleShortVersionString\",\n): Promise<string | null> {\n const plistPath = path.join(appPath, \"Contents\", \"Info.plist\");\n if (!existsSync(plistPath)) {\n return null;\n }\n\n const result = await runCommand(\"/usr/bin/plutil\", [\n \"-extract\",\n key,\n \"raw\",\n \"-o\",\n \"-\",\n plistPath,\n ]);\n if (result.code !== 0) {\n return null;\n }\n\n const bundleId = result.stdout.trim();\n return bundleId.length > 0 ? bundleId : null;\n}\n\nasync function discoverCodexAppCandidates(): Promise<OfficialCodexAppCandidate[]> {\n const now = Date.now();\n const envPath = process.env.CODEXUSE_OFFICIAL_CODEX_APP_PATH?.trim() || null;\n if (\n appDiscoveryCache &&\n appDiscoveryCache.envPath === envPath &&\n appDiscoveryCache.expiresAt > now\n ) {\n return appDiscoveryCache.candidates;\n }\n\n const rawPaths = new Set<string>();\n if (envPath) {\n rawPaths.add(envPath);\n }\n rawPaths.add(\"/Applications/Codex.app\");\n rawPaths.add(path.join(homedir(), \"Applications\", \"Codex.app\"));\n\n const mdfind = await runCommand(\n \"/usr/bin/mdfind\",\n [\"kMDItemFSName == 'Codex.app'\"],\n 1_500,\n );\n if (mdfind.code === 0) {\n for (const line of mdfind.stdout.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.endsWith(\"/Codex.app\")) {\n rawPaths.add(trimmed);\n }\n }\n }\n\n const candidates: OfficialCodexAppCandidate[] = [];\n for (const appPath of rawPaths) {\n if (!existsSync(appPath) || path.basename(appPath) !== \"Codex.app\") {\n continue;\n }\n\n const bundleId = await readBundleString(appPath, \"CFBundleIdentifier\");\n if (!bundleId || bundleId.toLowerCase().includes(\"codexuse\")) {\n continue;\n }\n candidates.push({\n appPath,\n bundleId,\n version: await readBundleString(appPath, \"CFBundleShortVersionString\"),\n executableName:\n (await readBundleString(appPath, \"CFBundleExecutable\")) ?? \"Codex\",\n });\n }\n\n const sorted = candidates.sort((a, b) => a.appPath.localeCompare(b.appPath));\n appDiscoveryCache = {\n envPath,\n expiresAt:\n now +\n (sorted.length > 0 ? APP_DISCOVERY_CACHE_TTL_MS : APP_DISCOVERY_MISS_CACHE_TTL_MS),\n candidates: sorted,\n };\n return sorted;\n}\n\nasync function getRunningCodexPids(candidate: OfficialCodexAppCandidate): Promise<number[]> {\n const result = await runCommand(\"/bin/ps\", [\"-axo\", \"pid=,args=\"], 2_000);\n const pids = new Set<number>();\n const appContentsRoot = `${path.join(candidate.appPath, \"Contents\")}${path.sep}`;\n if (result.code === 0) {\n for (const line of result.stdout.split(/\\r?\\n/)) {\n const match = line.match(/^\\s*(\\d+)\\s+(.+)$/);\n if (!match) {\n continue;\n }\n const pid = Number(match[1]);\n const args = match[2] ?? \"\";\n if (Number.isInteger(pid) && args.includes(appContentsRoot)) {\n pids.add(pid);\n }\n }\n }\n\n return Array.from(pids).sort((a, b) => a - b);\n}\n\nasync function getRunningCodexMainPids(\n candidate: OfficialCodexAppCandidate,\n): Promise<number[]> {\n const result = await runCommand(\"/bin/ps\", [\"-axo\", \"pid=,args=\"], 2_000);\n const pids = new Set<number>();\n const executablePath = path.join(\n candidate.appPath,\n \"Contents\",\n \"MacOS\",\n candidate.executableName,\n );\n if (result.code === 0) {\n for (const line of result.stdout.split(/\\r?\\n/)) {\n const match = line.match(/^\\s*(\\d+)\\s+(.+)$/);\n if (!match) {\n continue;\n }\n const pid = Number(match[1]);\n const args = match[2] ?? \"\";\n if (Number.isInteger(pid) && args.includes(executablePath)) {\n pids.add(pid);\n }\n }\n }\n\n return Array.from(pids).sort((a, b) => a - b);\n}\n\nasync function resolveCodexAppTarget(): Promise<OfficialCodexAppTarget> {\n const candidates = await discoverCodexAppCandidates();\n const fallback = candidates[0] ?? null;\n if (!fallback) {\n return { candidate: null, runningPids: [], mainPids: [] };\n }\n\n for (const candidate of candidates) {\n const [runningPids, mainPids] = await Promise.all([\n getRunningCodexPids(candidate),\n getRunningCodexMainPids(candidate),\n ]);\n if (mainPids.length > 0) {\n return { candidate, runningPids, mainPids };\n }\n }\n\n const [runningPids, mainPids] = await Promise.all([\n getRunningCodexPids(fallback),\n getRunningCodexMainPids(fallback),\n ]);\n return { candidate: fallback, runningPids, mainPids };\n}\n\nasync function waitForCodexExit(\n candidate: OfficialCodexAppCandidate,\n timeoutMs: number,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const pids = await getRunningCodexPids(candidate);\n if (pids.length === 0) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return false;\n}\n\nasync function signalPids(\n pids: number[],\n signal: NodeJS.Signals,\n): Promise<number[]> {\n const signaled: number[] = [];\n for (const pid of pids) {\n try {\n process.kill(pid, signal);\n signaled.push(pid);\n } catch {\n // Process may have already exited.\n }\n }\n return signaled;\n}\n\nasync function openCodex(candidate: OfficialCodexAppCandidate): Promise<boolean> {\n const byBundle = await runCommand(\"/usr/bin/open\", [\"-b\", candidate.bundleId]);\n if (byBundle.code === 0) {\n return true;\n }\n\n const byPath = await runCommand(\"/usr/bin/open\", [candidate.appPath]);\n return byPath.code === 0;\n}\n\nasync function waitForCodexLaunch(\n candidate: OfficialCodexAppCandidate,\n): Promise<number | null> {\n const deadline = Date.now() + LAUNCH_WAIT_MS;\n while (Date.now() < deadline) {\n const pids = await getRunningCodexMainPids(candidate);\n const pid = pids[0] ?? null;\n if (pid !== null) {\n return pid;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return null;\n}\n\nfunction toIso(value: number | null | undefined): string | null {\n return typeof value === \"number\" && Number.isFinite(value)\n ? new Date(value).toISOString()\n : null;\n}\n\nasync function rememberProfileSwitch(profileKey: string | null): Promise<void> {\n await patchAppState({\n officialCodex: {\n lastProfileSwitchAt: Date.now(),\n lastProfileSwitchProfileKey: profileKey,\n },\n });\n}\n\nasync function rememberRestartResult(args: {\n status: string;\n reason?: string | null;\n profileKey?: string | null;\n pid?: number | null;\n}): Promise<void> {\n const now = Date.now();\n const verified = args.status === \"restarted\" || args.status === \"started\";\n await patchAppState({\n officialCodex: {\n lastVerifiedLaunchAt: verified ? now : undefined,\n lastVerifiedLaunchProfileKey: verified ? (args.profileKey ?? null) : undefined,\n lastObservedPid: verified ? (args.pid ?? null) : undefined,\n lastRestartStatus: args.status,\n lastRestartReason: args.reason ?? null,\n },\n });\n}\n\nexport async function recordOfficialCodexProfileObservation(\n profileKey: string | null,\n pid: number | null,\n): Promise<void> {\n if (!profileKey || !pid) {\n return;\n }\n await patchAppState({\n officialCodex: {\n lastVerifiedLaunchProfileKey: profileKey,\n lastObservedPid: pid,\n },\n });\n}\n\nexport function recordOfficialCodexRestartResult(args: {\n status: string;\n reason?: string | null;\n profileKey?: string | null;\n pid?: number | null;\n}): Promise<void> {\n return rememberRestartResult(args);\n}\n\nasync function restartOfficialCodexAppOnce(options: {\n source: OfficialCodexRestartSource;\n currentProfileKey?: string | null;\n targetProfileName?: string | null;\n launchIfNotRunning: boolean;\n decisionId?: string | null;\n}): Promise<OfficialCodexRestartResult> {\n const profileKeyHash = hashProfileKey(options.currentProfileKey);\n if (process.platform !== \"darwin\") {\n logOfficialCodexRestart(\"warn\", \"Skipped official Codex restart.\", {\n source: options.source,\n profileKeyHash,\n result: \"skipped\",\n reason: \"unsupported-platform\",\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: \"skipped\",\n reason: \"unsupported-platform\",\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n profileKey: options.currentProfileKey,\n restartRequested: false,\n restartResult: \"skipped\",\n });\n await rememberRestartResult({ status: \"skipped\", reason: \"unsupported-platform\" });\n return { status: \"skipped\", reason: \"unsupported-platform\" };\n }\n\n const now = Date.now();\n if (\n options.source !== \"manual\" &&\n lastRestartStartedAt > 0 &&\n now - lastRestartStartedAt < RESTART_COOLDOWN_MS\n ) {\n logOfficialCodexRestart(\"warn\", \"Skipped official Codex restart.\", {\n source: options.source,\n profileKeyHash,\n result: \"skipped\",\n reason: \"cooldown\",\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: \"skipped\",\n reason: \"cooldown\",\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n profileKey: options.currentProfileKey,\n restartRequested: false,\n restartResult: \"skipped\",\n });\n await rememberRestartResult({\n status: \"skipped\",\n reason: \"cooldown\",\n profileKey: options.currentProfileKey,\n });\n return { status: \"skipped\", reason: \"cooldown\" };\n }\n\n const { candidate, runningPids, mainPids } = await resolveCodexAppTarget();\n if (!candidate) {\n logOfficialCodexRestart(\"warn\", \"Skipped official Codex restart.\", {\n source: options.source,\n profileKeyHash,\n result: \"skipped\",\n reason: \"official-codex-app-not-found\",\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: \"skipped\",\n reason: \"official-codex-app-not-found\",\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n profileKey: options.currentProfileKey,\n restartRequested: false,\n restartResult: \"skipped\",\n });\n await rememberRestartResult({\n status: \"skipped\",\n reason: \"official-codex-app-not-found\",\n profileKey: options.currentProfileKey,\n });\n return { status: \"skipped\", reason: \"official-codex-app-not-found\" };\n }\n\n const appIsRunning = mainPids.length > 0;\n if (!appIsRunning && !options.launchIfNotRunning) {\n logOfficialCodexRestart(\"warn\", \"Skipped official Codex restart.\", {\n source: options.source,\n profileKeyHash,\n result: \"skipped\",\n reason: \"official-codex-app-not-running\",\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: \"skipped\",\n reason: \"official-codex-app-not-running\",\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n profileKey: options.currentProfileKey,\n restartRequested: false,\n restartResult: \"skipped\",\n });\n await rememberRestartResult({\n status: \"skipped\",\n reason: \"official-codex-app-not-running\",\n profileKey: options.currentProfileKey,\n });\n return { status: \"skipped\", reason: \"official-codex-app-not-running\" };\n }\n\n if (options.source !== \"manual\") {\n lastRestartStartedAt = Date.now();\n }\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: \"started\",\n reason: null,\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n phase: appIsRunning ? \"relaunch\" : \"launch\",\n profileKey: options.currentProfileKey,\n restartRequested: true,\n });\n\n if (appIsRunning) {\n logOfficialCodexRestart(\"warn\", \"Force killing official Codex before relaunch.\", {\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n source: options.source,\n profileKeyHash,\n phase: \"quit\",\n runningPids,\n mainPids,\n });\n const killedPids = await signalPids(runningPids, \"SIGKILL\");\n logOfficialCodexRestart(\"warn\", \"Sent SIGKILL to official Codex pids.\", {\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n source: options.source,\n profileKeyHash,\n phase: \"quit\",\n killedPids,\n });\n const exited = await waitForCodexExit(candidate, EXIT_WAIT_MS);\n if (!exited) {\n const remainingPids = await getRunningCodexPids(candidate);\n logOfficialCodexRestart(\"error\", \"Official Codex pids remained after force kill.\", {\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n source: options.source,\n profileKeyHash,\n phase: \"quit\",\n result: \"failed\",\n remainingPids,\n });\n const failed = {\n status: \"failed\" as const,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n reason: \"force-quit-timeout\",\n phase: \"quit\",\n };\n await rememberRestartResult({\n status: failed.status,\n reason: failed.reason,\n profileKey: options.currentProfileKey,\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: failed.status,\n reason: failed.reason,\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n phase: failed.phase,\n profileKey: options.currentProfileKey,\n restartRequested: true,\n restartResult: failed.status,\n });\n return failed;\n }\n logOfficialCodexRestart(\"info\", \"Official Codex exited after force kill.\", {\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n source: options.source,\n profileKeyHash,\n phase: \"quit\",\n result: \"ok\",\n });\n }\n\n const opened = await openCodex(candidate);\n if (!opened) {\n const failed = {\n status: \"failed\" as const,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n reason: \"open-failed\",\n phase: \"launch\",\n };\n await rememberRestartResult({\n status: failed.status,\n reason: failed.reason,\n profileKey: options.currentProfileKey,\n });\n logOfficialCodexRestart(\"error\", \"Official Codex launch failed.\", {\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n source: options.source,\n profileKeyHash,\n phase: failed.phase,\n result: failed.status,\n reason: failed.reason,\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: failed.status,\n reason: failed.reason,\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n phase: failed.phase,\n profileKey: options.currentProfileKey,\n restartRequested: true,\n restartResult: failed.status,\n });\n return failed;\n }\n\n const launchedPid = await waitForCodexLaunch(candidate);\n if (launchedPid === null) {\n logOfficialCodexRestart(\"error\", \"Official Codex launch was not verified.\", {\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n source: options.source,\n profileKeyHash,\n phase: \"launch\",\n result: \"failed\",\n });\n const failed = {\n status: \"failed\" as const,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n reason: \"launch-timeout\",\n phase: \"launch\",\n };\n await rememberRestartResult({\n status: failed.status,\n reason: failed.reason,\n profileKey: options.currentProfileKey,\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status: failed.status,\n reason: failed.reason,\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n phase: failed.phase,\n profileKey: options.currentProfileKey,\n restartRequested: true,\n restartResult: failed.status,\n });\n return failed;\n }\n\n const status = appIsRunning ? \"restarted\" : \"started\";\n logOfficialCodexRestart(\"info\", \"Official Codex launch verified.\", {\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n source: options.source,\n profileKeyHash,\n phase: \"launch\",\n result: status,\n status,\n pid: launchedPid,\n });\n await rememberRestartResult({\n status,\n profileKey: options.currentProfileKey,\n pid: launchedPid,\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status,\n reason: null,\n decisionId: options.decisionId,\n targetProfileName: options.targetProfileName,\n phase: \"launch\",\n pid: launchedPid,\n profileKey: options.currentProfileKey,\n restartRequested: true,\n restartResult: status,\n });\n\n return {\n status,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: launchedPid,\n };\n}\n\nexport async function getOfficialCodexSyncStatus(\n currentProfileKey: string | null,\n): Promise<OfficialCodexSyncStatusPayload> {\n const state = await getAppState();\n const stored = state.officialCodex;\n const base = {\n runningPids: [],\n lastProfileSwitchAt: toIso(stored.lastProfileSwitchAt),\n lastVerifiedLaunchAt: toIso(stored.lastVerifiedLaunchAt),\n lastRestartStatus: stored.lastRestartStatus,\n lastRestartReason: stored.lastRestartReason,\n activity: stored.activity,\n };\n\n if (process.platform !== \"darwin\") {\n return {\n ...base,\n state: \"unsupported\",\n };\n }\n\n const { candidate, mainPids } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n ...base,\n state: \"not-found\",\n };\n }\n\n if (mainPids.length === 0) {\n return {\n ...base,\n state: \"not-running\",\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n runningPids: mainPids,\n };\n }\n\n const lastSwitchAt = stored.lastProfileSwitchAt;\n const lastLaunchAt = stored.lastVerifiedLaunchAt;\n const lastLaunchProfileKey = stored.lastVerifiedLaunchProfileKey;\n const lastObservedPid = stored.lastObservedPid;\n const observedSynced = Boolean(\n currentProfileKey &&\n lastLaunchProfileKey === currentProfileKey &&\n lastObservedPid &&\n mainPids.includes(lastObservedPid),\n );\n const stale = Boolean(\n !observedSynced &&\n currentProfileKey &&\n lastSwitchAt &&\n (!lastLaunchAt ||\n lastLaunchAt < lastSwitchAt ||\n lastLaunchProfileKey !== currentProfileKey),\n );\n\n return {\n ...base,\n state: observedSynced\n ? \"synced\"\n : stale\n ? \"stale\"\n : \"unknown\",\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n runningPids: mainPids,\n };\n}\n\nexport function recordOfficialCodexProfileSwitch(\n profileKey: string | null,\n): Promise<void> {\n return rememberProfileSwitch(profileKey);\n}\n\nexport async function getOfficialCodexProfileInstances(): Promise<OfficialCodexInstancesPayload> {\n if (process.platform !== \"darwin\") {\n return {\n state: \"unsupported\",\n appPath: null,\n bundleId: null,\n version: null,\n instances: [],\n unmanaged: [],\n };\n }\n\n const { candidate, mainPids } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n state: \"not-found\",\n appPath: null,\n bundleId: null,\n version: null,\n instances: [],\n unmanaged: [],\n };\n }\n\n const [state, rows] = await Promise.all([getAppState(), readProcessRows()]);\n const managed: OfficialCodexProfileInstancePayload[] = [];\n for (const instance of Object.values(state.officialCodex.instancesByProfileName)) {\n const runtime = await resolveInstanceRuntimeState({ instance, candidate, rows });\n managed.push(\n managedInstanceToPayload(\n instance,\n runtime.running,\n runtime.appServerPid,\n runtime.startedAt,\n ),\n );\n }\n managed.sort((a, b) => a.profileName.localeCompare(b.profileName));\n const managedPids = new Set(\n managed.flatMap((entry) => (entry.running && entry.pid ? [entry.pid] : [])),\n );\n\n const unmanaged: OfficialCodexUnmanagedInstancePayload[] = [];\n for (const pid of mainPids.filter((entry) => !managedPids.has(entry))) {\n const appServerPid = findAppServerPid(rows, pid);\n const startedAt = rows.find((row) => row.pid === pid)?.startedAt ?? null;\n unmanaged.push({\n pid,\n appServerPid,\n startedAt: toIso(startedAt),\n uptimeMs:\n typeof startedAt === \"number\" ? Math.max(0, Date.now() - startedAt) : null,\n ...(await describeUnmanagedProfileHint(appServerPid)),\n });\n }\n\n return {\n state: \"found\",\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n version: candidate.version,\n instances: managed,\n unmanaged,\n };\n}\n\nexport function launchOfficialCodexProfileInstance(\n options: OfficialCodexProfileLaunchOptions,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(() => launchOfficialCodexProfileInstanceOnce(options));\n}\n\nasync function launchOfficialCodexProfileInstanceOnce(\n options: OfficialCodexProfileLaunchOptions,\n): Promise<OfficialCodexProfileActionPayload> {\n if (process.platform !== \"darwin\") {\n return {\n status: \"skipped\",\n profileName: options.profileName,\n instance: null,\n reason: \"unsupported-platform\",\n };\n }\n\n const { candidate, mainPids } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"skipped\",\n profileName: options.profileName,\n instance: null,\n reason: \"official-codex-app-not-found\",\n };\n }\n\n const existing = await readManagedInstance(options.profileName);\n if (existing) {\n const rows = await readProcessRows();\n const runtime = await resolveInstanceRuntimeState({ instance: existing, candidate, rows });\n if (runtime.running) {\n const verified: OfficialCodexManagedInstanceState = {\n ...existing,\n profileHome: existing.profileHome ?? options.profileHome,\n appServerPid: runtime.appServerPid,\n lastVerifiedAt: Date.now(),\n lastStatus: \"already-running\",\n lastError: null,\n };\n await patchManagedInstance(verified);\n return {\n status: \"already-running\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(\n verified,\n true,\n runtime.appServerPid,\n runtime.startedAt,\n ),\n reason: null,\n };\n }\n }\n\n const launch = await openCodexWithProfileHome(\n candidate,\n options.profileHome,\n options.profileName,\n new Set(mainPids),\n );\n if (!launch.opened) {\n const failed: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: null,\n appServerPid: null,\n launchedAt: null,\n lastVerifiedAt: null,\n lastStatus: \"failed\",\n lastError: \"open-failed\",\n };\n await patchManagedInstance(failed);\n return {\n status: \"failed\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(failed, false),\n reason: \"open-failed\",\n };\n }\n\n const launchedPid = launch.pid;\n if (launchedPid === null) {\n const failed: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: null,\n appServerPid: null,\n launchedAt: null,\n lastVerifiedAt: null,\n lastStatus: \"failed\",\n lastError: \"launch-timeout\",\n };\n await patchManagedInstance(failed);\n return {\n status: \"failed\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(failed, false),\n reason: \"launch-timeout\",\n };\n }\n\n const appServerPid = await waitForAppServerPid(\n launchedPid,\n options.profileHome,\n );\n if (appServerPid === null) {\n const failed: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: null,\n appServerPid: null,\n launchedAt: null,\n lastVerifiedAt: Date.now(),\n lastStatus: \"failed\",\n lastError: \"app-server-not-verified\",\n };\n await patchManagedInstance(failed);\n return {\n status: \"failed\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(failed, false),\n reason: \"app-server-not-verified\",\n };\n }\n const now = Date.now();\n const instance: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: launchedPid,\n appServerPid,\n launchedAt: now,\n lastVerifiedAt: now,\n lastStatus: \"started\",\n lastError: null,\n };\n await patchManagedInstance(instance);\n return {\n status: \"started\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(instance, true, appServerPid),\n reason: null,\n };\n}\n\nexport function stopOfficialCodexProfileInstance(\n profileName: string,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(() => stopOfficialCodexProfileInstanceOnce(profileName));\n}\n\nasync function stopOfficialCodexProfileInstanceOnce(\n profileName: string,\n): Promise<OfficialCodexProfileActionPayload> {\n const existing = await readManagedInstance(profileName);\n if (!existing) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"not-managed\",\n };\n }\n\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n const stopped: OfficialCodexManagedInstanceState = {\n ...existing,\n pid: null,\n appServerPid: null,\n lastVerifiedAt: Date.now(),\n lastStatus: \"not-running\",\n lastError: \"official-codex-app-not-found\",\n };\n await patchManagedInstance(stopped);\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(stopped, false),\n reason: \"official-codex-app-not-found\",\n };\n }\n\n const rows = await readProcessRows();\n const runtime = await resolveInstanceRuntimeState({ instance: existing, candidate, rows });\n if (!runtime.running || !existing.pid) {\n const stopped: OfficialCodexManagedInstanceState = {\n ...existing,\n pid: null,\n appServerPid: null,\n lastVerifiedAt: Date.now(),\n lastStatus: \"not-running\",\n lastError: null,\n };\n await patchManagedInstance(stopped);\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(stopped, false),\n reason: null,\n };\n }\n\n const tree = [existing.pid, ...getDescendantPids(existing.pid, rows)]\n .filter((pid, index, all) => all.indexOf(pid) === index)\n .sort((a, b) => b - a);\n await signalPids(tree, \"SIGTERM\");\n const exited = await waitForMainPidExit(existing.pid, 5_000);\n if (!exited) {\n await signalPids(tree, \"SIGKILL\");\n await waitForMainPidExit(existing.pid, EXIT_WAIT_MS);\n }\n\n const stillRunning = (await readProcessRows()).some((row) => row.pid === existing.pid);\n const stopped: OfficialCodexManagedInstanceState = {\n ...existing,\n pid: stillRunning ? existing.pid : null,\n appServerPid: stillRunning ? runtime.appServerPid : null,\n lastVerifiedAt: Date.now(),\n lastStatus: stillRunning ? \"failed\" : \"stopped\",\n lastError: stillRunning ? \"stop-timeout\" : null,\n };\n await patchManagedInstance(stopped);\n return {\n status: stillRunning ? \"failed\" : \"stopped\",\n profileName,\n instance: managedInstanceToPayload(\n stopped,\n stillRunning,\n stopped.appServerPid,\n runtime.startedAt,\n ),\n reason: stillRunning ? \"stop-timeout\" : null,\n };\n}\n\nexport function focusOfficialCodexProfileInstance(\n profileName: string,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const existing = await readManagedInstance(profileName);\n if (!existing) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"not-managed\",\n };\n }\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(existing, false),\n reason: \"official-codex-app-not-found\",\n };\n }\n const rows = await readProcessRows();\n const runtime = await resolveInstanceRuntimeState({ instance: existing, candidate, rows });\n if (!runtime.running || !existing.pid) {\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(existing, false),\n reason: null,\n };\n }\n const focused = await focusMainPid(existing.pid);\n const verified: OfficialCodexManagedInstanceState = {\n ...existing,\n appServerPid: runtime.appServerPid,\n lastVerifiedAt: Date.now(),\n lastStatus: focused ? \"focused\" : \"focus-unknown\",\n lastError: focused ? null : \"focus-unknown\",\n };\n await patchManagedInstance(verified);\n return {\n status: focused ? \"focused\" : \"focus-unknown\",\n profileName,\n instance: managedInstanceToPayload(\n verified,\n true,\n runtime.appServerPid,\n runtime.startedAt,\n ),\n reason: focused ? null : \"focus-unknown\",\n };\n });\n}\n\nexport function focusOfficialCodexObservedProfileInstance(\n profileName: string,\n pid: number,\n appServerPid: number | null,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"official-codex-app-not-found\",\n };\n }\n const rows = await readProcessRows();\n const mainRow = rows.find((row) => row.pid === pid);\n if (!mainRow || !isMainProcessRow(mainRow, candidate)) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: null,\n };\n }\n\n const runtimeAppServerPid = findAppServerPid(rows, pid) ?? appServerPid;\n const focused = await focusMainPid(pid);\n const instance: OfficialCodexProfileInstancePayload = {\n profileName,\n profileKey: null,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid,\n appServerPid: runtimeAppServerPid,\n running: true,\n startedAt: toIso(mainRow.startedAt),\n uptimeMs:\n typeof mainRow.startedAt === \"number\"\n ? Math.max(0, Date.now() - mainRow.startedAt)\n : null,\n launchedAt: null,\n lastVerifiedAt: new Date().toISOString(),\n lastStatus: focused ? \"focused\" : \"focus-unknown\",\n lastError: focused ? null : \"focus-unknown\",\n };\n return {\n status: focused ? \"focused\" : \"focus-unknown\",\n profileName,\n instance,\n reason: focused ? null : \"focus-unknown\",\n };\n });\n}\n\nexport function stopOfficialCodexObservedProfileInstance(\n profileName: string,\n pid: number,\n appServerPid: number | null,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"official-codex-app-not-found\",\n };\n }\n const rows = await readProcessRows();\n const mainRow = rows.find((row) => row.pid === pid);\n if (!mainRow || !isMainProcessRow(mainRow, candidate)) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: null,\n };\n }\n\n const runtimeAppServerPid = findAppServerPid(rows, pid) ?? appServerPid;\n const tree = [pid, ...getDescendantPids(pid, rows)]\n .filter((entry, index, all) => all.indexOf(entry) === index)\n .sort((a, b) => b - a);\n await signalPids(tree, \"SIGTERM\");\n const exited = await waitForMainPidExit(pid, 5_000);\n if (!exited) {\n await signalPids(tree, \"SIGKILL\");\n await waitForMainPidExit(pid, EXIT_WAIT_MS);\n }\n\n const stillRunning = (await readProcessRows()).some((row) => row.pid === pid);\n const instance: OfficialCodexProfileInstancePayload = {\n profileName,\n profileKey: null,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: stillRunning ? pid : null,\n appServerPid: stillRunning ? runtimeAppServerPid : null,\n running: stillRunning,\n startedAt: stillRunning ? toIso(mainRow.startedAt) : null,\n uptimeMs:\n stillRunning && typeof mainRow.startedAt === \"number\"\n ? Math.max(0, Date.now() - mainRow.startedAt)\n : null,\n launchedAt: null,\n lastVerifiedAt: new Date().toISOString(),\n lastStatus: stillRunning ? \"failed\" : \"stopped\",\n lastError: stillRunning ? \"stop-timeout\" : null,\n };\n return {\n status: stillRunning ? \"failed\" : \"stopped\",\n profileName,\n instance,\n reason: stillRunning ? \"stop-timeout\" : null,\n };\n });\n}\n\nexport async function restartOfficialCodexProfileInstance(\n options: OfficialCodexProfileLaunchOptions,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const stopped = await stopOfficialCodexProfileInstanceOnce(options.profileName);\n if (stopped.status === \"failed\") {\n return stopped;\n }\n const launched = await launchOfficialCodexProfileInstanceOnce(options);\n return {\n ...launched,\n status: launched.status === \"started\" ? \"restarted\" : launched.status,\n };\n });\n}\n\nexport function restartOfficialCodexApp(\n options: {\n source?: OfficialCodexRestartSource;\n currentProfileKey?: string | null;\n targetProfileName?: string | null;\n launchIfNotRunning?: boolean;\n decisionId?: string | null;\n } = {},\n): Promise<OfficialCodexRestartResult> {\n if (restartPromise) {\n return restartPromise;\n }\n\n restartPromise = restartOfficialCodexAppOnce({\n source: options.source ?? \"manual\",\n currentProfileKey: options.currentProfileKey ?? null,\n targetProfileName: options.targetProfileName ?? null,\n launchIfNotRunning:\n options.launchIfNotRunning ?? (options.source ?? \"manual\") === \"manual\",\n decisionId: options.decisionId ?? null,\n }).finally(() => {\n restartPromise = null;\n });\n return restartPromise;\n}\n","import { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { assertProfileCreationAllowed } from \"@codexuse/runtime-profiles/license/guard\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { maxUsedPercent } from \"@codexuse/runtime-profiles/profiles/rate-limit-notifier\";\nimport { getStoredAutoRollSettings } from \"@codexuse/runtime-codex/codex/settings\";\nimport {\n getOfficialCodexProfileInstances,\n launchOfficialCodexProfileInstance,\n recordOfficialCodexActivity,\n recordOfficialCodexRestartResult,\n recordOfficialCodexProfileSwitch,\n restartOfficialCodexProfileInstance,\n stopOfficialCodexObservedProfileInstance,\n} from \"@codexuse/runtime-codex/codex/officialAppRestart\";\nimport type {\n OfficialCodexInstancesPayload,\n OfficialCodexProfileActionPayload,\n OfficialCodexUnmanagedInstancePayload,\n} from \"@codexuse/contracts/desktop/ipc-types\";\nimport type {\n OrganizationInfo,\n Profile,\n RateLimitSnapshot,\n RateLimitWindow,\n} from \"@codexuse/contracts/profiles/types\";\nimport { resolveProfileIdentityKeyFromProfile } from \"@codexuse/contracts/profiles/identity\";\nimport {\n AUTO_ROLL_SWITCH_REMAINING_MAX,\n AUTO_ROLL_SWITCH_REMAINING_MIN,\n DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD,\n DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD,\n sanitizeAutoRollRearmRemainingThreshold,\n sanitizeAutoRollSwitchRemainingThreshold,\n} from \"@codexuse/contracts/settings/auto-roll\";\nimport {\n DEFAULT_AUTOROLL_INTERVAL_SECONDS,\n hasFlag,\n parseIntegerFlag,\n parseLoginMode,\n parseNumericFlag,\n stripFlags,\n} from \"../platform/args\";\nimport {\n resolveCodexBinary,\n resolveLoginMode,\n runCodexLogin,\n} from \"../platform/codexCli\";\nimport { printHelp } from \"../app/help\";\n\nfunction formatProfileLabel(name: string, displayName?: string | null): string {\n if (displayName && displayName.trim() && displayName !== name) {\n return `${displayName} (${name})`;\n }\n return name;\n}\n\nfunction profileRateLimitKey(profile: Profile): string {\n return resolveProfileIdentityKeyFromProfile(profile);\n}\n\nfunction toTitleCase(value: string): string {\n return value.replace(/\\w\\S*/g, word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());\n}\n\nfunction formatShortDate(value?: string | null): string | null {\n if (!value) return null;\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return null;\n if (typeof Intl !== \"undefined\" && Intl.DateTimeFormat) {\n return new Intl.DateTimeFormat(undefined, { month: \"short\", day: \"numeric\" }).format(date);\n }\n return date.toLocaleDateString();\n}\n\nfunction formatRelativeTime(value?: string | null): string | null {\n if (!value) return null;\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) return null;\n const diffMs = parsed - Date.now();\n const absMs = Math.abs(diffMs);\n if (absMs < 60_000) {\n return null;\n }\n const minutes = Math.round(absMs / 60_000);\n if (minutes < 60) {\n return diffMs >= 0 ? `in ${minutes}m` : `${minutes}m ago`;\n }\n const hours = Math.round(minutes / 60);\n if (hours < 24) {\n return diffMs >= 0 ? `in ${hours}h` : `${hours}h ago`;\n }\n const days = Math.round(hours / 24);\n return diffMs >= 0 ? `in ${days}d` : `${days}d ago`;\n}\n\nfunction formatOrganizations(organizations?: OrganizationInfo[]): string | null {\n if (!organizations || !Array.isArray(organizations) || organizations.length === 0) {\n return null;\n }\n const parts = organizations\n .map(org => {\n if (!org) return null;\n const name = org.title || org.id;\n if (!name) return null;\n return org.role ? `${name} (${org.role})` : name;\n })\n .filter((value): value is string => Boolean(value));\n return parts.length > 0 ? parts.join(\", \") : null;\n}\n\nfunction formatWindowLabel(windowMinutes?: number): string | null {\n if (typeof windowMinutes !== \"number\" || Number.isNaN(windowMinutes)) {\n return null;\n }\n if (windowMinutes >= 2880) {\n const days = windowMinutes / 1440;\n const rounded = Math.round(days * 10) / 10;\n const display = Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1);\n return `${display.replace(/\\.0$/, \"\")}d window`;\n }\n if (windowMinutes >= 60) {\n const hours = windowMinutes / 60;\n const rounded = Math.round(hours * 10) / 10;\n const display = Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1);\n return `${display.replace(/\\.0$/, \"\")}h window`;\n }\n const minutes = Math.round(windowMinutes);\n return `${minutes}m window`;\n}\n\nfunction formatDurationFromSeconds(seconds?: number | null): string | null {\n if (typeof seconds !== \"number\" || Number.isNaN(seconds)) {\n return null;\n }\n if (seconds <= 0) {\n return \"now\";\n }\n const minutes = Math.floor(seconds / 60);\n if (minutes === 0) {\n return `${Math.max(1, Math.round(seconds))}s`;\n }\n if (minutes < 60) {\n return `${minutes}m`;\n }\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n if (hours < 24) {\n return remainingMinutes ? `${hours}h ${remainingMinutes}m` : `${hours}h`;\n }\n const days = Math.floor(hours / 24);\n const remainingHours = hours % 24;\n return remainingHours ? `${days}d ${remainingHours}h` : `${days}d`;\n}\n\nfunction formatResetText(window: RateLimitWindow): string | null {\n if (window.resetsAt) {\n return formatRelativeTime(window.resetsAt) ?? window.resetsAt;\n }\n const durationText = formatDurationFromSeconds(window.resetsInSeconds);\n if (!durationText) return null;\n if (durationText === \"now\") return \"now\";\n return `in ${durationText}`;\n}\n\ntype RateLimitRow = {\n label: string;\n used: string;\n reset: string | null;\n};\n\nfunction formatWindowUsage(window: RateLimitWindow): RateLimitRow | null {\n const label = formatWindowLabel(window.windowMinutes) ?? \"window\";\n const usedPercent =\n typeof window.usedPercent === \"number\" && Number.isFinite(window.usedPercent)\n ? `${Math.round(Math.max(0, Math.min(100, window.usedPercent)))}%`\n : \"n/a\";\n const resetText = formatResetText(window);\n return {\n label,\n used: usedPercent,\n reset: resetText ? `reset ${resetText}` : null,\n };\n}\n\ntype UsageInfo = {\n summary: string;\n rows: RateLimitRow[] | null;\n usageSummary: RateLimitUsageSummary;\n};\n\ntype RateLimitUsageKey = \"primary\" | \"secondary\";\n\ntype RateLimitUsageSummary = {\n windowKey: RateLimitUsageKey;\n usagePercent: number;\n remainingPercent: number;\n hasUsage: boolean;\n resetsInSeconds: number | null;\n windowMinutes: number | null;\n};\n\nconst EMPTY_USAGE_SUMMARY: RateLimitUsageSummary = {\n windowKey: \"primary\",\n usagePercent: 0,\n remainingPercent: 100,\n hasUsage: false,\n resetsInSeconds: null,\n windowMinutes: null,\n};\n\nfunction toFiniteNumberOrNull(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction summarizeRateLimitSnapshot(snapshot: RateLimitSnapshot | null | undefined): RateLimitUsageSummary {\n if (!snapshot) {\n return { ...EMPTY_USAGE_SUMMARY };\n }\n\n const entries: Array<{ key: RateLimitUsageKey; window: RateLimitWindow | undefined }> = [\n { key: \"primary\", window: snapshot.primary },\n { key: \"secondary\", window: snapshot.secondary },\n ];\n\n let summary: RateLimitUsageSummary = { ...EMPTY_USAGE_SUMMARY };\n let initialized = false;\n\n for (const entry of entries) {\n if (!entry.window) {\n continue;\n }\n\n const usageValueRaw = toFiniteNumberOrNull(entry.window.usedPercent);\n const usageValue = usageValueRaw === null ? 0 : Math.max(0, Math.min(100, usageValueRaw));\n const remainingValue = 100 - usageValue;\n const hasUsage = usageValueRaw !== null;\n const resetsInSeconds = toFiniteNumberOrNull(entry.window.resetsInSeconds);\n const windowMinutes = toFiniteNumberOrNull(entry.window.windowMinutes);\n\n if (!initialized) {\n initialized = true;\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n continue;\n }\n\n if (hasUsage && summary.hasUsage && usageValue > summary.usagePercent) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n continue;\n }\n\n if (!hasUsage && !summary.hasUsage && summary.resetsInSeconds !== null) {\n if (resetsInSeconds !== null && resetsInSeconds < summary.resetsInSeconds) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n }\n continue;\n }\n\n if (!hasUsage && !summary.hasUsage && summary.resetsInSeconds === null && resetsInSeconds !== null) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n continue;\n }\n\n if (hasUsage && !summary.hasUsage) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n }\n }\n\n return summary;\n}\n\nfunction fallbackUsage(profile: Profile): UsageInfo {\n const usageSummary = summarizeRateLimitSnapshot(profile.rateLimit ?? null);\n if (!profile.isValid) {\n return { summary: \"invalid\", rows: null, usageSummary };\n }\n if (profile.tokenStatus?.requiresUserAction) {\n return { summary: \"auth required\", rows: null, usageSummary };\n }\n return { summary: \"n/a\", rows: null, usageSummary };\n}\n\nasync function resolveProfileUsage(\n manager: ProfileManager,\n profile: Profile,\n codexPath: string,\n): Promise<UsageInfo> {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n return fallbackUsage(profile);\n }\n\n try {\n const snapshot = await manager.readLiveRateLimits(profile.name, { codexPath });\n if (!snapshot) {\n const usageSummary = summarizeRateLimitSnapshot(profile.rateLimit ?? null);\n return { summary: \"n/a\", rows: null, usageSummary };\n }\n const rows: RateLimitRow[] = [];\n if (snapshot.primary) {\n const row = formatWindowUsage(snapshot.primary);\n if (row) rows.push(row);\n }\n if (snapshot.secondary) {\n const row = formatWindowUsage(snapshot.secondary);\n if (row) rows.push(row);\n }\n const maxPercent = maxUsedPercent(snapshot);\n const summary = typeof maxPercent === \"number\"\n ? `${Math.round(maxPercent)}%`\n : \"n/a\";\n return { summary, rows: rows.length > 0 ? rows : null, usageSummary: summarizeRateLimitSnapshot(snapshot) };\n } catch {\n return fallbackUsage(profile);\n }\n}\n\ntype AutoRollCandidate = {\n profile: Profile;\n usageSummary: RateLimitUsageSummary;\n};\n\nfunction compareAutoRollCandidates(\n a: AutoRollCandidate,\n b: AutoRollCandidate,\n priorityRanks: Map<string, number>,\n): number {\n const aRank = priorityRanks.get(resolveProfileIdentityKeyFromProfile(a.profile));\n const bRank = priorityRanks.get(resolveProfileIdentityKeyFromProfile(b.profile));\n if (aRank !== undefined || bRank !== undefined) {\n if (aRank === undefined) return 1;\n if (bRank === undefined) return -1;\n if (aRank !== bRank) return aRank - bRank;\n }\n\n if (a.usageSummary.remainingPercent !== b.usageSummary.remainingPercent) {\n return b.usageSummary.remainingPercent - a.usageSummary.remainingPercent;\n }\n const aReset = a.usageSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n const bReset = b.usageSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n if (aReset !== bReset) {\n return aReset - bReset;\n }\n return a.profile.name.localeCompare(b.profile.name);\n}\n\nfunction computeAutoRollCandidate(\n profiles: Profile[],\n usageMap: Map<string, UsageInfo>,\n currentProfileName: string,\n currentSummary: RateLimitUsageSummary,\n switchRemainingThreshold: number,\n priorityOrder: string[] = [],\n blockedProfileNames: ReadonlySet<string> = new Set(),\n): AutoRollCandidate | null {\n const priorityRanks = new Map<string, number>();\n for (const [index, key] of priorityOrder.entries()) {\n const normalized = key.trim();\n if (normalized && !priorityRanks.has(normalized)) {\n priorityRanks.set(normalized, index);\n }\n }\n\n const candidates = profiles\n .filter(profile =>\n profile.name !== currentProfileName &&\n !blockedProfileNames.has(profile.name) &&\n profile.isValid &&\n !profile.tokenStatus?.requiresUserAction\n )\n .map(profile => ({\n profile,\n usageSummary: usageMap.get(profile.name)?.usageSummary ?? summarizeRateLimitSnapshot(profile.rateLimit ?? null),\n }));\n\n if (candidates.length === 0) {\n return null;\n }\n\n const belowThreshold = candidates\n .filter(\n candidate =>\n candidate.usageSummary.hasUsage &&\n candidate.usageSummary.remainingPercent > switchRemainingThreshold,\n )\n .sort((a, b) => compareAutoRollCandidates(a, b, priorityRanks));\n let selected = belowThreshold[0] ?? null;\n\n if (!selected) {\n selected = candidates\n .filter(candidate => !candidate.usageSummary.hasUsage)\n .sort((a, b) => compareAutoRollCandidates(a, b, priorityRanks))[0] ?? null;\n }\n\n if (!selected) {\n return null;\n }\n\n if (selected.usageSummary.hasUsage && currentSummary.hasUsage) {\n if (selected.usageSummary.remainingPercent < currentSummary.remainingPercent) {\n return null;\n }\n if (selected.usageSummary.remainingPercent === currentSummary.remainingPercent) {\n const selectedReset = selected.usageSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n const currentReset = currentSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n if (selectedReset >= currentReset) {\n return null;\n }\n }\n }\n\n return selected;\n}\n\nfunction formatPlan(profile: Profile): string {\n const metadata = profile.metadata;\n if (!metadata) {\n return \"No plan details\";\n }\n const parts: string[] = [];\n if (metadata.planType) {\n parts.push(toTitleCase(metadata.planType));\n }\n const until = metadata.subscription?.activeUntil;\n if (until) {\n const formatted = formatShortDate(until);\n if (formatted) {\n parts.push(`Until ${formatted}`);\n }\n }\n return parts.join(\" · \") || \"No plan details\";\n}\n\nfunction formatAuth(profile: Profile): string {\n const metadata = profile.metadata;\n const relative = formatRelativeTime(metadata?.tokenAuthTime);\n if (relative) return relative;\n if (metadata?.tokenAuthTime) return metadata.tokenAuthTime;\n return \"Not authenticated yet\";\n}\n\nfunction printProfileDetails(profile: Profile, usage?: UsageInfo | null): void {\n const email = profile.email ?? \"Unknown\";\n const plan = formatPlan(profile);\n const orgs = formatOrganizations(profile.metadata?.organizations) ?? \"No organizations\";\n const auth = formatAuth(profile);\n const workspace = profile.workspaceName ?? profile.workspaceId ?? null;\n\n const entries: Array<{ label: string; value: string }> = [\n { label: \"email\", value: email },\n { label: \"plan\", value: plan },\n { label: \"orgs\", value: orgs },\n { label: \"auth\", value: auth },\n ];\n if (workspace) {\n entries.push({ label: \"workspace\", value: workspace });\n }\n const pad = Math.max(...entries.map(entry => entry.label.length));\n for (const entry of entries) {\n console.log(` ${entry.label.padEnd(pad)} : ${entry.value}`);\n }\n\n if (usage) {\n if (usage.rows && usage.rows.length > 0) {\n const labelPad = Math.max(...usage.rows.map(row => row.label.length));\n const usedPad = Math.max(...usage.rows.map(row => row.used.length));\n console.log(` rate limits:`);\n for (const row of usage.rows) {\n const resetText = row.reset ? ` ${row.reset}` : \"\";\n console.log(` ${row.label.padEnd(labelPad)} ${row.used.padStart(usedPad)}${resetText}`);\n }\n return;\n }\n console.log(` rate limits: ${usage.summary}`);\n }\n}\n\nasync function mapWithConcurrency<T, R>(\n items: T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n const workerCount = Math.max(1, Math.min(limit, items.length));\n let nextIndex = 0;\n\n const workers = Array.from({ length: workerCount }, async () => {\n while (true) {\n const current = nextIndex++;\n if (current >= items.length) {\n return;\n }\n results[current] = await fn(items[current], current);\n }\n });\n\n await Promise.all(workers);\n return results;\n}\n\nfunction parseAutoRollSwitchRemainingThreshold(\n flags: string[],\n fallbackThreshold: number,\n): number {\n const explicitLeft = parseNumericFlag(flags, \"--switch-left\");\n const explicitLegacyUsed = parseNumericFlag(flags, \"--threshold\");\n if (explicitLeft !== null && explicitLegacyUsed !== null) {\n throw new Error(\"Use either --switch-left or legacy --threshold, not both.\");\n }\n\n if (explicitLeft !== null) {\n if (Number.isNaN(explicitLeft)) {\n throw new Error(\"Invalid --switch-left value. Use --switch-left=0-50.\");\n }\n if (\n explicitLeft < AUTO_ROLL_SWITCH_REMAINING_MIN ||\n explicitLeft > AUTO_ROLL_SWITCH_REMAINING_MAX\n ) {\n throw new Error(\"Invalid --switch-left value. Use a number between 0 and 50.\");\n }\n return sanitizeAutoRollSwitchRemainingThreshold(explicitLeft);\n }\n\n if (explicitLegacyUsed !== null) {\n if (Number.isNaN(explicitLegacyUsed)) {\n throw new Error(\"Invalid --threshold value. Use --threshold=50-100.\");\n }\n if (explicitLegacyUsed < 50 || explicitLegacyUsed > 100) {\n throw new Error(\"Invalid --threshold value. Use a number between 50 and 100.\");\n }\n return sanitizeAutoRollSwitchRemainingThreshold(100 - explicitLegacyUsed);\n }\n\n return sanitizeAutoRollSwitchRemainingThreshold(fallbackThreshold);\n}\n\nfunction parseAutoRollIntervalSeconds(flags: string[]): number {\n const explicitInterval = parseIntegerFlag(flags, \"--interval\");\n if (explicitInterval === null) {\n return DEFAULT_AUTOROLL_INTERVAL_SECONDS;\n }\n if (Number.isNaN(explicitInterval) || explicitInterval <= 0) {\n throw new Error(\"Invalid --interval value. Use --interval=<seconds> with a positive integer.\");\n }\n return explicitInterval;\n}\n\nfunction resolveRestartCodexFlag(flags: string[], fallback: boolean): boolean {\n const restart = hasFlag(flags, \"--restart-codex\");\n const noRestart = hasFlag(flags, \"--no-restart-codex\");\n if (restart && noRestart) {\n throw new Error(\"Use either --restart-codex or --no-restart-codex, not both.\");\n }\n if (restart) {\n return true;\n }\n if (noRestart) {\n return false;\n }\n return fallback;\n}\n\nfunction findProfileKey(profiles: Profile[], name: string): string | null {\n const profile = profiles.find(entry => entry.name === name);\n return profile ? profileRateLimitKey(profile) : null;\n}\n\nfunction rearmBlockedProfiles(\n blockedProfiles: Set<string> | undefined,\n usageMap: Map<string, UsageInfo>,\n rearmRemainingThreshold: number,\n): void {\n if (!blockedProfiles) {\n return;\n }\n for (const profileName of Array.from(blockedProfiles)) {\n const summary = usageMap.get(profileName)?.usageSummary;\n if (\n !summary ||\n !summary.hasUsage ||\n summary.remainingPercent > rearmRemainingThreshold\n ) {\n blockedProfiles.delete(profileName);\n }\n }\n}\n\nasync function rememberOfficialCodexSwitch(profileKey: string | null): Promise<void> {\n try {\n await recordOfficialCodexProfileSwitch(profileKey);\n } catch (error) {\n console.warn(\n `Could not record official Codex sync state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction formatOfficialCodexProfileAction(result: OfficialCodexProfileActionPayload): string {\n if (result.status === \"restarted\") {\n return \"Official Codex restarted.\";\n }\n if (result.status === \"started\") {\n return \"Official Codex started.\";\n }\n if (result.status === \"already-running\") {\n return \"Official Codex already running.\";\n }\n if (result.status === \"failed\") {\n return `Official Codex restart failed: ${result.reason}.`;\n }\n if (result.status === \"skipped\" || result.status === \"not-running\") {\n return `Official Codex restart skipped: ${result.reason}.`;\n }\n return \"Official Codex restart status unknown.\";\n}\n\nfunction findUnmanagedOfficialCodexRestartTarget(\n instances: OfficialCodexInstancesPayload,\n profileName: string,\n profileKey: string | null,\n): {\n target: OfficialCodexUnmanagedInstancePayload | null;\n ambiguous: boolean;\n unverified: boolean;\n} {\n const restartable = instances.unmanaged.filter((instance) => instance.pid);\n const matched =\n restartable.find((instance) => {\n if (profileKey && instance.profileKey) {\n return instance.profileKey === profileKey;\n }\n if (instance.profileKey) {\n return false;\n }\n return instance.profileName === profileName;\n }) ?? null;\n if (matched) {\n return { target: matched, ambiguous: false, unverified: false };\n }\n if (restartable.length > 1) {\n return { target: null, ambiguous: true, unverified: false };\n }\n return { target: null, ambiguous: false, unverified: restartable.length === 1 };\n}\n\nasync function restartUnmanagedOfficialCodexWindow(\n profileName: string,\n launchOptions: {\n profileName: string;\n profileKey: string | null;\n profileHome: string;\n },\n target: OfficialCodexUnmanagedInstancePayload,\n): Promise<OfficialCodexProfileActionPayload> {\n const stopped = await stopOfficialCodexObservedProfileInstance(\n target.profileName ?? profileName,\n target.pid,\n target.appServerPid,\n );\n if (stopped.status === \"failed\") {\n return stopped;\n }\n const launched = await launchOfficialCodexProfileInstance(launchOptions);\n return {\n ...launched,\n status:\n stopped.status === \"stopped\" && launched.status === \"started\"\n ? \"restarted\"\n : launched.status,\n };\n}\n\nasync function recordCliOfficialCodexRestartResult(\n profileName: string,\n profileKey: string | null,\n action: OfficialCodexProfileActionPayload,\n): Promise<void> {\n const pid =\n action.status === \"started\" || action.status === \"restarted\"\n ? action.instance?.pid ?? null\n : null;\n const status =\n action.status === \"started\" || action.status === \"restarted\"\n ? action.status\n : action.status === \"failed\"\n ? \"failed\"\n : \"skipped\";\n const reason =\n action.status === \"started\" || action.status === \"restarted\"\n ? null\n : action.reason ?? action.status;\n\n try {\n await recordOfficialCodexRestartResult({\n status,\n reason,\n profileKey,\n pid,\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-restart\",\n status,\n reason,\n targetProfileName: profileName,\n profileKey,\n phase: \"cli\",\n pid,\n restartRequested: true,\n restartResult: status,\n });\n } catch (error) {\n console.warn(\n `Could not record official Codex restart state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nasync function recordCliOfficialCodexRestartSkipped(\n profileName: string,\n profileKey: string | null,\n reason: string,\n): Promise<void> {\n await recordCliOfficialCodexRestartResult(profileName, profileKey, {\n status: \"skipped\",\n profileName,\n instance: null,\n reason,\n });\n}\n\nasync function maybeRestartOfficialCodex(options: {\n manager: ProfileManager;\n enabled: boolean;\n profileName: string;\n profileKey: string | null;\n launchIfNotRunning?: boolean;\n}): Promise<string | null> {\n if (!options.enabled) {\n return null;\n }\n try {\n const runtime = await options.manager.prepareProfileRuntime(options.profileName);\n const launchOptions = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: runtime.profileHome,\n };\n const instances = await getOfficialCodexProfileInstances();\n if (instances.state === \"unsupported\") {\n await recordCliOfficialCodexRestartSkipped(\n options.profileName,\n options.profileKey,\n \"unsupported-platform\",\n );\n return \"Official Codex restart skipped: unsupported-platform.\";\n }\n if (instances.state === \"not-found\") {\n await recordCliOfficialCodexRestartSkipped(\n options.profileName,\n options.profileKey,\n \"official-codex-app-not-found\",\n );\n return \"Official Codex restart skipped: official-codex-app-not-found.\";\n }\n const managedRunning = instances.instances.some(\n (instance) => instance.profileName === options.profileName && instance.running,\n );\n const unmanaged = findUnmanagedOfficialCodexRestartTarget(\n instances,\n options.profileName,\n options.profileKey,\n );\n if (unmanaged.target && !managedRunning) {\n const action = await restartUnmanagedOfficialCodexWindow(\n options.profileName,\n launchOptions,\n unmanaged.target,\n );\n await recordCliOfficialCodexRestartResult(\n options.profileName,\n options.profileKey,\n action,\n );\n return formatOfficialCodexProfileAction(action);\n }\n if (unmanaged.ambiguous && !managedRunning) {\n await recordCliOfficialCodexRestartSkipped(\n options.profileName,\n options.profileKey,\n \"ambiguous-official-codex-windows\",\n );\n return \"Official Codex restart skipped: ambiguous-official-codex-windows.\";\n }\n if (unmanaged.unverified && !managedRunning) {\n await recordCliOfficialCodexRestartSkipped(\n options.profileName,\n options.profileKey,\n \"unverified-official-codex-window\",\n );\n return \"Official Codex restart skipped: unverified-official-codex-window.\";\n }\n if (options.launchIfNotRunning === false) {\n if (!managedRunning) {\n await recordCliOfficialCodexRestartSkipped(\n options.profileName,\n options.profileKey,\n \"official-codex-app-not-running\",\n );\n return \"Official Codex restart skipped: official-codex-app-not-running.\";\n }\n const action = await restartOfficialCodexProfileInstance(launchOptions);\n await recordCliOfficialCodexRestartResult(\n options.profileName,\n options.profileKey,\n action,\n );\n return formatOfficialCodexProfileAction(action);\n }\n const action = await restartOfficialCodexProfileInstance(launchOptions);\n await recordCliOfficialCodexRestartResult(\n options.profileName,\n options.profileKey,\n action,\n );\n return formatOfficialCodexProfileAction(action);\n } catch (error) {\n await recordCliOfficialCodexRestartResult(options.profileName, options.profileKey, {\n status: \"failed\",\n profileName: options.profileName,\n instance: null,\n reason: error instanceof Error ? error.message : \"restart-threw\",\n });\n return `Official Codex restart failed: ${error instanceof Error ? error.message : String(error)}.`;\n }\n}\n\nasync function collectUsageMap(\n manager: ProfileManager,\n profiles: Profile[],\n codexPath: string,\n): Promise<Map<string, UsageInfo>> {\n const usageMap = new Map<string, UsageInfo>();\n const uniqueProfilesByAccount = new Map<string, Profile>();\n for (const profile of profiles) {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n continue;\n }\n const key = profileRateLimitKey(profile);\n if (!uniqueProfilesByAccount.has(key)) {\n uniqueProfilesByAccount.set(key, profile);\n }\n }\n\n const uniqueProfiles = Array.from(uniqueProfilesByAccount.values());\n const limit = Math.max(1, uniqueProfiles.length);\n const results = await mapWithConcurrency(uniqueProfiles, limit, (profile) =>\n resolveProfileUsage(manager, profile, codexPath),\n );\n\n const usageByAccount = new Map<string, UsageInfo>();\n for (const [index, profile] of uniqueProfiles.entries()) {\n usageByAccount.set(profileRateLimitKey(profile), results[index]);\n }\n\n for (const profile of profiles) {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n usageMap.set(profile.name, fallbackUsage(profile));\n continue;\n }\n usageMap.set(\n profile.name,\n usageByAccount.get(profileRateLimitKey(profile)) ?? fallbackUsage(profile),\n );\n }\n return usageMap;\n}\n\nasync function runAutoRollPass(\n manager: ProfileManager,\n options: {\n switchRemainingThreshold: number;\n rearmRemainingThreshold: number;\n dryRun: boolean;\n priorityOrder?: string[];\n restartOfficialCodex: boolean;\n launchOfficialCodexWhenClosed?: boolean;\n blockedProfiles?: Set<string>;\n blockCurrentUntilRearm?: boolean;\n },\n): Promise<{ switched: boolean; message: string; source: string | null; target: string | null }> {\n const profiles = await manager.listProfiles();\n if (!profiles.length) {\n return { switched: false, message: \"No profiles found.\", source: null, target: null };\n }\n\n const current = await manager.getCurrentProfile();\n if (!current.name) {\n return { switched: false, message: \"No active profile.\", source: null, target: null };\n }\n\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n throw new Error(\"Codex CLI binary not found on PATH. Auto-roll requires codex for live rate limits.\");\n }\n\n const usageMap = await collectUsageMap(manager, profiles, codexPath);\n rearmBlockedProfiles(\n options.blockedProfiles,\n usageMap,\n options.rearmRemainingThreshold,\n );\n const currentProfile = profiles.find(profile => profile.name === current.name);\n if (!currentProfile) {\n return {\n switched: false,\n message: `Current profile '${current.name}' is missing from saved profiles.`,\n source: current.name,\n target: null,\n };\n }\n\n const currentUsage = usageMap.get(current.name)?.usageSummary ?? summarizeRateLimitSnapshot(currentProfile.rateLimit ?? null);\n if (!currentUsage.hasUsage) {\n return {\n switched: false,\n message: `No live rate-limit usage for '${current.name}'. Skipping auto-roll.`,\n source: current.name,\n target: null,\n };\n }\n\n if (options.blockedProfiles?.has(current.name)) {\n if (currentUsage.remainingPercent > options.rearmRemainingThreshold) {\n options.blockedProfiles.delete(current.name);\n } else {\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left; waiting for re-arm above ${options.rearmRemainingThreshold}% left.`,\n source: current.name,\n target: null,\n };\n }\n }\n\n if (\n options.blockCurrentUntilRearm &&\n currentUsage.remainingPercent <= options.switchRemainingThreshold\n ) {\n options.blockedProfiles?.add(current.name);\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left; waiting for re-arm above ${options.rearmRemainingThreshold}% left.`,\n source: current.name,\n target: null,\n };\n }\n\n if (currentUsage.remainingPercent > options.switchRemainingThreshold) {\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left, above switch threshold ${options.switchRemainingThreshold}% left.`,\n source: current.name,\n target: null,\n };\n }\n\n const candidate = computeAutoRollCandidate(\n profiles,\n usageMap,\n current.name,\n currentUsage,\n options.switchRemainingThreshold,\n options.priorityOrder ?? [],\n options.blockedProfiles,\n );\n if (!candidate) {\n return {\n switched: false,\n message: `No eligible profile to switch from '${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left.`,\n source: current.name,\n target: null,\n };\n }\n\n const candidateUsage = candidate.usageSummary.hasUsage ? `${Math.round(candidate.usageSummary.remainingPercent)}% left` : \"n/a\";\n if (options.dryRun) {\n const restartSuffix = options.restartOfficialCodex\n ? \" Official Codex would restart after the switch if running.\"\n : \"\";\n return {\n switched: false,\n message: `[dry-run] Would switch '${current.name}' (${Math.round(currentUsage.remainingPercent)}% left) -> '${candidate.profile.name}' (${candidateUsage}).${restartSuffix}`,\n source: current.name,\n target: candidate.profile.name,\n };\n }\n\n await manager.switchToProfile(candidate.profile.name);\n const targetProfileKey = profileRateLimitKey(candidate.profile);\n await rememberOfficialCodexSwitch(targetProfileKey);\n const restartMessage = await maybeRestartOfficialCodex({\n manager,\n enabled: options.restartOfficialCodex,\n profileName: candidate.profile.name,\n profileKey: targetProfileKey,\n launchIfNotRunning: options.launchOfficialCodexWhenClosed === true,\n });\n options.blockedProfiles?.add(current.name);\n return {\n switched: true,\n message: `Auto-rolled '${current.name}' (${Math.round(currentUsage.remainingPercent)}% left) -> '${candidate.profile.name}' (${candidateUsage}).${restartMessage ? ` ${restartMessage}` : \"\"}`,\n source: current.name,\n target: candidate.profile.name,\n };\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport async function handleProfileCommand(\n args: string[],\n version: string,\n): Promise<void> {\n const flags = args.filter(arg => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printHelp(version);\n return;\n }\n\n const manager = new ProfileManager();\n\n switch (sub) {\n case \"list\": {\n const profiles = await manager.listProfiles();\n const current = await manager.getCurrentProfile();\n if (!profiles.length) {\n console.log(\"No profiles found.\");\n return;\n }\n const compact = hasFlag(flags, \"--compact\");\n const withUsage = !hasFlag(flags, \"--no-usage\");\n let usageMap: Map<string, UsageInfo> | null = null;\n if (withUsage) {\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n usageMap = new Map();\n for (const profile of profiles) {\n usageMap.set(profile.name, {\n summary: \"codex cli missing\",\n rows: null,\n usageSummary: summarizeRateLimitSnapshot(profile.rateLimit ?? null),\n });\n }\n } else {\n usageMap = await collectUsageMap(manager, profiles, codexPath);\n }\n }\n for (const [index, profile] of profiles.entries()) {\n const marker = current.name === profile.name ? \"*\" : \" \";\n const label = formatProfileLabel(profile.name, profile.displayName);\n if (index > 0) {\n console.log(\"\");\n }\n const activeLabel = current.name === profile.name ? \" (active)\" : \"\";\n console.log(`${marker} ${label}${activeLabel}`);\n if (compact) continue;\n const usage = usageMap?.get(profile.name) ?? null;\n printProfileDetails(profile, usage);\n }\n return;\n }\n case \"current\": {\n const current = await manager.getCurrentProfile();\n if (!current.name) {\n console.log(\"No active profile.\");\n return;\n }\n console.log(current.name);\n return;\n }\n case \"add\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n await assertProfileCreationAllowed(manager);\n if (!hasFlag(flags, \"--skip-login\")) {\n const loginMode = resolveLoginMode(parseLoginMode(flags));\n await runCodexLogin(loginMode);\n }\n const profile = await manager.createProfile(name);\n const label = profile ? formatProfileLabel(profile.name, profile.displayName) : name;\n console.log(`Profile created: ${label}`);\n return;\n }\n case \"refresh\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n if (!hasFlag(flags, \"--skip-login\")) {\n const loginMode = resolveLoginMode(parseLoginMode(flags));\n await runCodexLogin(loginMode);\n }\n const profile = await manager.refreshProfileAuth(name);\n const label = formatProfileLabel(profile.name, profile.displayName);\n console.log(`Profile refreshed: ${label}`);\n return;\n }\n case \"switch\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n const restartOfficialCodex = resolveRestartCodexFlag(flags, false);\n const profiles = await manager.listProfiles();\n const targetProfileKey = findProfileKey(profiles, name);\n await manager.switchToProfile(name);\n console.log(`Switched to profile: ${name}`);\n await rememberOfficialCodexSwitch(targetProfileKey);\n const restartMessage = await maybeRestartOfficialCodex({\n manager,\n enabled: restartOfficialCodex,\n profileName: name,\n profileKey: targetProfileKey,\n });\n if (restartMessage) {\n console.log(restartMessage);\n }\n return;\n }\n case \"autoroll\":\n case \"auto-roll\": {\n const license = await licenseService.getStatus();\n if (!license.isPro) {\n throw new Error(\"Auto-roll requires a Pro license.\");\n }\n const watch = hasFlag(flags, \"--watch\");\n const dryRun = hasFlag(flags, \"--dry-run\");\n const settings = await getStoredAutoRollSettings().catch(() => null);\n const restartOfficialCodex = resolveRestartCodexFlag(\n flags,\n settings?.restartOfficialCodexOnAutoRoll === true,\n );\n const fallbackSwitchRemainingThreshold =\n typeof settings?.switchRemainingThreshold === \"number\" &&\n Number.isFinite(settings.switchRemainingThreshold)\n ? settings.switchRemainingThreshold\n : DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD;\n const switchRemainingThreshold = parseAutoRollSwitchRemainingThreshold(\n flags,\n fallbackSwitchRemainingThreshold,\n );\n const rearmRemainingThreshold = sanitizeAutoRollRearmRemainingThreshold(\n settings?.rearmRemainingThreshold ??\n DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD,\n switchRemainingThreshold,\n );\n const intervalSeconds = parseAutoRollIntervalSeconds(flags);\n\n if (watch) {\n console.log(\n `Auto-roll watch: switch at/below ${switchRemainingThreshold}% left | re-arm above ${rearmRemainingThreshold}% left | interval ${intervalSeconds}s${dryRun ? \" | dry-run\" : \"\"}${restartOfficialCodex ? \" | restart-codex\" : \"\"}`,\n );\n const blockedProfiles = new Set<string>();\n let lastObservedProfile: string | null = null;\n let stop = false;\n process.on(\"SIGINT\", () => {\n stop = true;\n });\n process.on(\"SIGTERM\", () => {\n stop = true;\n });\n\n while (!stop) {\n const current = await manager.getCurrentProfile();\n const currentName = current.name ?? null;\n const blockCurrentUntilRearm = Boolean(\n currentName &&\n lastObservedProfile &&\n currentName !== lastObservedProfile,\n );\n const result = await runAutoRollPass(manager, {\n switchRemainingThreshold,\n rearmRemainingThreshold,\n dryRun,\n priorityOrder: settings?.priorityOrder ?? [],\n restartOfficialCodex,\n launchOfficialCodexWhenClosed:\n settings?.launchOfficialCodexWhenClosedOnAutoRoll === true,\n blockedProfiles,\n blockCurrentUntilRearm,\n });\n console.log(result.message);\n lastObservedProfile = result.switched\n ? (result.target ?? currentName)\n : (currentName ?? result.source);\n if (stop) {\n break;\n }\n await delay(intervalSeconds * 1000);\n }\n console.log(\"Auto-roll watch stopped.\");\n return;\n }\n\n const result = await runAutoRollPass(manager, {\n switchRemainingThreshold,\n rearmRemainingThreshold,\n dryRun,\n priorityOrder: settings?.priorityOrder ?? [],\n restartOfficialCodex,\n launchOfficialCodexWhenClosed:\n settings?.launchOfficialCodexWhenClosedOnAutoRoll === true,\n });\n console.log(result.message);\n return;\n }\n case \"delete\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n await manager.deleteProfile(name);\n console.log(`Profile deleted: ${name}`);\n return;\n }\n case \"rename\": {\n const from = params[1];\n const to = params[2];\n if (!from || !to) {\n throw new Error(\"Old and new profile names are required.\");\n }\n await manager.renameProfile(from, to);\n console.log(`Profile renamed: ${from} -> ${to}`);\n return;\n }\n default:\n printHelp(version);\n return;\n }\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n CLOUD_SYNC_SCHEMA_VERSION,\n type CloudSyncProfileRecord,\n type CloudSyncSnapshot,\n} from \"@codexuse/contracts/cloud-sync/types\";\nimport {\n CloudSyncClientError,\n fetchRemoteSnapshotMeta,\n fetchRemoteSnapshot,\n pushRemoteSnapshot,\n} from \"@codexuse/runtime-profiles/cloud-sync/client\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { getCodexConfigSnapshot, saveCodexConfigContent } from \"@codexuse/runtime-codex/codex/config\";\nimport { resolveCodexRuntimeContext } from \"@codexuse/runtime-codex/codex/home\";\nimport {\n getStoredLicense,\n readCodexSettingsJsonRaw,\n writeCodexSettingsJsonRaw,\n} from \"@codexuse/runtime-codex/codex/settings\";\nimport { getAppState, getUserDataDir, patchAppState } from \"@codexuse/runtime-app-state/app/state\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { logInfo, logWarn } from \"@codexuse/shared/core/logger\";\nimport { formatUserFacingError } from \"@codexuse/shared/core/errors\";\nimport type { CloudSyncRunResultPayload, CloudSyncStatusPayload } from \"@codexuse/contracts/desktop/ipc-types\";\nimport { isRecord } from \"@codexuse/shared/core/type-guards\";\n\nconst SYNC_BACKUP_DIR = \"sync-backups\";\nconst PRE_PULL_BACKUP_PREFIX = \"pre-pull-\";\nconst PRE_PULL_BACKUP_SUFFIX = \".json\";\nconst PRE_PULL_BACKUP_KEEP_COUNT = 3;\nconst SYNC_SIZE_WARN_BYTES = 1 * 1024 * 1024;\nconst SYNC_SIZE_MAX_BYTES = 5 * 1024 * 1024;\nconst MB_DIVISOR = 1024 * 1024;\n\ninterface CloudSyncStateFile {\n lastPushAt?: string;\n lastPullAt?: string;\n lastError?: string;\n remoteUpdatedAt?: string;\n}\n\ntype Eligibility = {\n canSync: boolean;\n reason: string | null;\n licenseKey: string | null;\n licenseState: string | null;\n};\n\ntype BuildLocalSnapshotOptions = {\n enforcePushGuards?: boolean;\n};\n\nfunction mapProfilesFromAppState(raw: unknown): CloudSyncProfileRecord[] {\n if (!isRecord(raw)) {\n return [];\n }\n\n const profiles: CloudSyncProfileRecord[] = [];\n\n for (const [name, value] of Object.entries(raw)) {\n if (!isRecord(value)) {\n continue;\n }\n\n const data = isRecord(value.data) ? value.data : null;\n if (!data) {\n continue;\n }\n\n const normalizedName = typeof name === \"string\" ? name.trim() : \"\";\n if (!normalizedName) {\n continue;\n }\n\n profiles.push({\n name: normalizedName,\n displayName: typeof value.displayName === \"string\" ? value.displayName : null,\n data,\n metadata: isRecord(value.metadata) ? value.metadata : undefined,\n accountId: typeof value.accountId === \"string\" ? value.accountId : null,\n workspaceId: typeof value.workspaceId === \"string\" ? value.workspaceId : null,\n workspaceName: typeof value.workspaceName === \"string\" ? value.workspaceName : null,\n email: typeof value.email === \"string\" ? value.email : null,\n authMethod: typeof value.authMethod === \"string\" ? value.authMethod : null,\n createdAt: typeof value.createdAt === \"string\" ? value.createdAt : null,\n updatedAt: typeof value.updatedAt === \"string\" ? value.updatedAt : null,\n });\n }\n\n return profiles;\n}\n\nfunction summarizeSnapshot(snapshot: CloudSyncSnapshot): {\n profiles: number;\n configBytes: number;\n settingsKeys: number;\n} {\n const configBytes =\n typeof snapshot.configTomlContent === \"string\" ? snapshot.configTomlContent.length : 0;\n const settingsKeys =\n isRecord(snapshot.settingsJson) ? Object.keys(snapshot.settingsJson).length : 0;\n\n return {\n profiles: snapshot.profiles.length,\n configBytes,\n settingsKeys,\n };\n}\n\nasync function readState(): Promise<CloudSyncStateFile> {\n const state = await getAppState();\n return {\n lastPushAt: state.sync.lastPushAt ?? undefined,\n lastPullAt: state.sync.lastPullAt ?? undefined,\n lastError: state.sync.lastError ?? undefined,\n remoteUpdatedAt: state.sync.remoteUpdatedAt ?? undefined,\n };\n}\n\nasync function writeState(patch: Partial<CloudSyncStateFile>): Promise<void> {\n await patchAppState({\n sync: {\n ...(typeof patch.lastPushAt === \"string\" ? { lastPushAt: patch.lastPushAt } : {}),\n ...(typeof patch.lastPullAt === \"string\" ? { lastPullAt: patch.lastPullAt } : {}),\n ...(typeof patch.lastError === \"string\" ? { lastError: patch.lastError } : patch.lastError === undefined ? { lastError: null } : {}),\n ...(typeof patch.remoteUpdatedAt === \"string\"\n ? { remoteUpdatedAt: patch.remoteUpdatedAt }\n : {}),\n },\n });\n}\n\nasync function resolveEligibility(): Promise<Eligibility> {\n const stored = await getStoredLicense();\n const licenseKey = typeof stored?.licenseKey === \"string\" ? stored.licenseKey.trim() : \"\";\n\n if (!licenseKey) {\n return {\n canSync: false,\n reason: \"License key is required for cloud sync.\",\n licenseKey: null,\n licenseState: null,\n };\n }\n\n const status = await licenseService.getStatus();\n const active = status.state === \"active\" || status.state === \"grace\";\n if (!active) {\n return {\n canSync: false,\n reason: \"Cloud sync requires an active Pro license.\",\n licenseKey,\n licenseState: status.state,\n };\n }\n\n return {\n canSync: true,\n reason: null,\n licenseKey,\n licenseState: status.state,\n };\n}\n\nfunction formatMegabytes(bytes: number): string {\n return (bytes / MB_DIVISOR).toFixed(2);\n}\n\nfunction resolveSyncBackupsDir(): string {\n return path.join(getUserDataDir(), SYNC_BACKUP_DIR);\n}\n\nfunction toSafeIsoForFileName(iso: string): string {\n return iso.replace(/:/g, \"-\");\n}\n\nasync function pruneOldPrePullBackups(backupsDir: string): Promise<void> {\n const entries = await fs.readdir(backupsDir, { withFileTypes: true });\n const files = entries\n .filter(\n (entry) =>\n entry.isFile() &&\n entry.name.startsWith(PRE_PULL_BACKUP_PREFIX) &&\n entry.name.endsWith(PRE_PULL_BACKUP_SUFFIX),\n )\n .map((entry) => entry.name)\n .sort((a, b) => b.localeCompare(a));\n\n if (files.length <= PRE_PULL_BACKUP_KEEP_COUNT) {\n return;\n }\n\n for (const stale of files.slice(PRE_PULL_BACKUP_KEEP_COUNT)) {\n await fs.rm(path.join(backupsDir, stale), { force: true });\n }\n}\n\nasync function createPrePullBackup(profileManager: ProfileManager): Promise<string> {\n const snapshot = await buildLocalSnapshot(profileManager, {\n enforcePushGuards: false,\n });\n const backupsDir = resolveSyncBackupsDir();\n await fs.mkdir(backupsDir, { recursive: true });\n\n const timestamp = toSafeIsoForFileName(new Date().toISOString());\n const backupPath = path.join(\n backupsDir,\n `${PRE_PULL_BACKUP_PREFIX}${timestamp}${PRE_PULL_BACKUP_SUFFIX}`,\n );\n await fs.writeFile(backupPath, `${JSON.stringify(snapshot, null, 2)}\\n`, \"utf8\");\n await pruneOldPrePullBackups(backupsDir);\n\n logInfo(\"[cloud-sync] created pre-pull backup\", { backupPath });\n return backupPath;\n}\n\nasync function buildLocalSnapshot(\n profileManager: ProfileManager,\n options: BuildLocalSnapshotOptions = {},\n): Promise<CloudSyncSnapshot> {\n const enforcePushGuards = options.enforcePushGuards !== false;\n const profilesFromManager = await profileManager.exportProfilesForCloudSync();\n const state = await getAppState();\n const profilesFromState = mapProfilesFromAppState(state.profilesByName);\n const profiles = profilesFromManager.length > 0 ? profilesFromManager : profilesFromState;\n const runtimeContext = await resolveCodexRuntimeContext();\n const config = await getCodexConfigSnapshot({\n codexHomePath: runtimeContext.codexHomePath,\n });\n const settingsJson = await readCodexSettingsJsonRaw();\n\n const hasProfiles = profiles.length > 0;\n const hasConfig = typeof config.content === \"string\" && config.content.trim().length > 0;\n const hasSettings = isRecord(settingsJson) && Object.keys(settingsJson).length > 0;\n\n if (enforcePushGuards && !hasProfiles && !hasConfig && !hasSettings) {\n throw new Error(\"Refusing to push an empty cloud sync snapshot.\");\n }\n\n const snapshot: CloudSyncSnapshot = {\n schemaVersion: CLOUD_SYNC_SCHEMA_VERSION,\n updatedAt: new Date().toISOString(),\n profiles,\n configTomlContent: config.exists ? config.content : null,\n settingsJson,\n };\n\n if (!enforcePushGuards) {\n return snapshot;\n }\n\n return snapshot;\n}\n\nasync function applyRemoteSnapshot(profileManager: ProfileManager, snapshot: CloudSyncSnapshot): Promise<void> {\n await profileManager.replaceProfilesFromCloudSync(snapshot.profiles ?? []);\n\n if (typeof snapshot.configTomlContent === \"string\") {\n const runtimeContext = await resolveCodexRuntimeContext();\n await saveCodexConfigContent(snapshot.configTomlContent, {\n codexHomePath: runtimeContext.codexHomePath,\n });\n }\n\n if (snapshot.settingsJson && isRecord(snapshot.settingsJson)) {\n await writeCodexSettingsJsonRaw(snapshot.settingsJson);\n } else {\n await writeCodexSettingsJsonRaw({});\n }\n}\n\nfunction toRunError(mode: \"push\" | \"pull\", error: unknown): CloudSyncRunResultPayload {\n const message = formatUserFacingError(error, {\n fallback: `Cloud sync ${mode} failed.`,\n });\n\n return {\n mode,\n status: \"error\",\n message,\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n}\n\nexport async function getCloudSyncStatus(): Promise<CloudSyncStatusPayload> {\n const eligibility = await resolveEligibility();\n const state = await readState();\n\n let remoteUpdatedAt: string | null = state.remoteUpdatedAt ?? null;\n if (eligibility.canSync && eligibility.licenseKey) {\n try {\n remoteUpdatedAt = await fetchRemoteSnapshotMeta(eligibility.licenseKey);\n } catch (error) {\n if (error instanceof CloudSyncClientError && error.status === 404) {\n try {\n const remote = await fetchRemoteSnapshot(eligibility.licenseKey);\n remoteUpdatedAt = remote?.updatedAt ?? null;\n } catch {\n // Keep status lightweight when remote endpoint is unavailable.\n }\n }\n // Keep status lightweight when remote endpoint is unavailable.\n }\n }\n\n return {\n canSync: eligibility.canSync,\n reason: eligibility.reason,\n licenseState: eligibility.licenseState,\n hasLicenseKey: Boolean(eligibility.licenseKey),\n lastPushAt: state.lastPushAt ?? null,\n lastPullAt: state.lastPullAt ?? null,\n lastError: state.lastError ?? null,\n remoteUpdatedAt,\n };\n}\n\nexport async function pushCloudSync(): Promise<CloudSyncRunResultPayload> {\n const eligibility = await resolveEligibility();\n if (!eligibility.canSync || !eligibility.licenseKey) {\n return {\n mode: \"push\",\n status: \"skipped\",\n message: eligibility.reason ?? \"Cloud sync unavailable.\",\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n }\n\n const profileManager = new ProfileManager();\n\n try {\n await profileManager.initialize();\n const localSnapshot = await buildLocalSnapshot(profileManager, { enforcePushGuards: true });\n const serializedSnapshot = JSON.stringify(localSnapshot);\n const snapshotBytes = Buffer.byteLength(serializedSnapshot, \"utf8\");\n if (snapshotBytes > SYNC_SIZE_WARN_BYTES) {\n logWarn(\"[cloud-sync] push snapshot is large\", {\n bytes: snapshotBytes,\n megabytes: formatMegabytes(snapshotBytes),\n });\n }\n if (snapshotBytes > SYNC_SIZE_MAX_BYTES) {\n throw new Error(\n `Snapshot too large to sync (${formatMegabytes(snapshotBytes)} MB). Reduce profiles or config size.`,\n );\n }\n if (process.env.NODE_ENV !== \"production\") {\n logInfo(\"[cloud-sync] push snapshot summary\", summarizeSnapshot(localSnapshot));\n }\n const remote = await pushRemoteSnapshot(eligibility.licenseKey, localSnapshot, {\n serializedSnapshot,\n });\n\n await writeState({\n lastPushAt: new Date().toISOString(),\n remoteUpdatedAt: remote.snapshot.updatedAt,\n lastError: undefined,\n });\n\n if (remote.status === \"stale\") {\n return {\n mode: \"push\",\n status: \"stale\",\n message: \"Remote cloud snapshot is newer. Pull first.\",\n localUpdatedAt: localSnapshot.updatedAt,\n remoteUpdatedAt: remote.snapshot.updatedAt,\n };\n }\n\n return {\n mode: \"push\",\n status: \"applied\",\n message: \"Cloud sync push completed.\",\n localUpdatedAt: localSnapshot.updatedAt,\n remoteUpdatedAt: remote.snapshot.updatedAt,\n };\n } catch (error) {\n const result = toRunError(\"push\", error);\n const lastError = error instanceof CloudSyncClientError ? error.message : result.message;\n await writeState({ lastError });\n return result;\n }\n}\n\nexport async function pullCloudSync(): Promise<CloudSyncRunResultPayload> {\n const eligibility = await resolveEligibility();\n if (!eligibility.canSync || !eligibility.licenseKey) {\n return {\n mode: \"pull\",\n status: \"skipped\",\n message: eligibility.reason ?? \"Cloud sync unavailable.\",\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n }\n\n const profileManager = new ProfileManager();\n\n try {\n await profileManager.initialize();\n const remote = await fetchRemoteSnapshot(eligibility.licenseKey);\n\n if (!remote) {\n return {\n mode: \"pull\",\n status: \"skipped\",\n message: \"No cloud snapshot found.\",\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n }\n\n let backupWarningSuffix = \"\";\n try {\n await createPrePullBackup(profileManager);\n } catch (backupError) {\n logWarn(\"[cloud-sync] pre-pull backup failed; continuing pull\", backupError);\n const reason = formatUserFacingError(backupError, { fallback: \"unknown error\" });\n backupWarningSuffix = ` Warning: pre-pull backup failed (${reason}).`;\n }\n await applyRemoteSnapshot(profileManager, remote);\n await writeState({\n lastPullAt: new Date().toISOString(),\n remoteUpdatedAt: remote.updatedAt,\n lastError: undefined,\n });\n\n return {\n mode: \"pull\",\n status: \"applied\",\n message: `Cloud sync pull completed.${backupWarningSuffix}`,\n localUpdatedAt: remote.updatedAt,\n remoteUpdatedAt: remote.updatedAt,\n };\n } catch (error) {\n const result = toRunError(\"pull\", error);\n const lastError = error instanceof CloudSyncClientError ? error.message : result.message;\n await writeState({ lastError });\n return result;\n }\n}\n","import type { ProfileData, ProfileMetadata } from \"../profiles/types.ts\";\n\nexport const CLOUD_SYNC_SCHEMA_VERSION = 1 as const;\n\nexport interface CloudSyncProfileRecord {\n name: string;\n displayName: string | null;\n data: ProfileData;\n metadata?: ProfileMetadata;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n email: string | null;\n authMethod: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n}\n\nexport interface CloudSyncSnapshot {\n schemaVersion: typeof CLOUD_SYNC_SCHEMA_VERSION;\n updatedAt: string;\n profiles: CloudSyncProfileRecord[];\n configTomlContent: string | null;\n settingsJson: Record<string, unknown> | null;\n}\n\nexport interface CloudSyncGetResponse {\n snapshot: CloudSyncSnapshot | null;\n}\n\nexport interface CloudSyncMetaResponse {\n updatedAt: string | null;\n}\n\nexport type CloudSyncPutStatus = \"applied\" | \"stale\";\n\nexport interface CloudSyncPutResponse {\n status: CloudSyncPutStatus;\n snapshot: CloudSyncSnapshot;\n}\n","export function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function toIsoOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : new Date(parsed).toISOString();\n}\n","import {\n CLOUD_SYNC_SCHEMA_VERSION,\n type CloudSyncGetResponse,\n type CloudSyncMetaResponse,\n type CloudSyncPutResponse,\n type CloudSyncSnapshot,\n} from \"@codexuse/contracts/cloud-sync/types\";\nimport { isRecord, toIsoOrNull } from \"@codexuse/shared/core/type-guards\";\n\nconst DEFAULT_CLOUD_SYNC_API_BASE_URL = \"https://api.codexuse.com\";\nconst CLOUD_SYNC_TIMEOUT_MS = 15_000;\n\nexport class CloudSyncClientError extends Error {\n readonly status: number | null;\n\n constructor(message: string, status: number | null = null) {\n super(message);\n this.name = \"CloudSyncClientError\";\n this.status = status;\n }\n}\n\nfunction normalizeBaseUrl(value: string): string {\n const trimmed = value.trim();\n return trimmed.endsWith(\"/\") ? trimmed.slice(0, -1) : trimmed;\n}\n\nexport function getCloudSyncApiBaseUrl(): string {\n const fromEnv = typeof process.env.CODEXUSE_API_BASE_URL === \"string\"\n ? process.env.CODEXUSE_API_BASE_URL\n : \"\";\n\n if (fromEnv.trim().length === 0) {\n return DEFAULT_CLOUD_SYNC_API_BASE_URL;\n }\n\n return normalizeBaseUrl(fromEnv);\n}\n\nfunction buildSyncUrl(pathname: string): string {\n const baseUrl = getCloudSyncApiBaseUrl();\n const normalizedPath = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n return `${baseUrl}${normalizedPath}`;\n}\n\nfunction normalizeSnapshot(value: unknown): CloudSyncSnapshot | null {\n if (!isRecord(value)) {\n return null;\n }\n\n // Tolerate malformed legacy payloads where snapshot is nested one level:\n // { snapshot: { ...actualSnapshot } }\n if (isRecord(value.snapshot)) {\n const nested = normalizeSnapshot(value.snapshot);\n if (nested) {\n return nested;\n }\n }\n\n const updatedAt = toIsoOrNull(value.updatedAt);\n if (!updatedAt) {\n return null;\n }\n\n const schemaVersion = Number(value.schemaVersion);\n if (!Number.isFinite(schemaVersion) || schemaVersion !== CLOUD_SYNC_SCHEMA_VERSION) {\n return null;\n }\n\n const rawProfiles = Array.isArray(value.profiles) ? value.profiles : [];\n const profiles = rawProfiles\n .map((entry) => (isRecord(entry) ? entry : null))\n .filter((entry): entry is Record<string, unknown> => Boolean(entry))\n .map((entry) => {\n const data = isRecord(entry.data) ? entry.data : {};\n const metadata = isRecord(entry.metadata) ? entry.metadata : undefined;\n return {\n name: typeof entry.name === \"string\" ? entry.name : \"\",\n displayName: typeof entry.displayName === \"string\" ? entry.displayName : null,\n data,\n metadata,\n accountId: typeof entry.accountId === \"string\" ? entry.accountId : null,\n workspaceId: typeof entry.workspaceId === \"string\" ? entry.workspaceId : null,\n workspaceName: typeof entry.workspaceName === \"string\" ? entry.workspaceName : null,\n email: typeof entry.email === \"string\" ? entry.email : null,\n authMethod: typeof entry.authMethod === \"string\" ? entry.authMethod : null,\n createdAt: typeof entry.createdAt === \"string\" ? entry.createdAt : null,\n updatedAt: typeof entry.updatedAt === \"string\" ? entry.updatedAt : null,\n };\n })\n .filter((entry) => entry.name.trim().length > 0);\n\n const rawSettings = value.settingsJson;\n const settingsJson = isRecord(rawSettings) ? rawSettings : null;\n\n return {\n schemaVersion: CLOUD_SYNC_SCHEMA_VERSION,\n updatedAt,\n profiles,\n configTomlContent: typeof value.configTomlContent === \"string\" ? value.configTomlContent : null,\n settingsJson,\n };\n}\n\nasync function requestJson<T>(\n method: \"GET\" | \"PUT\",\n pathname: string,\n licenseKey: string,\n body?: unknown,\n rawBody?: string,\n): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), CLOUD_SYNC_TIMEOUT_MS);\n\n try {\n const response = await fetch(buildSyncUrl(pathname), {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-codexuse-license-key\": licenseKey,\n },\n body: typeof rawBody === \"string\"\n ? rawBody\n : body === undefined\n ? undefined\n : JSON.stringify(body),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const message = await response.text().catch(() => \"\");\n throw new CloudSyncClientError(\n message || `Cloud sync request failed (${response.status}).`,\n response.status,\n );\n }\n\n return (await response.json()) as T;\n } catch (error) {\n if (error instanceof CloudSyncClientError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new CloudSyncClientError(\"Cloud sync request timed out.\");\n }\n\n throw new CloudSyncClientError(\n error instanceof Error ? error.message : \"Cloud sync request failed.\",\n );\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport async function fetchRemoteSnapshot(licenseKey: string): Promise<CloudSyncSnapshot | null> {\n const response = await requestJson<CloudSyncGetResponse>(\"GET\", \"/v1/sync/snapshot\", licenseKey);\n return normalizeSnapshot(response.snapshot);\n}\n\nexport async function fetchRemoteSnapshotMeta(licenseKey: string): Promise<string | null> {\n const response = await requestJson<CloudSyncMetaResponse>(\n \"GET\",\n \"/v1/sync/snapshot/meta\",\n licenseKey,\n );\n return toIsoOrNull(response.updatedAt);\n}\n\nexport async function pushRemoteSnapshot(\n licenseKey: string,\n snapshot: CloudSyncSnapshot,\n options?: { serializedSnapshot?: string },\n): Promise<CloudSyncPutResponse> {\n const serializedSnapshot = typeof options?.serializedSnapshot === \"string\"\n ? options.serializedSnapshot\n : JSON.stringify(snapshot);\n const response = await requestJson<CloudSyncPutResponse>(\n \"PUT\",\n \"/v1/sync/snapshot\",\n licenseKey,\n undefined,\n `{\"snapshot\":${serializedSnapshot}}`,\n );\n\n const normalized = normalizeSnapshot(response.snapshot);\n if (!normalized) {\n throw new CloudSyncClientError(\"Cloud sync server returned an invalid snapshot payload.\");\n }\n\n const status = response.status === \"stale\" ? \"stale\" : \"applied\";\n return {\n status,\n snapshot: normalized,\n };\n}\n","import { parse, stringify } from \"@iarna/toml\";\nimport {\n getCodexConfigMetadata,\n} from \"@codexuse/runtime-codex/codex/config-metadata\";\nimport {\n ensureTrailingNewline,\n getConfigPath,\n getUpdatedAt,\n normalizeLineEndings,\n readConfigContent,\n writeConfigContent,\n} from \"@codexuse/runtime-codex/codex/config-io\";\nimport type { CodexHomePathOptions } from \"@codexuse/runtime-codex/codex/home\";\nimport {\n CLI_SUPPORTED_REASONING_EFFORT,\n SUPPORTED_REASONING_EFFORT,\n YOLO_PRESET,\n} from \"@codexuse/runtime-codex/codex/config-presets\";\nimport type {\n CodexConfigDiagnostic,\n CodexConfigMetadata,\n CodexConfigSettingsSummary,\n CodexConfigSnapshotPayload,\n CodexConfigUpdatePayload,\n CodexFeatureStage,\n McpServerConfig,\n} from \"@codexuse/contracts/codex/config-types\";\nimport { formatUserFacingError } from \"@codexuse/shared/core/errors\";\n\nexport type {\n CodexConfigDiagnostic,\n CodexConfigSettingsSummary,\n CodexConfigSnapshotPayload,\n CodexConfigUpdatePayload,\n CodexFeatureUpdateMap,\n McpServerConfig,\n} from \"@codexuse/contracts/codex/config-types\";\n\ntype RawConfig = Record<string, unknown>;\n\ntype ParsedResult = {\n data: RawConfig | null;\n error: string | null;\n};\n\nfunction tryParseToml(content: string): ParsedResult {\n try {\n const parsed = parse(content) as RawConfig;\n return { data: parsed ?? {}, error: null };\n } catch (error) {\n const maybe = error as Partial<{ line: number; column: number; col: number }>;\n const line = typeof maybe?.line === \"number\" ? maybe.line : null;\n const column = typeof maybe?.column === \"number\" ? maybe.column : typeof maybe?.col === \"number\" ? maybe.col : null;\n const location = line !== null ? `line ${line}${column !== null ? `, column ${column}` : \"\"}` : null;\n\n const friendly = formatUserFacingError(error, {\n fallback: \"Invalid config.toml syntax. Fix it and try again.\",\n maxLength: 180,\n });\n const message = location ? `${friendly} (near ${location}).` : friendly;\n return { data: null, error: message };\n }\n}\n\nfunction toStringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction toBooleanOrNull(value: unknown): boolean | null {\n if (typeof value === \"boolean\") {\n return value;\n }\n return null;\n}\n\nfunction toNumberOrNull(value: unknown): number | null {\n if (typeof value !== \"number\") {\n return null;\n }\n return Number.isFinite(value) ? value : null;\n}\n\nfunction toStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value\n .map(entry => (typeof entry === \"string\" ? entry.trim() : \"\"))\n .filter(entry => entry.length > 0);\n}\n\nfunction toStringRecord(value: unknown): Record<string, string> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n\n const result: Record<string, string> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (typeof raw !== \"string\") {\n continue;\n }\n const normalizedKey = key.trim();\n const normalizedValue = raw.trim();\n if (!normalizedKey || !normalizedValue) {\n continue;\n }\n result[normalizedKey] = normalizedValue;\n }\n return result;\n}\n\nfunction buildSettingsSummary(data: RawConfig | null): CodexConfigSettingsSummary {\n const noticeCandidate = data && typeof data[\"notice\"] === \"object\" && data[\"notice\"] !== null\n ? (data[\"notice\"] as RawConfig)\n : null;\n\n const featuresCandidate =\n data && typeof data[\"features\"] === \"object\" && data[\"features\"] !== null && !Array.isArray(data[\"features\"])\n ? (data[\"features\"] as RawConfig)\n : null;\n\n const toolsCandidate =\n data && typeof data[\"tools\"] === \"object\" && data[\"tools\"] !== null && !Array.isArray(data[\"tools\"])\n ? (data[\"tools\"] as RawConfig)\n : null;\n\n const featureValues: Record<string, boolean | null> = {};\n if (featuresCandidate) {\n for (const [key, value] of Object.entries(featuresCandidate)) {\n featureValues[key] = toBooleanOrNull(value);\n }\n }\n\n const modelMigrationsRaw = noticeCandidate ? toStringRecord(noticeCandidate[\"model_migrations\"]) : {};\n\n return {\n model: data ? toStringOrNull(data[\"model\"]) : null,\n reviewModel: data ? toStringOrNull(data[\"review_model\"]) : null,\n modelReasoningEffort: data ? toStringOrNull(data[\"model_reasoning_effort\"]) : null,\n modelReasoningSummary: data ? toStringOrNull(data[\"model_reasoning_summary\"]) : null,\n modelVerbosity: data ? toStringOrNull(data[\"model_verbosity\"]) : null,\n approvalPolicy: data ? toStringOrNull(data[\"approval_policy\"]) : null,\n sandboxMode: data ? toStringOrNull(data[\"sandbox_mode\"]) : null,\n webSearch: data ? toStringOrNull(data[\"web_search\"]) : null,\n personality: data ? toStringOrNull(data[\"personality\"]) : null,\n toolOutputTokenLimit: data ? toNumberOrNull(data[\"tool_output_token_limit\"]) : null,\n modelAutoCompactTokenLimit: data ? toNumberOrNull(data[\"model_auto_compact_token_limit\"]) : null,\n modelContextWindow: data ? toNumberOrNull(data[\"model_context_window\"]) : null,\n features: {\n unifiedExec: featuresCandidate ? toBooleanOrNull(featuresCandidate[\"unified_exec\"]) : null,\n shellSnapshot: featuresCandidate ? toBooleanOrNull(featuresCandidate[\"shell_snapshot\"]) : null,\n values: featureValues,\n },\n tools: {\n webSearch: toolsCandidate ? toBooleanOrNull(toolsCandidate[\"web_search\"]) : null,\n viewImage: toolsCandidate ? toBooleanOrNull(toolsCandidate[\"view_image\"]) : null,\n },\n notice: {\n hideFullAccessWarning: noticeCandidate ? toBooleanOrNull(noticeCandidate[\"hide_full_access_warning\"]) : null,\n hideGpt51MigrationPrompt: noticeCandidate ? toBooleanOrNull(noticeCandidate[\"hide_gpt5_1_migration_prompt\"]) : null,\n hideLegacyGpt51CodexMaxMigrationPrompt: noticeCandidate\n ? toBooleanOrNull(noticeCandidate[\"hide_gpt-5.1-codex-max_migration_prompt\"])\n : null,\n hideRateLimitModelNudge: noticeCandidate ? toBooleanOrNull(noticeCandidate[\"hide_rate_limit_model_nudge\"]) : null,\n modelMigrations: Object.keys(modelMigrationsRaw).length > 0 ? modelMigrationsRaw : null,\n },\n };\n}\n\nfunction getUnsupportedReasoningEffort(\n data: RawConfig | null,\n allowed: Set<string> = SUPPORTED_REASONING_EFFORT,\n): string | null {\n if (!data || !Object.prototype.hasOwnProperty.call(data, \"model_reasoning_effort\")) {\n return null;\n }\n\n const raw = data[\"model_reasoning_effort\"];\n if (typeof raw !== \"string\") {\n return String(raw ?? \"\");\n }\n\n const value = raw.trim();\n if (!value) {\n return null;\n }\n\n return allowed.has(value) ? null : value;\n}\n\nfunction parseRmcpClientEnabled(data: RawConfig | null): boolean {\n const rawFeatures =\n data && typeof data[\"features\"] === \"object\" && data[\"features\"] !== null && !Array.isArray(data[\"features\"])\n ? (data[\"features\"] as RawConfig)\n : null;\n\n if (rawFeatures && typeof rawFeatures[\"rmcp_client\"] === \"boolean\") {\n return rawFeatures[\"rmcp_client\"] as boolean;\n }\n\n if (data && typeof data[\"experimental_use_rmcp_client\"] === \"boolean\") {\n return data[\"experimental_use_rmcp_client\"] as boolean;\n }\n\n return false;\n}\n\nfunction parseMcpServer(name: string, rawValue: unknown): McpServerConfig | null {\n if (typeof rawValue !== \"object\" || rawValue === null || Array.isArray(rawValue)) {\n return null;\n }\n const raw = rawValue as RawConfig;\n const typeValue = toStringOrNull(raw[\"type\"]);\n const command = toStringOrNull(raw[\"command\"]);\n const args = toStringArray(raw[\"args\"]);\n const env = toStringRecord(raw[\"env\"]);\n const envVars = toStringArray(raw[\"env_vars\"]);\n const cwd = toStringOrNull(raw[\"cwd\"]);\n const url = toStringOrNull(raw[\"url\"]);\n const bearerTokenEnvVar = toStringOrNull(raw[\"bearer_token_env_var\"]);\n const httpHeaders = toStringRecord(raw[\"http_headers\"]);\n const envHttpHeaders = toStringRecord(raw[\"env_http_headers\"]);\n const startupTimeoutSec = toNumberOrNull(raw[\"startup_timeout_sec\"]);\n const toolTimeoutSec = toNumberOrNull(raw[\"tool_timeout_sec\"]);\n const enabledTools = toStringArray(raw[\"enabled_tools\"]);\n const disabledTools = toStringArray(raw[\"disabled_tools\"]);\n const enabled = typeof raw[\"enabled\"] === \"boolean\" ? raw[\"enabled\"] : true;\n const transport: \"stdio\" | \"http\" | \"sse\" =\n typeValue === \"stdio\" || typeValue === \"http\" || typeValue === \"sse\"\n ? typeValue\n : url\n ? \"http\"\n : \"stdio\";\n\n return {\n name,\n transport,\n enabled,\n command,\n args: args.length > 0 ? args : null,\n cwd,\n env: Object.keys(env).length > 0 ? env : null,\n envVars: envVars.length > 0 ? envVars : null,\n url,\n bearerTokenEnvVar,\n httpHeaders: Object.keys(httpHeaders).length > 0 ? httpHeaders : null,\n envHttpHeaders: Object.keys(envHttpHeaders).length > 0 ? envHttpHeaders : null,\n startupTimeoutSec,\n toolTimeoutSec,\n enabledTools: enabledTools.length > 0 ? enabledTools : null,\n disabledTools: disabledTools.length > 0 ? disabledTools : null,\n };\n}\n\nfunction buildMcpServersList(data: RawConfig | null): McpServerConfig[] {\n const rawServers = data?.[\"mcp_servers\"];\n if (typeof rawServers !== \"object\" || rawServers === null || Array.isArray(rawServers)) {\n return [];\n }\n\n const servers: McpServerConfig[] = [];\n for (const [name, rawValue] of Object.entries(rawServers)) {\n const parsed = parseMcpServer(name, rawValue);\n if (parsed) {\n servers.push(parsed);\n }\n }\n return servers;\n}\n\nfunction getFeatureStage(metadata: CodexConfigMetadata, featureKey: string): CodexFeatureStage {\n const found = metadata.featureCatalog.find(entry => entry.key === featureKey);\n return found?.stage ?? \"unknown\";\n}\n\nfunction looksLikeSecretValue(value: string): boolean {\n const normalized = value.trim();\n if (normalized.length < 12) {\n return false;\n }\n if (/\\s/.test(normalized)) {\n return false;\n }\n if (!/^[A-Za-z0-9._:-]+$/.test(normalized)) {\n return false;\n }\n const hasLetters = /[A-Za-z]/.test(normalized);\n const hasNumbers = /\\d/.test(normalized);\n return hasLetters && hasNumbers;\n}\n\nfunction buildConfigDiagnostics(\n data: RawConfig | null,\n summary: CodexConfigSettingsSummary,\n mcpServers: McpServerConfig[],\n metadata: CodexConfigMetadata,\n): CodexConfigDiagnostic[] {\n const diagnostics: CodexConfigDiagnostic[] = [];\n\n const featureTable =\n data && typeof data[\"features\"] === \"object\" && data[\"features\"] !== null && !Array.isArray(data[\"features\"])\n ? (data[\"features\"] as RawConfig)\n : null;\n\n const knownTopLevelKeys = new Set(metadata.schemaTopLevelKeys);\n if (data) {\n for (const key of Object.keys(data)) {\n if (knownTopLevelKeys.has(key)) {\n continue;\n }\n diagnostics.push({\n id: `unknown-top-level:${key}`,\n category: \"config\",\n severity: \"warning\",\n title: `Unknown config key: ${key}`,\n message: `This top-level key is not in the known Codex schema and may be ignored by Codex CLI.`,\n fixId: null,\n fixLabel: null,\n });\n }\n }\n\n if (featureTable) {\n const knownFeatureKeys = new Set(metadata.schemaFeatureKeys);\n for (const [featureKey] of Object.entries(featureTable)) {\n if (!knownFeatureKeys.has(featureKey)) {\n diagnostics.push({\n id: `unknown-feature:${featureKey}`,\n category: \"feature\",\n severity: \"warning\",\n title: `Unknown feature flag: features.${featureKey}`,\n message: \"This feature is not recognized in the current schema. Keeping it is non-destructive, but it may do nothing.\",\n fixId: `remove-feature:${featureKey}`,\n fixLabel: \"Remove flag\",\n });\n continue;\n }\n\n const stage = getFeatureStage(metadata, featureKey);\n if (stage === \"deprecated\") {\n diagnostics.push({\n id: `deprecated-feature:${featureKey}`,\n category: \"feature\",\n severity: \"warning\",\n title: `Deprecated feature flag: features.${featureKey}`,\n message: \"Codex marks this feature as deprecated. Prefer removing it.\",\n fixId: `remove-feature:${featureKey}`,\n fixLabel: \"Remove deprecated flag\",\n });\n }\n }\n }\n\n for (const server of mcpServers) {\n if (server.transport === \"stdio\" && server.args) {\n for (let index = 0; index < server.args.length; index += 1) {\n const value = server.args[index] ?? \"\";\n if (/(api[-_]?key|token|secret)\\s*=\\s*/i.test(value)) {\n diagnostics.push({\n id: `mcp-secret-arg:${server.name}:${index}`,\n category: \"security\",\n severity: \"warning\",\n title: `Potential secret in MCP args (${server.name})`,\n message: \"Argument text appears to contain a literal token/API key. Move secrets to environment variables.\",\n fixId: null,\n fixLabel: null,\n });\n }\n }\n }\n\n if (server.httpHeaders) {\n for (const [header, headerValue] of Object.entries(server.httpHeaders)) {\n if (!looksLikeSecretValue(headerValue)) {\n continue;\n }\n diagnostics.push({\n id: `mcp-secret-header:${server.name}:${header}`,\n category: \"security\",\n severity: \"warning\",\n title: `Potential secret in MCP header (${server.name})`,\n message: `HTTP header '${header}' appears to contain a literal secret. Prefer env_http_headers or bearer_token_env_var.`,\n fixId: null,\n fixLabel: null,\n });\n }\n }\n }\n\n if (summary.approvalPolicy === \"never\" && summary.sandboxMode === \"danger-full-access\") {\n diagnostics.push({\n id: \"risk:yolo-combo\",\n category: \"risk\",\n severity: \"risk\",\n title: \"High-risk execution mode enabled\",\n message: \"approval_policy=never + sandbox_mode=danger-full-access removes approval and sandbox guardrails.\",\n fixId: null,\n fixLabel: null,\n });\n }\n\n return diagnostics;\n}\n\nfunction isYoloApplied(summary: CodexConfigSettingsSummary): boolean {\n return (\n summary.model === YOLO_PRESET.model &&\n summary.reviewModel === YOLO_PRESET.reviewModel &&\n summary.modelReasoningEffort === YOLO_PRESET.modelReasoningEffort &&\n summary.modelReasoningSummary === YOLO_PRESET.modelReasoningSummary &&\n summary.modelVerbosity === YOLO_PRESET.modelVerbosity &&\n summary.approvalPolicy === YOLO_PRESET.approvalPolicy &&\n summary.sandboxMode === YOLO_PRESET.sandboxMode &&\n summary.webSearch === YOLO_PRESET.webSearch &&\n summary.personality === YOLO_PRESET.personality &&\n summary.toolOutputTokenLimit === YOLO_PRESET.toolOutputTokenLimit &&\n summary.modelAutoCompactTokenLimit === YOLO_PRESET.modelAutoCompactTokenLimit &&\n summary.features.unifiedExec === true &&\n summary.features.shellSnapshot === true &&\n summary.notice.hideFullAccessWarning === true &&\n summary.notice.hideGpt51MigrationPrompt === true &&\n summary.notice.hideRateLimitModelNudge === true\n );\n}\n\nasync function buildSnapshot(\n content: string,\n exists: boolean,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const configPath = getConfigPath(options);\n const parsed = tryParseToml(content);\n const summary = buildSettingsSummary(parsed.data);\n const updatedAt = await getUpdatedAt(configPath, exists);\n const mcpServers = buildMcpServersList(parsed.data);\n const rmcpClientEnabled = parseRmcpClientEnabled(parsed.data);\n const metadata = await getCodexConfigMetadata();\n const diagnostics = parsed.error\n ? []\n : buildConfigDiagnostics(parsed.data, summary, mcpServers, metadata);\n\n return {\n path: configPath,\n exists,\n content,\n settings: summary,\n mcpServers,\n rmcpClientEnabled,\n parseError: parsed.error,\n isYoloPreset: parsed.error ? false : isYoloApplied(summary),\n updatedAt,\n metadata,\n diagnostics,\n };\n}\n\nfunction sanitizeString(value: string | null | undefined): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction sanitizeNumber(value: number | null | undefined): number | null {\n if (value === undefined || value === null) {\n return null;\n }\n if (!Number.isFinite(value)) {\n throw new Error(\"Numeric value must be finite.\");\n }\n return value;\n}\n\nfunction normalizeStringArrayInput(values?: string[] | null): string[] | null {\n if (!values) {\n return null;\n }\n const normalized = values\n .map(value => sanitizeString(value))\n .filter((value): value is string => Boolean(value));\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeStringRecordInput(record?: Record<string, string> | null): Record<string, string> | null {\n if (!record) {\n return null;\n }\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(record)) {\n const normalizedKey = sanitizeString(key);\n const normalizedValue = sanitizeString(value);\n if (normalizedKey && normalizedValue) {\n normalized[normalizedKey] = normalizedValue;\n }\n }\n return Object.keys(normalized).length > 0 ? normalized : null;\n}\n\nfunction applySuggestedFixes(current: RawConfig, fixIds?: string[] | null): RawConfig {\n if (!fixIds || fixIds.length === 0) {\n return current;\n }\n\n let next: RawConfig = { ...current };\n\n for (const fixId of fixIds) {\n if (!fixId.startsWith(\"remove-feature:\")) {\n continue;\n }\n\n const featureKey = fixId.slice(\"remove-feature:\".length).trim();\n if (!featureKey) {\n continue;\n }\n\n const rawFeatures =\n typeof next[\"features\"] === \"object\" && next[\"features\"] !== null && !Array.isArray(next[\"features\"])\n ? { ...(next[\"features\"] as RawConfig) }\n : {};\n\n if (!Object.prototype.hasOwnProperty.call(rawFeatures, featureKey)) {\n continue;\n }\n\n delete rawFeatures[featureKey];\n if (Object.keys(rawFeatures).length === 0) {\n delete next[\"features\"];\n } else {\n next[\"features\"] = rawFeatures;\n }\n }\n\n return next;\n}\n\nfunction applyUpdatesToConfig(current: RawConfig, updates: CodexConfigUpdatePayload): RawConfig {\n const next: RawConfig = { ...current };\n\n const applyStringField = (key: string, candidate?: string | null) => {\n if (candidate === undefined) {\n return;\n }\n const normalized = sanitizeString(candidate);\n if (!normalized) {\n delete next[key];\n } else {\n next[key] = normalized;\n }\n };\n\n const applyNumberField = (key: string, candidate?: number | null) => {\n if (candidate === undefined) {\n return;\n }\n const normalized = sanitizeNumber(candidate);\n if (normalized === null) {\n delete next[key];\n } else {\n next[key] = normalized;\n }\n };\n\n applyStringField(\"model\", updates.model);\n applyStringField(\"review_model\", updates.reviewModel);\n applyStringField(\"model_reasoning_effort\", updates.modelReasoningEffort);\n applyStringField(\"model_reasoning_summary\", updates.modelReasoningSummary);\n applyStringField(\"model_verbosity\", updates.modelVerbosity);\n applyStringField(\"approval_policy\", updates.approvalPolicy);\n applyStringField(\"sandbox_mode\", updates.sandboxMode);\n applyStringField(\"web_search\", updates.webSearch);\n applyStringField(\"personality\", updates.personality);\n\n applyNumberField(\"tool_output_token_limit\", updates.toolOutputTokenLimit);\n applyNumberField(\"model_auto_compact_token_limit\", updates.modelAutoCompactTokenLimit);\n applyNumberField(\"model_context_window\", updates.modelContextWindow);\n\n if (updates.features) {\n const rawFeatures =\n typeof next[\"features\"] === \"object\" && next[\"features\"] !== null && !Array.isArray(next[\"features\"])\n ? { ...(next[\"features\"] as RawConfig) }\n : {};\n\n const applyFeatureField = (key: string, candidate: boolean | null | undefined) => {\n if (candidate === undefined) {\n return;\n }\n if (candidate === null) {\n delete rawFeatures[key];\n return;\n }\n rawFeatures[key] = candidate;\n };\n\n for (const [rawKey, candidate] of Object.entries(updates.features)) {\n const key = rawKey === \"unifiedExec\"\n ? \"unified_exec\"\n : rawKey === \"shellSnapshot\"\n ? \"shell_snapshot\"\n : rawKey;\n applyFeatureField(key, candidate);\n }\n\n if (Object.keys(rawFeatures).length === 0) {\n delete next[\"features\"];\n } else {\n next[\"features\"] = rawFeatures;\n }\n }\n\n if (updates.tools) {\n const rawTools =\n typeof next[\"tools\"] === \"object\" && next[\"tools\"] !== null && !Array.isArray(next[\"tools\"])\n ? { ...(next[\"tools\"] as RawConfig) }\n : {};\n\n const applyToolField = (key: string, candidate?: boolean | null) => {\n if (candidate === undefined) {\n return;\n }\n if (candidate === null) {\n delete rawTools[key];\n } else {\n rawTools[key] = candidate;\n }\n };\n\n applyToolField(\"web_search\", updates.tools.webSearch);\n applyToolField(\"view_image\", updates.tools.viewImage);\n\n if (Object.keys(rawTools).length === 0) {\n delete next[\"tools\"];\n } else {\n next[\"tools\"] = rawTools;\n }\n }\n\n if (updates.notice) {\n const rawNotice = next[\"notice\"];\n const currentNotice =\n rawNotice && typeof rawNotice === \"object\" && rawNotice !== null\n ? { ...(rawNotice as RawConfig) }\n : {};\n\n const applyBooleanField = (key: string, candidate?: boolean | null) => {\n if (candidate === undefined) {\n return;\n }\n if (candidate === null) {\n delete currentNotice[key];\n } else {\n currentNotice[key] = candidate;\n }\n };\n\n const applyRecordField = (key: string, candidate?: Record<string, string> | null) => {\n if (candidate === undefined) {\n return;\n }\n const normalized = normalizeStringRecordInput(candidate);\n if (!normalized) {\n delete currentNotice[key];\n } else {\n currentNotice[key] = normalized;\n }\n };\n\n applyBooleanField(\"hide_full_access_warning\", updates.notice.hideFullAccessWarning);\n applyBooleanField(\"hide_gpt5_1_migration_prompt\", updates.notice.hideGpt51MigrationPrompt);\n applyBooleanField(\n \"hide_gpt-5.1-codex-max_migration_prompt\",\n updates.notice.hideLegacyGpt51CodexMaxMigrationPrompt,\n );\n applyBooleanField(\"hide_rate_limit_model_nudge\", updates.notice.hideRateLimitModelNudge);\n applyRecordField(\"model_migrations\", updates.notice.modelMigrations);\n\n if (Object.keys(currentNotice).length === 0) {\n delete next[\"notice\"];\n } else {\n next[\"notice\"] = currentNotice;\n }\n }\n\n return applySuggestedFixes(next, updates.applyFixes);\n}\n\nfunction validateMcpServerName(name: string): string {\n const normalized = sanitizeString(name);\n if (!normalized) {\n throw new Error(\"MCP server name is required.\");\n }\n if (!/^[A-Za-z0-9._-]+$/.test(normalized)) {\n throw new Error(\"MCP server name must use letters, numbers, periods, underscores, or hyphens.\");\n }\n return normalized;\n}\n\nfunction applyMcpServerUpsert(\n current: RawConfig,\n server: McpServerConfig,\n rmcpClientEnabled?: boolean | null,\n): RawConfig {\n const name = validateMcpServerName(server.name ?? \"\");\n const next: RawConfig = { ...current };\n const rawServers =\n typeof next[\"mcp_servers\"] === \"object\" && next[\"mcp_servers\"] !== null && !Array.isArray(next[\"mcp_servers\"])\n ? { ...(next[\"mcp_servers\"] as RawConfig) }\n : {};\n\n const base =\n typeof rawServers[name] === \"object\" && rawServers[name] !== null && !Array.isArray(rawServers[name])\n ? { ...(rawServers[name] as RawConfig) }\n : {};\n\n const updated: RawConfig = { ...base };\n\n const setStringField = (key: string, value: string | null | undefined) => {\n const normalized = sanitizeString(value ?? null);\n if (!normalized) {\n delete updated[key];\n return;\n }\n updated[key] = normalized;\n };\n\n const setStringArrayField = (key: string, values: string[] | null | undefined) => {\n const normalized = normalizeStringArrayInput(values);\n if (!normalized) {\n delete updated[key];\n return;\n }\n updated[key] = normalized;\n };\n\n const setRecordField = (key: string, values: Record<string, string> | null | undefined) => {\n const normalized = normalizeStringRecordInput(values);\n if (!normalized) {\n delete updated[key];\n return;\n }\n updated[key] = normalized;\n };\n\n const setNumberField = (key: string, value: number | null | undefined) => {\n if (value === null || value === undefined) {\n delete updated[key];\n return;\n }\n if (!Number.isFinite(value)) {\n throw new Error(`Invalid numeric value for ${key}.`);\n }\n updated[key] = value;\n };\n\n updated[\"enabled\"] = Boolean(server.enabled);\n updated[\"type\"] = server.transport;\n setNumberField(\"startup_timeout_sec\", server.startupTimeoutSec);\n setNumberField(\"tool_timeout_sec\", server.toolTimeoutSec);\n setStringArrayField(\"enabled_tools\", server.enabledTools);\n setStringArrayField(\"disabled_tools\", server.disabledTools);\n\n if (server.transport !== \"stdio\") {\n setStringField(\"url\", server.url);\n if (!sanitizeString(server.url)) {\n throw new Error(\"HTTP/SSE MCP server requires a URL.\");\n }\n setStringField(\"bearer_token_env_var\", server.bearerTokenEnvVar);\n setRecordField(\"http_headers\", server.httpHeaders);\n setRecordField(\"env_http_headers\", server.envHttpHeaders);\n delete updated[\"command\"];\n delete updated[\"args\"];\n delete updated[\"env\"];\n delete updated[\"env_vars\"];\n delete updated[\"cwd\"];\n } else {\n setStringField(\"command\", server.command);\n if (!sanitizeString(server.command)) {\n throw new Error(\"STDIO MCP server requires a command.\");\n }\n setStringArrayField(\"args\", server.args);\n setRecordField(\"env\", server.env);\n setStringArrayField(\"env_vars\", server.envVars);\n setStringField(\"cwd\", server.cwd);\n delete updated[\"url\"];\n delete updated[\"bearer_token_env_var\"];\n delete updated[\"http_headers\"];\n delete updated[\"env_http_headers\"];\n }\n\n rawServers[name] = updated;\n if (Object.keys(rawServers).length > 0) {\n next[\"mcp_servers\"] = rawServers;\n } else {\n delete next[\"mcp_servers\"];\n }\n\n const rmcpEnabledValue = rmcpClientEnabled ?? parseRmcpClientEnabled(next);\n return applyRmcpClientFlag(next, rmcpEnabledValue);\n}\n\nfunction applyMcpServerRemoval(current: RawConfig, serverName: string): RawConfig {\n const name = validateMcpServerName(serverName);\n const next: RawConfig = { ...current };\n const rawServers =\n typeof next[\"mcp_servers\"] === \"object\" && next[\"mcp_servers\"] !== null && !Array.isArray(next[\"mcp_servers\"])\n ? { ...(next[\"mcp_servers\"] as RawConfig) }\n : {};\n\n if (!Object.prototype.hasOwnProperty.call(rawServers, name)) {\n return next;\n }\n\n delete rawServers[name];\n if (Object.keys(rawServers).length > 0) {\n next[\"mcp_servers\"] = rawServers;\n } else {\n delete next[\"mcp_servers\"];\n }\n return next;\n}\n\nfunction applyRmcpClientFlag(current: RawConfig, enabled: boolean): RawConfig {\n const next: RawConfig = { ...current };\n const rawFeatures =\n typeof next[\"features\"] === \"object\" && next[\"features\"] !== null && !Array.isArray(next[\"features\"])\n ? { ...(next[\"features\"] as RawConfig) }\n : {};\n\n if (enabled) {\n rawFeatures[\"rmcp_client\"] = true;\n } else {\n delete rawFeatures[\"rmcp_client\"];\n }\n\n if (Object.keys(rawFeatures).length > 0) {\n next[\"features\"] = rawFeatures;\n } else {\n delete next[\"features\"];\n }\n\n delete next[\"experimental_use_rmcp_client\"];\n return next;\n}\n\nasync function readParsedConfigOrThrow(options?: CodexHomePathOptions): Promise<RawConfig> {\n const { content } = await readConfigContent(options);\n const parsed = tryParseToml(content);\n\n if (!parsed.data) {\n throw new Error(parsed.error ?? \"config.toml contains invalid TOML syntax.\");\n }\n\n return parsed.data;\n}\n\nexport async function getCodexConfigSnapshot(\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const { content, exists } = await readConfigContent(options);\n return buildSnapshot(content, exists, options);\n}\n\nexport async function saveCodexConfigContent(\n content: string,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const normalized = ensureTrailingNewline(normalizeLineEndings(content));\n const parsed = tryParseToml(normalized);\n if (!parsed.data) {\n throw new Error(parsed.error ?? \"config.toml contains invalid TOML syntax.\");\n }\n await writeConfigContent(normalized, options);\n return buildSnapshot(normalized, true, options);\n}\n\nexport async function updateCodexConfigValues(\n updates: CodexConfigUpdatePayload,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(options);\n const updated = applyUpdatesToConfig(parsed, updates);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, options);\n return buildSnapshot(serialized, true, options);\n}\n\nexport async function applyYoloOpinionatedMode(\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n return updateCodexConfigValues(YOLO_PRESET, options);\n}\n\nexport async function upsertMcpServer(\n server: McpServerConfig,\n options?: { rmcpClientEnabled?: boolean | null },\n storageOptions?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(storageOptions);\n const updated = applyMcpServerUpsert(parsed, server, options?.rmcpClientEnabled);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, storageOptions);\n return buildSnapshot(serialized, true, storageOptions);\n}\n\nexport async function removeMcpServer(\n serverName: string,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(options);\n const updated = applyMcpServerRemoval(parsed, serverName);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, options);\n return buildSnapshot(serialized, true, options);\n}\n\nexport async function setRmcpClient(\n enabled: boolean,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(options);\n const updated = applyRmcpClientFlag(parsed, enabled);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, options);\n return buildSnapshot(serialized, true, options);\n}\n\nexport async function sanitizeCodexConfigForCli(\n options?: CodexHomePathOptions,\n): Promise<(() => Promise<void>) | null> {\n const { content } = await readConfigContent(options);\n const parsed = tryParseToml(content);\n\n if (!parsed.data) {\n throw new Error(parsed.error ?? \"config.toml contains invalid TOML syntax.\");\n }\n\n const unsupportedReasoning = getUnsupportedReasoningEffort(parsed.data, CLI_SUPPORTED_REASONING_EFFORT);\n if (!unsupportedReasoning) {\n return null;\n }\n\n const sanitized = { ...(parsed.data as RawConfig) };\n delete sanitized[\"model_reasoning_effort\"];\n const sanitizedContent = ensureTrailingNewline(stringify(sanitized as Record<string, any>));\n await writeConfigContent(sanitizedContent, options);\n\n let restored = false;\n return async () => {\n if (restored) {\n return;\n }\n restored = true;\n const originalContent = ensureTrailingNewline(normalizeLineEndings(content));\n await writeConfigContent(originalContent, options);\n };\n}\n","import { spawn } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { requireCodexCli } from \"@codexuse/runtime-codex/codex/cli\";\nimport type {\n CodexConfigMetadata,\n CodexFeatureCatalogEntry,\n CodexFeatureStage,\n} from \"@codexuse/contracts/codex/config-types\";\n\nexport type {\n CodexConfigMetadata,\n CodexFeatureCatalogEntry,\n CodexFeatureStage,\n} from \"@codexuse/contracts/codex/config-types\";\n\nconst CONFIG_SCHEMA_URL = \"https://raw.githubusercontent.com/openai/codex/main/codex-rs/core/config.schema.json\";\nconst METADATA_CACHE_TTL_MS = 60_000;\n\nconst FALLBACK_SCHEMA_TOP_LEVEL_KEYS = [\n \"agents\",\n \"analytics\",\n \"approval_policy\",\n \"apps\",\n \"chatgpt_base_url\",\n \"check_for_update_on_startup\",\n \"cli_auth_credentials_store\",\n \"compact_prompt\",\n \"developer_instructions\",\n \"disable_paste_burst\",\n \"experimental_compact_prompt_file\",\n \"experimental_use_freeform_apply_patch\",\n \"experimental_use_unified_exec_tool\",\n \"features\",\n \"feedback\",\n \"file_opener\",\n \"forced_chatgpt_workspace_id\",\n \"forced_login_method\",\n \"ghost_snapshot\",\n \"hide_agent_reasoning\",\n \"history\",\n \"instructions\",\n \"log_dir\",\n \"mcp_oauth_callback_port\",\n \"mcp_oauth_credentials_store\",\n \"mcp_servers\",\n \"model\",\n \"model_auto_compact_token_limit\",\n \"model_context_window\",\n \"model_instructions_file\",\n \"model_provider\",\n \"model_providers\",\n \"model_reasoning_effort\",\n \"model_reasoning_summary\",\n \"model_supports_reasoning_summaries\",\n \"model_verbosity\",\n \"notice\",\n \"notify\",\n \"oss_provider\",\n \"otel\",\n \"personality\",\n \"profile\",\n \"profiles\",\n \"project_doc_fallback_filenames\",\n \"project_doc_max_bytes\",\n \"project_root_markers\",\n \"projects\",\n \"review_model\",\n \"sandbox_mode\",\n \"sandbox_workspace_write\",\n \"shell_environment_policy\",\n \"show_raw_agent_reasoning\",\n \"skills\",\n \"suppress_unstable_features_warning\",\n \"tool_output_token_limit\",\n \"tools\",\n \"tui\",\n \"web_search\",\n \"windows_wsl_setup_acknowledged\",\n];\n\nconst FALLBACK_FEATURE_KEYS = [\n \"apply_patch_freeform\",\n \"apps\",\n \"child_agents_md\",\n \"collab\",\n \"collaboration_modes\",\n \"connectors\",\n \"elevated_windows_sandbox\",\n \"enable_experimental_windows_sandbox\",\n \"enable_request_compression\",\n \"experimental_use_freeform_apply_patch\",\n \"experimental_use_unified_exec_tool\",\n \"experimental_windows_sandbox\",\n \"include_apply_patch_tool\",\n \"memory_tool\",\n \"personality\",\n \"powershell_utf8\",\n \"remote_models\",\n \"request_rule\",\n \"responses_websockets\",\n \"responses_websockets_v2\",\n \"runtime_metrics\",\n \"search_tool\",\n \"shell_snapshot\",\n \"shell_tool\",\n \"skill_env_var_dependency_prompt\",\n \"skill_mcp_dependency_install\",\n \"sqlite\",\n \"steer\",\n \"undo\",\n \"unified_exec\",\n \"use_linux_sandbox_bwrap\",\n \"web_search\",\n \"web_search_cached\",\n \"web_search_request\",\n];\n\nlet metadataCache: CodexConfigMetadata | null = null;\nlet metadataCacheAt = 0;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));\n}\n\nasync function runCommand(\n command: string,\n args: string[],\n timeoutMs = 3_000,\n): Promise<{ stdout: string; exitCode: number | null }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: process.env,\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout?.on(\"data\", chunk => {\n stdout += chunk.toString();\n });\n\n child.stderr?.on(\"data\", chunk => {\n stderr += chunk.toString();\n });\n\n const timeout = setTimeout(() => {\n child.kill();\n reject(new Error(`Command timed out: ${command} ${args.join(\" \")}`));\n }, timeoutMs);\n\n child.on(\"error\", error => {\n clearTimeout(timeout);\n reject(error);\n });\n\n child.on(\"close\", code => {\n clearTimeout(timeout);\n if (code !== 0 && !stdout.trim() && stderr.trim()) {\n resolve({ stdout: stderr, exitCode: code });\n return;\n }\n resolve({ stdout, exitCode: code });\n });\n });\n}\n\nasync function runCodexCommand(args: string[]): Promise<{ stdout: string; exitCode: number | null }> {\n const codexPath = await requireCodexCli();\n const isJsLauncher = codexPath.endsWith(\".js\");\n const command = isJsLauncher ? process.execPath : codexPath;\n const commandArgs = isJsLauncher ? [codexPath, ...args] : args;\n return runCommand(command, commandArgs);\n}\n\nfunction parseFeatureCatalog(output: string): CodexFeatureCatalogEntry[] {\n const entries: CodexFeatureCatalogEntry[] = [];\n const lines = output.split(/\\r?\\n/).map(line => line.trim()).filter(Boolean);\n\n for (const line of lines) {\n const match = line.match(/^(\\S+)\\s+(stable|experimental|deprecated|under development)\\s+(true|false)$/i);\n if (!match) {\n continue;\n }\n const [, key, stageRaw, enabledRaw] = match;\n const stage = stageRaw.toLowerCase() as Exclude<CodexFeatureStage, \"unknown\">;\n entries.push({\n key,\n stage,\n enabled: enabledRaw === \"true\",\n });\n }\n\n return entries.sort((a, b) => a.key.localeCompare(b.key));\n}\n\nfunction parseSchemaKeys(schemaRaw: string): { topLevelKeys: string[]; featureKeys: string[] } {\n const parsed = JSON.parse(schemaRaw) as unknown;\n if (!isRecord(parsed)) {\n return {\n topLevelKeys: FALLBACK_SCHEMA_TOP_LEVEL_KEYS,\n featureKeys: FALLBACK_FEATURE_KEYS,\n };\n }\n\n const properties = isRecord(parsed.properties) ? parsed.properties : {};\n const topLevelKeys = uniqueSorted(Object.keys(properties));\n\n const features = isRecord(properties.features) ? properties.features : {};\n const featureProperties = isRecord(features.properties) ? features.properties : {};\n const featureKeys = uniqueSorted(Object.keys(featureProperties));\n\n return {\n topLevelKeys: topLevelKeys.length > 0 ? topLevelKeys : FALLBACK_SCHEMA_TOP_LEVEL_KEYS,\n featureKeys: featureKeys.length > 0 ? featureKeys : FALLBACK_FEATURE_KEYS,\n };\n}\n\nasync function readSchemaFromLocal(): Promise<string | null> {\n const candidates = [\n process.env.CODEX_CONFIG_SCHEMA_PATH,\n path.join(process.cwd(), \"codex-rs\", \"core\", \"config.schema.json\"),\n path.join(process.cwd(), \"node_modules\", \"@openai\", \"codex\", \"codex-rs\", \"core\", \"config.schema.json\"),\n ].filter((candidate): candidate is string => Boolean(candidate));\n\n for (const candidate of candidates) {\n try {\n return await readFile(candidate, \"utf8\");\n } catch {\n // Continue to next candidate.\n }\n }\n\n return null;\n}\n\nasync function readSchemaFromRemote(): Promise<string | null> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 2_500);\n\n try {\n const response = await fetch(CONFIG_SCHEMA_URL, {\n signal: controller.signal,\n headers: {\n \"User-Agent\": \"codexuse-desktop\",\n },\n });\n\n if (!response.ok) {\n return null;\n }\n\n return await response.text();\n } catch {\n return null;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function readSchemaKeys(): Promise<{ topLevelKeys: string[]; featureKeys: string[] }> {\n const local = await readSchemaFromLocal();\n if (local) {\n try {\n return parseSchemaKeys(local);\n } catch {\n // Fallback to remote/fallback sets.\n }\n }\n\n const remote = await readSchemaFromRemote();\n if (remote) {\n try {\n return parseSchemaKeys(remote);\n } catch {\n // Fallback below.\n }\n }\n\n return {\n topLevelKeys: FALLBACK_SCHEMA_TOP_LEVEL_KEYS,\n featureKeys: FALLBACK_FEATURE_KEYS,\n };\n}\n\nasync function readCodexVersion(): Promise<string | null> {\n try {\n const { stdout } = await runCodexCommand([\"--version\"]);\n const value = stdout.trim();\n return value.length > 0 ? value : null;\n } catch {\n return null;\n }\n}\n\nasync function readFeatureCatalog(): Promise<CodexFeatureCatalogEntry[]> {\n try {\n const { stdout } = await runCodexCommand([\"features\", \"list\"]);\n return parseFeatureCatalog(stdout);\n } catch {\n return [];\n }\n}\n\nexport async function getCodexConfigMetadata(forceRefresh = false): Promise<CodexConfigMetadata> {\n const now = Date.now();\n if (!forceRefresh && metadataCache && (now - metadataCacheAt) < METADATA_CACHE_TTL_MS) {\n return metadataCache;\n }\n\n const [schemaKeys, featureCatalog, codexVersion] = await Promise.all([\n readSchemaKeys(),\n readFeatureCatalog(),\n readCodexVersion(),\n ]);\n\n const catalogMap = new Map<string, CodexFeatureCatalogEntry>();\n for (const entry of featureCatalog) {\n catalogMap.set(entry.key, entry);\n }\n\n for (const featureKey of schemaKeys.featureKeys) {\n if (!catalogMap.has(featureKey)) {\n catalogMap.set(featureKey, {\n key: featureKey,\n stage: \"unknown\",\n enabled: null,\n });\n }\n }\n\n const mergedFeatureCatalog = Array.from(catalogMap.values()).sort((a, b) => a.key.localeCompare(b.key));\n\n const metadata: CodexConfigMetadata = {\n schemaTopLevelKeys: uniqueSorted(schemaKeys.topLevelKeys),\n schemaFeatureKeys: uniqueSorted(schemaKeys.featureKeys),\n featureCatalog: mergedFeatureCatalog,\n codexVersion,\n fetchedAt: now,\n };\n\n metadataCache = metadata;\n metadataCacheAt = now;\n return metadata;\n}\n","import { mkdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { resolveCodexHomeDir, type CodexHomePathOptions } from \"@codexuse/runtime-codex/codex/home\";\nimport { DEFAULT_CONFIG_TEMPLATE } from \"@codexuse/runtime-codex/codex/config-presets\";\n\nexport function getConfigPath(options?: CodexHomePathOptions): string {\n return path.join(resolveCodexHomeDir(options), \"config.toml\");\n}\n\nasync function ensureConfigDirExists(filePath: string): Promise<void> {\n const dir = path.dirname(filePath);\n await mkdir(dir, { recursive: true });\n}\n\nexport function normalizeLineEndings(content: string): string {\n return content.replace(/\\r\\n/g, \"\\n\");\n}\n\nexport function ensureTrailingNewline(content: string): string {\n return content.endsWith(\"\\n\") ? content : `${content}\\n`;\n}\n\nexport async function readConfigContent(\n options?: CodexHomePathOptions,\n): Promise<{ exists: boolean; content: string }> {\n const configPath = getConfigPath(options);\n try {\n const content = await readFile(configPath, \"utf8\");\n return {\n exists: true,\n content: normalizeLineEndings(content),\n };\n } catch (error) {\n const nodeError = error as NodeJS.ErrnoException;\n if (nodeError.code === \"ENOENT\") {\n return {\n exists: false,\n content: DEFAULT_CONFIG_TEMPLATE,\n };\n }\n throw error;\n }\n}\n\nexport async function writeConfigContent(\n content: string,\n options?: CodexHomePathOptions,\n): Promise<void> {\n const configPath = getConfigPath(options);\n await ensureConfigDirExists(configPath);\n const normalized = ensureTrailingNewline(normalizeLineEndings(content));\n await writeFile(configPath, normalized, \"utf8\");\n}\n\nexport async function getUpdatedAt(\n configPath: string,\n exists: boolean,\n): Promise<number | null> {\n if (!exists) {\n return null;\n }\n\n try {\n const stats = await stat(configPath);\n return stats.mtimeMs;\n } catch (error) {\n const nodeError = error as NodeJS.ErrnoException;\n if (nodeError.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\nimport { getAppState, getUserDataDir } from \"@codexuse/runtime-app-state/app/state\";\n\nexport type CodexHomePathOptions = {\n codexHomePath?: string | null;\n};\n\nexport type CodexRuntimeContextSource = \"explicit\" | \"profile\" | \"settings\" | \"default\";\n\nexport type CodexRuntimeContext = {\n codexHomePath: string;\n profileName: string | null;\n source: CodexRuntimeContextSource;\n};\n\nexport function resolveHomeDir(): string {\n return process.env.HOME || process.env.USERPROFILE || os.homedir();\n}\n\nfunction expandHomePrefix(input: string, homeDir: string): string {\n if (input === \"~\") {\n return homeDir;\n }\n if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n return path.join(homeDir, input.slice(2));\n }\n return input;\n}\n\nfunction normalizePathCandidate(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nexport function normalizeCodexHomePath(input?: string | null): string | null {\n const configured = normalizePathCandidate(input);\n if (!configured) {\n return null;\n }\n return path.resolve(expandHomePrefix(configured, resolveHomeDir()));\n}\n\nexport function resolveDefaultCodexHomeDir(): string {\n return path.join(resolveHomeDir(), \".codex\");\n}\n\nexport function resolveProfileCodexHomeDir(profileName: string): string {\n return path.join(getUserDataDir(), \"profile-homes\", profileName);\n}\n\nexport function resolveCodexAuthPath(options?: CodexHomePathOptions): string {\n return path.join(resolveCodexHomeDir(options), \"auth.json\");\n}\n\nexport function resolveCodexHomeDir(options?: CodexHomePathOptions): string {\n return normalizeCodexHomePath(options?.codexHomePath) ?? resolveDefaultCodexHomeDir();\n}\n\nexport async function resolveCodexRuntimeContext(\n options?: CodexHomePathOptions,\n): Promise<CodexRuntimeContext> {\n const explicit = normalizeCodexHomePath(options?.codexHomePath);\n if (explicit) {\n return {\n codexHomePath: explicit,\n profileName: null,\n source: \"explicit\",\n };\n }\n\n const state = await getAppState();\n const configured = normalizeCodexHomePath(\n (state.runtimeSettings as Record<string, unknown>)?.codexHome as string | null | undefined,\n );\n if (configured) {\n return {\n codexHomePath: configured,\n profileName: null,\n source: \"settings\",\n };\n }\n\n return {\n codexHomePath: resolveDefaultCodexHomeDir(),\n profileName: null,\n source: \"default\",\n };\n}\n\nexport async function resolveExternalCodexRuntimeContext(\n options?: CodexHomePathOptions,\n): Promise<CodexRuntimeContext> {\n const explicit = normalizeCodexHomePath(options?.codexHomePath);\n if (explicit) {\n return {\n codexHomePath: explicit,\n profileName: null,\n source: \"explicit\",\n };\n }\n\n const state = await getAppState();\n const configured = normalizeCodexHomePath(\n (state.runtimeSettings as Record<string, unknown>)?.codexHome as string | null | undefined,\n );\n if (configured) {\n return {\n codexHomePath: configured,\n profileName: null,\n source: \"settings\",\n };\n }\n\n return {\n codexHomePath: resolveDefaultCodexHomeDir(),\n profileName: null,\n source: \"default\",\n };\n}\n\nexport async function resolveGlobalCodexRuntimeContext(\n options?: CodexHomePathOptions,\n): Promise<CodexRuntimeContext> {\n return resolveExternalCodexRuntimeContext(options);\n}\n","import type { CodexConfigUpdatePayload } from \"@codexuse/contracts/codex/config-types\";\n\nexport const DEFAULT_CONFIG_TEMPLATE = [\n \"# ~/.codex/config.toml (managed by CodexUse)\",\n \"# Safe defaults with prompts and sandboxed access.\",\n \"# To enable full access, opt into the YOLO preset from settings.\",\n \"\",\n 'model = \"gpt-5.3-codex\"',\n 'review_model = \"gpt-5.3-codex\"',\n 'model_reasoning_effort = \"medium\"',\n 'model_reasoning_summary = \"auto\"',\n 'model_verbosity = \"medium\"',\n 'approval_policy = \"on-request\"',\n 'sandbox_mode = \"read-only\"',\n 'web_search = \"cached\"',\n \"\",\n].join(\"\\n\");\n\nexport const SUPPORTED_REASONING_EFFORT = new Set([\"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"none\"]);\nexport const CLI_SUPPORTED_REASONING_EFFORT = new Set([\"minimal\", \"low\", \"medium\", \"high\", \"none\"]);\n\nexport const YOLO_PRESET: CodexConfigUpdatePayload = {\n model: \"gpt-5.3-codex\",\n reviewModel: \"gpt-5.3-codex\",\n modelReasoningEffort: \"xhigh\",\n modelReasoningSummary: \"detailed\",\n modelVerbosity: \"high\",\n approvalPolicy: \"never\",\n sandboxMode: \"danger-full-access\",\n webSearch: \"live\",\n personality: \"pragmatic\",\n toolOutputTokenLimit: 25_000,\n modelAutoCompactTokenLimit: 233_000,\n features: {\n unifiedExec: true,\n shellSnapshot: true,\n },\n notice: {\n hideFullAccessWarning: true,\n hideGpt51MigrationPrompt: true,\n hideRateLimitModelNudge: true,\n },\n};\n","/* eslint-disable-next-line no-control-regex */\nconst ANSI_PATTERN = /\\u001B\\[[0-9;]*m/g;\n\nexport type UserFacingErrorCode =\n | \"ERR_AUTH\"\n | \"ERR_CLI_UNAVAILABLE\"\n | \"ERR_DISK_FULL\"\n | \"ERR_NETWORK\"\n | \"ERR_NOT_FOUND\"\n | \"ERR_PERMISSION\"\n | \"ERR_PROVIDER\"\n | \"ERR_RATE_LIMIT\"\n | \"ERR_TIMEOUT\"\n | \"ERR_UNKNOWN\";\n\nexport type UserFacingErrorInfo = {\n code: UserFacingErrorCode;\n referenceId: string;\n title: string;\n message: string;\n recovery: string;\n technicalMessage: string;\n technicalDetails: string;\n retryable: boolean;\n};\n\nfunction stripAnsi(value: string): string {\n return value.replace(ANSI_PATTERN, \"\");\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nexport function compactErrorText(value: string, maxLength = 220): string {\n if (!value) {\n return \"\";\n }\n const cleaned = normalizeWhitespace(stripAnsi(String(value)));\n if (!cleaned) {\n return \"\";\n }\n if (cleaned.length <= maxLength) {\n return cleaned;\n }\n return `${cleaned.slice(0, maxLength).trimEnd()}…`;\n}\n\nfunction createErrorReferenceId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`.toUpperCase();\n}\n\nfunction serializeUnknownError(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof Error) {\n return value.stack ?? value.message;\n }\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n}\n\nfunction extractRawMessage(error: unknown): string {\n if (error === null || typeof error === \"undefined\") {\n return \"\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n\nfunction normalizeRawMessage(rawMessage: string): string {\n let cleaned = normalizeWhitespace(stripAnsi(rawMessage));\n if (!cleaned) {\n return \"\";\n }\n if (cleaned.startsWith(\"Error invoking remote method\")) {\n cleaned = cleaned.replace(/^Error invoking remote method '[^']+': Error: /, \"\");\n }\n if (cleaned.toLowerCase().includes(\"openai codex\") && cleaned.toLowerCase().includes(\"workdir:\")) {\n const parts = cleaned.split(/error:/i);\n if (parts.length > 1) {\n return parts[parts.length - 1]?.trim() ?? cleaned;\n }\n }\n return cleaned;\n}\n\nfunction resolveCategory(\n cleaned: string,\n options: {\n fallback: string;\n notFoundFallback?: string;\n },\n): Omit<UserFacingErrorInfo, \"referenceId\" | \"technicalMessage\" | \"technicalDetails\"> {\n const lower = cleaned.toLowerCase();\n\n if (options.notFoundFallback && (lower.includes(\"enoent\") || lower.includes(\"not found\"))) {\n return {\n code: \"ERR_NOT_FOUND\",\n title: \"We couldn't find that item\",\n message: options.notFoundFallback,\n recovery: \"Check the path or selection, then try again.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"rate limit\") ||\n lower.includes(\"quota exceeded\") ||\n lower.includes(\"too many requests\") ||\n lower.includes(\"429\")\n ) {\n return {\n code: \"ERR_RATE_LIMIT\",\n title: \"Rate limit reached\",\n message: \"The provider is rate limited right now.\",\n recovery: \"Wait a moment, switch profiles, or try again.\",\n retryable: true,\n };\n }\n\n if (lower.includes(\"timeout\") || lower.includes(\"timed out\")) {\n return {\n code: \"ERR_TIMEOUT\",\n title: \"Request timed out\",\n message: \"The operation took too long to finish.\",\n recovery: \"Check the connection and try again.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"network\") ||\n lower.includes(\"econn\") ||\n lower.includes(\"networkerror\") ||\n lower.includes(\"connection refused\") ||\n lower.includes(\"socket hang up\")\n ) {\n return {\n code: \"ERR_NETWORK\",\n title: \"Can't reach the service\",\n message: \"CodexUse couldn't connect to the required service.\",\n recovery: \"Check your internet or local server connection, then retry.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"token_invalidated\") ||\n lower.includes(\"session invalidated\") ||\n lower.includes(\"session expired\") ||\n lower.includes(\"refresh token\") ||\n lower.includes(\"unauthorized\") ||\n lower.includes(\"401\")\n ) {\n return {\n code: \"ERR_AUTH\",\n title: \"Sign-in expired\",\n message: \"This account needs to sign in again.\",\n recovery: \"Reconnect the profile, then retry the action.\",\n retryable: true,\n };\n }\n\n if (lower.includes(\"permission\") || lower.includes(\"eacces\") || lower.includes(\"operation not permitted\")) {\n return {\n code: \"ERR_PERMISSION\",\n title: \"Permission denied\",\n message: \"CodexUse doesn't have permission to do that.\",\n recovery: \"Check the file permissions or restart the app and try again.\",\n retryable: true,\n };\n }\n\n if (lower.includes(\"enospc\") || lower.includes(\"disk full\") || lower.includes(\"no space left\")) {\n return {\n code: \"ERR_DISK_FULL\",\n title: \"Disk is full\",\n message: \"CodexUse couldn't save data because the disk is full.\",\n recovery: \"Free up disk space, then try again.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"codex cli\") ||\n lower.includes(\"command not found\") ||\n lower.includes(\"spawn codex\") ||\n lower.includes(\"could not find codex\")\n ) {\n return {\n code: \"ERR_CLI_UNAVAILABLE\",\n title: \"Codex CLI unavailable\",\n message: \"CodexUse couldn't start the Codex CLI.\",\n recovery: \"Check Runtime > Codex and confirm the CLI is installed correctly.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"provider\") ||\n lower.includes(\"model\") ||\n lower.includes(\"openai\") ||\n lower.includes(\"anthropic\")\n ) {\n return {\n code: \"ERR_PROVIDER\",\n title: \"Provider request failed\",\n message: \"The AI provider rejected or failed the request.\",\n recovery: \"Try again, or switch the active profile or model.\",\n retryable: true,\n };\n }\n\n return {\n code: \"ERR_UNKNOWN\",\n title: \"Something went wrong\",\n message: options.fallback,\n recovery: \"Try again. If it keeps happening, report the error with the reference below.\",\n retryable: true,\n };\n}\n\nexport function resolveUserFacingError(\n error: unknown,\n options: {\n fallback?: string;\n notFoundFallback?: string;\n } = {},\n): UserFacingErrorInfo {\n const fallback = options.fallback ?? \"Something went wrong. Please try again.\";\n const rawMessage = extractRawMessage(error);\n const cleaned = normalizeRawMessage(rawMessage);\n const category = resolveCategory(cleaned, {\n fallback,\n ...(options.notFoundFallback ? { notFoundFallback: options.notFoundFallback } : {}),\n });\n\n return {\n ...category,\n referenceId: createErrorReferenceId(),\n technicalMessage: compactErrorText(cleaned || rawMessage || fallback, 400),\n technicalDetails: compactErrorText(serializeUnknownError(error), 4000),\n };\n}\n\nexport function formatUserFacingError(\n error: unknown,\n options: {\n fallback?: string;\n notFoundFallback?: string;\n maxLength?: number;\n } = {},\n): string {\n let cleaned = resolveUserFacingError(error, options).message;\n const maxLength = typeof options.maxLength === \"number\" ? options.maxLength : 220;\n if (cleaned.length > maxLength) {\n cleaned = `${cleaned.slice(0, maxLength).trimEnd()}…`;\n }\n\n return cleaned;\n}\n","import { getCloudSyncStatus, pullCloudSync, pushCloudSync } from \"@codexuse/runtime-profiles/cloud-sync/service\";\nimport { printHelp } from \"../app/help\";\nimport { hasFlag, stripFlags } from \"../platform/args\";\n\nfunction printSyncResult(result: Awaited<ReturnType<typeof pushCloudSync>>): void {\n console.log(result.message);\n if (result.localUpdatedAt) {\n console.log(`Local snapshot: ${result.localUpdatedAt}`);\n }\n if (result.remoteUpdatedAt) {\n console.log(`Remote snapshot: ${result.remoteUpdatedAt}`);\n }\n}\n\nexport async function handleSync(args: string[], version: string): Promise<void> {\n const flags = args.filter(arg => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printHelp(version);\n return;\n }\n\n switch (sub) {\n case \"status\": {\n const status = await getCloudSyncStatus();\n console.log(`Can sync: ${status.canSync ? \"yes\" : \"no\"}`);\n console.log(`Has key: ${status.hasLicenseKey ? \"yes\" : \"no\"}`);\n if (status.licenseState) {\n console.log(`License state: ${status.licenseState}`);\n }\n if (status.reason) {\n console.log(`Reason: ${status.reason}`);\n }\n if (status.remoteUpdatedAt) {\n console.log(`Remote snapshot: ${status.remoteUpdatedAt}`);\n }\n if (status.lastPushAt) {\n console.log(`Last push: ${status.lastPushAt}`);\n }\n if (status.lastPullAt) {\n console.log(`Last pull: ${status.lastPullAt}`);\n }\n if (status.lastError) {\n console.log(`Last error: ${status.lastError}`);\n }\n return;\n }\n case \"pull\": {\n const result = await pullCloudSync();\n printSyncResult(result);\n if (result.status === \"error\") {\n process.exitCode = 1;\n }\n return;\n }\n case \"push\": {\n const result = await pushCloudSync();\n printSyncResult(result);\n if (result.status === \"error\") {\n process.exitCode = 1;\n }\n return;\n }\n default:\n printHelp(version);\n }\n}\n","import { promises as fs, type Dirent } from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { normalizeAutoRollSettings, type AutoRollSettings } from \"@codexuse/contracts/settings/auto-roll\";\nimport {\n getAppState,\n getUserDataDir,\n resolveLegacyAppStatePath,\n updateAppState,\n type AppState,\n type AppStatePatch,\n type ProfileRecordState,\n type SkillsInstallState,\n} from \"@codexuse/runtime-app-state/app/state\";\nimport {\n LEGACY_LOCALSTORAGE_KEYS,\n type LegacyLocalStorageKey,\n} from \"@codexuse/contracts/settings/legacy-localstorage-keys\";\nimport type { ProfileData, ProfileMetadata } from \"@codexuse/contracts/profiles/types\";\nimport { logWarn } from \"@codexuse/shared/core/logger\";\n\nconst SQLITE_STORAGE_DIR = \".f86eb5e712267207\";\nconst LEGACY_SETTINGS_FILE = \"settings.json\";\nconst LEGACY_SETTINGS_BACKUP_FILE = \"settings.json.bak\";\nconst LEGACY_SYNC_STATE_FILE = \"sync-state.json\";\nconst LEGACY_APP_SETTINGS_PARITY_FILE = \"app-settings-parity.json\";\nconst LEGACY_PROFILE_HOMES_DIR = \"profile-homes\";\nconst LEGACY_SKILLS_DIR = \"skills\";\nconst LEGACY_SKILL_CACHE_DIR = \"skill-cache\";\nconst LEGACY_SKILLS_REPOS_FILE = \"repos.json\";\nconst LEGACY_SKILL_MANIFEST = \".codexuse-skill.json\";\nconst LEGACY_LICENSE_SECRET_FILE = \"license.secret\";\n\ntype LegacyLocalStorageMergeResult = {\n patch: AppStatePatch;\n consumedKeys: string[];\n skippedKeys: string[];\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction isMissingPathError(error: unknown): boolean {\n return (error as NodeJS.ErrnoException).code === \"ENOENT\";\n}\n\nfunction resolveHomeDir(): string {\n const home = process.env.HOME || process.env.USERPROFILE || os.homedir();\n if (!home) {\n throw new Error(\"HOME is not set.\");\n }\n return home;\n}\n\nfunction resolveCodexDir(): string {\n return path.join(resolveHomeDir(), \".codex\");\n}\n\nfunction resolveLegacyPath(...segments: string[]): string {\n return path.join(resolveCodexDir(), ...segments);\n}\n\nasync function readJsonFile(filePath: string): Promise<unknown> {\n const raw = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(raw) as unknown;\n}\n\nasync function readJsonFileIfExists(filePath: string): Promise<unknown | null> {\n try {\n return await readJsonFile(filePath);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n}\n\nasync function copyDirectoryManual(source: string, destination: string): Promise<void> {\n await fs.mkdir(destination, { recursive: true });\n const entries = await fs.readdir(source, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(source, entry.name);\n const destPath = path.join(destination, entry.name);\n\n if (entry.isSymbolicLink()) {\n const linkTarget = await fs.readlink(srcPath);\n await fs.symlink(linkTarget, destPath).catch(error => {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw error;\n }\n });\n continue;\n }\n\n if (entry.isDirectory()) {\n await copyDirectoryManual(srcPath, destPath);\n continue;\n }\n\n if (entry.isFile()) {\n await fs.copyFile(srcPath, destPath);\n }\n }\n}\n\nasync function copyDirIfExists(source: string, destination: string): Promise<void> {\n let stats: Awaited<ReturnType<typeof fs.stat>> | null = null;\n try {\n stats = await fs.stat(source);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n\n if (!stats.isDirectory()) {\n return;\n }\n\n // Retry-safe migration: clear partial destination from prior failed runs.\n await fs.rm(destination, { recursive: true, force: true });\n await fs.mkdir(path.dirname(destination), { recursive: true });\n try {\n await fs.cp(source, destination, {\n recursive: true,\n errorOnExist: false,\n force: true,\n dereference: false,\n verbatimSymlinks: true,\n });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ERR_FS_CP_EINVAL\") {\n await copyDirectoryManual(source, destination);\n return;\n }\n throw error;\n }\n}\n\nasync function copyFileIfExists(\n source: string,\n destination: string,\n options?: { mode?: number },\n): Promise<void> {\n try {\n const sourceStat = await fs.stat(source);\n if (!sourceStat.isFile()) {\n return;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n\n try {\n const destinationStat = await fs.stat(destination);\n if (destinationStat.isFile()) {\n return;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n\n await fs.mkdir(path.dirname(destination), { recursive: true });\n await fs.copyFile(source, destination);\n if (typeof options?.mode === \"number\") {\n await fs.chmod(destination, options.mode).catch(() => undefined);\n }\n}\n\nasync function cleanupCopiedSkillsMetadata(skillsDir: string): Promise<void> {\n await removeIfExists(path.join(skillsDir, LEGACY_SKILLS_REPOS_FILE));\n\n let entries: Dirent[] = [];\n try {\n entries = await fs.readdir(skillsDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\")) {\n continue;\n }\n await removeIfExists(path.join(skillsDir, entry.name, LEGACY_SKILL_MANIFEST));\n }\n}\n\nasync function migrateLegacyDirectoriesToUserData(): Promise<void> {\n const userDataDir = getUserDataDir();\n const legacyCodexDir = resolveCodexDir();\n\n await copyDirIfExists(\n path.join(legacyCodexDir, LEGACY_PROFILE_HOMES_DIR),\n path.join(userDataDir, LEGACY_PROFILE_HOMES_DIR),\n );\n await copyDirIfExists(\n path.join(legacyCodexDir, LEGACY_SKILLS_DIR),\n path.join(userDataDir, LEGACY_SKILLS_DIR),\n );\n await copyDirIfExists(\n path.join(legacyCodexDir, LEGACY_SKILL_CACHE_DIR),\n path.join(userDataDir, LEGACY_SKILL_CACHE_DIR),\n );\n await copyFileIfExists(\n path.join(legacyCodexDir, LEGACY_LICENSE_SECRET_FILE),\n path.join(userDataDir, LEGACY_LICENSE_SECRET_FILE),\n { mode: 0o600 },\n );\n\n await cleanupCopiedSkillsMetadata(path.join(userDataDir, LEGACY_SKILLS_DIR));\n}\n\nfunction pickAutoRoll(raw: unknown): AutoRollSettings | null {\n if (!raw) {\n return null;\n }\n try {\n return normalizeAutoRollSettings(raw as Partial<AutoRollSettings>);\n } catch {\n return null;\n }\n}\n\nfunction parseLegacyLicense(raw: unknown): AppState[\"license\"] {\n if (!isRecord(raw)) {\n return {\n licenseKey: null,\n purchaseEmail: null,\n lastVerifiedAt: null,\n nextCheckAt: null,\n lastVerificationError: null,\n status: \"inactive\",\n signature: null,\n };\n }\n\n const statusCandidate = asString(raw.status);\n const status = [\"inactive\", \"active\", \"grace\", \"error\"].includes(statusCandidate ?? \"\")\n ? (statusCandidate as AppState[\"license\"][\"status\"])\n : \"inactive\";\n\n return {\n licenseKey: asString(raw.licenseKey ?? raw.license_key),\n purchaseEmail: asString(raw.purchaseEmail ?? raw.purchase_email),\n lastVerifiedAt: asString(raw.lastVerifiedAt ?? raw.last_verified_at),\n nextCheckAt: asString(raw.nextCheckAt ?? raw.next_check_at),\n lastVerificationError: asString(raw.lastVerificationError ?? raw.last_verification_error),\n status,\n signature: asString(raw.signature),\n };\n}\n\nfunction parseLegacyProfileRecord(name: string, raw: unknown): ProfileRecordState | null {\n if (!isRecord(raw)) {\n return null;\n }\n\n const dataRaw = raw.data;\n let data: ProfileData | null = null;\n if (isRecord(dataRaw)) {\n data = dataRaw as ProfileData;\n } else if (typeof dataRaw === \"string\") {\n try {\n data = JSON.parse(dataRaw) as ProfileData;\n } catch {\n data = null;\n }\n }\n\n if (!data) {\n return null;\n }\n\n return {\n name,\n displayName: asString(raw.displayName ?? raw.display_name) ?? name,\n data,\n metadata: isRecord(raw.metadata) ? (raw.metadata as ProfileMetadata) : undefined,\n accountId: asString(raw.accountId ?? raw.account_id),\n workspaceId: asString(raw.workspaceId ?? raw.workspace_id),\n workspaceName: asString(raw.workspaceName ?? raw.workspace_name),\n email: asString(raw.email),\n authMethod: asString(raw.authMethod ?? raw.auth_method),\n createdAt: asString(raw.createdAt ?? raw.created_at),\n updatedAt: asString(raw.updatedAt ?? raw.updated_at),\n };\n}\n\nasync function loadLegacySettingsPatch(): Promise<AppStatePatch> {\n const filePath = resolveLegacyPath(LEGACY_SETTINGS_FILE);\n const raw = await readJsonFileIfExists(filePath);\n if (!isRecord(raw)) {\n return {};\n }\n\n const autoRoll = pickAutoRoll(raw.autoRoll ?? raw.auto_roll);\n const license = parseLegacyLicense(raw.license ?? raw.license_data ?? raw.license_state);\n\n return {\n app: {\n lastAppVersion: asString(raw.lastAppVersion ?? raw.last_app_version),\n pendingUpdateVersion: asString(raw.pendingUpdateVersion ?? raw.pending_update_version),\n lastProfileName: asString(raw.lastProfileName ?? raw.last_profile_name),\n },\n license,\n autoRoll: autoRoll\n ? {\n enabled: autoRoll.enabled,\n rearmRemainingThreshold: autoRoll.rearmRemainingThreshold,\n switchRemainingThreshold: autoRoll.switchRemainingThreshold,\n restartOfficialCodexOnAutoRoll: autoRoll.restartOfficialCodexOnAutoRoll,\n launchOfficialCodexWhenClosedOnAutoRoll:\n autoRoll.launchOfficialCodexWhenClosedOnAutoRoll,\n priorityOrder: autoRoll.priorityOrder,\n lowRemainingNotificationEnabled: autoRoll.lowRemainingNotificationEnabled,\n lowRemainingNotificationThreshold: autoRoll.lowRemainingNotificationThreshold,\n }\n : undefined,\n };\n}\n\nasync function loadLegacySyncPatch(): Promise<AppStatePatch> {\n const filePath = resolveLegacyPath(LEGACY_SYNC_STATE_FILE);\n const raw = await readJsonFileIfExists(filePath);\n if (!isRecord(raw)) {\n return {};\n }\n\n return {\n sync: {\n lastPushAt: asString(raw.lastPushAt),\n lastPullAt: asString(raw.lastPullAt),\n lastError: asString(raw.lastError),\n remoteUpdatedAt: asString(raw.remoteUpdatedAt),\n },\n };\n}\n\nasync function loadLegacyAppSettingsParityPatch(): Promise<AppStatePatch> {\n const filePath = path.join(getUserDataDir(), LEGACY_APP_SETTINGS_PARITY_FILE);\n const raw = await readJsonFileIfExists(filePath);\n if (!isRecord(raw)) {\n return {};\n }\n\n return {\n runtimeSettings: raw,\n };\n}\n\nasync function loadLegacyProfilesPatch(): Promise<AppStatePatch> {\n const root = resolveLegacyPath(LEGACY_PROFILE_HOMES_DIR);\n let entries: Dirent[] = [];\n try {\n entries = await fs.readdir(root, { withFileTypes: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return {};\n }\n throw error;\n }\n\n const profilesByName: Record<string, ProfileRecordState> = {};\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\")) {\n continue;\n }\n const profileFile = path.join(root, entry.name, \"profile.json\");\n const raw = await readJsonFileIfExists(profileFile);\n if (!raw) {\n continue;\n }\n\n const parsed = parseLegacyProfileRecord(entry.name, raw);\n if (!parsed) {\n continue;\n }\n\n profilesByName[entry.name] = parsed;\n }\n\n if (Object.keys(profilesByName).length === 0) {\n return {};\n }\n\n return { profilesByName };\n}\n\nfunction parseSkillInstallMetadata(raw: unknown): SkillsInstallState | null {\n if (!isRecord(raw)) {\n return null;\n }\n\n const id = asString(raw.id);\n if (!id) {\n return null;\n }\n\n return {\n id,\n repo: asString(raw.repo),\n repoPath: asString(raw.repoPath),\n sourceLabel: asString(raw.sourceLabel),\n sourceType:\n raw.sourceType === \"official\" || raw.sourceType === \"community\" || raw.sourceType === \"local\"\n ? raw.sourceType\n : undefined,\n viewUrl: asString(raw.viewUrl),\n createdAt: asString(raw.createdAt),\n };\n}\n\nasync function loadLegacySkillsPatch(): Promise<AppStatePatch> {\n const skillsRoot = resolveLegacyPath(LEGACY_SKILLS_DIR);\n const reposPath = path.join(skillsRoot, LEGACY_SKILLS_REPOS_FILE);\n const reposRaw = await readJsonFileIfExists(reposPath);\n\n const installsBySlug: Record<string, SkillsInstallState> = {};\n let dirEntries: Array<Dirent> = [];\n\n try {\n dirEntries = await fs.readdir(skillsRoot, { withFileTypes: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n\n for (const entry of dirEntries) {\n if (!entry.isDirectory()) {\n continue;\n }\n if (entry.name.startsWith(\".\")) {\n continue;\n }\n const manifestPath = path.join(skillsRoot, entry.name, LEGACY_SKILL_MANIFEST);\n const manifestRaw = await readJsonFileIfExists(manifestPath);\n const parsed = parseSkillInstallMetadata(manifestRaw);\n if (!parsed) {\n continue;\n }\n installsBySlug[entry.name] = parsed;\n }\n\n const sources = isRecord(reposRaw) && Array.isArray(reposRaw.sources)\n ? (reposRaw.sources as AppState[\"skills\"][\"sources\"])\n : [];\n\n if (sources.length === 0 && Object.keys(installsBySlug).length === 0) {\n return {};\n }\n\n return {\n skills: {\n sources,\n installsBySlug,\n },\n };\n}\n\nfunction mergeLegacyLocalStoragePatch(payload: Record<string, unknown>): LegacyLocalStorageMergeResult {\n const patch: AppStatePatch = {};\n const consumedKeys = new Set<string>();\n const skippedKeys = new Set<string>();\n const legacyPayloadKeys = new Set<LegacyLocalStorageKey>(\n Object.keys(payload).filter((key): key is LegacyLocalStorageKey =>\n (LEGACY_LOCALSTORAGE_KEYS as readonly string[]).includes(key),\n ),\n );\n const hasKey = (key: LegacyLocalStorageKey) => legacyPayloadKeys.has(key);\n const markSkippedIfPresent = (key: LegacyLocalStorageKey, consumed: boolean) => {\n if (!hasKey(key)) {\n return;\n }\n if (consumed) {\n consumedKeys.add(key);\n } else {\n skippedKeys.add(key);\n }\n };\n\n const settingsStorage = payload[\"settings-storage\"];\n if (isRecord(settingsStorage)) {\n const nextExcludeFolders = Array.isArray(settingsStorage.excludeFolders)\n ? (settingsStorage.excludeFolders.filter(item => typeof item === \"string\") as string[])\n : undefined;\n const nextBeep =\n typeof settingsStorage.enableTaskCompleteBeep === \"boolean\"\n ? settingsStorage.enableTaskCompleteBeep\n : undefined;\n const nextSleep =\n typeof settingsStorage.preventSleepDuringTasks === \"boolean\"\n ? settingsStorage.preventSleepDuringTasks\n : undefined;\n patch.preferences = {\n excludeFolders: nextExcludeFolders,\n enableTaskCompleteBeep: nextBeep,\n preventSleepDuringTasks: nextSleep,\n };\n markSkippedIfPresent(\n \"settings-storage\",\n nextExcludeFolders !== undefined || nextBeep !== undefined || nextSleep !== undefined,\n );\n } else {\n markSkippedIfPresent(\"settings-storage\", false);\n }\n\n markSkippedIfPresent(\"provider\", hasKey(\"provider\"));\n markSkippedIfPresent(\"sandbox-storage\", hasKey(\"sandbox-storage\"));\n\n const projectSettings = payload[\"project-settings-storage\"];\n if (isRecord(projectSettings) && isRecord(projectSettings.settingsByPath)) {\n patch.workspaceSettingsByPath = projectSettings.settingsByPath as AppState[\"workspaceSettingsByPath\"];\n markSkippedIfPresent(\"project-settings-storage\", true);\n } else {\n markSkippedIfPresent(\"project-settings-storage\", false);\n }\n\n const folder = payload[\"folder-storage\"];\n if (isRecord(folder)) {\n const folderHistory = Array.isArray(folder.folderHistory)\n ? (folder.folderHistory.filter(isRecord) as AppState[\"preferences\"][\"folderHistory\"])\n : undefined;\n const pinnedPaths = Array.isArray(folder.pinnedPaths)\n ? (folder.pinnedPaths.filter(item => typeof item === \"string\") as string[])\n : undefined;\n patch.preferences = {\n ...(patch.preferences ?? {}),\n folderHistory,\n pinnedPaths,\n };\n markSkippedIfPresent(\"folder-storage\", folderHistory !== undefined || pinnedPaths !== undefined);\n } else {\n markSkippedIfPresent(\"folder-storage\", false);\n }\n\n const categories = payload[\"conversation-categories-storage\"];\n let consumedCategories = false;\n if (isRecord(categories)) {\n if (isRecord(categories.categoriesByCwd)) {\n patch.conversationCategoriesByCwd =\n categories.categoriesByCwd as AppState[\"conversationCategoriesByCwd\"];\n consumedCategories = true;\n }\n if (isRecord(categories.conversationCategoryByCwd)) {\n patch.conversationCategoryAssignmentsByCwd =\n categories.conversationCategoryByCwd as AppState[\"conversationCategoryAssignmentsByCwd\"];\n consumedCategories = true;\n }\n }\n markSkippedIfPresent(\"conversation-categories-storage\", consumedCategories);\n\n const legacyAutoRoll = payload[\"codex:auto-roll-settings\"];\n const autoRoll = pickAutoRoll(legacyAutoRoll);\n if (autoRoll) {\n patch.autoRoll = {\n enabled: autoRoll.enabled,\n rearmRemainingThreshold: autoRoll.rearmRemainingThreshold,\n switchRemainingThreshold: autoRoll.switchRemainingThreshold,\n restartOfficialCodexOnAutoRoll: autoRoll.restartOfficialCodexOnAutoRoll,\n launchOfficialCodexWhenClosedOnAutoRoll:\n autoRoll.launchOfficialCodexWhenClosedOnAutoRoll,\n priorityOrder: autoRoll.priorityOrder,\n lowRemainingNotificationEnabled: autoRoll.lowRemainingNotificationEnabled,\n lowRemainingNotificationThreshold: autoRoll.lowRemainingNotificationThreshold,\n };\n markSkippedIfPresent(\"codex:auto-roll-settings\", true);\n } else {\n markSkippedIfPresent(\"codex:auto-roll-settings\", false);\n }\n\n return {\n patch,\n consumedKeys: Array.from(consumedKeys),\n skippedKeys: Array.from(skippedKeys),\n };\n}\n\nasync function removeIfExists(target: string): Promise<void> {\n await fs.rm(target, { recursive: true, force: true });\n}\n\nasync function cleanupLegacyCanonicalSources(): Promise<void> {\n const homeDir = resolveHomeDir();\n\n await removeIfExists(resolveLegacyAppStatePath());\n await removeIfExists(path.join(getUserDataDir(), LEGACY_APP_SETTINGS_PARITY_FILE));\n await removeIfExists(path.join(homeDir, SQLITE_STORAGE_DIR));\n await removeIfExists(resolveLegacyPath(LEGACY_SETTINGS_FILE));\n await removeIfExists(resolveLegacyPath(LEGACY_SETTINGS_BACKUP_FILE));\n await removeIfExists(resolveLegacyPath(LEGACY_SYNC_STATE_FILE));\n await removeIfExists(resolveLegacyPath(LEGACY_LICENSE_SECRET_FILE));\n await removeIfExists(resolveLegacyPath(LEGACY_SKILLS_DIR, LEGACY_SKILLS_REPOS_FILE));\n\n const profileHomesRoot = resolveLegacyPath(LEGACY_PROFILE_HOMES_DIR);\n try {\n const profileHomes = await fs.readdir(profileHomesRoot, { withFileTypes: true });\n for (const profileHome of profileHomes) {\n if (!profileHome.isDirectory()) {\n continue;\n }\n const profileDir = path.join(profileHomesRoot, profileHome.name);\n let files: string[] = [];\n try {\n files = await fs.readdir(profileDir);\n } catch {\n continue;\n }\n for (const file of files) {\n if (!file.startsWith(\"profile.json\")) {\n continue;\n }\n await removeIfExists(path.join(profileDir, file));\n }\n }\n } catch (error) {\n if (!isMissingPathError(error)) {\n // cleanup is best-effort; log for diagnostics without failing migration\n logWarn(\"Failed cleaning legacy profile metadata:\", {\n profileHomesRoot,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n const skillsRoot = resolveLegacyPath(LEGACY_SKILLS_DIR);\n try {\n const skillDirs = await fs.readdir(skillsRoot, { withFileTypes: true });\n for (const entry of skillDirs) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\")) {\n continue;\n }\n await removeIfExists(path.join(skillsRoot, entry.name, LEGACY_SKILL_MANIFEST));\n }\n } catch (error) {\n if (!isMissingPathError(error)) {\n // cleanup is best-effort; log for diagnostics without failing migration\n logWarn(\"Failed cleaning legacy skills metadata:\", {\n skillsRoot,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n\nexport async function runStorageMigrationV1(): Promise<AppState> {\n const current = await getAppState();\n if (current.migration.status === \"complete\") {\n return current;\n }\n if (current.migration.status === \"pending_local_storage\") {\n const completedAt = new Date().toISOString();\n return updateAppState((state) => ({\n ...state,\n migration: {\n ...state.migration,\n status: \"complete\",\n completedAt,\n lastError: null,\n },\n }), {\n mode: \"replace\",\n allowBeforeMigrationComplete: true,\n });\n }\n\n const startedAt = new Date().toISOString();\n\n try {\n await migrateLegacyDirectoriesToUserData();\n const patches = await Promise.all([\n loadLegacySettingsPatch(),\n loadLegacySyncPatch(),\n loadLegacyAppSettingsParityPatch(),\n loadLegacyProfilesPatch(),\n loadLegacySkillsPatch(),\n ]);\n\n const mergedPatch: AppStatePatch = patches.reduce((acc, patch) => {\n return {\n ...acc,\n ...patch,\n app: { ...(acc.app ?? {}), ...(patch.app ?? {}) },\n license: { ...(acc.license ?? {}), ...(patch.license ?? {}) },\n autoRoll: { ...(acc.autoRoll ?? {}), ...(patch.autoRoll ?? {}) },\n runtimeSettings: { ...(acc.runtimeSettings ?? {}), ...(patch.runtimeSettings ?? {}) },\n preferences: { ...(acc.preferences ?? {}), ...(patch.preferences ?? {}) },\n sync: { ...(acc.sync ?? {}), ...(patch.sync ?? {}) },\n profilesByName: { ...(acc.profilesByName ?? {}), ...(patch.profilesByName ?? {}) },\n workspaceSettingsByPath: {\n ...(acc.workspaceSettingsByPath ?? {}),\n ...(patch.workspaceSettingsByPath ?? {}),\n },\n conversationCategoriesByCwd: {\n ...(acc.conversationCategoriesByCwd ?? {}),\n ...(patch.conversationCategoriesByCwd ?? {}),\n },\n conversationCategoryAssignmentsByCwd: {\n ...(acc.conversationCategoryAssignmentsByCwd ?? {}),\n ...(patch.conversationCategoryAssignmentsByCwd ?? {}),\n },\n skills: {\n ...(acc.skills ?? {}),\n ...(patch.skills ?? {}),\n sources: patch.skills?.sources ?? acc.skills?.sources,\n installsBySlug: {\n ...(acc.skills?.installsBySlug ?? {}),\n ...(patch.skills?.installsBySlug ?? {}),\n },\n },\n };\n }, {} as AppStatePatch);\n\n return await updateAppState((state) => ({\n ...state,\n ...mergedPatch,\n app: { ...state.app, ...(mergedPatch.app ?? {}) },\n license: { ...state.license, ...(mergedPatch.license ?? {}) },\n autoRoll: { ...state.autoRoll, ...(mergedPatch.autoRoll ?? {}) },\n runtimeSettings: {\n ...state.runtimeSettings,\n ...(mergedPatch.runtimeSettings ?? {}),\n },\n preferences: { ...state.preferences, ...(mergedPatch.preferences ?? {}) },\n sync: { ...state.sync, ...(mergedPatch.sync ?? {}) },\n profilesByName: {\n ...state.profilesByName,\n ...(mergedPatch.profilesByName ?? {}),\n },\n workspaceSettingsByPath: {\n ...state.workspaceSettingsByPath,\n ...(mergedPatch.workspaceSettingsByPath ?? {}),\n },\n conversationCategoriesByCwd: {\n ...state.conversationCategoriesByCwd,\n ...(mergedPatch.conversationCategoriesByCwd ?? {}),\n },\n conversationCategoryAssignmentsByCwd: {\n ...state.conversationCategoryAssignmentsByCwd,\n ...(mergedPatch.conversationCategoryAssignmentsByCwd ?? {}),\n },\n skills: {\n ...state.skills,\n ...(mergedPatch.skills ?? {}),\n installsBySlug: {\n ...state.skills.installsBySlug,\n ...(mergedPatch.skills?.installsBySlug ?? {}),\n },\n },\n migration: {\n ...state.migration,\n status: \"complete\",\n startedAt: state.migration.startedAt ?? startedAt,\n completedAt: startedAt,\n localStorageImportedAt: null,\n lastError: null,\n },\n }), {\n mode: \"replace\",\n allowBeforeMigrationComplete: true,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n await updateAppState((state) => ({\n ...state,\n migration: {\n ...state.migration,\n status: \"pending\",\n startedAt: state.migration.startedAt ?? startedAt,\n lastError: message,\n },\n }), {\n mode: \"replace\",\n allowBeforeMigrationComplete: true,\n });\n throw error;\n }\n}\n\nexport async function importLegacyLocalStorageOnce(\n payload: Record<string, unknown>,\n): Promise<{ completed: boolean; importedKeys: string[]; skippedKeys?: string[] }> {\n const current = await getAppState();\n if (current.migration.status === \"pending\") {\n return { completed: false, importedKeys: [], skippedKeys: [] };\n }\n\n if (!payload || !isRecord(payload)) {\n return { completed: true, importedKeys: [], skippedKeys: [] };\n }\n\n const { patch, consumedKeys, skippedKeys } = mergeLegacyLocalStoragePatch(payload);\n\n const completedAt = new Date().toISOString();\n const next = await updateAppState((state) => {\n return {\n ...state,\n ...patch,\n app: { ...state.app, ...(patch.app ?? {}) },\n autoRoll: { ...state.autoRoll, ...(patch.autoRoll ?? {}) },\n license: { ...state.license, ...(patch.license ?? {}) },\n preferences: { ...state.preferences, ...(patch.preferences ?? {}) },\n workspaceSettingsByPath: {\n ...state.workspaceSettingsByPath,\n ...(patch.workspaceSettingsByPath ?? {}),\n },\n conversationCategoriesByCwd: {\n ...state.conversationCategoriesByCwd,\n ...(patch.conversationCategoriesByCwd ?? {}),\n },\n conversationCategoryAssignmentsByCwd: {\n ...state.conversationCategoryAssignmentsByCwd,\n ...(patch.conversationCategoryAssignmentsByCwd ?? {}),\n },\n migration: {\n ...state.migration,\n status: \"complete\",\n completedAt,\n localStorageImportedAt: completedAt,\n lastError: null,\n },\n };\n }, {\n mode: \"replace\",\n allowBeforeMigrationComplete: true,\n });\n\n if (next.migration.status !== \"complete\") {\n return { completed: false, importedKeys: [], skippedKeys: [] };\n }\n\n await cleanupLegacyCanonicalSources();\n return { completed: true, importedKeys: consumedKeys, skippedKeys };\n}\n","export const LEGACY_LOCALSTORAGE_KEYS = [\n \"settings-storage\",\n \"provider\",\n \"sandbox-storage\",\n \"project-settings-storage\",\n \"folder-storage\",\n \"conversation-categories-storage\",\n \"codex:auto-roll-settings\",\n] as const;\n\nexport const ORPHAN_LOCALSTORAGE_KEYS = [\n \"token-count-storage\",\n \"codexia-chat-input-store\",\n \"codex\",\n] as const;\n\nexport type LegacyLocalStorageKey = (typeof LEGACY_LOCALSTORAGE_KEYS)[number];\n","import { getAppState, getUserDataDir, initializeAppState } from \"@codexuse/runtime-app-state/app/state\";\nimport { importLegacyLocalStorageOnce, runStorageMigrationV1 } from \"@codexuse/runtime-app-state/storage/migrations/v1\";\n\nlet cliStorageReadyPromise: Promise<void> | null = null;\n\nexport async function ensureCliStorageReady(): Promise<void> {\n if (cliStorageReadyPromise) {\n return cliStorageReadyPromise;\n }\n\n cliStorageReadyPromise = (async () => {\n await initializeAppState(getUserDataDir());\n await runStorageMigrationV1();\n await importLegacyLocalStorageOnce({});\n const state = await getAppState();\n if (state.migration.status !== \"complete\") {\n throw new Error(\n `Storage migration is not complete (status: ${state.migration.status}). CLI cannot continue until migration succeeds.`,\n );\n }\n })().catch((error) => {\n cliStorageReadyPromise = null;\n throw error;\n });\n\n return cliStorageReadyPromise;\n}\n","import { handleAccountPoolCommand } from \"../commands/accountPool\";\nimport {\n handleBestCommand,\n handleDoctorCommand,\n handleRunCommand,\n} from \"../commands/codex\";\nimport { handleDaemonCommand } from \"../commands/daemon\";\nimport { handleLicense } from \"../commands/license\";\nimport { handleProfileCommand } from \"../commands/profile\";\nimport { handleSync } from \"../commands/sync\";\nimport { printHelp } from \"./help\";\nimport { hasFlag } from \"../platform/args\";\nimport { ensureCliStorageReady } from \"../platform/storage\";\n\ndeclare const __CODEXUSE_CLI_VERSION__: string;\n\nconst VERSION = typeof __CODEXUSE_CLI_VERSION__ === \"string\"\n ? __CODEXUSE_CLI_VERSION__\n : \"0.0.0\";\n\nasync function runCli(): Promise<void> {\n const args = process.argv.slice(2);\n\n if (args.length === 0) {\n printHelp(VERSION);\n return;\n }\n\n if (args[0]?.startsWith(\"-\") && (hasFlag(args, \"--help\") || hasFlag(args, \"-h\"))) {\n printHelp(VERSION);\n return;\n }\n\n if (args[0]?.startsWith(\"-\") && (hasFlag(args, \"--version\") || hasFlag(args, \"-v\"))) {\n console.log(VERSION);\n return;\n }\n\n const command = args[0];\n const rest = args.slice(1);\n\n switch (command) {\n case \"doctor\":\n await ensureCliStorageReady();\n await handleDoctorCommand(rest);\n return;\n case \"run\":\n await ensureCliStorageReady();\n await handleRunCommand(rest);\n return;\n case \"best\":\n await ensureCliStorageReady();\n await handleBestCommand(rest);\n return;\n case \"account-pool\":\n case \"accounts-pool\":\n await ensureCliStorageReady();\n await handleAccountPoolCommand(rest, VERSION);\n return;\n case \"profile\":\n await ensureCliStorageReady();\n await handleProfileCommand(rest, VERSION);\n return;\n case \"license\":\n await ensureCliStorageReady();\n await handleLicense(rest, VERSION);\n return;\n case \"sync\":\n await ensureCliStorageReady();\n await handleSync(rest, VERSION);\n return;\n case \"daemon\":\n await ensureCliStorageReady();\n await handleDaemonCommand(rest, VERSION);\n return;\n default:\n printHelp(VERSION);\n return;\n }\n}\n\nexport function runCliEntryPoint(): void {\n void runCli().catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exitCode = 1;\n });\n}\n","import { runCliEntryPoint } from \"./app/main\";\n\nrunCliEntryPoint();\n"],"mappings":";;;;;;;;;;;;;;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,YAAM,oBAAoB,MAAM,OAAO;AACvC;AAAA,IACF;AACE,gBAAU,OAAO;AACjB;AAAA,EACJ;AACF;AAEO,SAAS,mBAAyB;AACvC,OAAK,OAAO,EAAE,MAAM,CAAC,UAAU;AAC7B,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,YAAQ,MAAM,OAAO;AACrB,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;;;ACrFA,iBAAiB;","names":["exports","module","exports","module","exports","module","exports","module","exports","module","Date","exports","module","exports","module","exports","module","exports","module","index","blocksize","exports","module","exports","module","exports","module","stringify","tomlType","str","exports","import_node_crypto","import_node_os","import_node_path","import_node_fs","import_node_path","fs","path","sqlite","database","isRecord","clone","os","path","fs","clone","import_node_crypto","asString","isRecord","isRecord","asString","import_node_fs","import_node_path","crypto","path","fs","offer","crypto","fallbackStored","import_node_crypto","import_path","import_node_child_process","import_node_fs","import_node_os","import_node_path","import_node_fs","import_node_path","path","import_node_path","path","isRecord","asString","parseTimestamp","fs","path","os","readline","REFRESH_TOKEN_REDEEMED_SNIPPET","fs","path","REFRESH_TOKEN_REDEEMED_SNIPPET","path","os","asRecord","asString","import_node_child_process","import_node_child_process","import_node_fs","import_node_path","ENV_HINTS","fileExists","path","stat","buildCodexCommand","buildCodexCommand","import_node_child_process","import_node_crypto","import_node_fs","import_node_os","import_node_path","import_node_child_process","import_node_path","path","path","path","fs","resolveStateDir","os","net","port","import_node_child_process","import_node_crypto","import_node_fs","import_node_os","import_node_path","runCommand","path","path","runCommand","runningPids","mainPids","stopped","action","result","import_node_fs","import_node_path","isRecord","isRecord","import_toml","import_node_child_process","import_node_path","isRecord","runCommand","path","import_promises","import_node_path","import_node_os","import_node_path","os","path","path","normalizeLineEndings","normalizeLineEndings","isRecord","path","fs","import_node_fs","import_node_path","import_node_os","LEGACY_LICENSE_SECRET_FILE","isRecord","asString","resolveHomeDir","os","path","fs","hasKey"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js","../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js","../src/commands/accountPool.ts","../../../packages/contracts/src/settings/types.ts","../../../packages/runtime-app-state/src/app/state.ts","../../../packages/contracts/src/settings/auto-roll.ts","../../../packages/runtime-app-state/src/storage/documents.ts","../../../packages/runtime-app-state/src/app/runtimeSettings.ts","../../../packages/runtime-profiles/src/license/service.ts","../../../packages/runtime-codex/src/codex/settings.ts","../../../packages/runtime-profiles/src/license/secret.ts","../../../packages/contracts/src/license/offer-config.ts","../../../packages/runtime-profiles/src/profiles/profile-manager.ts","../../../packages/contracts/src/profiles/identity.ts","../../../packages/runtime-codex/src/codex/rpc.ts","../../../packages/runtime-codex/src/codex/cli.ts","../../../packages/runtime-codex/src/codex/command.ts","../../../packages/shared/src/core/logger.ts","../src/app/help.ts","../src/platform/args.ts","../src/commands/codex.ts","../../../packages/runtime-profiles/src/profiles/rate-limit-notifier.ts","../src/platform/codexCli.ts","../src/commands/license.ts","../../../packages/runtime-profiles/src/license/guard.ts","../../../packages/runtime-codex/src/codex/officialAppRestart.ts","../../../packages/runtime-codex/src/codex/threadUsage.ts","../src/commands/profile.ts","../../../packages/contracts/src/cloud-sync/types.ts","../../../packages/shared/src/core/type-guards.ts","../../../packages/runtime-profiles/src/cloud-sync/client.ts","../../../packages/runtime-codex/src/codex/config.ts","../../../packages/runtime-codex/src/codex/config-metadata.ts","../../../packages/runtime-codex/src/codex/config-io.ts","../../../packages/runtime-codex/src/codex/home.ts","../../../packages/runtime-codex/src/codex/config-presets.ts","../../../packages/shared/src/core/errors.ts","../../../packages/runtime-profiles/src/cloud-sync/service.ts","../src/commands/sync.ts","../src/platform/storage.ts","../src/app/main.ts","../src/index.ts"],"sourcesContent":["'use strict'\nconst ParserEND = 0x110000\nclass ParserError extends Error {\n /* istanbul ignore next */\n constructor (msg, filename, linenumber) {\n super('[ParserError] ' + msg, filename, linenumber)\n this.name = 'ParserError'\n this.code = 'ParserError'\n if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError)\n }\n}\nclass State {\n constructor (parser) {\n this.parser = parser\n this.buf = ''\n this.returned = null\n this.result = null\n this.resultTable = null\n this.resultArr = null\n }\n}\nclass Parser {\n constructor () {\n this.pos = 0\n this.col = 0\n this.line = 0\n this.obj = {}\n this.ctx = this.obj\n this.stack = []\n this._buf = ''\n this.char = null\n this.ii = 0\n this.state = new State(this.parseStart)\n }\n\n parse (str) {\n /* istanbul ignore next */\n if (str.length === 0 || str.length == null) return\n\n this._buf = String(str)\n this.ii = -1\n this.char = -1\n let getNext\n while (getNext === false || this.nextChar()) {\n getNext = this.runOne()\n }\n this._buf = null\n }\n nextChar () {\n if (this.char === 0x0A) {\n ++this.line\n this.col = -1\n }\n ++this.ii\n this.char = this._buf.codePointAt(this.ii)\n ++this.pos\n ++this.col\n return this.haveBuffer()\n }\n haveBuffer () {\n return this.ii < this._buf.length\n }\n runOne () {\n return this.state.parser.call(this, this.state.returned)\n }\n finish () {\n this.char = ParserEND\n let last\n do {\n last = this.state.parser\n this.runOne()\n } while (this.state.parser !== last)\n\n this.ctx = null\n this.state = null\n this._buf = null\n\n return this.obj\n }\n next (fn) {\n /* istanbul ignore next */\n if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn))\n this.state.parser = fn\n }\n goto (fn) {\n this.next(fn)\n return this.runOne()\n }\n call (fn, returnWith) {\n if (returnWith) this.next(returnWith)\n this.stack.push(this.state)\n this.state = new State(fn)\n }\n callNow (fn, returnWith) {\n this.call(fn, returnWith)\n return this.runOne()\n }\n return (value) {\n /* istanbul ignore next */\n if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'))\n if (value === undefined) value = this.state.buf\n this.state = this.stack.pop()\n this.state.returned = value\n }\n returnNow (value) {\n this.return(value)\n return this.runOne()\n }\n consume () {\n /* istanbul ignore next */\n if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'))\n this.state.buf += this._buf[this.ii]\n }\n error (err) {\n err.line = this.line\n err.col = this.col\n err.pos = this.pos\n return err\n }\n /* istanbul ignore next */\n parseStart () {\n throw new ParserError('Must declare a parseStart method')\n }\n}\nParser.END = ParserEND\nParser.Error = ParserError\nmodule.exports = Parser\n","'use strict'\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nmodule.exports = (d, num) => {\n num = String(num)\n while (num.length < d) num = '0' + num\n return num\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass FloatingDateTime extends Date {\n constructor (value) {\n super(value + 'Z')\n this.isFloating = true\n }\n toISOString () {\n const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n return `${date}T${time}`\n }\n}\n\nmodule.exports = value => {\n const date = new FloatingDateTime(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\nconst DateTime = global.Date\n\nclass Date extends DateTime {\n constructor (value) {\n super(value)\n this.isDate = true\n }\n toISOString () {\n return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\nconst f = require('./format-num.js')\n\nclass Time extends Date {\n constructor (value) {\n super(`0000-01-01T${value}Z`)\n this.isTime = true\n }\n toISOString () {\n return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Time(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n","'use strict'\n/* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */\nmodule.exports = makeParserClass(require('./parser.js'))\nmodule.exports.makeParserClass = makeParserClass\n\nclass TomlError extends Error {\n constructor (msg) {\n super(msg)\n this.name = 'TomlError'\n /* istanbul ignore next */\n if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError)\n this.fromTOML = true\n this.wrapped = null\n }\n}\nTomlError.wrap = err => {\n const terr = new TomlError(err.message)\n terr.code = err.code\n terr.wrapped = err\n return terr\n}\nmodule.exports.TomlError = TomlError\n\nconst createDateTime = require('./create-datetime.js')\nconst createDateTimeFloat = require('./create-datetime-float.js')\nconst createDate = require('./create-date.js')\nconst createTime = require('./create-time.js')\n\nconst CTRL_I = 0x09\nconst CTRL_J = 0x0A\nconst CTRL_M = 0x0D\nconst CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL\nconst CHAR_SP = 0x20\nconst CHAR_QUOT = 0x22\nconst CHAR_NUM = 0x23\nconst CHAR_APOS = 0x27\nconst CHAR_PLUS = 0x2B\nconst CHAR_COMMA = 0x2C\nconst CHAR_HYPHEN = 0x2D\nconst CHAR_PERIOD = 0x2E\nconst CHAR_0 = 0x30\nconst CHAR_1 = 0x31\nconst CHAR_7 = 0x37\nconst CHAR_9 = 0x39\nconst CHAR_COLON = 0x3A\nconst CHAR_EQUALS = 0x3D\nconst CHAR_A = 0x41\nconst CHAR_E = 0x45\nconst CHAR_F = 0x46\nconst CHAR_T = 0x54\nconst CHAR_U = 0x55\nconst CHAR_Z = 0x5A\nconst CHAR_LOWBAR = 0x5F\nconst CHAR_a = 0x61\nconst CHAR_b = 0x62\nconst CHAR_e = 0x65\nconst CHAR_f = 0x66\nconst CHAR_i = 0x69\nconst CHAR_l = 0x6C\nconst CHAR_n = 0x6E\nconst CHAR_o = 0x6F\nconst CHAR_r = 0x72\nconst CHAR_s = 0x73\nconst CHAR_t = 0x74\nconst CHAR_u = 0x75\nconst CHAR_x = 0x78\nconst CHAR_z = 0x7A\nconst CHAR_LCUB = 0x7B\nconst CHAR_RCUB = 0x7D\nconst CHAR_LSQB = 0x5B\nconst CHAR_BSOL = 0x5C\nconst CHAR_RSQB = 0x5D\nconst CHAR_DEL = 0x7F\nconst SURROGATE_FIRST = 0xD800\nconst SURROGATE_LAST = 0xDFFF\n\nconst escapes = {\n [CHAR_b]: '\\u0008',\n [CHAR_t]: '\\u0009',\n [CHAR_n]: '\\u000A',\n [CHAR_f]: '\\u000C',\n [CHAR_r]: '\\u000D',\n [CHAR_QUOT]: '\\u0022',\n [CHAR_BSOL]: '\\u005C'\n}\n\nfunction isDigit (cp) {\n return cp >= CHAR_0 && cp <= CHAR_9\n}\nfunction isHexit (cp) {\n return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9)\n}\nfunction isBit (cp) {\n return cp === CHAR_1 || cp === CHAR_0\n}\nfunction isOctit (cp) {\n return (cp >= CHAR_0 && cp <= CHAR_7)\n}\nfunction isAlphaNumQuoteHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_APOS\n || cp === CHAR_QUOT\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nfunction isAlphaNumHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nconst _type = Symbol('type')\nconst _declared = Symbol('declared')\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst defineProperty = Object.defineProperty\nconst descriptor = {configurable: true, enumerable: true, writable: true, value: undefined}\n\nfunction hasKey (obj, key) {\n if (hasOwnProperty.call(obj, key)) return true\n if (key === '__proto__') defineProperty(obj, '__proto__', descriptor)\n return false\n}\n\nconst INLINE_TABLE = Symbol('inline-table')\nfunction InlineTable () {\n return Object.defineProperties({}, {\n [_type]: {value: INLINE_TABLE}\n })\n}\nfunction isInlineTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_TABLE\n}\n\nconst TABLE = Symbol('table')\nfunction Table () {\n return Object.defineProperties({}, {\n [_type]: {value: TABLE},\n [_declared]: {value: false, writable: true}\n })\n}\nfunction isTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === TABLE\n}\n\nconst _contentType = Symbol('content-type')\nconst INLINE_LIST = Symbol('inline-list')\nfunction InlineList (type) {\n return Object.defineProperties([], {\n [_type]: {value: INLINE_LIST},\n [_contentType]: {value: type}\n })\n}\nfunction isInlineList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_LIST\n}\n\nconst LIST = Symbol('list')\nfunction List () {\n return Object.defineProperties([], {\n [_type]: {value: LIST}\n })\n}\nfunction isList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === LIST\n}\n\n// in an eval, to let bundlers not slurp in a util proxy\nlet _custom\ntry {\n const utilInspect = eval(\"require('util').inspect\")\n _custom = utilInspect.custom\n} catch (_) {\n /* eval require not available in transpiled bundle */\n}\n/* istanbul ignore next */\nconst _inspect = _custom || 'inspect'\n\nclass BoxedBigInt {\n constructor (value) {\n try {\n this.value = global.BigInt.asIntN(64, value)\n } catch (_) {\n /* istanbul ignore next */\n this.value = null\n }\n Object.defineProperty(this, _type, {value: INTEGER})\n }\n isNaN () {\n return this.value === null\n }\n /* istanbul ignore next */\n toString () {\n return String(this.value)\n }\n /* istanbul ignore next */\n [_inspect] () {\n return `[BigInt: ${this.toString()}]}`\n }\n valueOf () {\n return this.value\n }\n}\n\nconst INTEGER = Symbol('integer')\nfunction Integer (value) {\n let num = Number(value)\n // -0 is a float thing, not an int thing\n if (Object.is(num, -0)) num = 0\n /* istanbul ignore else */\n if (global.BigInt && !Number.isSafeInteger(num)) {\n return new BoxedBigInt(value)\n } else {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(num), {\n isNaN: {value: function () { return isNaN(this) }},\n [_type]: {value: INTEGER},\n [_inspect]: {value: () => `[Integer: ${value}]`}\n })\n }\n}\nfunction isInteger (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INTEGER\n}\n\nconst FLOAT = Symbol('float')\nfunction Float (value) {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(value), {\n [_type]: {value: FLOAT},\n [_inspect]: {value: () => `[Float: ${value}]`}\n })\n}\nfunction isFloat (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === FLOAT\n}\n\nfunction tomlType (value) {\n const type = typeof value\n if (type === 'object') {\n /* istanbul ignore if */\n if (value === null) return 'null'\n if (value instanceof Date) return 'datetime'\n /* istanbul ignore else */\n if (_type in value) {\n switch (value[_type]) {\n case INLINE_TABLE: return 'inline-table'\n case INLINE_LIST: return 'inline-list'\n /* istanbul ignore next */\n case TABLE: return 'table'\n /* istanbul ignore next */\n case LIST: return 'list'\n case FLOAT: return 'float'\n case INTEGER: return 'integer'\n }\n }\n }\n return type\n}\n\nfunction makeParserClass (Parser) {\n class TOMLParser extends Parser {\n constructor () {\n super()\n this.ctx = this.obj = Table()\n }\n\n /* MATCH HELPER */\n atEndOfWord () {\n return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine()\n }\n atEndOfLine () {\n return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M\n }\n\n parseStart () {\n if (this.char === Parser.END) {\n return null\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseTableOrList)\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (isAlphaNumQuoteHyphen(this.char)) {\n return this.callNow(this.parseAssignStatement)\n } else {\n throw this.error(new TomlError(`Unknown character \"${this.char}\"`))\n }\n }\n\n // HELPER, this strips any whitespace and comments to the end of the line\n // then RETURNS. Last state in a production.\n parseWhitespaceToEOL () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.goto(this.parseComment)\n } else if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n } else {\n throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'))\n }\n }\n\n /* ASSIGNMENT: key = value */\n parseAssignStatement () {\n return this.callNow(this.parseAssign, this.recordAssignStatement)\n }\n recordAssignStatement (kv) {\n let target = this.ctx\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n // unbox our numbers\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseWhitespaceToEOL)\n }\n\n /* ASSSIGNMENT expression, key = value possibly inside an inline table */\n parseAssign () {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n recordAssignKeyword (key) {\n if (this.state.resultTable) {\n this.state.resultTable.push(key)\n } else {\n this.state.resultTable = [key]\n }\n return this.goto(this.parseAssignKeywordPreDot)\n }\n parseAssignKeywordPreDot () {\n if (this.char === CHAR_PERIOD) {\n return this.next(this.parseAssignKeywordPostDot)\n } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.goto(this.parseAssignEqual)\n }\n }\n parseAssignKeywordPostDot () {\n if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n }\n\n parseAssignEqual () {\n if (this.char === CHAR_EQUALS) {\n return this.next(this.parseAssignPreValue)\n } else {\n throw this.error(new TomlError('Invalid character, expected \"=\"'))\n }\n }\n parseAssignPreValue () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseValue, this.recordAssignValue)\n }\n }\n recordAssignValue (value) {\n return this.returnNow({key: this.state.resultTable, value: value})\n }\n\n /* COMMENTS: #...eol */\n parseComment () {\n do {\n if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n }\n } while (this.nextChar())\n }\n\n /* TABLES AND LISTS, [foo] and [[foo]] */\n parseTableOrList () {\n if (this.char === CHAR_LSQB) {\n this.next(this.parseList)\n } else {\n return this.goto(this.parseTable)\n }\n }\n\n /* TABLE [foo.bar.baz] */\n parseTable () {\n this.ctx = this.obj\n return this.goto(this.parseTableNext)\n }\n parseTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseTableMore)\n }\n }\n parseTableMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n } else {\n this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table()\n this.ctx[_declared] = true\n }\n return this.next(this.parseWhitespaceToEOL)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n return this.next(this.parseTableNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* LIST [[a.b.c]] */\n parseList () {\n this.ctx = this.obj\n return this.goto(this.parseListNext)\n }\n parseListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseListMore)\n }\n }\n parseListMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx[keyword] = List()\n }\n if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isList(this.ctx[keyword])) {\n const next = Table()\n this.ctx[keyword].push(next)\n this.ctx = next\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListEnd)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isInlineTable(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline table\"))\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n parseListEnd (keyword) {\n if (this.char === CHAR_RSQB) {\n return this.next(this.parseWhitespaceToEOL)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* VALUE string, number, boolean, inline list, inline object */\n parseValue () {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key without value'))\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseDoubleString)\n } if (this.char === CHAR_APOS) {\n return this.next(this.parseSingleString)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n return this.goto(this.parseNumberSign)\n } else if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseNumberOrDateTime)\n } else if (this.char === CHAR_t || this.char === CHAR_f) {\n return this.goto(this.parseBoolean)\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseInlineList, this.recordValue)\n } else if (this.char === CHAR_LCUB) {\n return this.call(this.parseInlineTable, this.recordValue)\n } else {\n throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'))\n }\n }\n recordValue (value) {\n return this.returnNow(value)\n }\n\n parseInf () {\n if (this.char === CHAR_n) {\n return this.next(this.parseInf2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n parseInf2 () {\n if (this.char === CHAR_f) {\n if (this.state.buf === '-') {\n return this.return(-Infinity)\n } else {\n return this.return(Infinity)\n }\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n\n parseNan () {\n if (this.char === CHAR_a) {\n return this.next(this.parseNan2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n parseNan2 () {\n if (this.char === CHAR_n) {\n return this.return(NaN)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n\n /* KEYS, barewords or basic, literal, or dotted */\n parseKeyword () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseBasicString)\n } else if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralString)\n } else {\n return this.goto(this.parseBareKey)\n }\n }\n\n /* KEYS: barewords */\n parseBareKey () {\n do {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key ended without value'))\n } else if (isAlphaNumHyphen(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 0) {\n throw this.error(new TomlError('Empty bare keys are not allowed'))\n } else {\n return this.returnNow()\n }\n } while (this.nextChar())\n }\n\n /* STRINGS, single quoted (literal) */\n parseSingleString () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiStringMaybe)\n } else {\n return this.goto(this.parseLiteralString)\n }\n }\n parseLiteralString () {\n do {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiStringMaybe () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseLiteralMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseLiteralMultiStringContent)\n } else {\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiStringContent () {\n do {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiEnd () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd2)\n } else {\n this.state.buf += \"'\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiEnd2 () {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else {\n this.state.buf += \"''\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n\n /* STRINGS double quoted */\n parseDoubleString () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiStringMaybe)\n } else {\n return this.goto(this.parseBasicString)\n }\n }\n parseBasicString () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseEscape, this.recordEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n recordEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseBasicString)\n }\n parseMultiStringMaybe () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseMultiStringContent)\n } else {\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiStringContent () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n errorControlCharInString () {\n let displayCode = '\\\\u00'\n if (this.char < 16) {\n displayCode += '0'\n }\n displayCode += this.char.toString(16)\n\n return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))\n }\n recordMultiEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseMultiStringContent)\n }\n parseMultiEnd () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd2)\n } else {\n this.state.buf += '\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEnd2 () {\n if (this.char === CHAR_QUOT) {\n return this.return()\n } else {\n this.state.buf += '\"\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEscape () {\n if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else if (this.char === CHAR_SP || this.char === CTRL_I) {\n return this.next(this.parsePreMultiTrim)\n } else {\n return this.goto(this.parseEscape)\n }\n }\n parsePreMultiTrim () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else {\n throw this.error(new TomlError(\"Can't escape whitespace\"))\n }\n }\n parseMultiTrim () {\n // explicitly whitespace here, END should follow the same path as chars\n if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else {\n return this.returnNow()\n }\n }\n parseEscape () {\n if (this.char in escapes) {\n return this.return(escapes[this.char])\n } else if (this.char === CHAR_u) {\n return this.call(this.parseSmallUnicode, this.parseUnicodeReturn)\n } else if (this.char === CHAR_U) {\n return this.call(this.parseLargeUnicode, this.parseUnicodeReturn)\n } else {\n throw this.error(new TomlError('Unknown escape character: ' + this.char))\n }\n }\n parseUnicodeReturn (char) {\n try {\n const codePoint = parseInt(char, 16)\n if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {\n throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'))\n }\n return this.returnNow(String.fromCodePoint(codePoint))\n } catch (err) {\n throw this.error(TomlError.wrap(err))\n }\n }\n parseSmallUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 4) return this.return()\n }\n }\n parseLargeUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 8) return this.return()\n }\n }\n\n /* NUMBERS */\n parseNumberSign () {\n this.consume()\n return this.next(this.parseMaybeSignedInfOrNan)\n }\n parseMaybeSignedInfOrNan () {\n if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else {\n return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart)\n }\n }\n parseNumberIntegerStart () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberIntegerExponentOrDecimal)\n } else {\n return this.goto(this.parseNumberInteger)\n }\n }\n parseNumberIntegerExponentOrDecimal () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseNumberInteger () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseNoUnder () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNoUnderHexOctBinLiteral () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNumberFloat () {\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n parseNumberExponentSign () {\n if (isDigit(this.char)) {\n return this.goto(this.parseNumberExponent)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.call(this.parseNoUnder, this.parseNumberExponent)\n } else {\n throw this.error(new TomlError('Unexpected character, expected -, + or digit'))\n }\n }\n parseNumberExponent () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n\n /* NUMBERS or DATETIMES */\n parseNumberOrDateTime () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberBaseOrDateTime)\n } else {\n return this.goto(this.parseNumberOrDateTimeOnly)\n }\n }\n parseNumberOrDateTimeOnly () {\n // note, if two zeros are in a row then it MUST be a date\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length > 4) this.next(this.parseNumberInteger)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseDateTimeOnly () {\n if (this.state.buf.length < 4) {\n if (isDigit(this.char)) {\n return this.consume()\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n throw this.error(new TomlError('Expected digit while parsing year part of a date'))\n }\n } else {\n if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else {\n throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'))\n }\n }\n }\n parseNumberBaseOrDateTime () {\n if (this.char === CHAR_b) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin)\n } else if (this.char === CHAR_o) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct)\n } else if (this.char === CHAR_x) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex)\n } else if (this.char === CHAR_PERIOD) {\n return this.goto(this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseDateTimeOnly)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseIntegerHex () {\n if (isHexit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerOct () {\n if (isOctit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerBin () {\n if (isBit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n\n /* DATETIME */\n parseDateTime () {\n // we enter here having just consumed the year and about to consume the hyphen\n if (this.state.buf.length < 4) {\n throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateMonth)\n }\n parseDateMonth () {\n if (this.char === CHAR_HYPHEN) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateDay)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseDateDay () {\n if (this.char === CHAR_T || this.char === CHAR_SP) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseStartTimeHour)\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result + '-' + this.state.buf))\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseStartTimeHour () {\n if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result))\n } else {\n return this.goto(this.parseTimeHour)\n }\n }\n parseTimeHour () {\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result += 'T' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeMin)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeZoneOrFraction)\n }\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n\n parseOnlyTimeHour () {\n /* istanbul ignore else */\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeMin)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n return this.next(this.parseOnlyTimeFractionMaybe)\n }\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeFractionMaybe () {\n this.state.result += ':' + this.state.buf\n if (this.char === CHAR_PERIOD) {\n this.state.buf = ''\n this.next(this.parseOnlyTimeFraction)\n } else {\n return this.return(createTime(this.state.result))\n }\n }\n parseOnlyTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.atEndOfWord()) {\n if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'))\n return this.returnNow(createTime(this.state.result + '.' + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n\n parseTimeZoneOrFraction () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n this.next(this.parseDateTimeFraction)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseDateTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 1) {\n throw this.error(new TomlError('Expected digit in milliseconds'))\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseTimeZoneHour () {\n if (isDigit(this.char)) {\n this.consume()\n // FIXME: No more regexps\n if (/\\d\\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n parseTimeZoneSep () {\n if (this.char === CHAR_COLON) {\n this.consume()\n this.next(this.parseTimeZoneMin)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected colon'))\n }\n }\n parseTimeZoneMin () {\n if (isDigit(this.char)) {\n this.consume()\n if (/\\d\\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n\n /* BOOLEAN */\n parseBoolean () {\n /* istanbul ignore else */\n if (this.char === CHAR_t) {\n this.consume()\n return this.next(this.parseTrue_r)\n } else if (this.char === CHAR_f) {\n this.consume()\n return this.next(this.parseFalse_a)\n }\n }\n parseTrue_r () {\n if (this.char === CHAR_r) {\n this.consume()\n return this.next(this.parseTrue_u)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_u () {\n if (this.char === CHAR_u) {\n this.consume()\n return this.next(this.parseTrue_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_e () {\n if (this.char === CHAR_e) {\n return this.return(true)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_a () {\n if (this.char === CHAR_a) {\n this.consume()\n return this.next(this.parseFalse_l)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_l () {\n if (this.char === CHAR_l) {\n this.consume()\n return this.next(this.parseFalse_s)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_s () {\n if (this.char === CHAR_s) {\n this.consume()\n return this.next(this.parseFalse_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_e () {\n if (this.char === CHAR_e) {\n return this.return(false)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n /* INLINE LISTS */\n parseInlineList () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_RSQB) {\n return this.return(this.state.resultArr || InlineList())\n } else {\n return this.callNow(this.parseValue, this.recordInlineListValue)\n }\n }\n recordInlineListValue (value) {\n if (this.state.resultArr) {\n const listType = this.state.resultArr[_contentType]\n const valueType = tomlType(value)\n if (listType !== valueType) {\n throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))\n }\n } else {\n this.state.resultArr = InlineList(tomlType(value))\n }\n if (isFloat(value) || isInteger(value)) {\n // unbox now that we've verified they're ok\n this.state.resultArr.push(value.valueOf())\n } else {\n this.state.resultArr.push(value)\n }\n return this.goto(this.parseInlineListNext)\n }\n parseInlineListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineList)\n } else if (this.char === CHAR_RSQB) {\n return this.goto(this.parseInlineList)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n\n /* INLINE TABLE */\n parseInlineTable () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_RCUB) {\n return this.return(this.state.resultTable || InlineTable())\n } else {\n if (!this.state.resultTable) this.state.resultTable = InlineTable()\n return this.callNow(this.parseAssign, this.recordInlineTableValue)\n }\n }\n recordInlineTableValue (kv) {\n let target = this.state.resultTable\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseInlineTableNext)\n }\n parseInlineTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineTable)\n } else if (this.char === CHAR_RCUB) {\n return this.goto(this.parseInlineTable)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n }\n return TOMLParser\n}\n","'use strict'\nmodule.exports = prettyError\n\nfunction prettyError (err, buf) {\n /* istanbul ignore if */\n if (err.pos == null || err.line == null) return err\n let msg = err.message\n msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\\n`\n\n /* istanbul ignore else */\n if (buf && buf.split) {\n const lines = buf.split(/\\n/)\n const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length\n let linePadding = ' '\n while (linePadding.length < lineNumWidth) linePadding += ' '\n for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {\n let lineNum = String(ii + 1)\n if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum\n if (err.line === ii) {\n msg += lineNum + '> ' + lines[ii] + '\\n'\n msg += linePadding + ' '\n for (let hh = 0; hh < err.col; ++hh) {\n msg += ' '\n }\n msg += '^\\n'\n } else {\n msg += lineNum + ': ' + lines[ii] + '\\n'\n }\n }\n }\n err.message = msg + '\\n'\n return err\n}\n","'use strict'\nmodule.exports = parseString\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseString (str) {\n if (global.Buffer && global.Buffer.isBuffer(str)) {\n str = str.toString('utf8')\n }\n const parser = new TOMLParser()\n try {\n parser.parse(str)\n return parser.finish()\n } catch (err) {\n throw prettyError(err, str)\n }\n}\n","'use strict'\nmodule.exports = parseAsync\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseAsync (str, opts) {\n if (!opts) opts = {}\n const index = 0\n const blocksize = opts.blocksize || 40960\n const parser = new TOMLParser()\n return new Promise((resolve, reject) => {\n setImmediate(parseAsyncNext, index, blocksize, resolve, reject)\n })\n function parseAsyncNext (index, blocksize, resolve, reject) {\n if (index >= str.length) {\n try {\n return resolve(parser.finish())\n } catch (err) {\n return reject(prettyError(err, str))\n }\n }\n try {\n parser.parse(str.slice(index, index + blocksize))\n setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject)\n } catch (err) {\n reject(prettyError(err, str))\n }\n }\n}\n","'use strict'\nmodule.exports = parseStream\n\nconst stream = require('stream')\nconst TOMLParser = require('./lib/toml-parser.js')\n\nfunction parseStream (stm) {\n if (stm) {\n return parseReadable(stm)\n } else {\n return parseTransform(stm)\n }\n}\n\nfunction parseReadable (stm) {\n const parser = new TOMLParser()\n stm.setEncoding('utf8')\n return new Promise((resolve, reject) => {\n let readable\n let ended = false\n let errored = false\n function finish () {\n ended = true\n if (readable) return\n try {\n resolve(parser.finish())\n } catch (err) {\n reject(err)\n }\n }\n function error (err) {\n errored = true\n reject(err)\n }\n stm.once('end', finish)\n stm.once('error', error)\n readNext()\n\n function readNext () {\n readable = true\n let data\n while ((data = stm.read()) !== null) {\n try {\n parser.parse(data)\n } catch (err) {\n return error(err)\n }\n }\n readable = false\n /* istanbul ignore if */\n if (ended) return finish()\n /* istanbul ignore if */\n if (errored) return\n stm.once('readable', readNext)\n }\n })\n}\n\nfunction parseTransform () {\n const parser = new TOMLParser()\n return new stream.Transform({\n objectMode: true,\n transform (chunk, encoding, cb) {\n try {\n parser.parse(chunk.toString(encoding))\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n },\n flush (cb) {\n try {\n this.push(parser.finish())\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n }\n })\n}\n","'use strict'\nmodule.exports = require('./parse-string.js')\nmodule.exports.async = require('./parse-async.js')\nmodule.exports.stream = require('./parse-stream.js')\nmodule.exports.prettyError = require('./parse-pretty-error.js')\n","'use strict'\nmodule.exports = stringify\nmodule.exports.value = stringifyInline\n\nfunction stringify (obj) {\n if (obj === null) throw typeError('null')\n if (obj === void (0)) throw typeError('undefined')\n if (typeof obj !== 'object') throw typeError(typeof obj)\n\n if (typeof obj.toJSON === 'function') obj = obj.toJSON()\n if (obj == null) return null\n const type = tomlType(obj)\n if (type !== 'table') throw typeError(type)\n return stringifyObject('', '', obj)\n}\n\nfunction typeError (type) {\n return new Error('Can only stringify objects, not ' + type)\n}\n\nfunction arrayOneTypeError () {\n return new Error(\"Array values can't have mixed types\")\n}\n\nfunction getInlineKeys (obj) {\n return Object.keys(obj).filter(key => isInline(obj[key]))\n}\nfunction getComplexKeys (obj) {\n return Object.keys(obj).filter(key => !isInline(obj[key]))\n}\n\nfunction toJSON (obj) {\n let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {}\n for (let prop of Object.keys(obj)) {\n if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) {\n nobj[prop] = obj[prop].toJSON()\n } else {\n nobj[prop] = obj[prop]\n }\n }\n return nobj\n}\n\nfunction stringifyObject (prefix, indent, obj) {\n obj = toJSON(obj)\n var inlineKeys\n var complexKeys\n inlineKeys = getInlineKeys(obj)\n complexKeys = getComplexKeys(obj)\n var result = []\n var inlineIndent = indent || ''\n inlineKeys.forEach(key => {\n var type = tomlType(obj[key])\n if (type !== 'undefined' && type !== 'null') {\n result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true))\n }\n })\n if (result.length > 0) result.push('')\n var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : ''\n complexKeys.forEach(key => {\n result.push(stringifyComplex(prefix, complexIndent, key, obj[key]))\n })\n return result.join('\\n')\n}\n\nfunction isInline (value) {\n switch (tomlType(value)) {\n case 'undefined':\n case 'null':\n case 'integer':\n case 'nan':\n case 'float':\n case 'boolean':\n case 'string':\n case 'datetime':\n return true\n case 'array':\n return value.length === 0 || tomlType(value[0]) !== 'table'\n case 'table':\n return Object.keys(value).length === 0\n /* istanbul ignore next */\n default:\n return false\n }\n}\n\nfunction tomlType (value) {\n if (value === undefined) {\n return 'undefined'\n } else if (value === null) {\n return 'null'\n /* eslint-disable valid-typeof */\n } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) {\n return 'integer'\n } else if (typeof value === 'number') {\n return 'float'\n } else if (typeof value === 'boolean') {\n return 'boolean'\n } else if (typeof value === 'string') {\n return 'string'\n } else if ('toISOString' in value) {\n return isNaN(value) ? 'undefined' : 'datetime'\n } else if (Array.isArray(value)) {\n return 'array'\n } else {\n return 'table'\n }\n}\n\nfunction stringifyKey (key) {\n var keyStr = String(key)\n if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {\n return keyStr\n } else {\n return stringifyBasicString(keyStr)\n }\n}\n\nfunction stringifyBasicString (str) {\n return '\"' + escapeString(str).replace(/\"/g, '\\\\\"') + '\"'\n}\n\nfunction stringifyLiteralString (str) {\n return \"'\" + str + \"'\"\n}\n\nfunction numpad (num, str) {\n while (str.length < num) str = '0' + str\n return str\n}\n\nfunction escapeString (str) {\n return str.replace(/\\\\/g, '\\\\\\\\')\n .replace(/[\\b]/g, '\\\\b')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\f/g, '\\\\f')\n .replace(/\\r/g, '\\\\r')\n /* eslint-disable no-control-regex */\n .replace(/([\\u0000-\\u001f\\u007f])/, c => '\\\\u' + numpad(4, c.codePointAt(0).toString(16)))\n /* eslint-enable no-control-regex */\n}\n\nfunction stringifyMultilineString (str) {\n let escaped = str.split(/\\n/).map(str => {\n return escapeString(str).replace(/\"(?=\"\")/g, '\\\\\"')\n }).join('\\n')\n if (escaped.slice(-1) === '\"') escaped += '\\\\\\n'\n return '\"\"\"\\n' + escaped + '\"\"\"'\n}\n\nfunction stringifyAnyInline (value, multilineOk) {\n let type = tomlType(value)\n if (type === 'string') {\n if (multilineOk && /\\n/.test(value)) {\n type = 'string-multiline'\n } else if (!/[\\b\\t\\n\\f\\r']/.test(value) && /\"/.test(value)) {\n type = 'string-literal'\n }\n }\n return stringifyInline(value, type)\n}\n\nfunction stringifyInline (value, type) {\n /* istanbul ignore if */\n if (!type) type = tomlType(value)\n switch (type) {\n case 'string-multiline':\n return stringifyMultilineString(value)\n case 'string':\n return stringifyBasicString(value)\n case 'string-literal':\n return stringifyLiteralString(value)\n case 'integer':\n return stringifyInteger(value)\n case 'float':\n return stringifyFloat(value)\n case 'boolean':\n return stringifyBoolean(value)\n case 'datetime':\n return stringifyDatetime(value)\n case 'array':\n return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan'))\n case 'table':\n return stringifyInlineTable(value)\n /* istanbul ignore next */\n default:\n throw typeError(type)\n }\n}\n\nfunction stringifyInteger (value) {\n /* eslint-disable security/detect-unsafe-regex */\n return String(value).replace(/\\B(?=(\\d{3})+(?!\\d))/g, '_')\n}\n\nfunction stringifyFloat (value) {\n if (value === Infinity) {\n return 'inf'\n } else if (value === -Infinity) {\n return '-inf'\n } else if (Object.is(value, NaN)) {\n return 'nan'\n } else if (Object.is(value, -0)) {\n return '-0.0'\n }\n var chunks = String(value).split('.')\n var int = chunks[0]\n var dec = chunks[1] || 0\n return stringifyInteger(int) + '.' + dec\n}\n\nfunction stringifyBoolean (value) {\n return String(value)\n}\n\nfunction stringifyDatetime (value) {\n return value.toISOString()\n}\n\nfunction isNumber (type) {\n return type === 'float' || type === 'integer'\n}\nfunction arrayType (values) {\n var contentType = tomlType(values[0])\n if (values.every(_ => tomlType(_) === contentType)) return contentType\n // mixed integer/float, emit as floats\n if (values.every(_ => isNumber(tomlType(_)))) return 'float'\n return 'mixed'\n}\nfunction validateArray (values) {\n const type = arrayType(values)\n if (type === 'mixed') {\n throw arrayOneTypeError()\n }\n return type\n}\n\nfunction stringifyInlineArray (values) {\n values = toJSON(values)\n const type = validateArray(values)\n var result = '['\n var stringified = values.map(_ => stringifyInline(_, type))\n if (stringified.join(', ').length > 60 || /\\n/.test(stringified)) {\n result += '\\n ' + stringified.join(',\\n ') + '\\n'\n } else {\n result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '')\n }\n return result + ']'\n}\n\nfunction stringifyInlineTable (value) {\n value = toJSON(value)\n var result = []\n Object.keys(value).forEach(key => {\n result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false))\n })\n return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}'\n}\n\nfunction stringifyComplex (prefix, indent, key, value) {\n var valueType = tomlType(value)\n /* istanbul ignore else */\n if (valueType === 'array') {\n return stringifyArrayOfTables(prefix, indent, key, value)\n } else if (valueType === 'table') {\n return stringifyComplexTable(prefix, indent, key, value)\n } else {\n throw typeError(valueType)\n }\n}\n\nfunction stringifyArrayOfTables (prefix, indent, key, values) {\n values = toJSON(values)\n validateArray(values)\n var firstValueType = tomlType(values[0])\n /* istanbul ignore if */\n if (firstValueType !== 'table') throw typeError(firstValueType)\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n values.forEach(table => {\n if (result.length > 0) result += '\\n'\n result += indent + '[[' + fullKey + ']]\\n'\n result += stringifyObject(fullKey + '.', indent, table)\n })\n return result\n}\n\nfunction stringifyComplexTable (prefix, indent, key, value) {\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n if (getInlineKeys(value).length > 0) {\n result += indent + '[' + fullKey + ']\\n'\n }\n return result + stringifyObject(fullKey + '.', indent, value)\n}\n","'use strict'\nexports.parse = require('./parse.js')\nexports.stringify = require('./stringify.js')\n","import { createHash, randomBytes, randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport type {\n AccountPoolApiKeyCreateResult,\n AccountPoolApiKeyView,\n AccountPoolRoutingStrategy,\n AccountPoolSessionStatus,\n AccountPoolSessionView,\n} from \"@codexuse/contracts/account-pool/types\";\nimport {\n DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS,\n DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS,\n DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS,\n} from \"@codexuse/contracts/settings/types\";\nimport { getUserDataDir } from \"@codexuse/runtime-app-state/app/state\";\nimport { readAppSettings, writeAppSettings } from \"@codexuse/runtime-app-state/app/runtimeSettings\";\nimport {\n readDocument,\n updateDocument,\n} from \"@codexuse/runtime-app-state/storage/documents\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { printHelp } from \"../app/help\";\nimport { hasFlag, parseStringFlag, stripFlags } from \"../platform/args\";\n\ntype JsonRecord = Record<string, unknown>;\ntype AccountPoolRuntime = \"desktop\";\n\ntype AccountPoolSettings = {\n accountPoolEnabled: boolean;\n accountPoolRoutingStrategy: AccountPoolRoutingStrategy;\n accountPoolProfilePool: string[];\n accountPoolExposedModels: string[];\n accountPoolExposedReasoningEfforts: string[];\n accountPoolExposedFastModeReasoningEfforts: string[];\n};\n\ntype AccountPoolApiKeyRecord = {\n id: string;\n tokenHash: string;\n tokenPreview: string;\n createdAt: string;\n lastUsedAt: string | null;\n revokedAt: string | null;\n};\n\ntype AccountPoolSessionRecord = {\n id: string;\n affinityKind: AccountPoolSessionView[\"affinityKind\"];\n affinityKey: string | null;\n activeSegmentId: string;\n segmentIds: string[];\n model: string | null;\n status: AccountPoolSessionStatus;\n lastError: string | null;\n createdAt: string;\n lastUsedAt: string;\n expiresAt: string | null;\n lastResponseId: string | null;\n responseIds: string[];\n rolloverCount: number;\n lastRolloverReason: string | null;\n};\n\ntype AccountPoolSegmentRecord = {\n id: string;\n sessionId: string;\n profileName: string;\n createdAt: string;\n lastUsedAt: string;\n};\n\ntype AccountPoolResponseIndexRecord = {\n sessionId: string;\n segmentId: string;\n createdAt: string;\n};\n\ntype AccountPoolStore = {\n version: number;\n roundRobinCursor: number;\n apiKeysById: Record<string, AccountPoolApiKeyRecord>;\n sessionsById: Record<string, AccountPoolSessionRecord>;\n segmentsById: Record<string, AccountPoolSegmentRecord>;\n responseIndex: Record<string, AccountPoolResponseIndexRecord>;\n};\n\ntype AccountPoolRuntimeSummary = {\n runtime: AccountPoolRuntime;\n stateDir: string;\n baseUrl: string | null;\n enabled: boolean;\n hasProLicense: boolean;\n routingStrategy: AccountPoolRoutingStrategy;\n activeApiKeyCount: number;\n activeSessionCount: number;\n};\n\nconst ACCOUNT_POOL_DOCUMENT = \"desktop.account-pool.v2\";\nconst ACCOUNT_POOL_PRO_REQUIRED_MESSAGE = \"Accounts Pool requires a Pro license.\";\nconst DESKTOP_RPC_STATE_DIR = \"desktop-rpc\";\nconst ACCOUNT_POOL_STORE_VERSION = 3;\nconst MAX_RESPONSE_IDS_PER_SESSION = 64;\nconst MODEL_SLUG_ALIASES = {\n \"5.5\": \"gpt-5.5\",\n \"5.4\": \"gpt-5.4\",\n \"5.3\": \"gpt-5.3-codex\",\n \"gpt-5.3\": \"gpt-5.3-codex\",\n \"5.3-spark\": \"gpt-5.3-codex-spark\",\n \"gpt-5.3-spark\": \"gpt-5.3-codex-spark\",\n} as const;\n\nfunction asRecord(value: unknown): JsonRecord {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as JsonRecord) : {};\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction asNumber(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction normalizeIsoString(value: unknown): string | null {\n const normalized = asString(value);\n if (!normalized) {\n return null;\n }\n const parsed = Date.parse(normalized);\n return Number.isNaN(parsed) ? null : new Date(parsed).toISOString();\n}\n\nfunction normalizeStringArray(value: unknown): string[] {\n const input = Array.isArray(value) ? value : [];\n const result: string[] = [];\n const seen = new Set<string>();\n for (const entry of input) {\n const normalized = asString(entry);\n if (!normalized || seen.has(normalized)) {\n continue;\n }\n seen.add(normalized);\n result.push(normalized);\n }\n return result;\n}\n\nfunction normalizeReasoningEffort(value: unknown): string | null {\n const normalized = asString(value)?.toLowerCase() ?? null;\n return normalized && normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeRoutingStrategy(value: unknown): AccountPoolRoutingStrategy {\n return value === \"round_robin\" ? \"round_robin\" : \"least_used\";\n}\n\nfunction normalizeCodexModelSlug(value: string | null | undefined): string | null {\n const trimmed = value?.trim();\n if (!trimmed) {\n return null;\n }\n return MODEL_SLUG_ALIASES[trimmed as keyof typeof MODEL_SLUG_ALIASES] ?? trimmed;\n}\n\nfunction formatRoutingStrategy(value: AccountPoolRoutingStrategy): string {\n return value === \"round_robin\" ? \"round-robin\" : \"least-used\";\n}\n\nfunction parseRoutingStrategy(value: string | null | undefined): AccountPoolRoutingStrategy | null {\n const normalized = value?.trim().toLowerCase();\n if (!normalized) {\n return null;\n }\n if (normalized === \"round-robin\" || normalized === \"round_robin\" || normalized === \"roundrobin\") {\n return \"round_robin\";\n }\n if (normalized === \"least-used\" || normalized === \"least_used\" || normalized === \"leastused\") {\n return \"least_used\";\n }\n return null;\n}\n\nfunction normalizeAccountPoolExposedModels(\n value: unknown,\n fallbackToDefault: boolean,\n): string[] {\n const result: string[] = [];\n const seen = new Set<string>();\n const input = Array.isArray(value) ? value : [];\n for (const entry of input) {\n const raw = asString(entry);\n const normalized = normalizeCodexModelSlug(raw) ?? raw;\n if (!normalized || seen.has(normalized)) {\n continue;\n }\n seen.add(normalized);\n result.push(normalized);\n }\n if (result.length > 0) {\n return result;\n }\n return fallbackToDefault ? [...DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS] : [];\n}\n\nfunction normalizeAccountPoolReasoningEfforts(\n value: unknown,\n fallback: readonly string[] | null,\n): string[] {\n const input = Array.isArray(value) ? value : [];\n const result: string[] = [];\n const seen = new Set<string>();\n for (const entry of input) {\n const normalized = normalizeReasoningEffort(entry);\n if (!normalized || seen.has(normalized)) {\n continue;\n }\n seen.add(normalized);\n result.push(normalized);\n }\n if (result.length > 0 || Array.isArray(value)) {\n return result;\n }\n return fallback ? [...fallback] : [];\n}\n\nfunction normalizeAccountPoolSettings(settings: JsonRecord): AccountPoolSettings {\n return {\n accountPoolEnabled: settings.accountPoolEnabled === true,\n accountPoolRoutingStrategy: normalizeRoutingStrategy(settings.accountPoolRoutingStrategy),\n accountPoolProfilePool: normalizeStringArray(settings.accountPoolProfilePool),\n accountPoolExposedModels: normalizeAccountPoolExposedModels(\n settings.accountPoolExposedModels,\n true,\n ),\n accountPoolExposedReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n settings.accountPoolExposedReasoningEfforts,\n DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS,\n ),\n accountPoolExposedFastModeReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n settings.accountPoolExposedFastModeReasoningEfforts,\n DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS,\n ),\n };\n}\n\nfunction applyAccountPoolSettings(\n settings: JsonRecord,\n nextAccountPoolSettings: AccountPoolSettings,\n): JsonRecord {\n const next: JsonRecord = {\n ...settings,\n accountPoolEnabled: nextAccountPoolSettings.accountPoolEnabled,\n accountPoolRoutingStrategy: nextAccountPoolSettings.accountPoolRoutingStrategy,\n accountPoolProfilePool: nextAccountPoolSettings.accountPoolProfilePool.slice(),\n accountPoolExposedModels: nextAccountPoolSettings.accountPoolExposedModels.slice(),\n accountPoolExposedReasoningEfforts: nextAccountPoolSettings.accountPoolExposedReasoningEfforts.slice(),\n accountPoolExposedFastModeReasoningEfforts:\n nextAccountPoolSettings.accountPoolExposedFastModeReasoningEfforts.slice(),\n };\n return next;\n}\n\nfunction printAccountPoolHelp(version: string): void {\n console.log(`CodexUse CLI v${version}\n\nUsage:\n codexuse account-pool status [--runtime=desktop] [--state-dir=/abs/path]\n codexuse account-pool quickstart [--runtime=desktop] [--state-dir=/abs/path]\n codexuse account-pool enable\n codexuse account-pool disable\n codexuse account-pool routing <least-used|round-robin>\n\n codexuse account-pool profiles list\n codexuse account-pool profiles set <name> [more...]\n codexuse account-pool profiles add <name> [more...]\n codexuse account-pool profiles remove <name> [more...]\n codexuse account-pool profiles reset\n\n codexuse account-pool models list\n codexuse account-pool models add <model> [more...]\n codexuse account-pool models remove <model> [more...]\n codexuse account-pool models reset\n\n codexuse account-pool reasoning list\n codexuse account-pool reasoning add <effort> [more...]\n codexuse account-pool reasoning remove <effort> [more...]\n codexuse account-pool reasoning reset\n\n codexuse account-pool fast-mode list\n codexuse account-pool fast-mode add <effort> [more...]\n codexuse account-pool fast-mode remove <effort> [more...]\n codexuse account-pool fast-mode reset\n\n codexuse account-pool keys list [--runtime=desktop] [--state-dir=/abs/path]\n codexuse account-pool keys create [--runtime=desktop] [--state-dir=/abs/path]\n codexuse account-pool keys revoke <id> [--runtime=desktop] [--state-dir=/abs/path]\n\n codexuse account-pool sessions list [--runtime=desktop] [--state-dir=/abs/path]\n\nNotes:\n - Settings are shared with the desktop app.\n - Keys and sessions belong to the desktop app runtime store.\n - Session inspection is read-only here on purpose; pooled sessions are live runtime state.\n - Use --runtime=desktop (default) to inspect the desktop app store.\n`);\n}\n\nfunction normalizeSessionStatus(value: unknown): AccountPoolSessionStatus {\n return value === \"running\" || value === \"error\" || value === \"rollover_pending\"\n ? value\n : \"idle\";\n}\n\nfunction normalizeApiKeyRecord(id: string, value: unknown): AccountPoolApiKeyRecord | null {\n const record = asRecord(value);\n const tokenHash = asString(record.tokenHash);\n const tokenPreview = asString(record.tokenPreview);\n const createdAt = normalizeIsoString(record.createdAt);\n if (!tokenHash || !tokenPreview || !createdAt) {\n return null;\n }\n return {\n id,\n tokenHash,\n tokenPreview,\n createdAt,\n lastUsedAt: normalizeIsoString(record.lastUsedAt),\n revokedAt: normalizeIsoString(record.revokedAt),\n };\n}\n\nfunction normalizeSessionRecord(id: string, value: unknown): AccountPoolSessionRecord | null {\n const record = asRecord(value);\n const activeSegmentId = asString(record.activeSegmentId);\n const createdAt = normalizeIsoString(record.createdAt);\n const lastUsedAt = normalizeIsoString(record.lastUsedAt);\n if (!activeSegmentId || !createdAt || !lastUsedAt) {\n return null;\n }\n const affinityKind =\n record.affinityKind === \"pool_session\" || record.affinityKind === \"prompt_cache\"\n ? record.affinityKind\n : \"ephemeral\";\n return {\n id,\n affinityKind,\n affinityKey: asString(record.affinityKey),\n activeSegmentId,\n segmentIds: normalizeStringArray(record.segmentIds),\n model: asString(record.model),\n status: normalizeSessionStatus(record.status),\n lastError: asString(record.lastError),\n createdAt,\n lastUsedAt,\n expiresAt: normalizeIsoString(record.expiresAt),\n lastResponseId: asString(record.lastResponseId),\n responseIds: normalizeStringArray(record.responseIds).slice(0, MAX_RESPONSE_IDS_PER_SESSION),\n rolloverCount: asNumber(record.rolloverCount) ?? 0,\n lastRolloverReason: asString(record.lastRolloverReason),\n };\n}\n\nfunction normalizeSegmentRecord(id: string, value: unknown): AccountPoolSegmentRecord | null {\n const record = asRecord(value);\n const sessionId = asString(record.sessionId);\n const profileName = asString(record.profileName);\n const createdAt = normalizeIsoString(record.createdAt);\n const lastUsedAt = normalizeIsoString(record.lastUsedAt);\n if (!sessionId || !profileName || !createdAt || !lastUsedAt) {\n return null;\n }\n return {\n id,\n sessionId,\n profileName,\n createdAt,\n lastUsedAt,\n };\n}\n\nfunction normalizeResponseIndexRecord(value: unknown): AccountPoolResponseIndexRecord | null {\n const record = asRecord(value);\n const sessionId = asString(record.sessionId);\n const segmentId = asString(record.segmentId);\n const createdAt = normalizeIsoString(record.createdAt) ?? new Date(0).toISOString();\n if (!sessionId || !segmentId) {\n return null;\n }\n return { sessionId, segmentId, createdAt };\n}\n\nfunction normalizeAccountPoolStore(value: unknown): AccountPoolStore {\n const record = asRecord(value);\n const apiKeysById: Record<string, AccountPoolApiKeyRecord> = {};\n for (const [id, apiKeyValue] of Object.entries(asRecord(record.apiKeysById))) {\n const normalized = normalizeApiKeyRecord(id, apiKeyValue);\n if (normalized) {\n apiKeysById[id] = normalized;\n }\n }\n const sessionsById: Record<string, AccountPoolSessionRecord> = {};\n for (const [id, sessionValue] of Object.entries(asRecord(record.sessionsById))) {\n const normalized = normalizeSessionRecord(id, sessionValue);\n if (normalized) {\n sessionsById[id] = normalized;\n }\n }\n const segmentsById: Record<string, AccountPoolSegmentRecord> = {};\n for (const [id, segmentValue] of Object.entries(asRecord(record.segmentsById))) {\n const normalized = normalizeSegmentRecord(id, segmentValue);\n if (normalized) {\n segmentsById[id] = normalized;\n }\n }\n const responseIndex: Record<string, AccountPoolResponseIndexRecord> = {};\n for (const [responseId, responseValue] of Object.entries(asRecord(record.responseIndex))) {\n const normalized = normalizeResponseIndexRecord(responseValue);\n if (normalized) {\n responseIndex[responseId] = normalized;\n }\n }\n return {\n version: asNumber(record.version) ?? ACCOUNT_POOL_STORE_VERSION,\n roundRobinCursor: asNumber(record.roundRobinCursor) ?? 0,\n apiKeysById,\n sessionsById,\n segmentsById,\n responseIndex,\n };\n}\n\nfunction createDefaultStore(): AccountPoolStore {\n return {\n version: ACCOUNT_POOL_STORE_VERSION,\n roundRobinCursor: 0,\n apiKeysById: {},\n sessionsById: {},\n segmentsById: {},\n responseIndex: {},\n };\n}\n\nfunction deleteSessionFromStore(store: AccountPoolStore, sessionId: string): void {\n const session = store.sessionsById[sessionId];\n if (!session) {\n return;\n }\n for (const segmentId of session.segmentIds) {\n delete store.segmentsById[segmentId];\n }\n for (const [responseId, response] of Object.entries(store.responseIndex)) {\n if (response.sessionId === sessionId) {\n delete store.responseIndex[responseId];\n }\n }\n delete store.sessionsById[sessionId];\n}\n\nfunction pruneStore(store: AccountPoolStore): AccountPoolStore {\n const now = Date.now();\n for (const [sessionId, session] of Object.entries(store.sessionsById)) {\n const expiresAtMs = session.expiresAt ? Date.parse(session.expiresAt) : Number.NaN;\n if (Number.isFinite(expiresAtMs) && expiresAtMs < now) {\n deleteSessionFromStore(store, sessionId);\n }\n }\n for (const [segmentId, segment] of Object.entries(store.segmentsById)) {\n if (!store.sessionsById[segment.sessionId]) {\n delete store.segmentsById[segmentId];\n }\n }\n for (const [responseId, response] of Object.entries(store.responseIndex)) {\n if (!store.sessionsById[response.sessionId] || !store.segmentsById[response.segmentId]) {\n delete store.responseIndex[responseId];\n }\n }\n return store;\n}\n\nfunction resolveAccountPoolDbPath(stateDir: string): string {\n return path.join(stateDir, \"state.sqlite\");\n}\n\nasync function readStore(stateDir: string): Promise<AccountPoolStore> {\n const dbPath = resolveAccountPoolDbPath(stateDir);\n const store = await readDocument<AccountPoolStore>(\n dbPath,\n ACCOUNT_POOL_DOCUMENT,\n normalizeAccountPoolStore,\n );\n if (store) {\n return pruneStore(store);\n }\n return createDefaultStore();\n}\n\nasync function updateStore(\n stateDir: string,\n mutate: (store: AccountPoolStore) => void,\n): Promise<AccountPoolStore> {\n const dbPath = resolveAccountPoolDbPath(stateDir);\n return updateDocument<AccountPoolStore>({\n dbPath,\n namespace: ACCOUNT_POOL_DOCUMENT,\n normalize: normalizeAccountPoolStore,\n fallback: createDefaultStore,\n transform: (current) => {\n const next = pruneStore(current);\n mutate(next);\n return pruneStore(next);\n },\n });\n}\n\nfunction accountPoolApiKeyView(record: AccountPoolApiKeyRecord): AccountPoolApiKeyView {\n return {\n id: record.id,\n tokenPreview: record.tokenPreview,\n createdAt: record.createdAt,\n lastUsedAt: record.lastUsedAt,\n revokedAt: record.revokedAt,\n };\n}\n\nasync function listApiKeys(stateDir: string): Promise<AccountPoolApiKeyView[]> {\n const store = await readStore(stateDir);\n return Object.values(store.apiKeysById)\n .filter((key) => key.revokedAt === null)\n .sort((left, right) => right.createdAt.localeCompare(left.createdAt))\n .map(accountPoolApiKeyView);\n}\n\nfunction hashToken(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nasync function createApiKey(stateDir: string): Promise<AccountPoolApiKeyCreateResult> {\n const plaintextToken = `cux_pool_${randomBytes(24).toString(\"hex\")}`;\n const now = new Date().toISOString();\n const keyRecord: AccountPoolApiKeyRecord = {\n id: randomUUID(),\n tokenHash: hashToken(plaintextToken),\n tokenPreview: `${plaintextToken.slice(0, 8)}...${plaintextToken.slice(-6)}`,\n createdAt: now,\n lastUsedAt: null,\n revokedAt: null,\n };\n await updateStore(stateDir, (store) => {\n store.apiKeysById[keyRecord.id] = keyRecord;\n });\n return {\n key: accountPoolApiKeyView(keyRecord),\n plaintextToken,\n };\n}\n\nasync function revokeApiKey(stateDir: string, id: string): Promise<boolean> {\n let revoked = false;\n await updateStore(stateDir, (store) => {\n const existing = store.apiKeysById[id];\n if (!existing || existing.revokedAt !== null) {\n return;\n }\n existing.revokedAt = new Date().toISOString();\n revoked = true;\n });\n return revoked;\n}\n\nasync function listSessions(stateDir: string): Promise<AccountPoolSessionView[]> {\n const store = await readStore(stateDir);\n return Object.values(store.sessionsById)\n .sort((left, right) => right.lastUsedAt.localeCompare(left.lastUsedAt))\n .flatMap((session) => {\n const activeSegment = store.segmentsById[session.activeSegmentId];\n if (!activeSegment) {\n return [];\n }\n return [{\n id: session.id,\n affinityKind: session.affinityKind,\n affinityKey: session.affinityKey,\n activeProfileName: activeSegment.profileName,\n model: session.model,\n status: session.status,\n lastError: session.lastError,\n createdAt: session.createdAt,\n lastUsedAt: session.lastUsedAt,\n expiresAt: session.expiresAt,\n lastResponseId: session.lastResponseId,\n responseCount: session.responseIds.length,\n segmentCount: session.segmentIds.length,\n rolloverCount: session.rolloverCount,\n lastRolloverReason: session.lastRolloverReason,\n }];\n });\n}\n\nfunction resolveRuntimeStateDir(\n runtime: AccountPoolRuntime,\n explicitStateDir: string | null,\n): string {\n if (explicitStateDir) {\n return path.resolve(explicitStateDir);\n }\n return path.join(getUserDataDir(), DESKTOP_RPC_STATE_DIR);\n}\n\nfunction resolveStateDir(flags: string[]): { runtime: AccountPoolRuntime; stateDir: string } {\n const runtimeFlag = parseStringFlag(flags, \"--runtime\")?.trim().toLowerCase();\n if (runtimeFlag && runtimeFlag !== \"desktop\") {\n throw new Error(\"Only --runtime=desktop is supported.\");\n }\n const runtime: AccountPoolRuntime = \"desktop\";\n const explicitStateDir =\n parseStringFlag(flags, \"--state-dir\")\n ?? parseStringFlag(flags, \"--state\")\n ?? null;\n return {\n runtime,\n stateDir: resolveRuntimeStateDir(runtime, explicitStateDir),\n };\n}\n\nfunction resolveBaseUrlFromPort(runtime: AccountPoolRuntime, port: number | null): string | null {\n void runtime;\n void port;\n return null;\n}\n\nfunction resolveBaseUrl(runtime: AccountPoolRuntime, flags: string[]): string | null {\n void flags;\n return resolveBaseUrlFromPort(runtime, null);\n}\n\nexport async function readAccountPoolRuntimeSummary(input: {\n runtime?: AccountPoolRuntime;\n stateDir?: string | null;\n port?: number | null;\n} = {}): Promise<AccountPoolRuntimeSummary> {\n const runtime = input.runtime ?? \"desktop\";\n const stateDir = resolveRuntimeStateDir(runtime, input.stateDir ?? null);\n const [license, { normalized }, apiKeys, sessions] = await Promise.all([\n licenseService.getStatus().catch(() => null),\n readSettingsSnapshot(),\n listApiKeys(stateDir),\n listSessions(stateDir),\n ]);\n return {\n runtime,\n stateDir,\n baseUrl: resolveBaseUrlFromPort(runtime, input.port ?? null),\n enabled: normalized.accountPoolEnabled,\n hasProLicense: license?.isPro === true,\n routingStrategy: normalized.accountPoolRoutingStrategy,\n activeApiKeyCount: apiKeys.length,\n activeSessionCount: sessions.length,\n };\n}\n\nasync function readSettingsSnapshot(): Promise<{\n raw: JsonRecord;\n normalized: AccountPoolSettings;\n}> {\n const raw = asRecord(await readAppSettings());\n return {\n raw,\n normalized: normalizeAccountPoolSettings(raw),\n };\n}\n\nasync function updateSettings(\n transform: (current: AccountPoolSettings) => AccountPoolSettings,\n): Promise<{\n settings: AccountPoolSettings;\n forcedDisabledByLicense: boolean;\n}> {\n const { raw, normalized } = await readSettingsSnapshot();\n const nextSettings = transform(normalized);\n const license = await licenseService.getStatus().catch(() => null);\n const forcedDisabledByLicense = !license?.isPro && nextSettings.accountPoolEnabled === true;\n const sanitizedSettings: AccountPoolSettings = {\n ...nextSettings,\n accountPoolEnabled: forcedDisabledByLicense ? false : nextSettings.accountPoolEnabled,\n accountPoolRoutingStrategy: normalizeRoutingStrategy(nextSettings.accountPoolRoutingStrategy),\n accountPoolProfilePool: normalizeStringArray(nextSettings.accountPoolProfilePool),\n accountPoolExposedModels: normalizeAccountPoolExposedModels(\n nextSettings.accountPoolExposedModels,\n true,\n ),\n accountPoolExposedReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n nextSettings.accountPoolExposedReasoningEfforts,\n null,\n ),\n accountPoolExposedFastModeReasoningEfforts: normalizeAccountPoolReasoningEfforts(\n nextSettings.accountPoolExposedFastModeReasoningEfforts,\n null,\n ),\n };\n await writeAppSettings(applyAccountPoolSettings(raw, sanitizedSettings));\n return {\n settings: sanitizedSettings,\n forcedDisabledByLicense,\n };\n}\n\nasync function requireProAccess(): Promise<void> {\n const license = await licenseService.getStatus();\n if (!license.isPro) {\n throw new Error(ACCOUNT_POOL_PRO_REQUIRED_MESSAGE);\n }\n}\n\nasync function listSavedProfiles() {\n const manager = new ProfileManager();\n return manager.listProfiles();\n}\n\nfunction printStringList(label: string, values: string[]): void {\n console.log(`${label}: ${values.length > 0 ? values.join(\", \") : \"(none)\"}`);\n}\n\nfunction printSessionRow(session: AccountPoolSessionView): void {\n const fields = [\n `id=${session.id}`,\n `profile=${session.activeProfileName}`,\n `status=${session.status}`,\n `model=${session.model ?? \"-\"}`,\n `responses=${session.responseCount}`,\n `segments=${session.segmentCount}`,\n ];\n if (session.lastResponseId) {\n fields.push(`lastResponse=${session.lastResponseId}`);\n }\n if (session.lastRolloverReason) {\n fields.push(`rollover=${session.lastRolloverReason}`);\n }\n console.log(fields.join(\" \"));\n}\n\nfunction printApiKeyRow(apiKey: AccountPoolApiKeyView): void {\n const fields = [\n `id=${apiKey.id}`,\n `preview=${apiKey.tokenPreview}`,\n `created=${apiKey.createdAt}`,\n ];\n if (apiKey.lastUsedAt) {\n fields.push(`lastUsed=${apiKey.lastUsedAt}`);\n }\n console.log(fields.join(\" \"));\n}\n\nfunction getArrayValues(params: string[], startIndex: number): string[] {\n return params.slice(startIndex).map((value) => value.trim()).filter(Boolean);\n}\n\nasync function handleStatus(flags: string[]): Promise<void> {\n const license = await licenseService.getStatus().catch(() => null);\n const { normalized } = await readSettingsSnapshot();\n const { runtime, stateDir } = resolveStateDir(flags);\n const baseUrl = resolveBaseUrl(runtime, flags);\n const [profiles, apiKeys, sessions] = await Promise.all([\n listSavedProfiles(),\n listApiKeys(stateDir),\n listSessions(stateDir),\n ]);\n const explicitSelection = normalized.accountPoolProfilePool;\n const selectedProfiles =\n explicitSelection.length > 0\n ? explicitSelection\n : profiles.map((profile) => profile.name);\n const missingSelectedProfiles = explicitSelection.filter(\n (profileName) => !profiles.some((profile) => profile.name === profileName),\n );\n\n console.log(`License: ${license ? `${license.tier} (${license.state})` : \"unknown\"}`);\n console.log(`Enabled: ${normalized.accountPoolEnabled ? \"yes\" : \"no\"}`);\n console.log(`Runtime: ${runtime}`);\n console.log(`State dir: ${stateDir}`);\n console.log(`Routing: ${formatRoutingStrategy(normalized.accountPoolRoutingStrategy)}`);\n console.log(`Public API ready: ${normalized.accountPoolEnabled && license?.isPro === true && apiKeys.length > 0 ? \"yes\" : \"no\"}`);\n console.log(`API keys: ${apiKeys.length}`);\n console.log(`Sessions: ${sessions.length}`);\n console.log(`Selection mode: ${explicitSelection.length > 0 ? \"explicit\" : \"all saved profiles\"}`);\n if (baseUrl) {\n console.log(`Base URL: ${baseUrl}`);\n } else {\n console.log(\"Base URL: check the running desktop app for the current Accounts Pool URL.\");\n }\n printStringList(\"Selected profiles\", selectedProfiles);\n if (missingSelectedProfiles.length > 0) {\n printStringList(\"Missing configured profiles\", missingSelectedProfiles);\n }\n printStringList(\"Published models\", normalized.accountPoolExposedModels);\n printStringList(\"Reasoning aliases\", normalized.accountPoolExposedReasoningEfforts);\n printStringList(\"Fast-mode aliases\", normalized.accountPoolExposedFastModeReasoningEfforts);\n if (normalized.accountPoolEnabled && license?.isPro !== true) {\n console.log(ACCOUNT_POOL_PRO_REQUIRED_MESSAGE);\n }\n}\n\nasync function handleEnable(): Promise<void> {\n await requireProAccess();\n const result = await updateSettings((current) => ({\n ...current,\n accountPoolEnabled: true,\n }));\n console.log(result.settings.accountPoolEnabled ? \"Accounts Pool enabled.\" : \"Accounts Pool is disabled.\");\n}\n\nasync function handleDisable(): Promise<void> {\n const result = await updateSettings((current) => ({\n ...current,\n accountPoolEnabled: false,\n }));\n console.log(result.settings.accountPoolEnabled ? \"Accounts Pool is enabled.\" : \"Accounts Pool disabled.\");\n}\n\nasync function handleRouting(params: string[]): Promise<void> {\n const value = parseRoutingStrategy(params[1]);\n if (!value) {\n throw new Error(\"Routing strategy must be `least-used` or `round-robin`.\");\n }\n const result = await updateSettings((current) => ({\n ...current,\n accountPoolRoutingStrategy: value,\n }));\n console.log(`Accounts Pool routing set to ${formatRoutingStrategy(result.settings.accountPoolRoutingStrategy)}.`);\n}\n\nasync function handleProfiles(params: string[]): Promise<void> {\n const action = params[1];\n const profiles = await listSavedProfiles();\n const availableProfileNames = profiles.map((profile) => profile.name);\n const availableSet = new Set(availableProfileNames);\n const { normalized } = await readSettingsSnapshot();\n\n if (!action || action === \"list\") {\n const explicitSelection = normalized.accountPoolProfilePool;\n if (explicitSelection.length === 0) {\n console.log(\"Selection: all saved profiles\");\n } else {\n printStringList(\"Explicitly selected profiles\", explicitSelection);\n }\n for (const profile of profiles) {\n const selected = explicitSelection.length === 0 || explicitSelection.includes(profile.name);\n const invalidSuffix = profile.isValid ? \"\" : \" [needs re-auth]\";\n console.log(`${selected ? \"*\" : \"-\"} ${profile.name}${invalidSuffix}`);\n }\n const missing = explicitSelection.filter((name) => !availableSet.has(name));\n if (missing.length > 0) {\n printStringList(\"Missing configured profiles\", missing);\n }\n return;\n }\n\n const names = getArrayValues(params, 2);\n if ((action === \"set\" || action === \"add\" || action === \"remove\") && names.length === 0) {\n throw new Error(`Profile names are required for \\`${action}\\`.`);\n }\n for (const name of names) {\n if (!availableSet.has(name)) {\n throw new Error(`Unknown profile: ${name}`);\n }\n }\n\n const result = await updateSettings((current) => {\n const currentSelection =\n current.accountPoolProfilePool.length > 0\n ? current.accountPoolProfilePool.slice()\n : availableProfileNames.slice();\n let nextSelection: string[];\n switch (action) {\n case \"set\":\n nextSelection = names.slice();\n break;\n case \"add\":\n nextSelection = Array.from(new Set([...currentSelection, ...names]));\n break;\n case \"remove\":\n nextSelection = currentSelection.filter((name) => !names.includes(name));\n break;\n case \"reset\":\n nextSelection = [];\n break;\n default:\n throw new Error(\"Unknown profiles action.\");\n }\n return {\n ...current,\n accountPoolProfilePool:\n action === \"reset\" || nextSelection.length === availableProfileNames.length\n ? []\n : nextSelection,\n };\n });\n\n if (result.settings.accountPoolProfilePool.length === 0) {\n console.log(\"Accounts Pool now uses all saved profiles.\");\n return;\n }\n printStringList(\"Accounts Pool selected profiles\", result.settings.accountPoolProfilePool);\n}\n\ntype ArraySettingKey =\n | \"accountPoolExposedModels\"\n | \"accountPoolExposedReasoningEfforts\"\n | \"accountPoolExposedFastModeReasoningEfforts\";\n\nasync function handleArraySetting(input: {\n label: string;\n actionName: string;\n params: string[];\n key: ArraySettingKey;\n defaultValues: readonly string[];\n normalizeValue: (value: string) => string | null;\n}): Promise<void> {\n const action = input.params[1];\n const { normalized } = await readSettingsSnapshot();\n const currentValues = normalized[input.key];\n\n if (!action || action === \"list\") {\n printStringList(input.label, currentValues);\n return;\n }\n\n const rawValues = getArrayValues(input.params, 2);\n if ((action === \"add\" || action === \"remove\") && rawValues.length === 0) {\n throw new Error(`Values are required for \\`${input.actionName} ${action}\\`.`);\n }\n const normalizedValues = rawValues.map(input.normalizeValue).filter((value): value is string => Boolean(value));\n if ((action === \"add\" || action === \"remove\") && normalizedValues.length === 0) {\n throw new Error(\"No valid values were provided.\");\n }\n\n const result = await updateSettings((current) => {\n const existing = current[input.key];\n switch (action) {\n case \"add\":\n return {\n ...current,\n [input.key]: Array.from(new Set([...existing, ...normalizedValues])),\n };\n case \"remove\":\n return {\n ...current,\n [input.key]: existing.filter((value) => !normalizedValues.includes(value)),\n };\n case \"reset\":\n return {\n ...current,\n [input.key]: [...input.defaultValues],\n };\n default:\n throw new Error(`Unknown ${input.actionName} action.`);\n }\n });\n\n printStringList(input.label, result.settings[input.key]);\n}\n\nasync function handleKeys(params: string[], flags: string[]): Promise<void> {\n const action = params[1];\n const { runtime, stateDir } = resolveStateDir(flags);\n const baseUrl = resolveBaseUrl(runtime, flags);\n\n if (!action || action === \"list\") {\n const apiKeys = await listApiKeys(stateDir);\n if (apiKeys.length === 0) {\n console.log(\"No active Accounts Pool API keys.\");\n return;\n }\n for (const apiKey of apiKeys) {\n printApiKeyRow(apiKey);\n }\n return;\n }\n\n switch (action) {\n case \"create\": {\n await requireProAccess();\n const created = await createApiKey(stateDir);\n console.log(`Created key: ${created.key.id}`);\n console.log(`Preview: ${created.key.tokenPreview}`);\n console.log(`Token: ${created.plaintextToken}`);\n console.log(`Runtime: ${runtime}`);\n console.log(`State dir: ${stateDir}`);\n if (baseUrl) {\n console.log(`Base URL: ${baseUrl}`);\n } else {\n console.log(\"Base URL: use the current Accounts Pool URL shown by the running desktop app.\");\n }\n console.log(\"This key only works for the selected runtime state dir.\");\n console.log(\"Store this token now. The plaintext value is only shown once.\");\n return;\n }\n case \"revoke\": {\n const id = params[2]?.trim();\n if (!id) {\n throw new Error(\"API key id is required.\");\n }\n const removed = await revokeApiKey(stateDir, id);\n if (!removed) {\n throw new Error(`No Accounts Pool API key found for id ${id}.`);\n }\n console.log(`Revoked key: ${id}`);\n return;\n }\n default:\n throw new Error(\"Unknown keys action.\");\n }\n}\n\nasync function handleSessions(params: string[], flags: string[]): Promise<void> {\n const action = params[1];\n if (action && action !== \"list\") {\n throw new Error(\"Only `sessions list` is supported here. Session mutation stays runtime-owned.\");\n }\n const { stateDir } = resolveStateDir(flags);\n const sessions = await listSessions(stateDir);\n if (sessions.length === 0) {\n console.log(\"No pooled sessions in this runtime store.\");\n return;\n }\n for (const session of sessions) {\n printSessionRow(session);\n }\n console.log(\"Session mutation is intentionally not exposed here; pooled sessions belong to the live runtime owner.\");\n}\n\nasync function handleQuickstart(flags: string[]): Promise<void> {\n const { runtime, stateDir } = resolveStateDir(flags);\n const summary = await readAccountPoolRuntimeSummary({ runtime, stateDir });\n const baseUrl = summary.baseUrl ?? \"<shown-in-desktop-app>\";\n console.log(\"Accounts Pool quickstart\");\n console.log(`Runtime: ${summary.runtime}`);\n console.log(`Enabled: ${summary.enabled ? \"yes\" : \"no\"}`);\n console.log(`Pro: ${summary.hasProLicense ? \"yes\" : \"no\"}`);\n console.log(`API keys: ${summary.activeApiKeyCount}`);\n console.log(`Base URL: ${baseUrl}`);\n console.log(\"\");\n console.log(\"1. Enable pool:\");\n console.log(\" codexuse account-pool enable\");\n console.log(\"2. Create key:\");\n console.log(` codexuse account-pool keys create --runtime=${summary.runtime}`);\n console.log(\"3. Use OpenAI-compatible settings:\");\n console.log(` Base URL: ${baseUrl}/v1`);\n console.log(\" API key: cux_pool_...\");\n console.log(\"4. Verify:\");\n console.log(` curl ${baseUrl}/v1/models -H 'Authorization: Bearer cux_pool_...'`);\n}\n\nexport async function handleAccountPoolCommand(args: string[], version: string): Promise<void> {\n const flags = args.filter((arg) => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printAccountPoolHelp(version);\n return;\n }\n\n switch (sub) {\n case \"status\":\n await handleStatus(flags);\n return;\n case \"quickstart\":\n await handleQuickstart(flags);\n return;\n case \"enable\":\n await handleEnable();\n return;\n case \"disable\":\n await handleDisable();\n return;\n case \"routing\":\n await handleRouting(params);\n return;\n case \"profiles\":\n await handleProfiles(params);\n return;\n case \"models\":\n await handleArraySetting({\n label: \"Published models\",\n actionName: \"models\",\n params,\n key: \"accountPoolExposedModels\",\n defaultValues: DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS,\n normalizeValue: (value) => normalizeCodexModelSlug(value) ?? asString(value),\n });\n return;\n case \"reasoning\":\n await handleArraySetting({\n label: \"Reasoning aliases\",\n actionName: \"reasoning\",\n params,\n key: \"accountPoolExposedReasoningEfforts\",\n defaultValues: DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS,\n normalizeValue: (value) => normalizeReasoningEffort(value),\n });\n return;\n case \"fast-mode\":\n await handleArraySetting({\n label: \"Fast-mode aliases\",\n actionName: \"fast-mode\",\n params,\n key: \"accountPoolExposedFastModeReasoningEfforts\",\n defaultValues: DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS,\n normalizeValue: (value) => normalizeReasoningEffort(value),\n });\n return;\n case \"keys\":\n await handleKeys(params, flags);\n return;\n case \"sessions\":\n await handleSessions(params, flags);\n return;\n default:\n printHelp(version);\n return;\n }\n}\n","export type AccessMode = \"read-only\" | \"current\" | \"full-access\";\nexport type ComposerSendIntent = \"default\" | \"queue\" | \"steer\";\n\nexport type SendMessageResult = {\n status: \"sent\" | \"blocked\" | \"steer_failed\";\n};\n\nexport type AccountPoolRoutingStrategy = \"round_robin\" | \"least_used\";\nexport type RateLimitPercentMode = \"remaining\" | \"used\";\nexport type OfficialCodexRelayMode =\n | \"off\"\n | \"official\"\n | \"responses\"\n | \"chat-completions\";\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS = [\n \"gpt-5.5\",\n \"gpt-5.4\",\n \"gpt-5.4-mini\",\n \"gpt-5.4-nano\",\n] as const;\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_REASONING_EFFORTS = [\n \"none\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n] as const;\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_FAST_MODE_REASONING_EFFORTS = [\n \"xhigh\",\n] as const;\n\nexport function buildAccountPoolVariantModelId(input: {\n modelId: string;\n reasoningEffort: string;\n fastMode?: boolean;\n}): string {\n return [\n input.modelId.trim(),\n input.reasoningEffort.trim().toLowerCase(),\n ...(input.fastMode ? [\"fast\"] : []),\n ].join(\"-\");\n}\n\nexport type AppSettings = {\n codexBin: string | null;\n codexArgs: string | null;\n codexHome: string | null;\n automaticAppUpdateChecksEnabled: boolean;\n keepAppRunningAfterWindowClose: boolean;\n rateLimitPercentMode: RateLimitPercentMode;\n officialCodexWideViewEnabled: boolean;\n officialCodexWideViewMaxWidth: number | null;\n officialCodexScrollRestoreEnabled: boolean;\n officialCodexConversationTimelineEnabled: boolean;\n officialCodexInCodexStatusEnabled: boolean;\n officialCodexHandoffChipEnabled: boolean;\n officialCodexAutoControlEnabled: boolean;\n officialCodexRelayMode: OfficialCodexRelayMode;\n officialCodexRelayProfileId: string | null;\n officialCodexModelWhitelistUnlockEnabled: boolean;\n officialCodexPluginMarketplaceUnlockEnabled: boolean;\n officialCodexForcePluginInstallEnabled: boolean;\n telegramBridgeEnabled: boolean;\n telegramBotToken: string | null;\n telegramAllowedChatIds: string[];\n defaultAccessMode: AccessMode;\n reviewDeliveryMode: \"inline\" | \"detached\";\n lastComposerModelId: string | null;\n lastComposerReasoningEffort: string | null;\n codexCustomModels: string[];\n accountPoolEnabled: boolean;\n accountPoolRoutingStrategy: AccountPoolRoutingStrategy;\n accountPoolProfilePool: string[];\n accountPoolExposedModels: string[];\n accountPoolExposedReasoningEfforts: string[];\n accountPoolExposedFastModeReasoningEfforts: string[];\n};\n\nexport type TelegramBridgeStreamMode = \"draft\" | \"message\" | \"none\";\n\nexport type TelegramBridgeStatus = {\n state: \"running\" | \"stopped\" | \"error\";\n running: boolean;\n botUsername: string | null;\n allowedChats: number;\n activeChats: number;\n streamMode: TelegramBridgeStreamMode;\n lastError: string | null;\n startedAtMs: number | null;\n};\n\nexport type TelegramBridgeTokenTestResult = {\n ok: boolean;\n username: string | null;\n error: string | null;\n};\n\nexport type CodexFeatureStage =\n | \"under_development\"\n | \"beta\"\n | \"stable\"\n | \"deprecated\"\n | \"removed\";\n\nexport type CodexFeature = {\n name: string;\n stage: CodexFeatureStage;\n enabled: boolean;\n defaultEnabled: boolean;\n displayName: string | null;\n description: string | null;\n announcement: string | null;\n};\n\nexport type CodexDoctorResult = {\n ok: boolean;\n codexBin: string | null;\n version: string | null;\n appServerOk: boolean;\n authStatus: \"authenticated\" | \"unauthenticated\" | \"unknown\";\n authMessage: string | null;\n accountLabel: string | null;\n details: string | null;\n path: string | null;\n nodeOk: boolean;\n nodeVersion: string | null;\n nodeDetails: string | null;\n};\n\nexport type CodexModelReasoningEffortOption = {\n reasoningEffort: string;\n description: string;\n};\n\nexport type CodexConnectedModelOption = {\n id: string;\n model: string;\n displayName: string;\n description: string;\n supportedReasoningEfforts: CodexModelReasoningEffortOption[];\n defaultReasoningEffort: string | null;\n isDefault: boolean;\n};\n\nexport type CodexRuntimeInspection = {\n doctor: CodexDoctorResult;\n models: CodexConnectedModelOption[];\n modelsError: string | null;\n};\n\nexport type CodexUpdateMethod =\n | \"brew_formula\"\n | \"brew_cask\"\n | \"npm\"\n | \"unknown\";\n\nexport type CodexUpdateResult = {\n ok: boolean;\n method: CodexUpdateMethod;\n package: string | null;\n beforeVersion: string | null;\n afterVersion: string | null;\n upgraded: boolean;\n output: string | null;\n details: string | null;\n};\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport type {\n ProfileData,\n ProfileMetadata,\n} from \"@codexuse/contracts/profiles/types\";\nimport type {\n AutoRollActivityEntry,\n OfficialCodexBridgeActivityState,\n OfficialCodexBridgeCapabilitiesPayload,\n OfficialCodexPowerSettingsPayload,\n OfficialCodexPowerStatusPayload,\n OfficialCodexQolSettingsPayload,\n OfficialCodexQolStatusPayload,\n OfficialCodexRelayMode,\n OfficialCodexRelayProfilePayload,\n OfficialCodexRelayStatusPayload,\n OfficialCodexBridgeStatus,\n} from \"@codexuse/contracts/desktop/ipc-types\";\nimport { normalizeAutoRollSettings } from \"@codexuse/contracts/settings/auto-roll\";\nimport {\n readDocumentStrict,\n resolveAppStorageDbPath,\n resetAppStorageInitialization,\n writeDocument,\n} from \"@codexuse/runtime-app-state/storage/documents\";\n\nconst APP_STATE_DOCUMENT = \"desktop.app-state\";\nconst APP_NAME = \"codexuse-desktop\";\n\nexport type LicenseStatusCode = \"inactive\" | \"active\" | \"grace\" | \"error\";\nexport type ReasoningEffort =\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"none\";\n\nexport type ProfileRecordState = {\n name: string;\n displayName: string | null;\n data: ProfileData;\n metadata?: ProfileMetadata;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n email: string | null;\n authMethod: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n};\n\nexport type ProfileDashboardState = {\n customGroupsByAccountKey: Record<string, string>;\n};\n\nexport type OfficialCodexState = {\n lastProfileSwitchAt: number | null;\n lastProfileSwitchProfileKey: string | null;\n lastVerifiedLaunchAt: number | null;\n lastVerifiedLaunchProfileKey: string | null;\n lastObservedPid: number | null;\n lastActivationStatus: string | null;\n lastActivationReason: string | null;\n activity: AutoRollActivityEntry[];\n instancesByProfileName: Record<string, OfficialCodexManagedInstanceState>;\n relayProfilesById: Record<string, OfficialCodexRelayProfilePayload>;\n pendingActivationDebt: OfficialCodexActivationDebtState | null;\n};\n\nexport type OfficialCodexManagedInstanceState = {\n profileName: string;\n profileKey: string | null;\n profileHome: string | null;\n appPath: string | null;\n bundleId: string | null;\n pid: number | null;\n appServerPid: number | null;\n cdpPort: number | null;\n bridgeStatus: OfficialCodexBridgeStatus;\n bridgeLastCheckedAt: number | null;\n bridgeError: string | null;\n bridgeVersion: string | null;\n bridgeRoute: string | null;\n bridgeDevToolsUrl: string | null;\n bridgeCapabilities: OfficialCodexBridgeCapabilitiesPayload | null;\n bridgeActiveThreadId: string | null;\n bridgeActiveThreadTitle: string | null;\n bridgeActiveThreadUpdatedAt: number | null;\n bridgeComposerText: string | null;\n bridgeWorkspacePath: string | null;\n bridgeModel: string | null;\n bridgeActivityState: OfficialCodexBridgeActivityState;\n bridgeQol: OfficialCodexQolStatusPayload | null;\n bridgePower: OfficialCodexPowerStatusPayload | null;\n bridgeRelayStatus: OfficialCodexRelayStatusPayload | null;\n desiredQolSettings?: OfficialCodexQolSettingsPayload | null;\n desiredPowerSettings?: OfficialCodexPowerSettingsPayload | null;\n launchedAt: number | null;\n lastVerifiedAt: number | null;\n lastStatus: string | null;\n lastError: string | null;\n};\n\nexport type OfficialCodexActivationDebtState = {\n targetProfileName: string;\n targetProfileKey: string | null;\n sourceProfileName: string | null;\n sourceProfileKey: string | null;\n decisionId: string | null;\n attempts: number;\n lastReason: string | null;\n};\n\nexport type SkillsInstallState = {\n id: string;\n repo?: string | null;\n repoPath?: string | null;\n sourceLabel?: string | null;\n sourceType?: \"official\" | \"community\" | \"local\";\n viewUrl?: string | null;\n createdAt?: string | null;\n};\n\nexport type SyncState = {\n lastPushAt: string | null;\n lastPullAt: string | null;\n lastError: string | null;\n remoteUpdatedAt: string | null;\n};\n\nexport type AnalyticsState = {\n anonymousId: string | null;\n enabled: boolean;\n lastFlushAt: string | null;\n lastError: string | null;\n};\n\nexport type AppUiState = {\n themeMode: \"light\" | \"dark\" | null;\n layout: {\n sidebarCollapsed: boolean | null;\n };\n profiles: {\n viewMode: \"cards\" | \"compact\" | null;\n sortBy: string | null;\n groupBy: string | null;\n planFilter: string | null;\n healthFilter: string | null;\n customGroupFilter: string | null;\n toolbarOpen: boolean | null;\n collapsedSections: Record<string, boolean>;\n };\n onboarding: {\n welcomeCompleted: boolean;\n welcomeCompletedAt: number | null;\n welcomeResumeStep: 2 | null;\n milestones: {\n firstProfileAdded: boolean;\n secondProfileAdded: boolean;\n };\n sessionCount: number;\n nudgeCooldowns: Record<string, number>;\n nudgeDismissCount: Record<string, number>;\n proUnlockedCelebrated: boolean;\n };\n duplicateWarningDismissedKey: string | null;\n pendingLicenseActivation: boolean;\n};\n\nexport type AppState = {\n schemaVersion: 1;\n autoRoll: {\n enabled: boolean;\n rearmRemainingThreshold: number;\n switchRemainingThreshold: number;\n launchOfficialCodexWhenClosedOnAutoRoll: boolean;\n priorityOrder: string[];\n lowRemainingNotificationEnabled: boolean;\n lowRemainingNotificationThreshold: number;\n };\n officialCodex: OfficialCodexState;\n app: {\n lastAppVersion: string | null;\n pendingUpdateVersion: string | null;\n lastProfileName: string | null;\n };\n license: {\n licenseKey: string | null;\n purchaseEmail: string | null;\n lastVerifiedAt: string | null;\n nextCheckAt: string | null;\n lastVerificationError: string | null;\n status: LicenseStatusCode;\n signature: string | null;\n };\n preferences: {\n excludeFolders: string[];\n enableTaskCompleteBeep: boolean;\n preventSleepDuringTasks: boolean;\n systemNotificationsEnabled: boolean;\n subagentSystemNotificationsEnabled: boolean;\n folderHistory: Array<{ path: string; name: string; lastVisited: number }>;\n pinnedPaths: string[];\n };\n runtimeSettings: Record<string, unknown>;\n ui: AppUiState;\n profileDashboard: ProfileDashboardState;\n skills: {\n sources: Array<{\n id: string;\n repo: string;\n label: string;\n branch?: string | null;\n url?: string | null;\n official?: boolean;\n compatibilityNote?: string | null;\n priority?: number;\n }>;\n installsBySlug: Record<string, SkillsInstallState>;\n };\n sync: SyncState;\n analytics: AnalyticsState;\n profilesByName: Record<string, ProfileRecordState>;\n};\n\nexport type AppStatePatch = DeepPartial<AppState>;\ntype AppStateUpdateMode = \"replace\" | \"patch\";\ntype AppStateUpdateOptions = {\n mode?: AppStateUpdateMode;\n cloneCurrent?: boolean;\n normalize?: boolean;\n};\ntype AppStateUpdateTransform = (current: AppState) => AppState | AppStatePatch;\n\ntype DeepPartial<T> = {\n [K in keyof T]?: T[K] extends Array<infer U>\n ? U[]\n : T[K] extends object\n ? DeepPartial<T[K]>\n : T[K];\n};\n\nlet configuredUserDataDir: string | null = null;\nlet appStateCache: AppState | null = null;\nlet writeLock: Promise<void> = Promise.resolve();\nconst writeLockContext = new AsyncLocalStorage<boolean>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction clone<T>(value: T): T {\n if (value === null || value === undefined || typeof value !== \"object\") {\n return value;\n }\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction freezeDeep<T>(value: T, seen = new WeakSet<object>()): T {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n const objectValue = value as object;\n if (seen.has(objectValue)) {\n return value;\n }\n seen.add(objectValue);\n for (const child of Object.values(objectValue)) {\n freezeDeep(child, seen);\n }\n return Object.freeze(value);\n}\n\nfunction resolveDefaultUserDataDir(): string {\n const home = process.env.HOME || os.homedir();\n if (!home) {\n throw new Error(\"Unable to resolve home directory for app state.\");\n }\n\n return path.join(home, \"Library\", \"Application Support\", APP_NAME);\n}\n\nexport function getUserDataDir(): string {\n return configuredUserDataDir ?? resolveDefaultUserDataDir();\n}\n\nfunction resolveStorageDbPath(): string {\n return resolveAppStorageDbPath(getUserDataDir());\n}\n\nfunction createDefaultAppState(): AppState {\n return {\n schemaVersion: 1,\n autoRoll: {\n enabled: false,\n rearmRemainingThreshold: 15,\n switchRemainingThreshold: 5,\n launchOfficialCodexWhenClosedOnAutoRoll: false,\n priorityOrder: [],\n lowRemainingNotificationEnabled: false,\n lowRemainingNotificationThreshold: 1,\n },\n officialCodex: {\n lastProfileSwitchAt: null,\n lastProfileSwitchProfileKey: null,\n lastVerifiedLaunchAt: null,\n lastVerifiedLaunchProfileKey: null,\n lastObservedPid: null,\n lastActivationStatus: null,\n lastActivationReason: null,\n activity: [],\n instancesByProfileName: {},\n relayProfilesById: {},\n pendingActivationDebt: null,\n },\n app: {\n lastAppVersion: null,\n pendingUpdateVersion: null,\n lastProfileName: null,\n },\n license: {\n licenseKey: null,\n purchaseEmail: null,\n lastVerifiedAt: null,\n nextCheckAt: null,\n lastVerificationError: null,\n status: \"inactive\",\n signature: null,\n },\n preferences: {\n excludeFolders: [],\n enableTaskCompleteBeep: true,\n preventSleepDuringTasks: true,\n systemNotificationsEnabled: true,\n subagentSystemNotificationsEnabled: true,\n folderHistory: [],\n pinnedPaths: [],\n },\n runtimeSettings: {},\n ui: {\n themeMode: null,\n layout: {\n sidebarCollapsed: null,\n },\n profiles: {\n viewMode: null,\n sortBy: null,\n groupBy: null,\n planFilter: null,\n healthFilter: null,\n customGroupFilter: null,\n toolbarOpen: null,\n collapsedSections: {},\n },\n onboarding: {\n welcomeCompleted: false,\n welcomeCompletedAt: null,\n welcomeResumeStep: null,\n milestones: {\n firstProfileAdded: false,\n secondProfileAdded: false,\n },\n sessionCount: 0,\n nudgeCooldowns: {},\n nudgeDismissCount: {},\n proUnlockedCelebrated: false,\n },\n duplicateWarningDismissedKey: null,\n pendingLicenseActivation: false,\n },\n profileDashboard: {\n customGroupsByAccountKey: {},\n },\n skills: {\n sources: [],\n installsBySlug: {},\n },\n sync: {\n lastPushAt: null,\n lastPullAt: null,\n lastError: null,\n remoteUpdatedAt: null,\n },\n analytics: {\n anonymousId: null,\n enabled: true,\n lastFlushAt: null,\n lastError: null,\n },\n profilesByName: {},\n };\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction asBooleanOrNull(value: unknown): boolean | null {\n return typeof value === \"boolean\" ? value : null;\n}\n\nfunction asOfficialCodexBridgeStatus(\n value: unknown,\n): OfficialCodexBridgeStatus {\n return value === \"unattached\" ||\n value === \"healthy\" ||\n value === \"unhealthy\"\n ? value\n : \"not-configured\";\n}\n\nfunction asOfficialCodexBridgeActivityState(\n value: unknown,\n): OfficialCodexBridgeActivityState {\n return value === \"idle\" || value === \"generating\" ? value : \"unknown\";\n}\n\nfunction asOfficialCodexRelayMode(value: unknown): OfficialCodexRelayMode {\n return value === \"official\" ||\n value === \"responses\" ||\n value === \"chat-completions\"\n ? value\n : \"off\";\n}\n\nfunction normalizeOfficialCodexQolSettings(\n value: unknown,\n): OfficialCodexQolSettingsPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n const actionTargets = Array.isArray(value.actionTargets)\n ? value.actionTargets\n .map((item) => {\n if (!isRecord(item)) {\n return null;\n }\n const profileKey =\n typeof item.profileKey === \"string\"\n ? item.profileKey.trim().slice(0, 200)\n : \"\";\n if (!profileKey) return null;\n return {\n profileKey,\n label:\n typeof item.label === \"string\" && item.label.trim()\n ? item.label.trim().slice(0, 80)\n : \"Account\",\n detail:\n typeof item.detail === \"string\" && item.detail.trim()\n ? item.detail.trim().slice(0, 120)\n : null,\n current: item.current === true,\n eligible: item.eligible !== false,\n };\n })\n .filter((item): item is NonNullable<typeof item> => Boolean(item))\n .slice(0, 8)\n : [];\n return {\n wideViewEnabled: value.wideViewEnabled === true,\n wideViewMaxWidth:\n typeof value.wideViewMaxWidth === \"number\" &&\n Number.isFinite(value.wideViewMaxWidth)\n ? Math.max(640, Math.min(2400, value.wideViewMaxWidth))\n : null,\n scrollRestoreEnabled: value.scrollRestoreEnabled === true,\n conversationTimelineEnabled: value.conversationTimelineEnabled === true,\n inCodexStatusEnabled: value.inCodexStatusEnabled !== false,\n handoffChipEnabled: value.handoffChipEnabled !== false,\n actionTargets,\n overlayAutoRollEnabled:\n typeof value.overlayAutoRollEnabled === \"boolean\"\n ? value.overlayAutoRollEnabled\n : null,\n };\n}\n\nfunction normalizeOfficialCodexPowerSettings(\n value: unknown,\n): OfficialCodexPowerSettingsPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n const relayMode = asOfficialCodexRelayMode(value.relayMode);\n const relayProfileId = normalizeOfficialCodexRelayProfileId(\n value.relayProfileId,\n );\n return {\n relayMode,\n relayProfileId:\n relayMode === \"responses\" || relayMode === \"chat-completions\"\n ? relayProfileId\n : null,\n modelWhitelistUnlockEnabled: value.modelWhitelistUnlockEnabled === true,\n pluginMarketplaceUnlockEnabled:\n value.pluginMarketplaceUnlockEnabled === true,\n forcePluginInstallEnabled: value.forcePluginInstallEnabled === true,\n };\n}\n\nfunction normalizeOfficialCodexBridgeCapabilities(\n value: unknown,\n): OfficialCodexBridgeCapabilitiesPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n return {\n health: value.health === true,\n snapshot: value.snapshot === true,\n draft: value.draft === true,\n qol: value.qol === true,\n power: value.power === true,\n modelWhitelist: value.modelWhitelist === true,\n pluginMarketplace: value.pluginMarketplace === true,\n forcePluginInstall: value.forcePluginInstall === true,\n };\n}\n\nfunction normalizeOfficialCodexFeatureStatus(\n value: unknown,\n): OfficialCodexQolStatusPayload[\"wideView\"] | null {\n if (!isRecord(value)) {\n return null;\n }\n const status =\n value.status === \"applied\" || value.status === \"disabled\"\n ? value.status\n : \"degraded\";\n return {\n enabled: value.enabled === true,\n applied: value.applied === true,\n status,\n version: asString(value.version),\n error: asString(value.error),\n };\n}\n\nfunction normalizeOfficialCodexQolStatus(\n value: unknown,\n): OfficialCodexQolStatusPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n const wideView = normalizeOfficialCodexFeatureStatus(value.wideView);\n const scrollRestore = normalizeOfficialCodexFeatureStatus(value.scrollRestore);\n const conversationTimeline = normalizeOfficialCodexFeatureStatus(\n value.conversationTimeline,\n );\n const inCodexStatus = normalizeOfficialCodexFeatureStatus(value.inCodexStatus);\n if (!wideView || !scrollRestore || !conversationTimeline || !inCodexStatus) {\n return null;\n }\n return {\n wideView,\n scrollRestore,\n conversationTimeline,\n inCodexStatus,\n appliedAt: asString(value.appliedAt),\n };\n}\n\nfunction normalizeOfficialCodexRelayStatus(\n value: unknown,\n): OfficialCodexRelayStatusPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n const mode =\n value.mode === \"official\" ||\n value.mode === \"responses\" ||\n value.mode === \"chat-completions\"\n ? value.mode\n : \"off\";\n const status =\n value.status === \"configured\" ||\n value.status === \"missing-key\" ||\n value.status === \"degraded\"\n ? value.status\n : \"off\";\n const profileId = normalizeOfficialCodexRelayProfileId(value.profileId);\n return {\n mode,\n profileId:\n mode === \"responses\" || mode === \"chat-completions\" ? profileId : null,\n status,\n error: asString(value.error),\n };\n}\n\nfunction normalizeOfficialCodexRelayProfileId(value: unknown): string | null {\n const id = asString(value);\n return id && /^[A-Za-z0-9][A-Za-z0-9_-]{2,79}$/.test(id) ? id : null;\n}\n\nfunction normalizeOfficialCodexRelayProfile(\n value: unknown,\n): OfficialCodexRelayProfilePayload | null {\n if (!isRecord(value)) {\n return null;\n }\n const id = normalizeOfficialCodexRelayProfileId(value.id);\n const name = asString(value.name);\n const baseUrl = asString(value.baseUrl);\n if (!id || !name || !baseUrl) {\n return null;\n }\n return {\n id,\n name,\n baseUrl,\n protocol:\n value.protocol === \"chat-completions\" ? \"chat-completions\" : \"responses\",\n model: asString(value.model),\n hasApiKey: value.hasApiKey === true,\n createdAt: asString(value.createdAt),\n updatedAt: asString(value.updatedAt),\n lastTestAt: asString(value.lastTestAt),\n lastTestStatus:\n value.lastTestStatus === \"ok\" || value.lastTestStatus === \"failed\"\n ? value.lastTestStatus\n : null,\n lastTestHttpStatus: asNumberOrNull(value.lastTestHttpStatus),\n lastTestError: asString(value.lastTestError),\n };\n}\n\nfunction normalizeOfficialCodexPowerStatus(\n value: unknown,\n): OfficialCodexPowerStatusPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n const modelWhitelistUnlock = normalizeOfficialCodexFeatureStatus(\n value.modelWhitelistUnlock,\n );\n const pluginMarketplaceUnlock = normalizeOfficialCodexFeatureStatus(\n value.pluginMarketplaceUnlock,\n );\n const forcePluginInstall = normalizeOfficialCodexFeatureStatus(\n value.forcePluginInstall,\n );\n const relay = normalizeOfficialCodexRelayStatus(value.relay);\n if (\n !modelWhitelistUnlock ||\n !pluginMarketplaceUnlock ||\n !forcePluginInstall ||\n !relay\n ) {\n return null;\n }\n return {\n modelWhitelistUnlock,\n pluginMarketplaceUnlock,\n forcePluginInstall,\n relay,\n appliedAt: asString(value.appliedAt),\n };\n}\n\nfunction normalizeAppState(raw: unknown): AppState {\n const defaults = createDefaultAppState();\n if (!isRecord(raw)) {\n return defaults;\n }\n\n const rawAutoRoll = isRecord(raw.autoRoll) ? raw.autoRoll : undefined;\n const next = deepMerge(defaults, raw as AppStatePatch);\n const merged = next;\n\n merged.schemaVersion = 1;\n merged.autoRoll = normalizeAutoRollSettings(rawAutoRoll);\n if (!isRecord(merged.officialCodex)) {\n merged.officialCodex = clone(defaults.officialCodex);\n }\n merged.officialCodex.lastProfileSwitchAt = asNumberOrNull(\n merged.officialCodex.lastProfileSwitchAt,\n );\n merged.officialCodex.lastProfileSwitchProfileKey = asString(\n merged.officialCodex.lastProfileSwitchProfileKey,\n );\n merged.officialCodex.lastVerifiedLaunchAt = asNumberOrNull(\n merged.officialCodex.lastVerifiedLaunchAt,\n );\n merged.officialCodex.lastVerifiedLaunchProfileKey = asString(\n merged.officialCodex.lastVerifiedLaunchProfileKey,\n );\n merged.officialCodex.lastObservedPid = asNumberOrNull(\n merged.officialCodex.lastObservedPid,\n );\n merged.officialCodex.lastActivationStatus =\n asString(merged.officialCodex.lastActivationStatus);\n merged.officialCodex.lastActivationReason =\n asString(merged.officialCodex.lastActivationReason);\n merged.officialCodex.activity = Array.isArray(merged.officialCodex.activity)\n ? merged.officialCodex.activity\n .filter((entry): entry is AutoRollActivityEntry => isRecord(entry))\n .map((entry) => ({\n id: asString(entry.id) ?? \"\",\n at: asString(entry.at) ?? new Date(0).toISOString(),\n kind:\n entry.kind === \"auto-roll-eval\" ||\n entry.kind === \"profile-switch\" ||\n entry.kind === \"auth-verified\" ||\n entry.kind === \"official-codex-activation\" ||\n entry.kind === \"official-codex-restart\" ||\n entry.kind === \"reset-window-activation\" ||\n entry.kind === \"low-remaining-alert\"\n ? entry.kind\n : \"auto-roll-eval\",\n status: asString(entry.status) ?? \"unknown\",\n reason: asString(entry.reason),\n decisionId: asString(entry.decisionId),\n profileName: asString(entry.profileName),\n sourceProfileName: asString(entry.sourceProfileName),\n targetProfileName: asString(entry.targetProfileName),\n remainingPercent: asNumberOrNull(entry.remainingPercent),\n threshold: asNumberOrNull(entry.threshold),\n snapshotAgeMs: asNumberOrNull(entry.snapshotAgeMs),\n snapshotSource: asString(entry.snapshotSource),\n phase: asString(entry.phase),\n pid: asNumberOrNull(entry.pid),\n profileKeyHash: asString(entry.profileKeyHash),\n switchVerified: asBooleanOrNull(entry.switchVerified),\n activationRequested:\n asBooleanOrNull(entry.activationRequested),\n activationResult: asString(entry.activationResult),\n restartRequested: asBooleanOrNull(entry.restartRequested),\n restartResult: asString(entry.restartResult),\n observedProfileName: asString(entry.observedProfileName),\n observedProfileKeyHash: asString(entry.observedProfileKeyHash),\n observedProfileMatchSource: asString(\n entry.observedProfileMatchSource,\n ) as AutoRollActivityEntry[\"observedProfileMatchSource\"] | null,\n }))\n .filter((entry) => entry.id && entry.at)\n .slice(-50)\n : [];\n if (!isRecord(merged.officialCodex.instancesByProfileName)) {\n merged.officialCodex.instancesByProfileName = {};\n } else {\n const nextInstances: Record<string, OfficialCodexManagedInstanceState> = {};\n for (const [key, value] of Object.entries(\n merged.officialCodex.instancesByProfileName,\n )) {\n if (!isRecord(value)) {\n continue;\n }\n const profileName = asString(value.profileName) ?? asString(key);\n if (!profileName) {\n continue;\n }\n nextInstances[profileName] = {\n profileName,\n profileKey: asString(value.profileKey),\n profileHome: asString(value.profileHome),\n appPath: asString(value.appPath),\n bundleId: asString(value.bundleId),\n pid: asNumberOrNull(value.pid),\n appServerPid: asNumberOrNull(value.appServerPid),\n cdpPort: asNumberOrNull(value.cdpPort),\n bridgeStatus: asOfficialCodexBridgeStatus(value.bridgeStatus),\n bridgeLastCheckedAt: asNumberOrNull(value.bridgeLastCheckedAt),\n bridgeError: asString(value.bridgeError),\n bridgeVersion: asString(value.bridgeVersion),\n bridgeRoute: asString(value.bridgeRoute),\n bridgeDevToolsUrl: asString(value.bridgeDevToolsUrl),\n bridgeCapabilities: normalizeOfficialCodexBridgeCapabilities(\n value.bridgeCapabilities,\n ),\n bridgeActiveThreadId: asString(value.bridgeActiveThreadId),\n bridgeActiveThreadTitle: asString(value.bridgeActiveThreadTitle),\n bridgeActiveThreadUpdatedAt: asNumberOrNull(\n value.bridgeActiveThreadUpdatedAt,\n ),\n bridgeComposerText: asString(value.bridgeComposerText),\n bridgeWorkspacePath: asString(value.bridgeWorkspacePath),\n bridgeModel: asString(value.bridgeModel),\n bridgeActivityState: asOfficialCodexBridgeActivityState(\n value.bridgeActivityState,\n ),\n bridgeQol: normalizeOfficialCodexQolStatus(value.bridgeQol),\n bridgePower: normalizeOfficialCodexPowerStatus(value.bridgePower),\n bridgeRelayStatus: normalizeOfficialCodexRelayStatus(\n value.bridgeRelayStatus,\n ),\n desiredQolSettings: normalizeOfficialCodexQolSettings(\n value.desiredQolSettings,\n ),\n desiredPowerSettings: normalizeOfficialCodexPowerSettings(\n value.desiredPowerSettings,\n ),\n launchedAt: asNumberOrNull(value.launchedAt),\n lastVerifiedAt: asNumberOrNull(value.lastVerifiedAt),\n lastStatus: asString(value.lastStatus),\n lastError: asString(value.lastError),\n };\n }\n merged.officialCodex.instancesByProfileName = nextInstances;\n }\n if (!isRecord(merged.officialCodex.relayProfilesById)) {\n merged.officialCodex.relayProfilesById = {};\n } else {\n const nextProfiles: Record<string, OfficialCodexRelayProfilePayload> = {};\n for (const [key, value] of Object.entries(\n merged.officialCodex.relayProfilesById,\n )) {\n const profile = normalizeOfficialCodexRelayProfile(value);\n if (!profile) {\n continue;\n }\n nextProfiles[profile.id || key] = profile;\n }\n merged.officialCodex.relayProfilesById = nextProfiles;\n }\n const rawActivationDebt = isRecord(merged.officialCodex.pendingActivationDebt)\n ? merged.officialCodex.pendingActivationDebt\n : null;\n if (rawActivationDebt) {\n const debt = rawActivationDebt;\n const targetProfileName = asString(debt.targetProfileName);\n merged.officialCodex.pendingActivationDebt = targetProfileName\n ? {\n targetProfileName,\n targetProfileKey: asString(debt.targetProfileKey),\n sourceProfileName: asString(debt.sourceProfileName),\n sourceProfileKey: asString(debt.sourceProfileKey),\n decisionId: asString(debt.decisionId),\n attempts: asNumberOrNull(debt.attempts) ?? 0,\n lastReason: asString(debt.lastReason),\n }\n : null;\n } else {\n merged.officialCodex.pendingActivationDebt = null;\n }\n {\n const allowedOfficialCodexKeys = new Set(Object.keys(defaults.officialCodex));\n for (const key of Object.keys(merged.officialCodex as Record<string, unknown>)) {\n if (!allowedOfficialCodexKeys.has(key)) {\n delete (merged.officialCodex as Record<string, unknown>)[key];\n }\n }\n }\n merged.app.lastAppVersion = asString(merged.app.lastAppVersion);\n merged.app.pendingUpdateVersion = asString(merged.app.pendingUpdateVersion);\n merged.app.lastProfileName = asString(merged.app.lastProfileName);\n {\n const allowedAppKeys = new Set(Object.keys(defaults.app));\n for (const key of Object.keys(merged.app as Record<string, unknown>)) {\n if (!allowedAppKeys.has(key)) {\n delete (merged.app as Record<string, unknown>)[key];\n }\n }\n }\n\n merged.license.licenseKey = asString(merged.license.licenseKey);\n merged.license.purchaseEmail = asString(merged.license.purchaseEmail);\n merged.license.lastVerifiedAt = asString(merged.license.lastVerifiedAt);\n merged.license.nextCheckAt = asString(merged.license.nextCheckAt);\n merged.license.lastVerificationError = asString(\n merged.license.lastVerificationError,\n );\n merged.license.signature = asString(merged.license.signature);\n if (\n ![\"inactive\", \"active\", \"grace\", \"error\"].includes(merged.license.status)\n ) {\n merged.license.status = \"inactive\";\n }\n\n if (!Array.isArray(merged.preferences.excludeFolders)) {\n merged.preferences.excludeFolders = [];\n }\n if (typeof merged.preferences.enableTaskCompleteBeep !== \"boolean\") {\n merged.preferences.enableTaskCompleteBeep = true;\n }\n if (typeof merged.preferences.preventSleepDuringTasks !== \"boolean\") {\n merged.preferences.preventSleepDuringTasks = true;\n }\n if (typeof merged.preferences.systemNotificationsEnabled !== \"boolean\") {\n merged.preferences.systemNotificationsEnabled = true;\n }\n if (\n typeof merged.preferences.subagentSystemNotificationsEnabled !== \"boolean\"\n ) {\n merged.preferences.subagentSystemNotificationsEnabled = true;\n }\n if (!Array.isArray(merged.preferences.folderHistory)) {\n merged.preferences.folderHistory = [];\n }\n if (!Array.isArray(merged.preferences.pinnedPaths)) {\n merged.preferences.pinnedPaths = [];\n }\n {\n const allowedPreferenceKeys = new Set(Object.keys(defaults.preferences));\n for (const key of Object.keys(\n merged.preferences as Record<string, unknown>,\n )) {\n if (!allowedPreferenceKeys.has(key)) {\n delete (merged.preferences as Record<string, unknown>)[key];\n }\n }\n }\n\n if (!isRecord(merged.runtimeSettings)) {\n merged.runtimeSettings = {};\n }\n if (!isRecord(merged.ui)) {\n merged.ui = clone(defaults.ui);\n }\n merged.ui.themeMode =\n merged.ui.themeMode === \"light\" || merged.ui.themeMode === \"dark\"\n ? merged.ui.themeMode\n : null;\n if (!isRecord(merged.ui.layout)) {\n merged.ui.layout = clone(defaults.ui.layout);\n }\n if (typeof merged.ui.layout.sidebarCollapsed !== \"boolean\") {\n merged.ui.layout.sidebarCollapsed = null;\n }\n if (!isRecord(merged.ui.profiles)) {\n merged.ui.profiles = clone(defaults.ui.profiles);\n }\n merged.ui.profiles.viewMode =\n merged.ui.profiles.viewMode === \"cards\" ||\n merged.ui.profiles.viewMode === \"compact\"\n ? merged.ui.profiles.viewMode\n : null;\n merged.ui.profiles.sortBy = asString(merged.ui.profiles.sortBy);\n merged.ui.profiles.groupBy = asString(merged.ui.profiles.groupBy);\n merged.ui.profiles.planFilter = asString(merged.ui.profiles.planFilter);\n merged.ui.profiles.healthFilter = asString(merged.ui.profiles.healthFilter);\n merged.ui.profiles.customGroupFilter = asString(\n merged.ui.profiles.customGroupFilter,\n );\n if (typeof merged.ui.profiles.toolbarOpen !== \"boolean\") {\n merged.ui.profiles.toolbarOpen = null;\n }\n if (!isRecord(merged.ui.profiles.collapsedSections)) {\n merged.ui.profiles.collapsedSections = {};\n } else {\n merged.ui.profiles.collapsedSections = Object.fromEntries(\n Object.entries(merged.ui.profiles.collapsedSections).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || typeof value !== \"boolean\") {\n return [];\n }\n return [[normalizedKey, value]];\n },\n ),\n );\n }\n if (!isRecord(merged.ui.onboarding)) {\n merged.ui.onboarding = clone(defaults.ui.onboarding);\n }\n if (typeof merged.ui.onboarding.welcomeCompleted !== \"boolean\") {\n merged.ui.onboarding.welcomeCompleted = false;\n }\n if (!Number.isFinite(merged.ui.onboarding.welcomeCompletedAt)) {\n merged.ui.onboarding.welcomeCompletedAt = null;\n }\n merged.ui.onboarding.welcomeResumeStep =\n merged.ui.onboarding.welcomeResumeStep === 2 ? 2 : null;\n if (!isRecord(merged.ui.onboarding.milestones)) {\n merged.ui.onboarding.milestones = clone(defaults.ui.onboarding.milestones);\n }\n if (typeof merged.ui.onboarding.milestones.firstProfileAdded !== \"boolean\") {\n merged.ui.onboarding.milestones.firstProfileAdded = false;\n }\n if (typeof merged.ui.onboarding.milestones.secondProfileAdded !== \"boolean\") {\n merged.ui.onboarding.milestones.secondProfileAdded = false;\n }\n if (!Number.isFinite(merged.ui.onboarding.sessionCount)) {\n merged.ui.onboarding.sessionCount = 0;\n }\n if (!isRecord(merged.ui.onboarding.nudgeCooldowns)) {\n merged.ui.onboarding.nudgeCooldowns = {};\n } else {\n merged.ui.onboarding.nudgeCooldowns = Object.fromEntries(\n Object.entries(merged.ui.onboarding.nudgeCooldowns).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || !Number.isFinite(value)) {\n return [];\n }\n return [[normalizedKey, Number(value)]];\n },\n ),\n );\n }\n if (!isRecord(merged.ui.onboarding.nudgeDismissCount)) {\n merged.ui.onboarding.nudgeDismissCount = {};\n } else {\n merged.ui.onboarding.nudgeDismissCount = Object.fromEntries(\n Object.entries(merged.ui.onboarding.nudgeDismissCount).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || !Number.isFinite(value)) {\n return [];\n }\n return [[normalizedKey, Number(value)]];\n },\n ),\n );\n }\n if (typeof merged.ui.onboarding.proUnlockedCelebrated !== \"boolean\") {\n merged.ui.onboarding.proUnlockedCelebrated = false;\n }\n merged.ui.duplicateWarningDismissedKey = asString(\n merged.ui.duplicateWarningDismissedKey,\n );\n if (typeof merged.ui.pendingLicenseActivation !== \"boolean\") {\n merged.ui.pendingLicenseActivation = false;\n }\n {\n const allowedUiKeys = new Set(Object.keys(defaults.ui));\n for (const key of Object.keys(merged.ui as Record<string, unknown>)) {\n if (!allowedUiKeys.has(key)) {\n delete (merged.ui as Record<string, unknown>)[key];\n }\n }\n }\n if (!isRecord(merged.profileDashboard)) {\n merged.profileDashboard = clone(defaults.profileDashboard);\n }\n if (!isRecord(merged.profileDashboard.customGroupsByAccountKey)) {\n merged.profileDashboard.customGroupsByAccountKey = {};\n } else {\n merged.profileDashboard.customGroupsByAccountKey = Object.fromEntries(\n Object.entries(merged.profileDashboard.customGroupsByAccountKey).flatMap(\n ([key, value]) => {\n const normalizedKey = asString(key);\n const normalizedValue = asString(value);\n if (!normalizedKey || !normalizedValue) {\n return [];\n }\n return [[normalizedKey, normalizedValue]];\n },\n ),\n );\n }\n {\n const allowedProfileDashboardKeys = new Set(\n Object.keys(defaults.profileDashboard),\n );\n for (const key of Object.keys(\n merged.profileDashboard as Record<string, unknown>,\n )) {\n if (!allowedProfileDashboardKeys.has(key)) {\n delete (merged.profileDashboard as Record<string, unknown>)[key];\n }\n }\n }\n\n delete (merged as Record<string, unknown>).projectSettingsByPath;\n delete (merged as Record<string, unknown>).workspaceSettingsByPath;\n delete (merged as Record<string, unknown>).conversationCategoriesByCwd;\n delete (merged as Record<string, unknown>).conversationCategoryAssignmentsByCwd;\n delete (merged as Record<string, unknown>).git;\n\n if (!isRecord(merged.skills)) {\n merged.skills = clone(defaults.skills);\n }\n if (!Array.isArray(merged.skills.sources)) {\n merged.skills.sources = [];\n }\n if (!isRecord(merged.skills.installsBySlug)) {\n merged.skills.installsBySlug = {};\n }\n\n if (!isRecord(merged.sync)) {\n merged.sync = clone(defaults.sync);\n }\n merged.sync.lastPushAt = asString(merged.sync.lastPushAt);\n merged.sync.lastPullAt = asString(merged.sync.lastPullAt);\n merged.sync.lastError = asString(merged.sync.lastError);\n merged.sync.remoteUpdatedAt = asString(merged.sync.remoteUpdatedAt);\n\n if (!isRecord(merged.analytics)) {\n merged.analytics = clone(defaults.analytics);\n }\n merged.analytics.anonymousId = asString(merged.analytics.anonymousId);\n if (typeof merged.analytics.enabled !== \"boolean\") {\n merged.analytics.enabled = true;\n }\n merged.analytics.lastFlushAt = asString(merged.analytics.lastFlushAt);\n merged.analytics.lastError = asString(merged.analytics.lastError);\n\n if (\"telemetry\" in merged) {\n delete (merged as Record<string, unknown>).telemetry;\n }\n\n if (!isRecord(merged.profilesByName)) {\n merged.profilesByName = {};\n }\n\n return merged;\n}\n\nfunction deepMerge<T>(base: T, patch: DeepPartial<T>): T {\n if (!isRecord(base) || !isRecord(patch)) {\n return clone((patch as T) ?? base);\n }\n\n const next: Record<string, unknown> = {\n ...(base as Record<string, unknown>),\n };\n for (const [key, patchValue] of Object.entries(patch)) {\n if (patchValue === undefined) {\n continue;\n }\n\n const currentValue = next[key];\n if (Array.isArray(patchValue)) {\n next[key] = clone(patchValue);\n continue;\n }\n\n if (isRecord(currentValue) && isRecord(patchValue)) {\n next[key] = deepMerge(\n currentValue,\n patchValue as DeepPartial<typeof currentValue>,\n );\n continue;\n }\n\n next[key] = clone(patchValue);\n }\n\n return next as T;\n}\n\nasync function readAppStateFromStorage(): Promise<AppState | null> {\n return readDocumentStrict(\n resolveStorageDbPath(),\n APP_STATE_DOCUMENT,\n normalizeAppState,\n );\n}\n\nasync function writeNormalizedAppStateToStorage(state: AppState): Promise<AppState> {\n const stored = await writeDocument(\n resolveStorageDbPath(),\n APP_STATE_DOCUMENT,\n state,\n { cloneValue: false },\n );\n return freezeDeep(stored);\n}\n\nasync function ensureInitialized(): Promise<AppState> {\n if (appStateCache) {\n return appStateCache;\n }\n\n const loaded = await readAppStateFromStorage();\n const normalized = loaded ?? normalizeAppState(null);\n appStateCache = await writeNormalizedAppStateToStorage(normalized);\n return appStateCache;\n}\n\nasync function withWriteLock<T>(task: () => Promise<T>): Promise<T> {\n if (writeLockContext.getStore()) {\n return task();\n }\n\n const previous = writeLock;\n let release: (() => void) | undefined;\n writeLock = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n try {\n return await writeLockContext.run(true, task);\n } finally {\n if (release) {\n release();\n }\n }\n}\n\nexport async function initializeAppState(\n userDataDir: string,\n): Promise<AppState> {\n if (configuredUserDataDir !== userDataDir) {\n configuredUserDataDir = userDataDir;\n appStateCache = null;\n resetAppStorageInitialization(resolveStorageDbPath());\n }\n const state = await ensureInitialized();\n return state;\n}\n\nexport async function getAppState(): Promise<AppState> {\n const state = await ensureInitialized();\n return state;\n}\n\nexport async function refreshAppStateCache(): Promise<AppState> {\n const current =\n (await readAppStateFromStorage()) ?? (await ensureInitialized());\n appStateCache = freezeDeep(current);\n return appStateCache;\n}\n\nexport async function updateAppState(\n transform: AppStateUpdateTransform,\n options: AppStateUpdateOptions = {},\n): Promise<AppState> {\n const mode = options.mode ?? \"patch\";\n\n return withWriteLock(async () => {\n const current = await ensureInitialized();\n const transformed = transform(\n options.cloneCurrent === false ? current : clone(current),\n );\n const shouldNormalize = options.normalize !== false;\n const nextState =\n mode === \"replace\"\n ? shouldNormalize\n ? normalizeAppState(transformed)\n : (transformed as AppState)\n : shouldNormalize\n ? normalizeAppState(deepMerge(current, transformed as AppStatePatch))\n : (deepMerge(current, transformed as AppStatePatch) as AppState);\n appStateCache = await writeNormalizedAppStateToStorage(nextState);\n return appStateCache;\n });\n}\n\nexport async function patchAppState(patch: AppStatePatch): Promise<AppState> {\n return updateAppState(() => patch, {\n cloneCurrent: false,\n mode: \"patch\",\n });\n}\n\nexport async function replaceAppStateSlice<K extends keyof AppState>(\n key: K,\n value: AppState[K],\n): Promise<AppState> {\n return updateAppState(\n (state) => ({\n ...state,\n [key]: value,\n }),\n {\n cloneCurrent: false,\n mode: \"replace\",\n normalize: false,\n },\n );\n}\n","export type { AutoRollSettings } from \"./auto-roll-types.ts\";\nimport type { AutoRollSettings } from \"./auto-roll-types.ts\";\n\nexport const DEFAULT_AUTO_ROLL_ENABLED = false;\nexport const DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD = 15;\nexport const DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD = 5;\nexport const DEFAULT_LAUNCH_OFFICIAL_CODEX_WHEN_CLOSED_ON_AUTO_ROLL = false;\nexport const DEFAULT_AUTO_ROLL_PRIORITY_ORDER: string[] = [];\nexport const DEFAULT_LOW_REMAINING_NOTIFICATION_ENABLED = false;\nexport const DEFAULT_LOW_REMAINING_NOTIFICATION_THRESHOLD = 1;\nexport const AUTO_ROLL_SWITCH_REMAINING_MIN = 0;\nexport const AUTO_ROLL_SWITCH_REMAINING_MAX = 50;\nexport const AUTO_ROLL_REARM_REMAINING_MAX = 100;\nexport const LOW_REMAINING_NOTIFICATION_MIN = 1;\nexport const LOW_REMAINING_NOTIFICATION_MAX = 50;\n\ntype AutoRollSettingsInput = Partial<AutoRollSettings>;\nconst normalizedAutoRollSettingsCache = new WeakMap<\n AutoRollSettingsInput,\n AutoRollSettings\n>();\nlet normalizedDefaultAutoRollSettings: AutoRollSettings | null = null;\n\nfunction clampNumber(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\nfunction resolveFiniteNumber(value: unknown, fallback: number): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nexport function sanitizeAutoRollSwitchRemainingThreshold(value: unknown): number {\n const numeric = resolveFiniteNumber(\n value,\n DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD,\n );\n return clampNumber(\n numeric,\n AUTO_ROLL_SWITCH_REMAINING_MIN,\n AUTO_ROLL_SWITCH_REMAINING_MAX,\n );\n}\n\nexport function sanitizeAutoRollRearmRemainingThreshold(\n value: unknown,\n switchRemainingThreshold: number,\n): number {\n const sanitizedSwitch = sanitizeAutoRollSwitchRemainingThreshold(\n switchRemainingThreshold,\n );\n const numeric = resolveFiniteNumber(\n value,\n DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD,\n );\n return clampNumber(\n numeric,\n sanitizedSwitch + 1,\n AUTO_ROLL_REARM_REMAINING_MAX,\n );\n}\n\nexport function sanitizeAutoRollThresholds(\n rearmRemainingThreshold: unknown,\n switchRemainingThreshold: unknown,\n): Pick<AutoRollSettings, \"rearmRemainingThreshold\" | \"switchRemainingThreshold\"> {\n const sanitizedSwitch = sanitizeAutoRollSwitchRemainingThreshold(\n switchRemainingThreshold,\n );\n const sanitizedRearm = sanitizeAutoRollRearmRemainingThreshold(\n rearmRemainingThreshold,\n sanitizedSwitch,\n );\n return {\n rearmRemainingThreshold: sanitizedRearm,\n switchRemainingThreshold: sanitizedSwitch,\n };\n}\n\nexport function sanitizeAutoRollPriorityOrder(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [...DEFAULT_AUTO_ROLL_PRIORITY_ORDER];\n }\n\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const item of value) {\n if (typeof item !== \"string\") {\n continue;\n }\n const trimmed = item.trim();\n if (!trimmed || seen.has(trimmed)) {\n continue;\n }\n seen.add(trimmed);\n normalized.push(trimmed);\n }\n return normalized;\n}\n\nexport function sanitizeLowRemainingNotificationThreshold(value: number): number {\n const numeric = resolveFiniteNumber(value, DEFAULT_LOW_REMAINING_NOTIFICATION_THRESHOLD);\n return clampNumber(\n numeric,\n LOW_REMAINING_NOTIFICATION_MIN,\n LOW_REMAINING_NOTIFICATION_MAX,\n );\n}\n\nexport function normalizeAutoRollSettings(\n raw?: AutoRollSettingsInput | null,\n): AutoRollSettings {\n if (!raw) {\n normalizedDefaultAutoRollSettings ??= normalizeAutoRollSettings({});\n return normalizedDefaultAutoRollSettings;\n }\n const cached = normalizedAutoRollSettingsCache.get(raw);\n if (cached) {\n return cached;\n }\n const enabled = typeof raw?.enabled === \"boolean\" ? raw.enabled : DEFAULT_AUTO_ROLL_ENABLED;\n const {\n rearmRemainingThreshold: normalizedRearm,\n switchRemainingThreshold: normalizedSwitch,\n } = sanitizeAutoRollThresholds(\n raw?.rearmRemainingThreshold,\n raw?.switchRemainingThreshold,\n );\n\n const normalized = {\n enabled,\n rearmRemainingThreshold: normalizedRearm,\n switchRemainingThreshold: normalizedSwitch,\n launchOfficialCodexWhenClosedOnAutoRoll:\n raw?.launchOfficialCodexWhenClosedOnAutoRoll === true\n ? true\n : DEFAULT_LAUNCH_OFFICIAL_CODEX_WHEN_CLOSED_ON_AUTO_ROLL,\n priorityOrder: sanitizeAutoRollPriorityOrder(raw?.priorityOrder),\n lowRemainingNotificationEnabled:\n raw?.lowRemainingNotificationEnabled === true\n ? true\n : DEFAULT_LOW_REMAINING_NOTIFICATION_ENABLED,\n lowRemainingNotificationThreshold: sanitizeLowRemainingNotificationThreshold(\n typeof raw?.lowRemainingNotificationThreshold === \"number\"\n ? raw.lowRemainingNotificationThreshold\n : Number.NaN,\n ),\n };\n normalizedAutoRollSettingsCache.set(raw, normalized);\n return normalized;\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nconst APP_STORAGE_TABLE = \"app_storage_documents\";\nconst APP_STORAGE_DB_DIR = \"app-state\";\nconst APP_STORAGE_DB_NAME = \"state.sqlite\";\nconst SQLITE_BUSY_TIMEOUT_MS = 5_000;\nconst SQLITE_BUSY_MAX_ATTEMPTS = 3;\nconst SQLITE_BUSY_RETRY_DELAY_MS = 100;\nconst writeQueueByDbPath = new Map<string, Promise<void>>();\n\ntype StatementLike = {\n get: (...params: any[]) => any;\n all: (...params: any[]) => any[];\n run: (...params: any[]) => any;\n finalize?: () => void;\n};\n\ntype DatabaseLike = {\n exec: (sql: string) => unknown;\n prepare: (sql: string) => StatementLike;\n close: () => unknown;\n};\n\nconst initializedDbPaths = new Set<string>();\n\nexport class AppStorageCorruptionError extends Error {\n readonly dbPath: string;\n readonly namespace: string | null;\n\n constructor(message: string, options: { dbPath: string; namespace?: string | null; cause?: unknown }) {\n super(message);\n this.name = \"AppStorageCorruptionError\";\n this.dbPath = options.dbPath;\n this.namespace = options.namespace ?? null;\n if (options.cause !== undefined) {\n (this as Error & { cause?: unknown }).cause = options.cause;\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction clone<T>(value: T): T {\n if (value === null || value === undefined || typeof value !== \"object\") {\n return value;\n }\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction safeParseJson<T>(raw: string | null | undefined): T | null {\n if (typeof raw !== \"string\" || raw.trim().length === 0) {\n return null;\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\nfunction parseJsonStrict<T>(raw: string | null | undefined, options: {\n dbPath: string;\n namespace: string;\n}): T | null {\n if (typeof raw !== \"string\" || raw.trim().length === 0) {\n return null;\n }\n try {\n return JSON.parse(raw) as T;\n } catch (error) {\n throw new AppStorageCorruptionError(\n `App storage document ${options.namespace} contains invalid JSON.`,\n {\n dbPath: options.dbPath,\n namespace: options.namespace,\n cause: error,\n },\n );\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isSqliteBusyError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n\n const sqliteError = error as {\n code?: unknown;\n cause?: unknown;\n errno?: unknown;\n error?: unknown;\n message?: unknown;\n };\n if (\n sqliteError.cause &&\n sqliteError.cause !== error &&\n isSqliteBusyError(sqliteError.cause)\n ) {\n return true;\n }\n if (\n sqliteError.error &&\n sqliteError.error !== error &&\n isSqliteBusyError(sqliteError.error)\n ) {\n return true;\n }\n const message =\n typeof sqliteError.message === \"string\"\n ? sqliteError.message.toLowerCase()\n : String(error).toLowerCase();\n\n return sqliteError.code === \"SQLITE_BUSY\" ||\n sqliteError.errno === 5 ||\n message.includes(\"sqlite_busy\") ||\n message.includes(\"database is locked\");\n}\n\nfunction isSqliteCorruptionError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n\n const sqliteError = error as {\n cause?: unknown;\n code?: unknown;\n errno?: unknown;\n error?: unknown;\n message?: unknown;\n };\n if (\n sqliteError.cause &&\n sqliteError.cause !== error &&\n isSqliteCorruptionError(sqliteError.cause)\n ) {\n return true;\n }\n if (\n sqliteError.error &&\n sqliteError.error !== error &&\n isSqliteCorruptionError(sqliteError.error)\n ) {\n return true;\n }\n const message =\n typeof sqliteError.message === \"string\" ? sqliteError.message.toLowerCase() : \"\";\n\n return sqliteError.code === \"SQLITE_CORRUPT\" ||\n sqliteError.code === \"SQLITE_NOTADB\" ||\n sqliteError.errno === 11 ||\n sqliteError.errno === 26 ||\n message.includes(\"database disk image is malformed\") ||\n message.includes(\"file is not a database\") ||\n message.includes(\"database corruption\") ||\n message.includes(\"sqlite_corrupt\") ||\n message.includes(\"sqlite_notadb\");\n}\n\nexport function isAppStorageCorruptionError(error: unknown): boolean {\n return error instanceof AppStorageCorruptionError || isSqliteCorruptionError(error);\n}\n\nfunction beginImmediate(db: DatabaseLike): void {\n db.exec(\"BEGIN IMMEDIATE\");\n}\n\nfunction commit(db: DatabaseLike): void {\n db.exec(\"COMMIT\");\n}\n\nfunction rollback(db: DatabaseLike): void {\n try {\n db.exec(\"ROLLBACK\");\n } catch {\n // Ignore rollback failures after a failed transaction.\n }\n}\n\nfunction useStatement<T>(\n db: DatabaseLike,\n sql: string,\n task: (statement: StatementLike) => T,\n): T {\n const statement = db.prepare(sql);\n try {\n return task(statement);\n } finally {\n statement.finalize?.();\n }\n}\n\nasync function withWriteQueue<T>(dbPath: string, task: () => Promise<T>): Promise<T> {\n const previous = writeQueueByDbPath.get(dbPath) ?? Promise.resolve();\n let release: (() => void) | undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n writeQueueByDbPath.set(dbPath, current);\n\n await previous;\n try {\n return await task();\n } finally {\n release?.();\n if (writeQueueByDbPath.get(dbPath) === current) {\n writeQueueByDbPath.delete(dbPath);\n }\n }\n}\n\nfunction applyConnectionPragmas(db: DatabaseLike): void {\n // These PRAGMAs are connection-scoped, so every opened handle must set them.\n db.exec(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS};`);\n db.exec(\"PRAGMA journal_mode = WAL;\");\n db.exec(\"PRAGMA foreign_keys = ON;\");\n}\n\nfunction ensureSchema(db: DatabaseLike, dbPath: string): void {\n if (initializedDbPaths.has(dbPath)) {\n return;\n }\n\n db.exec(`\n CREATE TABLE IF NOT EXISTS ${APP_STORAGE_TABLE} (\n namespace TEXT PRIMARY KEY,\n value_json TEXT NOT NULL,\n updated_at TEXT NOT NULL\n )\n `);\n initializedDbPaths.add(dbPath);\n}\n\nasync function openDatabase(dbPath: string): Promise<DatabaseLike> {\n await fs.mkdir(path.dirname(dbPath), { recursive: true });\n\n if (process.versions.bun !== undefined) {\n const sqlite = await (Function(\"return import('bun:sqlite')\")() as Promise<any>);\n const database = new sqlite.Database(dbPath);\n return {\n exec: database.exec.bind(database),\n prepare: database.prepare.bind(database),\n close: database.close.bind(database),\n };\n }\n\n // Keep the builtin import opaque so the CLI CJS bundle does not rewrite it to bare \"sqlite\".\n const sqlite = await (Function(\"return import('node:sqlite')\")() as Promise<any>);\n const database = new sqlite.DatabaseSync(dbPath);\n return {\n exec: database.exec.bind(database),\n prepare: database.prepare.bind(database),\n close: database.close.bind(database),\n };\n}\n\nexport function resetAppStorageInitialization(dbPath: string): void {\n initializedDbPaths.delete(dbPath);\n}\n\nasync function withDatabase<T>(dbPath: string, task: (db: DatabaseLike) => T): Promise<T> {\n for (let attempt = 1; attempt <= SQLITE_BUSY_MAX_ATTEMPTS; attempt += 1) {\n let db: DatabaseLike | null = null;\n try {\n db = await openDatabase(dbPath);\n applyConnectionPragmas(db);\n ensureSchema(db, dbPath);\n return task(db);\n } catch (error) {\n if (error instanceof AppStorageCorruptionError) {\n throw error;\n }\n if (isSqliteCorruptionError(error)) {\n throw new AppStorageCorruptionError(\n \"App storage database is corrupt.\",\n { dbPath, cause: error },\n );\n }\n if (!isSqliteBusyError(error) || attempt >= SQLITE_BUSY_MAX_ATTEMPTS) {\n throw error;\n }\n } finally {\n db?.close();\n }\n\n await sleep(SQLITE_BUSY_RETRY_DELAY_MS * attempt);\n }\n\n throw new Error(\"App storage database remained busy after retrying.\");\n}\n\nexport function resolveAppStorageDbPath(userDataDir: string): string {\n return path.join(userDataDir, APP_STORAGE_DB_DIR, APP_STORAGE_DB_NAME);\n}\n\nexport async function readDocument<T>(\n dbPath: string,\n namespace: string,\n normalize: (value: unknown) => T,\n): Promise<T | null> {\n return withDatabase(dbPath, (db) => {\n const row = useStatement(\n db,\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n (statement) => statement.get(namespace),\n );\n const parsed = isRecord(row) ? safeParseJson<T>(row.valueJson as string | null) : null;\n if (parsed === null) {\n return null;\n }\n return normalize(parsed);\n });\n}\n\nexport async function readDocumentStrict<T>(\n dbPath: string,\n namespace: string,\n normalize: (value: unknown) => T,\n): Promise<T | null> {\n return withDatabase(dbPath, (db) => {\n const row = useStatement(\n db,\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n (statement) => statement.get(namespace),\n );\n if (!isRecord(row)) {\n return null;\n }\n const parsed = parseJsonStrict<T>(row.valueJson as string | null, {\n dbPath,\n namespace,\n });\n if (parsed === null) {\n throw new AppStorageCorruptionError(\n `App storage document ${namespace} is empty.`,\n { dbPath, namespace },\n );\n }\n try {\n return normalize(parsed);\n } catch (error) {\n throw new AppStorageCorruptionError(\n `App storage document ${namespace} failed normalization.`,\n {\n dbPath,\n namespace,\n cause: error,\n },\n );\n }\n });\n}\n\nexport async function writeDocument<T>(\n dbPath: string,\n namespace: string,\n value: T,\n options: { cloneValue?: boolean } = {},\n): Promise<T> {\n return withWriteQueue(\n dbPath,\n async () =>\n withDatabase(dbPath, (db) => {\n const normalizedValue = options.cloneValue === false ? value : clone(value);\n beginImmediate(db);\n try {\n useStatement(\n db,\n `\n INSERT INTO ${APP_STORAGE_TABLE} (namespace, value_json, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(namespace)\n DO UPDATE SET\n value_json = excluded.value_json,\n updated_at = excluded.updated_at\n `,\n (statement) =>\n statement.run(namespace, JSON.stringify(normalizedValue), new Date().toISOString()),\n );\n commit(db);\n return normalizedValue;\n } catch (error) {\n rollback(db);\n throw error;\n }\n }),\n );\n}\n\nexport async function updateDocument<T>(input: {\n dbPath: string;\n namespace: string;\n normalize: (value: unknown) => T;\n fallback: () => T;\n transform: (current: T) => T;\n cloneBeforeTransform?: boolean;\n normalizeResult?: boolean;\n cloneResult?: boolean;\n}): Promise<T> {\n return withWriteQueue(\n input.dbPath,\n async () =>\n withDatabase(input.dbPath, (db) => {\n beginImmediate(db);\n try {\n const row = useStatement(\n db,\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n (statement) => statement.get(input.namespace),\n );\n const current = isRecord(row)\n ? input.normalize(\n safeParseJson(row.valueJson as string | null) ?? input.fallback(),\n )\n : input.fallback();\n const transformInput =\n input.cloneBeforeTransform === false ? current : clone(current);\n const transformed = input.transform(transformInput);\n const next =\n input.normalizeResult === false\n ? transformed\n : input.normalize(transformed);\n useStatement(\n db,\n `\n INSERT INTO ${APP_STORAGE_TABLE} (namespace, value_json, updated_at)\n VALUES (?, ?, ?)\n ON CONFLICT(namespace)\n DO UPDATE SET\n value_json = excluded.value_json,\n updated_at = excluded.updated_at\n `,\n (statement) =>\n statement.run(input.namespace, JSON.stringify(next), new Date().toISOString()),\n );\n commit(db);\n return input.cloneResult === false ? next : clone(next);\n } catch (error) {\n rollback(db);\n throw error;\n }\n }),\n );\n}\n\nexport async function deleteDocument(dbPath: string, namespace: string): Promise<void> {\n await withWriteQueue(\n dbPath,\n async () =>\n withDatabase(dbPath, (db) => {\n beginImmediate(db);\n try {\n useStatement(\n db,\n `DELETE FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n (statement) => statement.run(namespace),\n );\n commit(db);\n } catch (error) {\n rollback(db);\n throw error;\n }\n }),\n );\n}\n","import {\n getAppState,\n replaceAppStateSlice,\n} from \"./state\";\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction asRecord(value: unknown): JsonRecord {\n return value && typeof value === \"object\" ? (value as JsonRecord) : {};\n}\n\nfunction normalizeRelayProfileId(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const id = value.trim();\n return /^[A-Za-z0-9][A-Za-z0-9_-]{2,79}$/.test(id) ? id : null;\n}\n\nfunction withCurrentRuntimeDefaults(\n settings: JsonRecord,\n): { settings: JsonRecord; changed: boolean } {\n let changed = false;\n const next: JsonRecord = { ...settings };\n\n if (!(\"keepAppRunningAfterWindowClose\" in next)) {\n next.keepAppRunningAfterWindowClose = true;\n changed = true;\n }\n\n if (typeof next.officialCodexAutoControlEnabled !== \"boolean\") {\n next.officialCodexAutoControlEnabled = true;\n changed = true;\n }\n\n if (typeof next.officialCodexInCodexStatusEnabled !== \"boolean\") {\n next.officialCodexInCodexStatusEnabled = true;\n changed = true;\n }\n\n if (\n next.rateLimitPercentMode !== \"remaining\" &&\n next.rateLimitPercentMode !== \"used\"\n ) {\n next.rateLimitPercentMode = \"remaining\";\n changed = true;\n }\n\n if (\n next.officialCodexRelayMode !== \"official\" &&\n next.officialCodexRelayMode !== \"responses\" &&\n next.officialCodexRelayMode !== \"chat-completions\" &&\n next.officialCodexRelayMode !== undefined\n ) {\n next.officialCodexRelayMode = \"off\";\n changed = true;\n }\n\n const relayMode =\n next.officialCodexRelayMode === \"official\" ||\n next.officialCodexRelayMode === \"responses\" ||\n next.officialCodexRelayMode === \"chat-completions\"\n ? next.officialCodexRelayMode\n : \"off\";\n const relayProfileAllowed =\n relayMode === \"responses\" || relayMode === \"chat-completions\";\n if (!relayProfileAllowed && next.officialCodexRelayProfileId != null) {\n next.officialCodexRelayProfileId = null;\n changed = true;\n } else if (relayProfileAllowed) {\n const relayProfileId = normalizeRelayProfileId(\n next.officialCodexRelayProfileId,\n );\n if (next.officialCodexRelayProfileId !== relayProfileId) {\n next.officialCodexRelayProfileId = relayProfileId;\n changed = true;\n }\n }\n\n return { settings: changed ? next : settings, changed };\n}\n\nexport async function readAppSettings(): Promise<JsonRecord> {\n const appState = await getAppState();\n const next = withCurrentRuntimeDefaults(asRecord(appState.runtimeSettings));\n if (next.changed) {\n await replaceAppStateSlice(\"runtimeSettings\", next.settings);\n }\n return next.settings;\n}\n\nexport async function writeAppSettings(\n settings: JsonRecord,\n onUpdated?: (settings: JsonRecord) => void | Promise<void>,\n): Promise<JsonRecord> {\n const nextSettings = withCurrentRuntimeDefaults(asRecord(settings)).settings;\n await replaceAppStateSlice(\"runtimeSettings\", nextSettings);\n if (onUpdated) {\n try {\n await onUpdated(nextSettings);\n } catch (error) {\n console.warn(\"Failed to apply runtime settings update hook:\", error);\n }\n }\n return nextSettings;\n}\n","import crypto from 'node:crypto';\nimport { persistLicense, getStoredLicense, type StoredLicense } from '@codexuse/runtime-codex/codex/settings';\nimport { getLicenseSecret } from '@codexuse/runtime-profiles/license/secret';\nimport { getActiveOffer, buildCheckoutUrl } from '@codexuse/contracts/license/offer-config';\nimport type { LicenseState, LicenseStatus, LicenseTier } from '@codexuse/contracts/license/types';\n\nconst offer = getActiveOffer();\nconst PRODUCT_PERMALINK = offer.productPermalink;\nconst PRODUCT_ID = '3_CcyVEXt2FOMiEpPx8xzw==';\nconst PRODUCT_URL = buildCheckoutUrl(offer);\nconst CHECKOUT_URL = buildCheckoutUrl(offer, { directCheckout: true });\nconst LICENSE_PRICE_DISPLAY = offer.isActive ? offer.salePriceDisplay : offer.basePriceDisplay;\nconst BASE_PRICE_DISPLAY = offer.basePriceDisplay;\nconst PROMO_CODE = offer.couponCode;\nconst PROMO_PERCENT = offer.discountPercent;\nconst PROMO_ACTIVE = offer.isActive;\nconst LICENSE_MAX_USES = 5;\nconst FREE_PROFILE_LIMIT = 2;\nconst LICENSE_REFRESH_INTERVAL_MS = 5 * 60 * 1000;\nconst MAX_NEXT_CHECK_MS = 60 * 60 * 1000;\nconst GRACE_MAX_AGE_MS = 3 * 60 * 60 * 1000;\n\ninterface GumroadLicenseResponse {\n success: boolean;\n message?: string;\n uses?: number;\n purchase?: {\n id: string;\n email: string;\n product_id?: string;\n product_permalink?: string;\n refunded?: boolean;\n chargebacked?: boolean;\n subscription_cancelled?: boolean;\n subscription_failed?: boolean;\n license_disabled?: boolean;\n variants?: string;\n };\n license_disabled?: boolean;\n}\n\ntype VerificationMode = 'activation' | 'refresh';\n\nclass LicenseError extends Error {\n readonly code: 'network' | 'invalid' | 'revoked';\n\n constructor(message: string, code: 'network' | 'invalid' | 'revoked') {\n super(message);\n this.name = 'LicenseError';\n this.code = code;\n }\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nfunction maskLicenseKey(key: string | null | undefined): string | null {\n if (!key || typeof key !== 'string') {\n return null;\n }\n\n const trimmed = key.trim();\n if (trimmed.length <= 4) {\n return '••••';\n }\n\n const visible = trimmed.slice(-4);\n return `••••${visible}`;\n}\n\nfunction resolveProfilesRemaining(limit: number | null, currentProfiles: number): number | null {\n if (typeof limit !== 'number') {\n return null;\n }\n return Math.max(0, limit - currentProfiles);\n}\n\nfunction determineTierFromStored(stored: StoredLicense | null): LicenseTier {\n if (!stored || !stored.licenseKey) {\n return 'free';\n }\n\n if (stored.status === 'inactive') {\n return 'free';\n }\n\n return 'pro';\n}\n\nfunction licenseSignaturePayload(license: StoredLicense): string {\n const payload = {\n licenseKey: license.licenseKey ?? null,\n purchaseEmail: license.purchaseEmail ?? null,\n lastVerifiedAt: license.lastVerifiedAt ?? null,\n nextCheckAt: license.nextCheckAt ?? null,\n lastVerificationError: license.lastVerificationError ?? null,\n status: license.status ?? null,\n };\n return JSON.stringify(payload);\n}\n\nfunction signLicense(license: StoredLicense, secret: string): string {\n return crypto.createHmac('sha256', secret).update(licenseSignaturePayload(license)).digest('hex');\n}\n\nfunction withSignature(license: StoredLicense, secret: string): StoredLicense {\n return {\n ...license,\n signature: signLicense(license, secret),\n };\n}\n\nfunction isSignatureValid(license: StoredLicense, secret: string): boolean {\n if (!license.signature) {\n return false;\n }\n const expected = signLicense(license, secret);\n return expected === license.signature;\n}\n\nasync function requestGumroadVerify(licenseKey: string, mode: VerificationMode): Promise<GumroadLicenseResponse> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 10_000);\n\n try {\n const body = new URLSearchParams({\n product_permalink: PRODUCT_PERMALINK,\n product_id: PRODUCT_ID,\n license_key: licenseKey,\n increment_uses_count: mode === 'activation' ? 'true' : 'false',\n });\n\n const response = await fetch('https://api.gumroad.com/v2/licenses/verify', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body,\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => null);\n const message = errorText\n ? `License verification failed (${response.status}): ${errorText}`\n : `License verification failed (${response.status}).`;\n throw new LicenseError(message, 'network');\n }\n\n const json = (await response.json()) as GumroadLicenseResponse;\n return json;\n } catch (error) {\n if (error instanceof LicenseError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === 'AbortError') {\n throw new LicenseError('License verification timed out.', 'network');\n }\n\n throw new LicenseError(\n error instanceof Error ? error.message : 'Unable to reach Gumroad for license verification.',\n 'network',\n );\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction normalizeVerificationResult(response: GumroadLicenseResponse): { email: string | null } {\n if (!response.success) {\n const message = response.message ?? 'License key is invalid.';\n throw new LicenseError(message, 'invalid');\n }\n\n if (!response.purchase) {\n throw new LicenseError('License verification response was incomplete.', 'network');\n }\n\n if (response.purchase.chargebacked || response.purchase.refunded || response.license_disabled) {\n throw new LicenseError('This license has been revoked or refunded.', 'revoked');\n }\n\n if (response.purchase.subscription_cancelled || response.purchase.subscription_failed) {\n throw new LicenseError('This license subscription is no longer active.', 'revoked');\n }\n\n const email = response.purchase.email ?? null;\n return { email };\n}\n\nfunction ensureWithinUseLimit(response: GumroadLicenseResponse): void {\n if (!response.success) {\n return;\n }\n\n if (typeof response.uses !== 'number') {\n return;\n }\n\n if (response.uses > LICENSE_MAX_USES) {\n throw new LicenseError(\n `This license has reached the activation limit (${LICENSE_MAX_USES}). Contact support to move it to another device.`,\n 'invalid',\n );\n }\n}\n\nfunction toLicenseStatus(stored: StoredLicense | null, overrides: Partial<LicenseStatus> = {}): LicenseStatus {\n const tier = determineTierFromStored(stored);\n const isPro = tier === 'pro';\n\n const state: LicenseState =\n stored && stored.status\n ? stored.status\n : isPro\n ? 'active'\n : 'inactive';\n\n const base: LicenseStatus = {\n tier,\n state,\n isPro,\n profileLimit: isPro ? null : FREE_PROFILE_LIMIT,\n profilesRemaining: null,\n purchaseEmail: stored?.purchaseEmail ?? null,\n maskedLicenseKey: maskLicenseKey(stored?.licenseKey),\n lastVerifiedAt: stored?.lastVerifiedAt ?? null,\n nextCheckAt: stored?.nextCheckAt ?? null,\n message: null,\n error: stored?.lastVerificationError ?? null,\n productUrl: PRODUCT_URL,\n checkoutUrl: CHECKOUT_URL,\n productId: PRODUCT_ID,\n productPermalink: PRODUCT_PERMALINK,\n priceDisplay: LICENSE_PRICE_DISPLAY,\n basePriceDisplay: BASE_PRICE_DISPLAY,\n promoCode: PROMO_ACTIVE ? PROMO_CODE : null,\n promoPercent: PROMO_ACTIVE ? PROMO_PERCENT : null,\n maxDevices: LICENSE_MAX_USES,\n };\n\n return { ...base, ...overrides };\n}\n\nfunction parseTimestamp(value: string | null | undefined): number | null {\n if (typeof value !== 'string' || value.trim() === '') {\n return null;\n }\n\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\nclass LicenseService {\n private refreshPromise: Promise<void> | null = null;\n private verificationPromise: Promise<LicenseStatus> | null = null;\n\n async getCachedStatus(): Promise<LicenseStatus> {\n return this.getStatus({ allowStale: true, refreshInBackground: true });\n }\n\n async getStatus(options: {\n forceRefresh?: boolean;\n allowStale?: boolean;\n refreshInBackground?: boolean;\n } = {}): Promise<LicenseStatus> {\n const forceRefresh = Boolean(options.forceRefresh);\n const allowStale = Boolean(options.allowStale);\n const refreshInBackground = Boolean(options.refreshInBackground);\n const secret = await getLicenseSecret();\n const stored = await getStoredLicense();\n\n if (!stored?.licenseKey) {\n return toLicenseStatus(null);\n }\n\n const now = Date.now();\n const nextCheckTs = parseTimestamp(stored.nextCheckAt);\n const lastVerifiedTs = parseTimestamp(stored.lastVerifiedAt);\n const graceStale =\n (stored.status === 'grace' || stored.status === 'error') &&\n (lastVerifiedTs === null || lastVerifiedTs + GRACE_MAX_AGE_MS < now);\n\n let workingStored: StoredLicense = { ...stored };\n const signatureValid = isSignatureValid(workingStored, secret);\n\n let cappedNextCheckTs = nextCheckTs;\n\n if (nextCheckTs !== null && nextCheckTs > now + MAX_NEXT_CHECK_MS) {\n cappedNextCheckTs = now;\n const updated = {\n ...workingStored,\n nextCheckAt: new Date(cappedNextCheckTs).toISOString(),\n };\n const signed = withSignature(updated, secret);\n workingStored = signed;\n await persistLicense(signed);\n }\n\n const tampered = Boolean(workingStored.licenseKey) && !signatureValid;\n\n const cached = tampered\n ? toLicenseStatus(null, {\n state: 'verifying',\n message: 'License data changed, rechecking.',\n error: 'Untrusted license data.',\n })\n : toLicenseStatus(workingStored);\n\n const shouldRefresh =\n forceRefresh || graceStale || tampered || cappedNextCheckTs === null || cappedNextCheckTs <= now;\n\n if (!shouldRefresh || allowStale) {\n // Startup/bootstrap callers should render from durable cached state and\n // let the online recheck happen off the critical path.\n if (allowStale && shouldRefresh && refreshInBackground) {\n this.refreshStatusInBackground({ force: forceRefresh });\n }\n return cached;\n }\n\n if (this.verificationPromise && !forceRefresh) {\n return this.verificationPromise;\n }\n\n const verify = async (): Promise<LicenseStatus> => {\n try {\n const result = await requestGumroadVerify(workingStored.licenseKey!, 'refresh');\n ensureWithinUseLimit(result);\n const normalized = normalizeVerificationResult(result);\n const updated: StoredLicense = {\n licenseKey: workingStored.licenseKey,\n purchaseEmail: normalized.email,\n lastVerifiedAt: nowIso(),\n nextCheckAt: new Date(Date.now() + LICENSE_REFRESH_INTERVAL_MS).toISOString(),\n status: 'active',\n lastVerificationError: null,\n };\n\n const signed = withSignature(updated, secret);\n\n await persistLicense(signed);\n return toLicenseStatus(signed);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'License verification failed.';\n\n if (error instanceof LicenseError && error.code === 'network') {\n const fallbackStored: StoredLicense = withSignature(\n {\n ...workingStored,\n status: tampered ? 'inactive' : workingStored.status === 'inactive' ? 'inactive' : 'grace',\n lastVerificationError: message,\n nextCheckAt: new Date(Date.now() + LICENSE_REFRESH_INTERVAL_MS).toISOString(),\n },\n secret,\n );\n await persistLicense(fallbackStored);\n const fallback = toLicenseStatus(fallbackStored, {\n state: fallbackStored.status ?? 'grace',\n error: message,\n });\n return fallback;\n }\n\n const fallbackStored: StoredLicense = withSignature({\n licenseKey: workingStored.licenseKey,\n purchaseEmail: workingStored.purchaseEmail ?? null,\n lastVerifiedAt: workingStored.lastVerifiedAt ?? null,\n nextCheckAt: null,\n status: 'inactive',\n lastVerificationError: message,\n }, secret);\n await persistLicense(fallbackStored);\n return toLicenseStatus(fallbackStored, { error: message });\n }\n };\n\n this.verificationPromise = verify();\n try {\n return await this.verificationPromise;\n } finally {\n this.verificationPromise = null;\n }\n }\n\n async activate(licenseKey: string): Promise<LicenseStatus> {\n const trimmed = licenseKey.trim();\n if (!trimmed) {\n throw new Error('License key is required.');\n }\n\n const secret = await getLicenseSecret();\n const digest = crypto.createHash('sha256').update(trimmed).digest('hex');\n\n const result = await requestGumroadVerify(trimmed, 'activation');\n ensureWithinUseLimit(result);\n const normalized = normalizeVerificationResult(result);\n const stored: StoredLicense = {\n licenseKey: trimmed,\n purchaseEmail: normalized.email,\n lastVerifiedAt: nowIso(),\n nextCheckAt: new Date(Date.now() + LICENSE_REFRESH_INTERVAL_MS).toISOString(),\n status: 'active',\n lastVerificationError: null,\n };\n\n const signed = withSignature(stored, secret);\n\n await persistLicense(signed);\n return toLicenseStatus(signed, {\n message: `License verified (${digest.slice(0, 8)}).`,\n });\n }\n\n applyProfileCount(status: LicenseStatus, profileCount: number): LicenseStatus {\n const profilesRemaining = resolveProfilesRemaining(status.profileLimit, profileCount);\n return {\n ...status,\n profilesRemaining,\n };\n }\n\n refreshStatusInBackground(options: { force?: boolean } = {}): void {\n if (this.refreshPromise) {\n return;\n }\n\n const forceRefresh = Boolean(options.force);\n this.refreshPromise = (async () => {\n try {\n await this.getStatus({ forceRefresh });\n } catch (error) {\n console.warn('Background license refresh failed:', error);\n } finally {\n this.refreshPromise = null;\n }\n })();\n }\n}\n\nexport const licenseService = new LicenseService();\nexport { FREE_PROFILE_LIMIT };\n\nfunction isExplicitInvalidation(message: string | null | undefined): boolean {\n if (!message) {\n return false;\n }\n const normalized = message.toLowerCase();\n return (\n normalized.includes('revoked') ||\n normalized.includes('refunded') ||\n normalized.includes('invalid') ||\n normalized.includes('no longer active')\n );\n}\n\n/**\n * Determines when it is safe to enforce profile limits (e.g., pruning).\n * We skip enforcement when the license state is uncertain (grace/error/verifying)\n * and only enforce limits for true free/unlicensed states or explicit revocations.\n */\nexport function shouldEnforceProfileLimit(status: LicenseStatus): boolean {\n if (status.isPro) {\n return false;\n }\n\n if (status.state === 'grace' || status.state === 'verifying' || status.state === 'error') {\n return false;\n }\n\n if (isExplicitInvalidation(status.error)) {\n return true;\n }\n\n return status.state === 'inactive';\n}\n","import { normalizeAutoRollSettings, type AutoRollSettings } from \"@codexuse/contracts/settings/auto-roll\";\nimport { getAppState, patchAppState } from \"@codexuse/runtime-app-state/app/state\";\n\ntype LicenseStatusCode = \"inactive\" | \"active\" | \"grace\" | \"error\";\n\ninterface StoredLicense {\n licenseKey?: string | null;\n purchaseEmail?: string | null;\n lastVerifiedAt?: string | null;\n nextCheckAt?: string | null;\n lastVerificationError?: string | null;\n status?: LicenseStatusCode;\n signature?: string | null;\n}\n\nfunction asString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction parseAutoRoll(raw: unknown): AutoRollSettings | null {\n if (!raw) {\n return null;\n }\n try {\n return normalizeAutoRollSettings(raw as Partial<AutoRollSettings>);\n } catch {\n return null;\n }\n}\n\nfunction parseStoredLicense(raw?: unknown): StoredLicense | null {\n if (!isRecord(raw)) {\n return null;\n }\n\n const statusCandidate = asString(raw.status);\n const status = [\"inactive\", \"active\", \"grace\", \"error\"].includes(statusCandidate ?? \"\")\n ? (statusCandidate as LicenseStatusCode)\n : undefined;\n\n const license: StoredLicense = {\n licenseKey: asString(raw.licenseKey ?? raw.license_key),\n purchaseEmail: asString(raw.purchaseEmail ?? raw.purchase_email),\n lastVerifiedAt: asString(raw.lastVerifiedAt ?? raw.last_verified_at),\n nextCheckAt: asString(raw.nextCheckAt ?? raw.next_check_at),\n lastVerificationError: asString(raw.lastVerificationError ?? raw.last_verification_error),\n status,\n signature: asString(raw.signature),\n };\n\n const hasValue = Boolean(\n license.licenseKey ||\n license.purchaseEmail ||\n license.lastVerifiedAt ||\n license.nextCheckAt ||\n license.lastVerificationError ||\n license.status,\n );\n\n return hasValue ? license : null;\n}\n\nexport async function getLastProfileName(): Promise<string | null> {\n const state = await getAppState();\n return asString(state.app.lastProfileName);\n}\n\nexport async function persistLastProfileName(profileName: string | null): Promise<void> {\n await patchAppState({\n app: {\n lastProfileName: asString(profileName),\n },\n });\n}\n\nexport async function getStoredLicense(): Promise<StoredLicense | null> {\n const state = await getAppState();\n return parseStoredLicense(state.license);\n}\n\nexport async function persistLicense(license: StoredLicense | null): Promise<void> {\n const parsed = parseStoredLicense(license);\n await patchAppState({\n license: parsed\n ? {\n licenseKey: parsed.licenseKey ?? null,\n purchaseEmail: parsed.purchaseEmail ?? null,\n lastVerifiedAt: parsed.lastVerifiedAt ?? null,\n nextCheckAt: parsed.nextCheckAt ?? null,\n lastVerificationError: parsed.lastVerificationError ?? null,\n status: parsed.status ?? \"inactive\",\n signature: parsed.signature ?? null,\n }\n : {\n licenseKey: null,\n purchaseEmail: null,\n lastVerifiedAt: null,\n nextCheckAt: null,\n lastVerificationError: null,\n status: \"inactive\",\n signature: null,\n },\n });\n}\n\nexport async function getStoredAutoRollSettings(): Promise<AutoRollSettings | null> {\n const state = await getAppState();\n return normalizeAutoRollSettings(state.autoRoll);\n}\n\nexport async function persistAutoRollSettings(settings: AutoRollSettings | null): Promise<void> {\n const normalized = normalizeAutoRollSettings(settings ?? undefined);\n await patchAppState({\n autoRoll: {\n enabled: normalized.enabled,\n rearmRemainingThreshold: normalized.rearmRemainingThreshold,\n switchRemainingThreshold: normalized.switchRemainingThreshold,\n launchOfficialCodexWhenClosedOnAutoRoll:\n normalized.launchOfficialCodexWhenClosedOnAutoRoll,\n priorityOrder: normalized.priorityOrder,\n lowRemainingNotificationEnabled: normalized.lowRemainingNotificationEnabled,\n lowRemainingNotificationThreshold: normalized.lowRemainingNotificationThreshold,\n },\n });\n}\n\nexport async function getStoredAppVersion(): Promise<string | null> {\n const state = await getAppState();\n return asString(state.app.lastAppVersion);\n}\n\nexport async function persistAppVersion(version: string | null): Promise<void> {\n await patchAppState({\n app: {\n lastAppVersion: asString(version),\n },\n });\n}\n\nexport async function getPendingUpdateVersion(): Promise<string | null> {\n const state = await getAppState();\n return asString(state.app.pendingUpdateVersion);\n}\n\nexport async function persistPendingUpdateVersion(version: string | null): Promise<void> {\n await patchAppState({\n app: {\n pendingUpdateVersion: asString(version),\n },\n });\n}\n\nexport async function readCodexSettingsJsonRaw(): Promise<Record<string, unknown>> {\n const state = await getAppState();\n return {\n lastProfileName: state.app.lastProfileName,\n lastAppVersion: state.app.lastAppVersion,\n pendingUpdateVersion: state.app.pendingUpdateVersion,\n autoRoll: state.autoRoll,\n license: state.license,\n excludeFolders: state.preferences.excludeFolders,\n enableTaskCompleteBeep: state.preferences.enableTaskCompleteBeep,\n preventSleepDuringTasks: state.preferences.preventSleepDuringTasks,\n systemNotificationsEnabled: state.preferences.systemNotificationsEnabled,\n subagentSystemNotificationsEnabled:\n state.preferences.subagentSystemNotificationsEnabled,\n folderHistory: state.preferences.folderHistory,\n pinnedPaths: state.preferences.pinnedPaths,\n sync: state.sync,\n };\n}\n\nexport async function writeCodexSettingsJsonRaw(payload: Record<string, unknown> | null | undefined): Promise<void> {\n if (!isRecord(payload)) {\n return;\n }\n\n const autoRoll = parseAutoRoll(payload.autoRoll ?? payload.auto_roll);\n const license = parseStoredLicense(payload.license);\n\n await patchAppState({\n app: {\n lastProfileName: asString(payload.lastProfileName ?? payload.last_profile_name),\n lastAppVersion: asString(payload.lastAppVersion ?? payload.last_app_version),\n pendingUpdateVersion: asString(payload.pendingUpdateVersion ?? payload.pending_update_version),\n },\n autoRoll: autoRoll\n ? {\n enabled: autoRoll.enabled,\n rearmRemainingThreshold: autoRoll.rearmRemainingThreshold,\n switchRemainingThreshold: autoRoll.switchRemainingThreshold,\n launchOfficialCodexWhenClosedOnAutoRoll:\n autoRoll.launchOfficialCodexWhenClosedOnAutoRoll,\n priorityOrder: autoRoll.priorityOrder,\n lowRemainingNotificationEnabled: autoRoll.lowRemainingNotificationEnabled,\n lowRemainingNotificationThreshold: autoRoll.lowRemainingNotificationThreshold,\n }\n : undefined,\n license: license\n ? {\n licenseKey: license.licenseKey ?? null,\n purchaseEmail: license.purchaseEmail ?? null,\n lastVerifiedAt: license.lastVerifiedAt ?? null,\n nextCheckAt: license.nextCheckAt ?? null,\n lastVerificationError: license.lastVerificationError ?? null,\n status: license.status ?? \"inactive\",\n signature: license.signature ?? null,\n }\n : undefined,\n preferences: {\n excludeFolders: Array.isArray(payload.excludeFolders)\n ? (payload.excludeFolders as string[])\n : undefined,\n enableTaskCompleteBeep:\n typeof payload.enableTaskCompleteBeep === \"boolean\"\n ? payload.enableTaskCompleteBeep\n : undefined,\n preventSleepDuringTasks:\n typeof payload.preventSleepDuringTasks === \"boolean\"\n ? payload.preventSleepDuringTasks\n : undefined,\n systemNotificationsEnabled:\n typeof payload.systemNotificationsEnabled === \"boolean\"\n ? payload.systemNotificationsEnabled\n : undefined,\n subagentSystemNotificationsEnabled:\n typeof payload.subagentSystemNotificationsEnabled === \"boolean\"\n ? payload.subagentSystemNotificationsEnabled\n : undefined,\n folderHistory: Array.isArray(payload.folderHistory)\n ? (payload.folderHistory as Array<{ path: string; name: string; lastVisited: number }>)\n : undefined,\n pinnedPaths: Array.isArray(payload.pinnedPaths)\n ? (payload.pinnedPaths as string[])\n : undefined,\n },\n sync: isRecord(payload.sync)\n ? (payload.sync as {\n lastPushAt: string | null;\n lastPullAt: string | null;\n lastError: string | null;\n remoteUpdatedAt: string | null;\n })\n : undefined,\n });\n}\n\nexport type { StoredLicense };\n","import crypto from \"node:crypto\";\nimport {\n getUserDataDir,\n} from \"@codexuse/runtime-app-state/app/state\";\nimport {\n readDocument,\n resolveAppStorageDbPath,\n writeDocument,\n} from \"@codexuse/runtime-app-state/storage/documents\";\n\nconst LICENSE_SECRET_DOCUMENT = \"desktop.license-secret\";\n\nasync function generateSecret(): Promise<string> {\n return crypto.randomBytes(32).toString(\"hex\");\n}\n\nfunction normalizeSecret(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\nasync function persistLicenseSecret(dbPath: string, secret: string): Promise<string> {\n await writeDocument(dbPath, LICENSE_SECRET_DOCUMENT, secret);\n return secret;\n}\n\nexport async function getLicenseSecret(): Promise<string> {\n const dbPath = resolveAppStorageDbPath(getUserDataDir());\n const existing = await readDocument<string>(dbPath, LICENSE_SECRET_DOCUMENT, normalizeSecret);\n const normalizedExisting = normalizeSecret(existing);\n if (normalizedExisting.length > 0) {\n return normalizedExisting;\n }\n\n const secret = await generateSecret();\n return persistLicenseSecret(dbPath, secret);\n}\n","export interface OfferConfig {\n basePriceUsd: number;\n basePriceDisplay: string;\n couponCode: string | null;\n discountPercent: number;\n salePriceUsd: number;\n salePriceDisplay: string;\n isActive: boolean;\n campaign: string | null;\n productPermalink: string;\n checkoutBaseUrl: string;\n}\n\nexport interface CheckoutUrlOptions {\n source?: string;\n medium?: string;\n campaign?: string;\n directCheckout?: boolean;\n}\n\nexport function getActiveOffer(): OfferConfig {\n const basePriceUsd = 39;\n const discountPercent = 50;\n const salePriceUsd = basePriceUsd * (100 - discountPercent) / 100;\n\n return {\n basePriceUsd,\n basePriceDisplay: `$${basePriceUsd}`,\n couponCode: \"SPRING50\",\n discountPercent,\n salePriceUsd,\n salePriceDisplay: `$${salePriceUsd.toFixed(2)}`,\n isActive: true,\n campaign: \"spring-2026\",\n productPermalink: \"codex-use\",\n checkoutBaseUrl: \"https://hweihwang.gumroad.com/l/codex-use\",\n };\n}\n\nexport function buildCheckoutUrl(\n offer: OfferConfig,\n options?: CheckoutUrlOptions,\n): string {\n const base = offer.checkoutBaseUrl;\n const withCoupon = offer.isActive && offer.couponCode\n ? `${base}/${offer.couponCode}`\n : base;\n\n const url = new URL(withCoupon);\n\n if (options?.directCheckout) {\n url.searchParams.set(\"wanted\", \"true\");\n }\n\n if (!options?.source || !options?.medium) {\n return url.toString();\n }\n\n url.searchParams.set(\"utm_source\", options.source);\n url.searchParams.set(\"utm_medium\", options.medium);\n if (options.campaign) {\n url.searchParams.set(\"utm_campaign\", options.campaign);\n } else if (offer.campaign) {\n url.searchParams.set(\"utm_campaign\", offer.campaign);\n }\n\n return url.toString();\n}\n","import { createHash } from 'node:crypto';\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { join } from 'path';\nimport { parse, stringify } from '@iarna/toml';\nimport type {\n Profile,\n ProfileData,\n ActiveAuth,\n ProfileMetadata,\n OrganizationInfo,\n RateLimitSnapshot,\n SubscriptionInfo,\n TokenAlert,\n TokenIssue,\n TokenStatus,\n} from '@codexuse/contracts/profiles/types';\nimport { resolveProfileIdentityKey as resolveSharedProfileIdentityKey } from '@codexuse/contracts/profiles/identity';\nimport type { ActiveCodexAuthStatus } from '@codexuse/contracts/profiles/view-types';\nimport {\n activateResetWindowViaRpc,\n fetchRateLimitsViaRpc,\n type CodexResetWindowActivationResult,\n} from '@codexuse/runtime-codex/codex/rpc';\nimport type { CloudSyncProfileRecord } from '@codexuse/contracts/cloud-sync/types';\nimport {\n getAppState,\n getUserDataDir,\n replaceAppStateSlice,\n type ProfileDashboardState,\n type ProfileRecordState,\n} from '@codexuse/runtime-app-state/app/state';\nimport { logError, logInfo, logWarn } from '@codexuse/shared/core/logger';\n\nconst TOKEN_EXPIRING_SOON_WINDOW_MS = 15 * 60 * 1000;\nconst REFRESH_TOKEN_REDEEMED_SNIPPET = 'refresh token was already used';\nconst REFRESH_TOKEN_REDEEMED_REASON =\n 'Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.';\nconst DEFAULT_WORKSPACE_ID = '__default__';\nlet globalAuthSwapLock: Promise<void> = Promise.resolve();\nconst profileOperationLocks = new Map<string, Promise<void>>();\n\nexport function detectRefreshTokenRedeemedMessage(output: string | Buffer | null | undefined): string | null {\n if (!output) {\n return null;\n }\n\n const text = output.toString();\n if (!text) {\n return null;\n }\n\n const normalized = text\n .toLowerCase()\n .replace(/\\s+/g, ' ');\n if (!normalized.includes(REFRESH_TOKEN_REDEEMED_SNIPPET)) {\n return null;\n }\n\n const trimmed = text.trim();\n return trimmed.length > 0 ? trimmed : REFRESH_TOKEN_REDEEMED_REASON;\n}\n\ntype ProfileRecord = {\n name: string;\n displayName: string | null;\n data: ProfileData;\n metadata?: ProfileMetadata;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n email: string | null;\n authMethod: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n};\n\ntype ProfileRecordIndex = {\n source: Record<string, ProfileRecordState>;\n records: ProfileRecord[];\n byIdentityWorkspace: Map<string, ProfileRecord[]>;\n};\n\nexport type ActiveAuthSnapshot = {\n fingerprint: string | null;\n email: string | null;\n accountId: string | null;\n userId: string | null;\n chatgptUserId: string | null;\n chatgptAccountUserId: string | null;\n workspaceId: string | null;\n};\n\nexport type PreparedProfileRuntime = {\n profileHome: string;\n env: NodeJS.ProcessEnv;\n};\n\nfunction resolveFallbackAccountKey(profileName: string): string {\n return `profile:${profileName}`;\n}\n\nfunction cloneJson<T>(value: T): T {\n if (value === null || value === undefined || typeof value !== 'object') {\n return value;\n }\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction errorWithCause(message: string, cause: unknown): Error {\n const error = new Error(message) as Error & { cause?: unknown };\n error.cause = cause;\n return error;\n}\n\nexport class ProfileManager {\n private codexDir: string;\n private profileHomesRoot: string;\n private activeAuth: string;\n private lastActiveAuthErrorSignature: string | null;\n private jwtPayloadCache: Map<string, Record<string, unknown> | null>;\n private profileRecordIndexCache: ProfileRecordIndex | null;\n private profileHomeAuthSyncCache: Map<\n string,\n { fileKey: string; tokenRecencyMs: number | null }\n >;\n constructor() {\n const homeDir = process.env.HOME || '';\n this.codexDir = join(homeDir, '.codex');\n this.profileHomesRoot = join(getUserDataDir(), 'profile-homes');\n this.activeAuth = join(this.codexDir, 'auth.json');\n this.lastActiveAuthErrorSignature = null;\n this.jwtPayloadCache = new Map();\n this.profileRecordIndexCache = null;\n this.profileHomeAuthSyncCache = new Map();\n }\n\n private computeExpiryIso(data: ProfileData | null | undefined): string | undefined {\n if (!data) {\n return undefined;\n }\n if (typeof data.expired === 'string' && data.expired.trim()) {\n const parsed = Date.parse(data.expired);\n if (!Number.isNaN(parsed)) {\n return new Date(parsed).toISOString();\n }\n }\n const expiresIn = typeof data.expires_in === 'number' && Number.isFinite(data.expires_in)\n ? data.expires_in\n : undefined;\n const issuedMs =\n typeof data.timestamp === 'number' && Number.isFinite(data.timestamp)\n ? data.timestamp\n : undefined;\n const issuedAt = issuedMs ? issuedMs : undefined;\n const baseMs = issuedAt ?? Date.now();\n if (expiresIn && expiresIn > 0) {\n return new Date(baseMs + expiresIn * 1000).toISOString();\n }\n return undefined;\n }\n\n private normalizeProfileName(name: string): string {\n if (typeof name !== 'string') {\n throw new Error('Profile name is required');\n }\n\n const trimmed = name.trim();\n if (!trimmed) {\n throw new Error('Profile name must not be empty.');\n }\n\n if (trimmed === '.' || trimmed === '..') {\n throw new Error(`Profile name '${name}' is not allowed.`);\n }\n\n if (/[\\\\/]/.test(trimmed)) {\n throw new Error(\"Profile name cannot contain path separators.\");\n }\n\n if (trimmed.includes('\\0')) {\n throw new Error('Profile name contains invalid characters.');\n }\n\n return trimmed;\n }\n\n private isNotFoundError(error: unknown): boolean {\n return Boolean(\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as NodeJS.ErrnoException).code === 'ENOENT',\n );\n }\n\n private toStateRecord(record: ProfileRecord): ProfileRecordState {\n return {\n name: record.name,\n displayName: record.displayName ?? null,\n data: record.data,\n metadata: record.metadata,\n accountId: record.accountId ?? null,\n workspaceId: record.workspaceId ?? null,\n workspaceName: record.workspaceName ?? null,\n email: record.email ?? null,\n authMethod: record.authMethod ?? null,\n createdAt: record.createdAt ?? null,\n updatedAt: record.updatedAt ?? null,\n };\n }\n\n private fromStateRecord(profileName: string, raw: ProfileRecordState): ProfileRecord | null {\n if (!raw || typeof raw !== 'object') {\n return null;\n }\n\n const dataRaw = raw.data;\n if (!dataRaw || typeof dataRaw !== 'object') {\n return null;\n }\n\n return {\n name: profileName,\n displayName: typeof raw.displayName === 'string' ? raw.displayName : null,\n data: cloneJson(dataRaw as ProfileData),\n metadata: raw.metadata ? cloneJson(raw.metadata) : undefined,\n accountId: typeof raw.accountId === 'string' ? raw.accountId : null,\n workspaceId: typeof raw.workspaceId === 'string' ? raw.workspaceId : null,\n workspaceName: typeof raw.workspaceName === 'string' ? raw.workspaceName : null,\n email: typeof raw.email === 'string' ? raw.email : null,\n authMethod: typeof raw.authMethod === 'string' ? raw.authMethod : null,\n createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : null,\n updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : null,\n };\n }\n\n private async readProfilesStateSource(): Promise<Record<string, ProfileRecordState>> {\n const state = await getAppState();\n return state.profilesByName ?? {};\n }\n\n private async readProfilesStateMap(): Promise<Record<string, ProfileRecordState>> {\n return { ...(await this.readProfilesStateSource()) };\n }\n\n private async writeProfilesStateMap(nextMap: Record<string, ProfileRecordState>): Promise<void> {\n this.profileRecordIndexCache = null;\n await replaceAppStateSlice('profilesByName', nextMap);\n }\n\n private async readProfileDashboardState(): Promise<ProfileDashboardState> {\n const state = await getAppState();\n return {\n customGroupsByAccountKey: { ...(state.profileDashboard?.customGroupsByAccountKey ?? {}) },\n };\n }\n\n private async writeProfileDashboardState(nextState: ProfileDashboardState): Promise<void> {\n await replaceAppStateSlice('profileDashboard', {\n customGroupsByAccountKey: { ...nextState.customGroupsByAccountKey },\n });\n }\n\n private async readProfileRecord(profileName: string): Promise<ProfileRecord | null> {\n const map = await this.readProfilesStateMap();\n const raw = map[profileName];\n if (!raw) {\n return null;\n }\n return this.fromStateRecord(profileName, raw);\n }\n\n private async listProfileRecords(): Promise<ProfileRecord[]> {\n return [...(await this.getProfileRecordIndex()).records];\n }\n\n private async writeProfileRecord(record: ProfileRecord): Promise<void> {\n const map = await this.readProfilesStateMap();\n map[record.name] = this.toStateRecord(record);\n await this.writeProfilesStateMap(map);\n }\n\n private async deleteProfileRecord(name: string): Promise<void> {\n const map = await this.readProfilesStateMap();\n if (!Object.prototype.hasOwnProperty.call(map, name)) {\n return;\n }\n delete map[name];\n await this.writeProfilesStateMap(map);\n }\n\n private resolveAuthMethod(data: ProfileData | null | undefined): string {\n const raw = typeof data?.auth_method === 'string' ? data.auth_method.trim().toLowerCase() : '';\n return raw || 'codex-cli';\n }\n\n private async readActiveAuthFile(): Promise<ActiveAuth | null> {\n try {\n const raw = await fs.readFile(this.activeAuth, 'utf8');\n const trimmed = raw.trim();\n if (!trimmed) {\n return null;\n }\n return JSON.parse(trimmed) as ActiveAuth;\n } catch (error) {\n if (this.isNotFoundError(error)) {\n return null;\n }\n const message = error instanceof Error ? error.message : 'unknown error';\n const signature = typeof message === 'string' ? `${message}:${this.activeAuth}` : this.activeAuth;\n if (this.lastActiveAuthErrorSignature !== signature) {\n logWarn('Failed to read active auth file:', error);\n this.lastActiveAuthErrorSignature = signature;\n }\n return null;\n }\n }\n\n private emptyAuthSnapshot(fingerprint: string | null = null): ActiveAuthSnapshot {\n return {\n fingerprint,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n chatgptAccountUserId: null,\n workspaceId: null,\n };\n }\n\n private async captureAuthSnapshotAtPath(authPath: string): Promise<ActiveAuthSnapshot> {\n let raw: string;\n try {\n raw = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (this.isNotFoundError(error)) {\n return this.emptyAuthSnapshot();\n }\n const message = error instanceof Error ? error.message : 'unknown error';\n const signature = typeof message === 'string' ? `${message}:${authPath}` : authPath;\n if (this.lastActiveAuthErrorSignature !== signature) {\n logWarn('Failed to snapshot auth file:', error);\n this.lastActiveAuthErrorSignature = signature;\n }\n return this.emptyAuthSnapshot();\n }\n\n const trimmed = raw.trim();\n if (!trimmed) {\n return this.emptyAuthSnapshot();\n }\n\n const fingerprint = createHash('sha256').update(trimmed).digest('hex');\n\n try {\n const parsed = JSON.parse(trimmed) as ActiveAuth;\n const normalized = this.normalizeProfileData(parsed);\n const metadata = this.extractProfileMetadata(normalized);\n const workspace = this.resolveWorkspaceIdentity(normalized, metadata);\n return {\n fingerprint,\n email: this.resolveProfileEmail(normalized, metadata) ?? null,\n accountId: this.getAccountIdFromData(normalized) ?? null,\n userId: metadata?.userId ?? null,\n chatgptUserId: metadata?.chatgptUserId ?? null,\n chatgptAccountUserId: metadata?.chatgptAccountUserId ?? null,\n workspaceId: workspace.id ?? null,\n };\n } catch {\n return this.emptyAuthSnapshot(fingerprint);\n }\n }\n\n async captureAuthSnapshot(authPath?: string): Promise<ActiveAuthSnapshot> {\n const targetPath = authPath ?? this.activeAuth;\n if (targetPath === this.activeAuth) {\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n return this.captureAuthSnapshotAtPath(targetPath);\n });\n }\n\n await this.initialize();\n return this.captureAuthSnapshotAtPath(targetPath);\n }\n\n async captureActiveAuthSnapshot(): Promise<ActiveAuthSnapshot> {\n return this.captureAuthSnapshot(this.activeAuth);\n }\n\n /**\n * Decode a JWT payload into an object without validating the signature.\n */\n private decodeJwtPayload(token?: string | null): Record<string, unknown> | null {\n if (!token || typeof token !== 'string') {\n return null;\n }\n const cached = this.jwtPayloadCache.get(token);\n if (cached !== undefined) {\n return cached;\n }\n\n const segments = token.split('.');\n if (segments.length < 2) {\n this.jwtPayloadCache.set(token, null);\n return null;\n }\n\n try {\n const payload = Buffer.from(segments[1], 'base64url').toString('utf8');\n const parsed = JSON.parse(payload);\n const result =\n parsed && typeof parsed === 'object'\n ? (parsed as Record<string, unknown>)\n : null;\n if (this.jwtPayloadCache.size >= 512) {\n const oldest = this.jwtPayloadCache.keys().next().value;\n if (oldest) {\n this.jwtPayloadCache.delete(oldest);\n }\n }\n this.jwtPayloadCache.set(token, result);\n return result;\n } catch {\n this.jwtPayloadCache.set(token, null);\n return null;\n }\n }\n\n private toIsoStringFromSeconds(seconds?: number): string | undefined {\n if (typeof seconds !== 'number' || Number.isNaN(seconds)) {\n return undefined;\n }\n\n try {\n return new Date(seconds * 1000).toISOString();\n } catch {\n return undefined;\n }\n }\n\n private getProfileTokenRecencyMs(data: ProfileData | null | undefined): number | null {\n if (!data) {\n return null;\n }\n const candidates: number[] = [];\n const lastRefresh = typeof data.last_refresh === 'string' ? Date.parse(data.last_refresh) : Number.NaN;\n if (Number.isFinite(lastRefresh)) {\n candidates.push(lastRefresh);\n }\n const accessIssuedAt = this.decodeJwtPayload(data.access_token)?.iat;\n if (typeof accessIssuedAt === 'number' && Number.isFinite(accessIssuedAt)) {\n candidates.push(accessIssuedAt * 1000);\n }\n const idIssuedAt = this.decodeJwtPayload(data.id_token)?.iat;\n if (typeof idIssuedAt === 'number' && Number.isFinite(idIssuedAt)) {\n candidates.push(idIssuedAt * 1000);\n }\n return candidates.length > 0 ? Math.max(...candidates) : null;\n }\n\n private normalizeEmailCandidate(value: unknown): string | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (!trimmed || trimmed.includes(' ')) {\n return undefined;\n }\n\n const atIndex = trimmed.indexOf('@');\n if (atIndex <= 0 || atIndex === trimmed.length - 1) {\n return undefined;\n }\n\n const domain = trimmed.slice(atIndex + 1);\n if (!domain || !domain.includes('.')) {\n return undefined;\n }\n\n return trimmed;\n }\n\n private pickFirstEmail(candidates: Array<string | undefined>): string | undefined {\n for (const candidate of candidates) {\n const normalized = this.normalizeEmailCandidate(candidate);\n if (normalized) {\n return normalized;\n }\n }\n return undefined;\n }\n\n private findEmailInObject(value: unknown, seen = new Set<unknown>()): string | undefined {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n\n if (seen.has(value)) {\n return undefined;\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const entry of value) {\n const nested = this.findEmailInObject(entry, seen);\n if (nested) {\n return nested;\n }\n }\n return undefined;\n }\n\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (typeof entry === 'string') {\n const normalized = this.normalizeEmailCandidate(entry);\n const lowerKey = key.toLowerCase();\n const keyHintsAtEmail =\n lowerKey.includes('email') ||\n lowerKey.includes('contact') ||\n lowerKey.includes('username') ||\n lowerKey.includes('login');\n\n if (normalized && (keyHintsAtEmail || entry.includes('@'))) {\n return normalized;\n }\n }\n\n if (entry && typeof entry === 'object') {\n const nested = this.findEmailInObject(entry, seen);\n if (nested) {\n return nested;\n }\n }\n }\n\n return undefined;\n }\n\n private resolveProfileEmail(data: ProfileData, metadata?: ProfileMetadata): string | undefined {\n const direct = this.normalizeEmailCandidate(data.email);\n if (direct) {\n return direct;\n }\n\n if (metadata?.email) {\n return metadata.email;\n }\n\n return this.findEmailInObject(data);\n }\n\n private evaluateTokenStatus(data: ProfileData, metadata?: ProfileMetadata): TokenStatus {\n const expiresAt = metadata?.tokenExpiresAt ?? this.computeExpiryIso(data);\n const parsedExpiry = expiresAt ? Date.parse(expiresAt) : Number.NaN;\n const hasExpiry = !Number.isNaN(parsedExpiry);\n const tokenAlert = data.tokenAlert;\n\n if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {\n return {\n state: 'missing',\n reason: 'No authentication data saved for this profile.',\n expiresAt,\n issue: 'auth-missing',\n requiresUserAction: true,\n };\n }\n\n if (tokenAlert?.issue) {\n const reason = typeof tokenAlert.reason === 'string' && tokenAlert.reason.trim().length > 0\n ? tokenAlert.reason.trim()\n : tokenAlert.issue === 'refresh-redeemed'\n ? REFRESH_TOKEN_REDEEMED_REASON\n : 'Authentication needs attention. Re-login this profile.';\n const issue = (tokenAlert.issue as TokenIssue) ?? 'auth-missing';\n return {\n state: 'invalid',\n reason,\n expiresAt,\n issue,\n requiresUserAction: true,\n };\n }\n\n if (!data.access_token) {\n return {\n state: 'missing',\n reason: 'Access token is missing. Re-authenticate with Codex CLI.',\n expiresAt,\n issue: 'access-missing',\n requiresUserAction: true,\n };\n }\n\n if (!this.decodeJwtPayload(data.access_token)) {\n return {\n state: 'invalid',\n reason: 'Access token is corrupted or not a valid JWT.',\n expiresAt,\n issue: 'access-invalid',\n requiresUserAction: true,\n };\n }\n\n const refreshToken = typeof data.refresh_token === 'string' ? data.refresh_token.trim() : '';\n if (!refreshToken) {\n return {\n state: 'missing',\n reason: 'Refresh token is missing. Run Codex login again.',\n expiresAt,\n issue: 'refresh-missing',\n requiresUserAction: true,\n };\n }\n\n if (hasExpiry) {\n const diff = parsedExpiry - Date.now();\n if (diff <= 0) {\n return {\n state: 'expiring',\n reason: 'Access token expired.',\n expiresAt,\n accessTokenExpired: true,\n issue: 'access-expired',\n requiresUserAction: false,\n };\n }\n\n if (diff <= TOKEN_EXPIRING_SOON_WINDOW_MS) {\n return {\n state: 'expiring',\n reason: 'Access token expires soon.',\n expiresAt,\n issue: 'access-expiring',\n requiresUserAction: false,\n };\n }\n }\n\n return {\n state: 'ok',\n expiresAt,\n requiresUserAction: false,\n };\n }\n\n private extractProfileMetadata(data: ProfileData): ProfileMetadata | undefined {\n const idPayload = this.decodeJwtPayload(data.id_token) as Record<string, unknown> | null;\n const accessPayload = this.decodeJwtPayload(data.access_token) as Record<string, unknown> | null;\n\n if (!idPayload && !accessPayload) {\n return undefined;\n }\n\n const authInfo = (idPayload?.['https://api.openai.com/auth'] ??\n accessPayload?.['https://api.openai.com/auth']) as Record<string, unknown> | undefined;\n\n const profileInfo = accessPayload?.['https://api.openai.com/profile'] as Record<string, unknown> | undefined;\n\n const getNumber = (obj: Record<string, unknown> | null | undefined, key: string): number | undefined =>\n typeof obj?.[key] === 'number' ? (obj[key] as number) : undefined;\n\n const getString = (obj: Record<string, unknown> | undefined | null, key: string): string | undefined =>\n typeof obj?.[key] === 'string' ? (obj[key] as string) : undefined;\n\n const exp = getNumber(idPayload, 'exp') ?? getNumber(accessPayload, 'exp');\n const iat = getNumber(idPayload, 'iat') ?? getNumber(accessPayload, 'iat');\n const authTime = getNumber(idPayload, 'auth_time') ?? getNumber(accessPayload, 'auth_time');\n\n const organizationsRaw = Array.isArray(authInfo?.['organizations'])\n ? (authInfo?.['organizations'] as unknown[])\n : undefined;\n\n const organizations = organizationsRaw\n ? organizationsRaw\n .map((org): OrganizationInfo => {\n const record = org as Record<string, unknown> | undefined;\n return {\n id: getString(record, 'id'),\n title: getString(record, 'title'),\n role: getString(record, 'role'),\n isDefault: typeof record?.['is_default'] === 'boolean' ? (record?.['is_default'] as boolean) : undefined,\n };\n })\n .filter(\n org =>\n org.id ||\n org.title ||\n org.role ||\n typeof org.isDefault === 'boolean'\n )\n : undefined;\n\n const groups = Array.isArray(authInfo?.['groups'])\n ? (authInfo?.['groups'] as unknown[]).filter((group): group is string => typeof group === 'string')\n : undefined;\n\n const emailVerified =\n typeof profileInfo?.['email_verified'] === 'boolean'\n ? (profileInfo?.['email_verified'] as boolean)\n : typeof idPayload?.['email_verified'] === 'boolean'\n ? (idPayload?.['email_verified'] as boolean)\n : typeof accessPayload?.['email_verified'] === 'boolean'\n ? (accessPayload?.['email_verified'] as boolean)\n : undefined;\n\n const email =\n this.pickFirstEmail([\n getString(profileInfo, 'email'),\n getString(profileInfo, 'email_address'),\n getString(profileInfo, 'primary_email'),\n getString(profileInfo, 'default_email'),\n getString(profileInfo, 'contact_email'),\n ]) ??\n this.findEmailInObject(profileInfo) ??\n this.pickFirstEmail([\n getString(authInfo, 'user_email'),\n getString(authInfo, 'email'),\n getString(authInfo, 'userEmail'),\n getString(authInfo, 'chatgpt_user_email'),\n ]) ??\n this.findEmailInObject(authInfo) ??\n this.pickFirstEmail([\n getString(idPayload, 'email'),\n getString(idPayload, 'preferred_username'),\n getString(idPayload, 'username'),\n ]) ??\n this.findEmailInObject(idPayload) ??\n this.pickFirstEmail([\n getString(accessPayload, 'email'),\n ]) ??\n this.findEmailInObject(accessPayload);\n\n const subscription: SubscriptionInfo | undefined = authInfo\n ? {\n activeStart: getString(authInfo, 'chatgpt_subscription_active_start'),\n activeUntil: getString(authInfo, 'chatgpt_subscription_active_until'),\n lastChecked: getString(authInfo, 'chatgpt_subscription_last_checked'),\n }\n : undefined;\n\n const planType = getString(authInfo, 'chatgpt_plan_type');\n const chatgptUserId = getString(authInfo, 'chatgpt_user_id');\n const chatgptAccountUserId = getString(authInfo, 'chatgpt_account_user_id');\n const userId =\n getString(authInfo, 'user_id') ??\n chatgptAccountUserId ??\n getString(idPayload ?? undefined, 'sub') ??\n getString(accessPayload ?? undefined, 'sub');\n\n const metadata: ProfileMetadata = {\n email,\n planType,\n subscription,\n organizations,\n groups,\n userId,\n chatgptUserId,\n chatgptAccountUserId,\n emailVerified,\n tokenExpiresAt: this.toIsoStringFromSeconds(exp),\n tokenIssuedAt: this.toIsoStringFromSeconds(iat),\n tokenAuthTime: this.toIsoStringFromSeconds(authTime),\n };\n\n const hasMeaningfulData =\n Boolean(metadata.planType) ||\n Boolean(\n metadata.subscription &&\n (metadata.subscription.activeStart ||\n metadata.subscription.activeUntil ||\n metadata.subscription.lastChecked)\n ) ||\n Boolean(metadata.organizations && metadata.organizations.length > 0) ||\n Boolean(metadata.groups && metadata.groups.length > 0) ||\n Boolean(metadata.userId) ||\n Boolean(metadata.chatgptUserId) ||\n Boolean(metadata.chatgptAccountUserId) ||\n Boolean(metadata.email) ||\n typeof metadata.emailVerified === 'boolean' ||\n Boolean(metadata.tokenExpiresAt) ||\n Boolean(metadata.tokenIssuedAt) ||\n Boolean(metadata.tokenAuthTime);\n\n return hasMeaningfulData ? metadata : undefined;\n }\n\n /**\n * Initialize the profile manager and create necessary directories\n */\n async initialize(): Promise<void> {\n this.profileHomesRoot = join(getUserDataDir(), 'profile-homes');\n\n try {\n await fs.mkdir(this.codexDir, { recursive: true });\n } catch (error) {\n logError('Failed to ensure Codex directory exists:', error);\n throw errorWithCause('Failed to initialize profile manager', error);\n }\n try {\n await fs.mkdir(this.profileHomesRoot, { recursive: true });\n } catch (error) {\n logError('Failed to ensure profile homes directory exists:', error);\n throw errorWithCause('Failed to initialize profile manager', error);\n }\n }\n\n private enqueueAuthSwap<T>(task: () => Promise<T>): Promise<T> {\n const run = globalAuthSwapLock.then(task, task);\n globalAuthSwapLock = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private enqueueProfileOperation<T>(name: string, task: () => Promise<T>): Promise<T> {\n const key = this.normalizeProfileName(name);\n const previous = profileOperationLocks.get(key) ?? Promise.resolve();\n const run = previous.then(task, task);\n const tail = run.then(\n () => undefined,\n () => undefined,\n );\n profileOperationLocks.set(key, tail);\n void tail.finally(() => {\n if (profileOperationLocks.get(key) === tail) {\n profileOperationLocks.delete(key);\n }\n });\n return run;\n }\n\n private async writeAtomic(filePath: string, contents: string): Promise<void> {\n const tempPath = `${filePath}.tmp`;\n const dir = path.dirname(filePath);\n await fs.mkdir(dir, { recursive: true });\n\n await fs.writeFile(tempPath, contents, 'utf8');\n try {\n await fs.rename(tempPath, filePath);\n } catch (error) {\n // Fall back to writing directly if rename fails for any reason.\n try {\n await fs.writeFile(filePath, contents, 'utf8');\n } catch (writeError) {\n // Surface the original error context to aid debugging.\n const original = error instanceof Error ? error.message : String(error);\n const fallback = writeError instanceof Error ? writeError.message : String(writeError);\n throw errorWithCause(\n `Atomic write failed (rename: ${original}; direct write: ${fallback})`,\n writeError,\n );\n }\n }\n // Best-effort cleanup of temp file if it still exists.\n try {\n await fs.rm(tempPath, { force: true });\n } catch {\n // ignore cleanup failures\n }\n }\n\n /**\n * Extract account_id from auth data (supports both formats)\n */\n private getAccountIdFromData(data: ProfileData | ActiveAuth): string | undefined {\n if ('account_id' in data && typeof data.account_id === 'string' && data.account_id.trim()) {\n return data.account_id.trim();\n }\n\n if ('tokens' in data && data.tokens && typeof data.tokens === 'object') {\n const accountId = (data.tokens as { account_id?: unknown }).account_id;\n if (typeof accountId === 'string' && accountId.trim()) {\n return accountId.trim();\n }\n }\n\n const email =\n 'email' in data && typeof (data as ProfileData).email === 'string'\n ? (data as ProfileData).email?.trim()\n : undefined;\n return email || undefined;\n }\n\n private resolveProfileIdentityKey(args: {\n name?: string | null;\n accountId?: string | null;\n workspaceId?: string | null;\n email?: string | null;\n metadata?: ProfileMetadata;\n }): string | null {\n return resolveSharedProfileIdentityKey(args);\n }\n\n private resolveProfileIdentityFromData(\n name: string | null | undefined,\n data: ProfileData | ActiveAuth,\n metadata?: ProfileMetadata,\n ): string | null {\n const resolvedMetadata = metadata ?? this.extractProfileMetadata(data);\n const workspace = this.resolveWorkspaceIdentity(data, resolvedMetadata);\n const email = this.resolveProfileEmail(data, resolvedMetadata) ?? null;\n return this.resolveProfileIdentityKey({\n name,\n accountId: this.getAccountIdFromData(data) ?? null,\n workspaceId: workspace.id ?? null,\n email,\n metadata: resolvedMetadata,\n });\n }\n\n private resolveProfileIdentityFromRecord(record: ProfileRecord): string {\n return (\n this.resolveProfileIdentityFromData(record.name, record.data, record.metadata) ??\n resolveFallbackAccountKey(record.name)\n );\n }\n\n private identityWorkspaceIndexKey(identityKey: string, workspaceId: string): string {\n return `${identityKey}\\u0000${this.normalizeWorkspaceId(workspaceId)}`;\n }\n\n private async getProfileRecordIndex(): Promise<ProfileRecordIndex> {\n const source = await this.readProfilesStateSource();\n if (this.profileRecordIndexCache?.source === source) {\n return this.profileRecordIndexCache;\n }\n\n const records: ProfileRecord[] = [];\n const byIdentityWorkspace = new Map<string, ProfileRecord[]>();\n for (const [profileName, raw] of Object.entries(source)) {\n const record = this.fromStateRecord(profileName, raw);\n if (!record) {\n continue;\n }\n records.push(record);\n const identityKey = this.resolveProfileIdentityFromRecord(record);\n const workspaceId = record.workspaceId ?? record.data.workspace_id ?? DEFAULT_WORKSPACE_ID;\n const key = this.identityWorkspaceIndexKey(identityKey, workspaceId);\n const bucket = byIdentityWorkspace.get(key);\n if (bucket) {\n bucket.push(record);\n } else {\n byIdentityWorkspace.set(key, [record]);\n }\n }\n\n const index = { source, records, byIdentityWorkspace };\n this.profileRecordIndexCache = index;\n return index;\n }\n\n private describeActiveAuth(auth: ActiveAuth): {\n normalized: ProfileData;\n metadata?: ProfileMetadata;\n workspaceId: string;\n workspaceName: string | null;\n email: string | null;\n accountId: string | null;\n identityKey: string | null;\n hasTokenPayload: boolean;\n } {\n const normalized = this.normalizeProfileData(auth);\n if (typeof normalized.auth_method === 'string') {\n normalized.auth_method = normalized.auth_method.trim().toLowerCase();\n }\n normalized.auth_method = normalized.auth_method ?? 'codex-cli';\n\n const metadata = this.extractProfileMetadata(normalized);\n const workspace = this.resolveWorkspaceIdentity(normalized, metadata);\n const workspaceId = workspace.id || DEFAULT_WORKSPACE_ID;\n const workspaceName = workspace.name ?? null;\n normalized.workspace_id = normalized.workspace_id ?? workspaceId;\n if (workspaceName) {\n normalized.workspace_name = normalized.workspace_name ?? workspaceName;\n }\n\n const email = this.resolveProfileEmail(normalized, metadata) ?? null;\n if (email) {\n normalized.email = email;\n }\n\n const accountId = this.getAccountIdFromData(normalized) ?? null;\n const identityKey = this.resolveProfileIdentityFromData(null, normalized, metadata);\n const hasTokenPayload = Boolean(\n normalized.id_token ||\n normalized.access_token ||\n normalized.refresh_token ||\n accountId ||\n email,\n );\n\n return {\n normalized,\n metadata,\n workspaceId,\n workspaceName,\n email,\n accountId,\n identityKey,\n hasTokenPayload,\n };\n }\n\n private async findProfileForActiveAuth(\n identityKey: string,\n workspaceId: string,\n ): Promise<ProfileRecord | undefined> {\n return this.getProfileRowByIdentityAndWorkspace(identityKey, workspaceId, {\n preferAuthMethod: 'codex-cli',\n });\n }\n\n private async syncMatchedProfileFromActiveAuth(\n record: ProfileRecord,\n description: ReturnType<ProfileManager['describeActiveAuth']>,\n ): Promise<void> {\n if (!this.hasTokenChanges(record.data, description.normalized)) {\n return;\n }\n const { profile: merged, metadata } = this.mergeProfileRecords(record.data, description.normalized);\n delete merged.tokenAlert;\n await this.persistProfileRecord(record.name, merged, metadata);\n }\n\n private async assertActiveAuthMatchesRecord(record: ProfileRecord, message: string): Promise<void> {\n const activeAuth = await this.readActiveAuthFile();\n if (!activeAuth) {\n throw new Error('Active Codex auth is missing. Refresh profiles and try again.');\n }\n\n const activeDescription = this.describeActiveAuth(activeAuth);\n const targetIdentity = this.resolveProfileIdentityFromRecord(record);\n const targetWorkspaceId = this.normalizeWorkspaceId(record.workspaceId ?? record.data.workspace_id);\n if (\n activeDescription.identityKey !== targetIdentity ||\n this.normalizeWorkspaceId(activeDescription.workspaceId) !== targetWorkspaceId\n ) {\n throw new Error(message);\n }\n }\n\n private async writeActiveAuthForRecord(record: ProfileRecord): Promise<void> {\n const profileData = record.data;\n const targetIdentity = this.resolveProfileIdentityFromRecord(record);\n const targetWorkspaceId = this.normalizeWorkspaceId(record.workspaceId ?? profileData.workspace_id);\n const codexFormat = this.convertToCodexFormat(profileData);\n await this.writeAtomic(this.activeAuth, JSON.stringify(codexFormat, null, 2));\n\n const written = await this.readActiveAuthFile();\n if (!written) {\n throw new Error('Codex auth file was not written.');\n }\n const writtenDescription = this.describeActiveAuth(written);\n if (writtenDescription.identityKey !== targetIdentity) {\n throw new Error('Codex auth verification failed after profile switch.');\n }\n if (this.normalizeWorkspaceId(writtenDescription.workspaceId) !== targetWorkspaceId) {\n throw new Error('Codex auth workspace verification failed after profile switch.');\n }\n }\n\n private async syncActiveAuthFromProfileIfCurrent(name: string): Promise<void> {\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n return;\n }\n\n const activeAuth = await this.readActiveAuthFile();\n if (!activeAuth) {\n return;\n }\n\n const activeDescription = this.describeActiveAuth(activeAuth);\n const targetIdentity = this.resolveProfileIdentityFromRecord(record);\n const targetWorkspaceId = this.normalizeWorkspaceId(record.workspaceId ?? record.data.workspace_id);\n if (\n activeDescription.identityKey !== targetIdentity ||\n this.normalizeWorkspaceId(activeDescription.workspaceId) !== targetWorkspaceId\n ) {\n return;\n }\n\n await this.writeActiveAuthForRecord(record);\n }\n\n private async removeActiveAuthFiles(): Promise<void> {\n await fs.rm(this.activeAuth, { force: true });\n await fs.rm(`${this.activeAuth}.tmp`, { force: true });\n }\n\n private resolveAutoImportedProfileName(email: string | null, existingRecords: ProfileRecord[]): string {\n const source = email ? email.split('@')[0] : 'codex-account';\n const base =\n source\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 48) || 'codex-account';\n const used = new Set(existingRecords.map(record => record.name));\n let candidate = this.normalizeProfileName(base);\n let suffix = 2;\n while (used.has(candidate)) {\n candidate = this.normalizeProfileName(`${base}-${suffix}`);\n suffix += 1;\n }\n return candidate;\n }\n\n private buildActiveCodexAuthStatus(\n state: ActiveCodexAuthStatus['state'],\n description?: ReturnType<ProfileManager['describeActiveAuth']>,\n options?: {\n profileName?: string | null;\n importedProfileName?: string | null;\n importBlockedReason?: string | null;\n },\n ): ActiveCodexAuthStatus {\n return {\n state,\n profileName: options?.profileName ?? null,\n email: description?.email ?? null,\n accountId: description?.accountId ?? null,\n workspaceId: description?.workspaceId ?? null,\n workspaceName: description?.workspaceName ?? null,\n importedProfileName: options?.importedProfileName ?? null,\n importBlockedReason: options?.importBlockedReason ?? null,\n };\n }\n\n private resolveWorkspaceIdentity(data: ProfileData | ActiveAuth, metadata?: ProfileMetadata): { id: string; name?: string } {\n const directId =\n 'workspace_id' in data && typeof data.workspace_id === 'string'\n ? data.workspace_id.trim()\n : undefined;\n const directName =\n 'workspace_name' in data && typeof data.workspace_name === 'string'\n ? data.workspace_name.trim()\n : undefined;\n\n if (directId) {\n return { id: directId, name: directName };\n }\n\n const organizations = metadata?.organizations;\n if (organizations && organizations.length > 0) {\n const preferred = organizations.find(org => org.isDefault) ?? organizations[0];\n if (preferred?.id) {\n return { id: preferred.id, name: preferred.title ?? directName };\n }\n }\n\n return { id: DEFAULT_WORKSPACE_ID, name: directName };\n }\n\n private async getProfileRowByName(name: string): Promise<ProfileRecord | undefined> {\n const normalized = this.normalizeProfileName(name);\n const record = await this.readProfileRecord(normalized);\n return record ?? undefined;\n }\n\n private async getProfileRowByIdentityAndWorkspace(\n identityKey: string,\n workspaceId: string,\n options?: { authMethod?: string | null; preferAuthMethod?: string | null },\n ): Promise<ProfileRecord | undefined> {\n const index = await this.getProfileRecordIndex();\n const matches =\n index.byIdentityWorkspace.get(this.identityWorkspaceIndexKey(identityKey, workspaceId)) ?? [];\n\n if (matches.length === 0) {\n return undefined;\n }\n\n const mustMatch = typeof options?.authMethod === 'string' ? options.authMethod.trim().toLowerCase() : null;\n if (mustMatch) {\n return matches.find(record => this.resolveAuthMethod(record.data) === mustMatch);\n }\n\n const prefer = typeof options?.preferAuthMethod === 'string' ? options.preferAuthMethod.trim().toLowerCase() : null;\n if (prefer) {\n return matches.find(record => this.resolveAuthMethod(record.data) === prefer) ?? matches[0];\n }\n\n return matches[0];\n }\n\n private normalizeWorkspaceId(value: string | null | undefined): string {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : DEFAULT_WORKSPACE_ID;\n }\n\n private async persistProfileRecord(\n name: string,\n data: ProfileData,\n metadata?: ProfileMetadata,\n options?: { displayName?: string | null },\n ): Promise<void> {\n const resolvedName = this.normalizeProfileName(name);\n const existingRecord = await this.readProfileRecord(resolvedName);\n if (typeof data.auth_method === 'string') {\n data.auth_method = data.auth_method.trim().toLowerCase();\n }\n if (!data.auth_method) {\n data.auth_method = 'codex-cli';\n }\n const resolvedMetadata = metadata ?? this.extractProfileMetadata(data) ?? existingRecord?.metadata;\n const workspace = this.resolveWorkspaceIdentity(data, resolvedMetadata);\n const workspaceId = workspace.id || DEFAULT_WORKSPACE_ID;\n const workspaceName = workspace.name ?? null;\n if (!data.workspace_id) {\n data.workspace_id = workspaceId;\n }\n if (!data.workspace_name && workspaceName) {\n data.workspace_name = workspaceName;\n }\n\n const now = new Date().toISOString();\n const accountId = this.getAccountIdFromData(data) ?? null;\n const resolvedEmail = this.resolveProfileEmail(data, resolvedMetadata) ?? data.email ?? null;\n if (resolvedEmail) {\n data.email = resolvedEmail;\n }\n const createdAt = data.created_at ?? existingRecord?.createdAt ?? now;\n data.created_at = createdAt;\n const updatedAt = data.updated_at ?? now;\n data.updated_at = updatedAt;\n\n const displayName =\n typeof options?.displayName === 'string' && options.displayName.trim().length > 0\n ? options.displayName.trim()\n : existingRecord?.displayName ?? resolvedName;\n\n const record: ProfileRecord = {\n name: resolvedName,\n displayName,\n data,\n metadata: resolvedMetadata,\n accountId,\n workspaceId: data.workspace_id ?? workspaceId,\n workspaceName: data.workspace_name ?? workspaceName,\n email: resolvedEmail ?? null,\n authMethod: typeof data.auth_method === 'string' ? data.auth_method : null,\n createdAt,\n updatedAt,\n };\n\n await fs.mkdir(this.getProfileHomePath(resolvedName), { recursive: true });\n await this.writeProfileRecord(record);\n }\n\n private buildProfileFromRow(row: ProfileRecord): Profile {\n const profile = this.buildProfileFromData(row.name, row.data, {\n displayName: row.displayName ?? undefined,\n email: row.email ?? undefined,\n createdAt: row.createdAt ?? undefined,\n authMethod: row.authMethod ?? undefined,\n accountId: row.accountId ?? undefined,\n workspaceId: row.workspaceId ?? undefined,\n workspaceName: row.workspaceName ?? undefined,\n metadata: row.metadata,\n });\n\n return profile;\n }\n\n private async deleteProfileRecordAndHome(record: ProfileRecord): Promise<void> {\n const profileName = this.normalizeProfileName(record.name);\n if (!record.accountId) {\n const dashboardState = await this.readProfileDashboardState();\n delete dashboardState.customGroupsByAccountKey[resolveFallbackAccountKey(profileName)];\n await this.writeProfileDashboardState(dashboardState);\n }\n try {\n await fs.rm(this.getProfileHomePath(profileName), { recursive: true, force: true });\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to remove profile home for '${profileName}':`, error);\n }\n }\n await this.deleteProfileRecord(profileName);\n }\n\n private buildProfileFromData(\n name: string,\n data: ProfileData,\n fallback?: {\n displayName?: string;\n email?: string;\n createdAt?: string;\n authMethod?: string;\n accountId?: string;\n workspaceId?: string;\n workspaceName?: string;\n metadata?: ProfileMetadata;\n },\n ): Profile {\n const metadata = fallback?.metadata ?? this.extractProfileMetadata(data);\n const workspace = this.resolveWorkspaceIdentity(data, metadata);\n const workspaceId = workspace.id || fallback?.workspaceId || DEFAULT_WORKSPACE_ID;\n const workspaceName = workspace.name ?? fallback?.workspaceName ?? undefined;\n const email = this.resolveProfileEmail(data, metadata) ?? fallback?.email ?? undefined;\n const tokenStatus = this.evaluateTokenStatus(data, metadata);\n const accountId = this.getAccountIdFromData(data) ?? fallback?.accountId;\n\n return {\n name,\n displayName: fallback?.displayName ?? name,\n isValid: Boolean(data && Object.keys(data).length > 0),\n accountId,\n workspaceId,\n workspaceName,\n email,\n createdAt: data.created_at ?? fallback?.createdAt ?? undefined,\n authMethod: typeof data.auth_method === 'string'\n ? data.auth_method.trim().toLowerCase()\n : fallback?.authMethod ?? undefined,\n metadata,\n tokenStatus,\n };\n }\n\n /**\n * Convert profile data to Codex's expected format\n */\n private convertToCodexFormat(data: ProfileData): ActiveAuth {\n // Check if data is already in Codex format\n if ('tokens' in data) {\n return data as ActiveAuth;\n }\n\n // Convert flat structure to nested Codex format.\n // Keep existing refresh metadata if present; never forge it.\n const lastRefresh = typeof data.last_refresh === 'string' ? data.last_refresh.trim() : '';\n let normalizedLastRefresh = lastRefresh.length > 0 ? lastRefresh : undefined;\n if (!normalizedLastRefresh) {\n const accessPayload = this.decodeJwtPayload(data.access_token);\n const tokenIssuedAt = typeof accessPayload?.iat === 'number'\n ? this.toIsoStringFromSeconds(accessPayload.iat)\n : undefined;\n if (tokenIssuedAt) {\n normalizedLastRefresh = tokenIssuedAt;\n }\n }\n if (!normalizedLastRefresh) {\n const createdAt = typeof data.created_at === 'string' ? data.created_at.trim() : '';\n if (createdAt) {\n normalizedLastRefresh = createdAt;\n }\n }\n const codexAuth: ActiveAuth = {\n OPENAI_API_KEY: null,\n tokens: {\n id_token: data.id_token,\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n account_id: data.account_id,\n ...(normalizedLastRefresh ? { last_refresh: normalizedLastRefresh } : {}),\n },\n };\n if (normalizedLastRefresh) {\n codexAuth.last_refresh = normalizedLastRefresh;\n }\n const email = typeof data.email === 'string' ? data.email.trim() : '';\n if (email) {\n codexAuth.email = email;\n }\n const workspaceId = typeof data.workspace_id === 'string' ? data.workspace_id.trim() : '';\n if (workspaceId) {\n codexAuth.workspace_id = workspaceId;\n }\n const workspaceName = typeof data.workspace_name === 'string' ? data.workspace_name.trim() : '';\n if (workspaceName) {\n codexAuth.workspace_name = workspaceName;\n }\n return codexAuth;\n }\n\n /**\n * Normalize Codex auth data to flat profile format\n */\n private normalizeProfileData(data: ActiveAuth): ProfileData {\n // If data is already in flat format, return as-is\n if ('id_token' in data) {\n return data as ProfileData;\n }\n\n // Convert nested Codex format to flat\n const tokens = data.tokens || {};\n const profile: ProfileData = {\n id_token: tokens.id_token,\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n account_id: tokens.account_id,\n };\n const tokenLastRefresh = typeof tokens.last_refresh === 'string' ? tokens.last_refresh.trim() : '';\n const rootLastRefresh = typeof data.last_refresh === 'string' ? data.last_refresh.trim() : '';\n const normalizedLastRefresh = tokenLastRefresh || rootLastRefresh;\n if (normalizedLastRefresh) {\n profile.last_refresh = normalizedLastRefresh;\n }\n\n const email = typeof data.email === 'string' ? data.email.trim() : '';\n if (email) {\n profile.email = email;\n }\n const workspaceId = typeof data.workspace_id === 'string' ? data.workspace_id.trim() : '';\n if (workspaceId) {\n profile.workspace_id = workspaceId;\n }\n const workspaceName = typeof data.workspace_name === 'string' ? data.workspace_name.trim() : '';\n if (workspaceName) {\n profile.workspace_name = workspaceName;\n }\n\n return profile;\n }\n\n private mergeProfileRecords(existing: ProfileData, incoming: ProfileData): {\n profile: ProfileData;\n metadata?: ProfileMetadata;\n } {\n const merged: ProfileData = {\n ...existing,\n ...incoming,\n created_at: existing.created_at ?? incoming.created_at ?? new Date().toISOString(),\n };\n\n if (typeof merged.auth_method === 'string') {\n merged.auth_method = merged.auth_method.trim().toLowerCase();\n }\n if (!merged.auth_method) {\n merged.auth_method = 'codex-cli';\n }\n\n const metadata = this.extractProfileMetadata(merged);\n const resolvedEmail = this.resolveProfileEmail(merged, metadata);\n\n if (resolvedEmail) {\n merged.email = resolvedEmail;\n }\n\n const workspace = this.resolveWorkspaceIdentity(merged, metadata);\n if (!merged.workspace_id) {\n merged.workspace_id = workspace.id || existing.workspace_id || DEFAULT_WORKSPACE_ID;\n }\n if (!merged.workspace_name) {\n merged.workspace_name = workspace.name ?? existing.workspace_name;\n }\n\n if (this.hasTokenChanges(existing, incoming)) {\n delete merged.tokenAlert;\n }\n\n return { profile: merged, metadata };\n }\n\n private hasTokenChanges(existing: ProfileData, incoming: ProfileData): boolean {\n const tokenKeys: Array<keyof ProfileData> = [\n 'id_token',\n 'access_token',\n 'refresh_token',\n 'last_refresh',\n 'account_id',\n 'workspace_id',\n ];\n\n return tokenKeys.some(key => {\n const nextValue = incoming[key];\n if (typeof nextValue !== 'string' || nextValue.length === 0) {\n return false;\n }\n return nextValue !== existing[key];\n });\n }\n\n async flagAuthIssue(\n name: string,\n issue: TokenIssue,\n reason?: string,\n options?: { observedAt?: string },\n ): Promise<void> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n logWarn(`Cannot flag auth issue '${issue}' for missing profile '${profileName}'.`);\n return;\n }\n\n const observedAt = options?.observedAt ? Date.parse(options.observedAt) : null;\n const updatedAt = record.updatedAt ? Date.parse(record.updatedAt) : null;\n if (observedAt !== null && updatedAt !== null && observedAt <= updatedAt) {\n return;\n }\n\n const data: ProfileData = record.data;\n\n const trimmedReason = typeof reason === 'string' && reason.trim().length > 0 ? reason.trim() : undefined;\n const normalized = trimmedReason?.toLowerCase() ?? '';\n const storedReason = issue === 'refresh-redeemed'\n ? (normalized.includes(REFRESH_TOKEN_REDEEMED_SNIPPET)\n ? REFRESH_TOKEN_REDEEMED_REASON\n : trimmedReason ?? REFRESH_TOKEN_REDEEMED_REASON)\n : trimmedReason;\n const alert: TokenAlert = {\n issue,\n reason: storedReason,\n recordedAt: new Date().toISOString(),\n };\n\n data.tokenAlert = alert;\n\n try {\n const metadata = this.extractProfileMetadata(data);\n await this.persistProfileRecord(profileName, data, metadata);\n } catch (error) {\n logError(`Failed to persist token alert for profile '${profileName}':`, error);\n }\n }\n\n async flagRefreshTokenRedeemed(name: string, reason?: string, options?: { observedAt?: string }): Promise<void> {\n await this.flagAuthIssue(name, 'refresh-redeemed', reason, options);\n }\n\n private async syncProfileTokensFromActiveAuth(\n profileName: string,\n baselineProfile: ProfileData,\n authPath?: string,\n ): Promise<void> {\n const targetPath = authPath ?? this.activeAuth;\n try {\n const authRaw = await fs.readFile(targetPath, 'utf8');\n await this.syncProfileTokensFromAuthContent(profileName, baselineProfile, authRaw);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read Codex auth for '${profileName}' while syncing tokens:`, error);\n }\n }\n }\n\n private async syncProfileTokensFromProfileHome(\n profileName: string,\n baselineProfile: ProfileData,\n ): Promise<ProfileData> {\n const authPath = path.join(this.getProfileHomePath(profileName), 'auth.json');\n let fileKey: string;\n try {\n const stats = await fs.stat(authPath);\n fileKey = `${stats.mtimeMs}:${stats.size}`;\n const cached = this.profileHomeAuthSyncCache.get(profileName);\n const currentRecency = this.getProfileTokenRecencyMs(baselineProfile);\n if (\n cached?.fileKey === fileKey &&\n (cached.tokenRecencyMs === null ||\n (typeof currentRecency === 'number' && currentRecency >= cached.tokenRecencyMs))\n ) {\n return baselineProfile;\n }\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to stat profile-home auth for '${profileName}' while syncing tokens:`, error);\n }\n return baselineProfile;\n }\n let authRaw: string;\n try {\n authRaw = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read profile-home auth for '${profileName}' while syncing tokens:`, error);\n }\n return baselineProfile;\n }\n\n const updatedRecord = await this.getProfileRowByName(profileName);\n const currentProfile = updatedRecord?.data ?? baselineProfile;\n let normalized: ProfileData;\n try {\n normalized = this.normalizeProfileData(JSON.parse(authRaw) as ActiveAuth);\n } catch (error) {\n logWarn(`Failed to parse profile-home auth for '${profileName}' while syncing tokens:`, error);\n return currentProfile;\n }\n\n const profileHomeRecency = this.getProfileTokenRecencyMs(normalized);\n this.profileHomeAuthSyncCache.set(profileName, {\n fileKey,\n tokenRecencyMs: profileHomeRecency,\n });\n const currentRecency = this.getProfileTokenRecencyMs(currentProfile);\n if (\n typeof profileHomeRecency !== 'number' ||\n (typeof currentRecency === 'number' && profileHomeRecency <= currentRecency)\n ) {\n return currentProfile;\n }\n\n await this.syncProfileTokensFromAuthContent(profileName, currentProfile, authRaw);\n return (await this.getProfileRowByName(profileName))?.data ?? currentProfile;\n }\n\n private async syncProfileTokensFromAuthContent(\n profileName: string,\n baselineProfile: ProfileData,\n authContent: string,\n ): Promise<void> {\n let activeAuth: ActiveAuth;\n try {\n activeAuth = JSON.parse(authContent) as ActiveAuth;\n } catch (error) {\n logWarn(`Failed to parse Codex auth while syncing tokens for '${profileName}':`, error);\n return;\n }\n\n const normalized = this.normalizeProfileData(activeAuth);\n const metadata = this.extractProfileMetadata(normalized);\n const workspace = this.resolveWorkspaceIdentity(normalized, metadata);\n normalized.workspace_id = normalized.workspace_id ?? workspace.id ?? DEFAULT_WORKSPACE_ID;\n if (workspace.name) {\n normalized.workspace_name = normalized.workspace_name ?? workspace.name;\n }\n const hasTokens =\n typeof normalized.id_token === 'string' ||\n typeof normalized.access_token === 'string' ||\n typeof normalized.refresh_token === 'string';\n\n if (!hasTokens) {\n return;\n }\n\n let existing = baselineProfile;\n const latestRow = await this.getProfileRowByName(profileName);\n if (latestRow) {\n existing = latestRow.data;\n }\n\n const existingMetadata = this.extractProfileMetadata(existing);\n const existingWorkspace = this.resolveWorkspaceIdentity(existing, existingMetadata);\n existing.workspace_id = existing.workspace_id ?? existingWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (existingWorkspace.name) {\n existing.workspace_name = existing.workspace_name ?? existingWorkspace.name;\n }\n const existingIdentity = this.resolveProfileIdentityFromData(profileName, existing, existingMetadata);\n const nextIdentity = this.resolveProfileIdentityFromData(profileName, normalized, metadata);\n\n if (existingIdentity && nextIdentity && existingIdentity !== nextIdentity) {\n logInfo(\n `Skipped syncing tokens for profile '${profileName}' because Codex auth switched to a different OpenAI identity.`,\n );\n return;\n }\n if (this.normalizeWorkspaceId(existing.workspace_id) !== this.normalizeWorkspaceId(normalized.workspace_id)) {\n logInfo(\n `Skipped syncing tokens for profile '${profileName}' because Codex auth switched to a different workspace.`,\n );\n return;\n }\n\n if (!this.hasTokenChanges(existing, normalized)) {\n return;\n }\n\n const { profile: merged, metadata: mergedMetadata } = this.mergeProfileRecords(existing, normalized);\n\n try {\n await this.persistProfileRecord(profileName, merged, mergedMetadata);\n } catch (error) {\n logError(`Failed to persist refreshed tokens for profile '${profileName}':`, error);\n }\n }\n\n private async copyCodexConfig(targetCodexHome: string): Promise<void> {\n const candidates = ['config.toml', 'config.json', 'config.yaml', 'config.yml'];\n for (const file of candidates) {\n const source = join(this.codexDir, file);\n const destination = join(targetCodexHome, file);\n try {\n await fs.copyFile(source, destination);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to copy Codex config '${file}' to profile home:`, error);\n }\n }\n }\n }\n\n private getProfileHomePath(profileName: string): string {\n return join(this.profileHomesRoot, profileName);\n }\n\n private ensureTrailingNewline(content: string): string {\n return content.endsWith('\\n') ? content : `${content}\\n`;\n }\n\n private async sanitizeProfileConfig(profileHome: string): Promise<void> {\n const configPath = join(profileHome, 'config.toml');\n let raw: string;\n try {\n raw = await fs.readFile(configPath, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read config for profile home '${profileHome}':`, error);\n }\n return;\n }\n\n let parsed: Record<string, unknown>;\n try {\n parsed = parse(raw) as Record<string, unknown>;\n } catch (error) {\n logWarn(`Failed to parse config.toml for profile home '${profileHome}':`, error);\n return;\n }\n\n if (!Object.prototype.hasOwnProperty.call(parsed, 'model_reasoning_effort')) {\n return;\n }\n\n delete parsed['model_reasoning_effort'];\n const sanitized = this.ensureTrailingNewline(\n stringify(parsed as Parameters<typeof stringify>[0]),\n );\n try {\n await fs.writeFile(configPath, sanitized, 'utf8');\n } catch (error) {\n logWarn(`Failed to write sanitized config.toml for profile home '${profileHome}':`, error);\n }\n }\n\n private async prepareProfileHome(profileName: string, authData: ActiveAuth): Promise<string> {\n const profileHome = this.getProfileHomePath(profileName);\n await fs.mkdir(profileHome, { recursive: true });\n const authPath = join(profileHome, 'auth.json');\n await this.writeAtomic(authPath, JSON.stringify(authData, null, 2));\n await this.copyCodexConfig(profileHome);\n await this.sanitizeProfileConfig(profileHome);\n return profileHome;\n }\n\n /**\n * List all available profiles\n */\n async profileExists(name: string): Promise<boolean> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n return Boolean(await this.getProfileRowByName(profileName));\n }\n\n async listProfiles(): Promise<Profile[]> {\n await this.initialize();\n try {\n const records = await this.listProfileRecords();\n return records\n .map(record => this.buildProfileFromRow(record))\n .filter(profile => !profile.authMethod || profile.authMethod === 'codex-cli')\n .sort((a, b) => {\n const aLabel = a.displayName ?? a.name;\n const bLabel = b.displayName ?? b.name;\n const base = aLabel.localeCompare(bLabel);\n return base !== 0 ? base : a.name.localeCompare(b.name);\n });\n } catch (error) {\n logError('Error reading profiles from disk:', error);\n return [];\n }\n }\n\n private async runWithPreparedProfileHome<T>(\n name: string,\n action: (env: NodeJS.ProcessEnv) => Promise<T>,\n options: { syncFromActiveAuthBeforeAction?: boolean } = {},\n ): Promise<T> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n let profileData: ProfileData = record.data;\n if (options.syncFromActiveAuthBeforeAction !== false) {\n await this.syncProfileTokensFromActiveAuth(profileName, profileData);\n const updatedRecord = await this.getProfileRowByName(profileName);\n if (updatedRecord) {\n profileData = updatedRecord.data;\n }\n } else {\n profileData = await this.syncProfileTokensFromProfileHome(profileName, profileData);\n }\n\n if (profileData.auth_method && profileData.auth_method !== 'codex-cli') {\n throw new Error('Unsupported auth method. Codex CLI profiles only.');\n }\n\n const codexFormat = this.convertToCodexFormat(profileData);\n const profileHome = await this.prepareProfileHome(profileName, codexFormat);\n const authPath = path.join(profileHome, 'auth.json');\n\n const envOverrides: NodeJS.ProcessEnv = {\n ...process.env,\n HOME: profileHome,\n CODEX_HOME: profileHome,\n };\n\n try {\n return await action(envOverrides);\n } finally {\n let finalAuthContent: string | null = null;\n try {\n finalAuthContent = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read isolated auth for '${profileName}' after action:`, error);\n }\n }\n\n try {\n if (finalAuthContent) {\n await this.syncProfileTokensFromAuthContent(profileName, profileData, finalAuthContent);\n } else {\n await this.syncProfileTokensFromActiveAuth(profileName, profileData, authPath);\n }\n } catch (error) {\n logWarn(`Failed to sync refreshed tokens for profile '${profileName}':`, error);\n }\n }\n }\n\n async prepareProfileRuntime(\n name: string,\n options: { syncFromActiveAuthBeforeAction?: boolean } = {},\n ): Promise<PreparedProfileRuntime> {\n return this.enqueueProfileOperation(name, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n let profileData: ProfileData = record.data;\n if (options.syncFromActiveAuthBeforeAction !== false) {\n await this.syncProfileTokensFromActiveAuth(profileName, profileData);\n const updatedRecord = await this.getProfileRowByName(profileName);\n if (updatedRecord) {\n profileData = updatedRecord.data;\n }\n } else {\n profileData = await this.syncProfileTokensFromProfileHome(profileName, profileData);\n }\n\n if (profileData.auth_method && profileData.auth_method !== 'codex-cli') {\n throw new Error('Unsupported auth method. Codex CLI profiles only.');\n }\n\n const codexFormat = this.convertToCodexFormat(profileData);\n const profileHome = await this.prepareProfileHome(profileName, codexFormat);\n return {\n profileHome,\n env: {\n ...process.env,\n HOME: profileHome,\n CODEX_HOME: profileHome,\n },\n };\n }),\n );\n }\n\n async syncProfileRuntime(name: string, profileHome?: string): Promise<void> {\n return this.enqueueProfileOperation(name, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const authPath = path.join(profileHome ?? this.getProfileHomePath(profileName), 'auth.json');\n let finalAuthContent: string | null = null;\n try {\n finalAuthContent = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to read isolated auth for '${profileName}' while syncing runtime:`, error);\n }\n }\n\n if (finalAuthContent) {\n await this.syncProfileTokensFromAuthContent(profileName, record.data, finalAuthContent);\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n return;\n }\n\n await this.syncProfileTokensFromActiveAuth(profileName, record.data, authPath);\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n }),\n );\n }\n\n /**\n * Create a new profile by running codex login\n */\n private async readAuthFileForImport(authPath: string, actionLabel: string): Promise<ActiveAuth> {\n let authRaw: string;\n try {\n authRaw = await fs.readFile(authPath, 'utf8');\n } catch (error) {\n if (this.isNotFoundError(error)) {\n throw errorWithCause(\n `Codex CLI did not produce an auth file. Complete the login before ${actionLabel}.`,\n error,\n );\n }\n logError(`Failed to read Codex auth file during ${actionLabel}:`, error);\n throw errorWithCause(\n 'Failed to read Codex auth file. Complete the login and try again.',\n error,\n );\n }\n\n try {\n return JSON.parse(authRaw) as ActiveAuth;\n } catch (error) {\n logError(`Failed to parse Codex auth file during ${actionLabel}:`, error);\n throw errorWithCause(\n 'Failed to parse Codex auth file. Complete the login and try again.',\n error,\n );\n }\n }\n\n private async persistNewProfileFromAuth(profileName: string, authData: ActiveAuth): Promise<Profile | null> {\n const description = this.describeActiveAuth(authData);\n const normalizedProfile = description.normalized;\n normalizedProfile.created_at = normalizedProfile.created_at ?? new Date().toISOString();\n\n await this.persistProfileRecord(profileName, normalizedProfile, description.metadata);\n const stored = await this.getProfileRowByName(profileName);\n return stored ? this.buildProfileFromRow(stored) : null;\n }\n\n async createProfile(name: string): Promise<Profile | null> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n\n if (await this.getProfileRowByName(profileName)) {\n throw new Error(`Profile '${profileName}' already exists!`);\n }\n\n try {\n const authData = await this.readAuthFileForImport(this.activeAuth, 'profile creation');\n return await this.persistNewProfileFromAuth(profileName, authData);\n } catch (error) {\n logError('Error creating profile:', error);\n throw errorWithCause(\n 'Failed to create profile. Make sure Codex CLI is installed and you are logged in.',\n error,\n );\n }\n }),\n );\n }\n\n async createProfileFromAuthFile(name: string, authPath: string): Promise<Profile | null> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, async () => {\n await this.initialize();\n\n if (await this.getProfileRowByName(profileName)) {\n throw new Error(`Profile '${profileName}' already exists!`);\n }\n\n try {\n const authData = await this.readAuthFileForImport(authPath, 'profile creation');\n return await this.persistNewProfileFromAuth(profileName, authData);\n } catch (error) {\n logError('Error creating profile:', error);\n throw errorWithCause(\n 'Failed to create profile. Make sure Codex CLI is installed and you are logged in.',\n error,\n );\n }\n });\n }\n\n private async refreshProfileAuthWithData(\n profileName: string,\n record: ProfileRecord,\n activeAuth: ActiveAuth,\n ): Promise<Profile> {\n const existing: ProfileData = record.data;\n const normalized = this.normalizeProfileData(activeAuth);\n const existingMetadata = record.metadata ?? this.extractProfileMetadata(existing);\n const currentWorkspace = this.resolveWorkspaceIdentity(existing, existingMetadata);\n existing.workspace_id = existing.workspace_id ?? currentWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (currentWorkspace.name) {\n existing.workspace_name = existing.workspace_name ?? currentWorkspace.name;\n }\n\n const normalizedMetadata = this.extractProfileMetadata(normalized);\n const normalizedWorkspace = this.resolveWorkspaceIdentity(normalized, normalizedMetadata);\n normalized.workspace_id = normalized.workspace_id ?? normalizedWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (normalizedWorkspace.name) {\n normalized.workspace_name = normalized.workspace_name ?? normalizedWorkspace.name;\n }\n const existingIdentity = this.resolveProfileIdentityFromData(profileName, existing, existingMetadata);\n const newIdentity = this.resolveProfileIdentityFromData(profileName, normalized, normalizedMetadata);\n\n if (existingIdentity && newIdentity && existingIdentity !== newIdentity) {\n throw new Error(\n `Active Codex login is for a different OpenAI identity than profile '${profileName}'. Create a new profile for that login instead.`,\n );\n }\n\n if (existingIdentity && normalized.workspace_id) {\n const targetWorkspaceId = normalized.workspace_id;\n const currentWorkspaceId = currentWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (targetWorkspaceId !== currentWorkspaceId) {\n const duplicate = await this.getProfileRowByIdentityAndWorkspace(existingIdentity, targetWorkspaceId, {\n authMethod: this.resolveAuthMethod(existing),\n });\n if (duplicate && duplicate.name !== profileName) {\n throw new Error(\n `Account is already saved as profile '${duplicate.name}'. Switch to or delete that profile before creating another.`,\n );\n }\n }\n }\n\n const { profile: merged, metadata } = this.mergeProfileRecords(existing, normalized);\n delete merged.tokenAlert;\n\n await this.persistProfileRecord(profileName, merged, metadata);\n const updated = await this.getProfileRowByName(profileName);\n if (!updated) {\n throw new Error('Failed to persist refreshed profile data.');\n }\n\n const profile = this.buildProfileFromRow(updated);\n if (metadata) {\n profile.metadata = metadata;\n profile.tokenStatus = this.evaluateTokenStatus(merged, metadata);\n }\n return profile;\n }\n\n /**\n * Switch to a different profile\n */\n async switchToProfile(name: string): Promise<boolean> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n try {\n await this.writeActiveAuthForRecord(record);\n return true;\n } catch (error) {\n logError('Error switching profile:', error);\n throw errorWithCause('Failed to switch profile', error);\n }\n }),\n );\n }\n\n async refreshProfileAuth(name: string): Promise<Profile> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, () =>\n this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const activeAuth = await this.readAuthFileForImport(this.activeAuth, 'profile refresh');\n return this.refreshProfileAuthWithData(profileName, record, activeAuth);\n }),\n );\n }\n\n async refreshProfileAuthFromFile(name: string, authPath: string): Promise<Profile> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueProfileOperation(profileName, async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const activeAuth = await this.readAuthFileForImport(authPath, 'profile refresh');\n const profile = await this.refreshProfileAuthWithData(profileName, record, activeAuth);\n await this.enqueueAuthSwap(async () => {\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n });\n return profile;\n });\n }\n\n /**\n * Execute an action with a profile's auth injected.\n * Creates an isolated CODEX_HOME with the profile's auth/config, invokes the action\n * with env overrides, then syncs any refreshed tokens back to the profile.\n */\n async runWithProfileAuth<T>(\n name: string,\n action: (env: NodeJS.ProcessEnv) => Promise<T>,\n ): Promise<T> {\n return this.enqueueProfileOperation(name, () =>\n this.enqueueAuthSwap(async () => {\n try {\n return await this.runWithPreparedProfileHome(name, action, {\n syncFromActiveAuthBeforeAction: true,\n });\n } finally {\n await this.syncActiveAuthFromProfileIfCurrent(name);\n }\n }),\n );\n }\n\n async readLiveRateLimits(\n name: string,\n options: { codexPath?: string } = {},\n ): Promise<RateLimitSnapshot | null> {\n const profileName = this.normalizeProfileName(name);\n try {\n return await this.enqueueProfileOperation(profileName, () =>\n this.runWithPreparedProfileHome(\n profileName,\n env => fetchRateLimitsViaRpc(env, { codexPath: options.codexPath }),\n { syncFromActiveAuthBeforeAction: false },\n ),\n );\n } finally {\n await this.enqueueAuthSwap(async () => {\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n }).catch(error => {\n logWarn(`Failed to sync active auth after rate-limit probe for '${profileName}':`, error);\n });\n }\n }\n\n async activateResetWindow(\n name: string,\n options: { codexPath?: string } = {},\n ): Promise<CodexResetWindowActivationResult> {\n const profileName = this.normalizeProfileName(name);\n try {\n return await this.enqueueProfileOperation(profileName, () =>\n this.runWithPreparedProfileHome(\n profileName,\n env => activateResetWindowViaRpc(env, { codexPath: options.codexPath }),\n { syncFromActiveAuthBeforeAction: false },\n ),\n );\n } finally {\n await this.enqueueAuthSwap(async () => {\n await this.syncActiveAuthFromProfileIfCurrent(profileName);\n }).catch(error => {\n logWarn(`Failed to sync active auth after reset-window activation for '${profileName}':`, error);\n });\n }\n }\n\n /**\n * Rename a profile\n */\n async renameProfile(oldName: string, newName: string): Promise<boolean> {\n await this.initialize();\n const sourceName = this.normalizeProfileName(oldName);\n const targetName = this.normalizeProfileName(newName);\n\n const existing = await this.getProfileRowByName(sourceName);\n if (!existing) {\n throw new Error(`Profile '${sourceName}' not found!`);\n }\n\n if (await this.getProfileRowByName(targetName)) {\n throw new Error(`Profile '${targetName}' already exists!`);\n }\n\n const oldHome = this.getProfileHomePath(sourceName);\n const newHome = this.getProfileHomePath(targetName);\n try {\n await fs.mkdir(this.profileHomesRoot, { recursive: true });\n await fs.rename(oldHome, newHome);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to move profile home from '${sourceName}' to '${targetName}':`, error);\n }\n }\n\n try {\n const updatedRecord: ProfileRecord = {\n ...existing,\n name: targetName,\n };\n const map = await this.readProfilesStateMap();\n delete map[sourceName];\n map[targetName] = this.toStateRecord(updatedRecord);\n await this.writeProfilesStateMap(map);\n } catch (error) {\n logWarn(`Failed to rewrite profile record after renaming '${sourceName}' to '${targetName}':`, error);\n }\n\n return true;\n }\n\n async updateProfileDisplayName(name: string, displayName: string): Promise<boolean> {\n await this.initialize();\n\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n const trimmed = typeof displayName === 'string' ? displayName.trim() : '';\n if (!trimmed) {\n throw new Error('Profile name must not be empty.');\n }\n\n const now = new Date().toISOString();\n record.displayName = trimmed;\n record.updatedAt = now;\n (record.data as ProfileData & { updated_at?: string }).updated_at = now;\n\n await this.writeProfileRecord(record);\n return true;\n }\n\n async getCustomGroupsByAccountKey(): Promise<Record<string, string>> {\n await this.initialize();\n const state = await this.readProfileDashboardState();\n return { ...state.customGroupsByAccountKey };\n }\n\n async updateCustomGroup(accountKey: string, groupName: string | null): Promise<Record<string, string>> {\n await this.initialize();\n\n const normalizedAccountKey = this.normalizeProfileName(accountKey);\n const normalizedGroupName =\n typeof groupName === 'string' && groupName.trim().length > 0\n ? groupName.trim()\n : null;\n const nextState = await this.readProfileDashboardState();\n\n if (normalizedGroupName) {\n nextState.customGroupsByAccountKey[normalizedAccountKey] = normalizedGroupName;\n } else {\n delete nextState.customGroupsByAccountKey[normalizedAccountKey];\n }\n\n await this.writeProfileDashboardState(nextState);\n return { ...nextState.customGroupsByAccountKey };\n }\n\n /**\n * Delete a profile\n */\n async deleteProfile(name: string): Promise<boolean> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n await this.deleteProfileRecordAndHome(record);\n return true;\n }\n\n async deleteActiveProfileAndSwitch(name: string, replacementName: string): Promise<boolean> {\n const profileName = this.normalizeProfileName(name);\n const nextProfileName = this.normalizeProfileName(replacementName);\n if (profileName === nextProfileName) {\n throw new Error('Replacement profile must be different from the deleted profile.');\n }\n\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n const replacement = await this.getProfileRowByName(nextProfileName);\n if (!replacement) {\n throw new Error(`Profile '${nextProfileName}' not found!`);\n }\n\n await this.assertActiveAuthMatchesRecord(\n record,\n 'Active Codex login changed before deletion. Refresh profiles and try again.',\n );\n await this.writeActiveAuthForRecord(replacement);\n await this.deleteProfileRecordAndHome(record);\n return true;\n });\n }\n\n async deleteActiveProfileAndAuth(name: string): Promise<boolean> {\n const profileName = this.normalizeProfileName(name);\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n await this.assertActiveAuthMatchesRecord(\n record,\n 'Active Codex login changed before deletion. Refresh profiles and try again.',\n );\n await this.removeActiveAuthFiles();\n await this.deleteProfileRecordAndHome(record);\n return true;\n });\n }\n\n /**\n * Delete every profile that does not appear in the allow-list.\n * Used to enforce plan limits when local storage was tampered with.\n */\n async deleteProfilesNotIn(allowedNames: Iterable<string>): Promise<string[]> {\n await this.initialize();\n const normalized = new Set<string>();\n for (const name of allowedNames) {\n try {\n normalized.add(this.normalizeProfileName(name));\n } catch {\n // Skip invalid names so we only retain well-formed entries.\n }\n }\n\n const records = await this.listProfileRecords();\n const deleteCandidates = records\n .map(record => {\n try {\n return this.normalizeProfileName(record.name);\n } catch {\n return null;\n }\n })\n .filter((name): name is string => typeof name === 'string')\n .filter(name => !normalized.has(name));\n\n if (deleteCandidates.length === 0) {\n return [];\n }\n\n const nextMap = await this.readProfilesStateMap();\n const removed: string[] = [];\n for (const name of deleteCandidates) {\n try {\n await fs.rm(this.getProfileHomePath(name), { recursive: true, force: true });\n delete nextMap[name];\n removed.push(name);\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to remove profile '${name}' during plan enforcement:`, error);\n }\n }\n }\n if (removed.length > 0) {\n await this.writeProfilesStateMap(nextMap);\n }\n return removed;\n }\n\n async getActiveCodexAuthStatus(options: {\n autoImport?: boolean;\n canAutoImport?: boolean;\n importBlockedReason?: string | null;\n } = {}): Promise<ActiveCodexAuthStatus> {\n return this.enqueueAuthSwap(async () => {\n await this.initialize();\n const activeAuth = await this.readActiveAuthFile();\n if (!activeAuth) {\n return this.buildActiveCodexAuthStatus('missing');\n }\n\n const description = this.describeActiveAuth(activeAuth);\n if (!description.hasTokenPayload || !description.identityKey) {\n return this.buildActiveCodexAuthStatus('unknown', description);\n }\n\n const matching = await this.findProfileForActiveAuth(\n description.identityKey,\n description.workspaceId,\n );\n if (matching) {\n const normalized = this.normalizeProfileName(matching.name);\n await this.syncMatchedProfileFromActiveAuth(matching, description);\n return this.buildActiveCodexAuthStatus('matched', description, {\n profileName: normalized,\n });\n }\n\n if (!options.autoImport) {\n return this.buildActiveCodexAuthStatus('unmanaged', description);\n }\n\n if (options.canAutoImport === false) {\n return this.buildActiveCodexAuthStatus('unmanaged', description, {\n importBlockedReason:\n options.importBlockedReason ??\n 'Profile limit reached. Upgrade to CodexUse Pro or remove a profile before importing this Codex login.',\n });\n }\n\n const records = await this.listProfileRecords();\n const profileName = this.resolveAutoImportedProfileName(description.email, records);\n const profileData: ProfileData = {\n ...description.normalized,\n auth_method: 'codex-cli',\n created_at: description.normalized.created_at ?? new Date().toISOString(),\n };\n await this.persistProfileRecord(profileName, profileData, description.metadata, {\n displayName: description.email ?? profileName,\n });\n\n return this.buildActiveCodexAuthStatus('matched', description, {\n profileName,\n importedProfileName: profileName,\n });\n });\n }\n\n /**\n * Check if the real Codex auth file matches a saved profile.\n */\n async getCurrentProfile(): Promise<{ name: string | null; trusted: boolean }> {\n const status = await this.getActiveCodexAuthStatus({ autoImport: false });\n if (status.state === 'matched' && status.profileName) {\n return { name: status.profileName, trusted: true };\n }\n return { name: null, trusted: false };\n }\n\n /**\n * Export a profile to a portable format.\n * Sensitive tokens are included but should be handled securely.\n */\n async exportProfile(name: string): Promise<{\n name: string;\n displayName: string | null;\n email: string | null;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n authMethod: string | null;\n createdAt: string | null;\n metadata: ProfileMetadata | undefined;\n exportedAt: string;\n }> {\n await this.initialize();\n const profileName = this.normalizeProfileName(name);\n const record = await this.getProfileRowByName(profileName);\n if (!record) {\n throw new Error(`Profile '${profileName}' not found!`);\n }\n\n return {\n name: record.name,\n displayName: record.displayName,\n email: record.email,\n accountId: record.accountId,\n workspaceId: record.workspaceId,\n workspaceName: record.workspaceName,\n authMethod: record.authMethod,\n createdAt: record.createdAt,\n metadata: record.metadata,\n exportedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Export profiles for cloud sync (includes token-bearing auth data).\n */\n async exportProfilesForCloudSync(): Promise<CloudSyncProfileRecord[]> {\n await this.initialize();\n const records = await this.listProfileRecords();\n return records.map(record => ({\n name: record.name,\n displayName: record.displayName,\n data: record.data,\n metadata: record.metadata,\n accountId: record.accountId,\n workspaceId: record.workspaceId,\n workspaceName: record.workspaceName,\n email: record.email,\n authMethod: record.authMethod,\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n }));\n }\n\n /**\n * Replace local profiles with a full snapshot from cloud sync.\n */\n async replaceProfilesFromCloudSync(records: CloudSyncProfileRecord[]): Promise<{ imported: number; removed: number }> {\n await this.initialize();\n const now = new Date().toISOString();\n const normalized = new Map<string, ProfileRecord>();\n const existingMap = await this.readProfilesStateMap();\n const existingNames = new Set(Object.keys(existingMap));\n\n for (const candidate of records ?? []) {\n try {\n const name = this.normalizeProfileName(candidate?.name ?? '');\n const data =\n candidate && typeof candidate.data === 'object' && candidate.data !== null\n ? (candidate.data as ProfileData)\n : null;\n if (!data) {\n continue;\n }\n\n const metadata =\n candidate.metadata && typeof candidate.metadata === 'object'\n ? candidate.metadata\n : undefined;\n\n const record: ProfileRecord = {\n name,\n displayName: typeof candidate.displayName === 'string' ? candidate.displayName : null,\n data,\n metadata,\n accountId: typeof candidate.accountId === 'string' ? candidate.accountId : null,\n workspaceId: typeof candidate.workspaceId === 'string' ? candidate.workspaceId : null,\n workspaceName: typeof candidate.workspaceName === 'string' ? candidate.workspaceName : null,\n email: typeof candidate.email === 'string' ? candidate.email : null,\n authMethod: typeof candidate.authMethod === 'string' ? candidate.authMethod : this.resolveAuthMethod(data),\n createdAt: typeof candidate.createdAt === 'string' ? candidate.createdAt : now,\n updatedAt: typeof candidate.updatedAt === 'string' ? candidate.updatedAt : now,\n };\n\n normalized.set(name, record);\n } catch {\n // Ignore malformed record entries.\n }\n }\n\n const nextMap: Record<string, ProfileRecordState> = {};\n for (const record of normalized.values()) {\n nextMap[record.name] = this.toStateRecord(record);\n }\n await this.writeProfilesStateMap(nextMap);\n\n let removed = 0;\n\n for (const name of existingNames) {\n if (normalized.has(name)) {\n continue;\n }\n try {\n await fs.rm(this.getProfileHomePath(name), { recursive: true, force: true });\n removed += 1;\n } catch (error) {\n if (!this.isNotFoundError(error)) {\n logWarn(`Failed to remove profile '${name}' during cloud sync replace:`, error);\n }\n }\n }\n\n return {\n imported: normalized.size,\n removed,\n };\n }\n}\n","import type { Profile, ProfileMetadata } from \"./types\";\n\ntype ProfileIdentityLike = {\n name?: string | null;\n accountId?: string | null;\n workspaceId?: string | null;\n email?: string | null;\n metadata?: Pick<\n ProfileMetadata,\n \"email\" | \"userId\" | \"chatgptUserId\" | \"chatgptAccountUserId\"\n > | null;\n};\n\nfunction normalizeValue(value?: string | null): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeEmail(value?: string | null): string | null {\n const normalized = normalizeValue(value);\n return normalized ? normalized.toLowerCase() : null;\n}\n\nfunction encodeIdentityPart(value: string): string {\n return encodeURIComponent(value);\n}\n\nexport function resolveProfileIdentityKey(profile: ProfileIdentityLike): string | null {\n const workspaceId = normalizeValue(profile.workspaceId);\n const accountUserId = normalizeValue(profile.metadata?.chatgptAccountUserId);\n if (accountUserId) {\n return `seat:${encodeIdentityPart(accountUserId)}`;\n }\n\n const userId =\n normalizeValue(profile.metadata?.userId) ??\n normalizeValue(profile.metadata?.chatgptUserId);\n if (workspaceId && userId) {\n return `workspace-user:${encodeIdentityPart(workspaceId)}|${encodeIdentityPart(userId)}`;\n }\n\n const accountId = normalizeValue(profile.accountId);\n if (accountId) {\n return accountId;\n }\n\n const email = normalizeEmail(profile.email ?? profile.metadata?.email);\n if (workspaceId && email) {\n return `workspace-email:${encodeIdentityPart(workspaceId)}|${encodeIdentityPart(email)}`;\n }\n if (userId) {\n return `user:${encodeIdentityPart(userId)}`;\n }\n if (email) {\n return `email:${encodeIdentityPart(email)}`;\n }\n\n const profileName = normalizeValue(profile.name);\n return profileName ? `profile:${profileName}` : null;\n}\n\nexport function resolveProfileIdentityKeyFromProfile(profile: Profile): string {\n return resolveProfileIdentityKey(profile) ?? `profile:${profile.name}`;\n}\n","import { spawn } from \"node:child_process\";\nimport readline from \"node:readline\";\nimport { promises as fs } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { requireCodexCli } from \"@codexuse/runtime-codex/codex/cli\";\nimport { buildCodexCommand } from \"@codexuse/runtime-codex/codex/command\";\nimport { logWarn } from \"@codexuse/shared/core/logger\";\nimport type {\n RateLimitSnapshot,\n RateLimitWindow,\n} from \"@codexuse/contracts/profiles/types\";\n\ntype RpcError = {\n code?: number;\n message?: string;\n data?: unknown;\n};\n\ntype RpcMessage = {\n id?: number | string | null;\n method?: string;\n params?: unknown;\n result?: unknown;\n error?: RpcError;\n};\n\ntype RpcRateLimitWindow = {\n usedPercent?: number;\n windowDurationMins?: number;\n resetsAt?: number;\n};\n\ntype RpcRateLimitSnapshot = {\n primary?: RpcRateLimitWindow | null;\n secondary?: RpcRateLimitWindow | null;\n};\n\nexport type CodexResetWindowActivationResult = {\n status: \"completed\" | \"failed\" | \"skipped\";\n reason: string | null;\n threadId?: string | null;\n turnId?: string | null;\n};\n\nconst RPC_TIMEOUT_MS = 10_000;\nconst ACTIVATION_TURN_TIMEOUT_MS = 90_000;\nconst ACTIVATION_PROMPT = \"Reply with exactly: ok.\";\nconst ACTIVATION_MODEL = \"gpt-5.1-codex-mini\";\nconst MAX_STDERR_CAPTURE_CHARS = 32_768;\nconst REFRESH_TOKEN_REDEEMED_SNIPPET = \"refresh token was already used\";\n\ntype AuthRecord = {\n last_refresh?: unknown;\n access_token?: unknown;\n tokens?: {\n last_refresh?: unknown;\n access_token?: unknown;\n };\n};\n\ntype AuthFileCacheEntry = {\n mtimeMs: number;\n size: number;\n content: string;\n};\n\nconst authFileCache = new Map<string, AuthFileCacheEntry>();\n\ntype RpcMessageReader = {\n readResponse: (\n requestId: number | string,\n timeoutMs: number,\n ) => Promise<RpcMessage>;\n read: (\n predicate: (message: RpcMessage) => boolean,\n timeoutMs: number,\n ) => Promise<RpcMessage>;\n dispose: () => void;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction asString(value: unknown): string {\n return typeof value === \"string\" ? value : value != null ? String(value) : \"\";\n}\n\nfunction createRpcMessageReader(rl: readline.Interface): RpcMessageReader {\n type Waiter = {\n predicate: (message: RpcMessage) => boolean;\n resolve: (message: RpcMessage) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n };\n\n const queue: RpcMessage[] = [];\n const waiters: Waiter[] = [];\n const responseQueueById = new Map<string, RpcMessage[]>();\n const responseWaitersById = new Map<string, Waiter[]>();\n let closedError: Error | null = null;\n\n const responseKey = (id: RpcMessage[\"id\"]): string | null =>\n id === null || id === undefined ? null : String(id);\n\n const isResponse = (message: RpcMessage): boolean =>\n Object.prototype.hasOwnProperty.call(message, \"result\") ||\n Object.prototype.hasOwnProperty.call(message, \"error\");\n\n const enqueueResponse = (key: string, message: RpcMessage): void => {\n const bucket = responseQueueById.get(key);\n if (bucket) {\n bucket.push(message);\n } else {\n responseQueueById.set(key, [message]);\n }\n };\n\n const rejectAll = (error: Error): void => {\n closedError = error;\n while (waiters.length > 0) {\n const waiter = waiters.shift()!;\n clearTimeout(waiter.timer);\n waiter.reject(error);\n }\n for (const bucket of responseWaitersById.values()) {\n for (const waiter of bucket) {\n clearTimeout(waiter.timer);\n waiter.reject(error);\n }\n }\n responseWaitersById.clear();\n };\n\n const onLine = (line: string): void => {\n let parsed: RpcMessage;\n try {\n parsed = JSON.parse(line) as RpcMessage;\n } catch {\n rejectAll(new Error(\"codex RPC returned malformed JSON\"));\n return;\n }\n\n const key = isResponse(parsed) ? responseKey(parsed.id) : null;\n if (key) {\n const bucket = responseWaitersById.get(key);\n const waiter = bucket?.shift();\n if (waiter) {\n if (bucket?.length === 0) {\n responseWaitersById.delete(key);\n }\n clearTimeout(waiter.timer);\n waiter.resolve(parsed);\n return;\n }\n enqueueResponse(key, parsed);\n return;\n }\n\n const waiterIndex = waiters.findIndex((waiter) => waiter.predicate(parsed));\n if (waiterIndex >= 0) {\n const [waiter] = waiters.splice(waiterIndex, 1);\n clearTimeout(waiter.timer);\n waiter.resolve(parsed);\n return;\n }\n queue.push(parsed);\n };\n\n const onClose = (): void => {\n rejectAll(new Error(\"codex RPC stream closed before response\"));\n };\n\n rl.on(\"line\", onLine);\n rl.on(\"close\", onClose);\n\n return {\n readResponse(requestId, timeoutMs) {\n const key = String(requestId);\n const bucket = responseQueueById.get(key);\n const queued = bucket?.shift();\n if (queued) {\n if (bucket?.length === 0) {\n responseQueueById.delete(key);\n }\n return Promise.resolve(queued);\n }\n if (closedError) {\n return Promise.reject(closedError);\n }\n return new Promise<RpcMessage>((resolve, reject) => {\n const waiter: Waiter = {\n predicate: () => true,\n resolve,\n reject,\n timer: setTimeout(\n () => {\n const waitersForKey = responseWaitersById.get(key);\n const index = waitersForKey?.indexOf(waiter) ?? -1;\n if (waitersForKey && index >= 0) {\n waitersForKey.splice(index, 1);\n if (waitersForKey.length === 0) {\n responseWaitersById.delete(key);\n }\n }\n reject(new Error(\"codex RPC timed out\"));\n },\n Math.max(1, timeoutMs),\n ),\n };\n const waitersForKey = responseWaitersById.get(key);\n if (waitersForKey) {\n waitersForKey.push(waiter);\n } else {\n responseWaitersById.set(key, [waiter]);\n }\n });\n },\n read(predicate, timeoutMs) {\n const queuedIndex = queue.findIndex(predicate);\n if (queuedIndex >= 0) {\n const [message] = queue.splice(queuedIndex, 1);\n return Promise.resolve(message);\n }\n if (closedError) {\n return Promise.reject(closedError);\n }\n return new Promise<RpcMessage>((resolve, reject) => {\n const waiter: Waiter = {\n predicate,\n resolve,\n reject,\n timer: setTimeout(\n () => {\n const index = waiters.indexOf(waiter);\n if (index >= 0) {\n waiters.splice(index, 1);\n }\n reject(new Error(\"codex RPC timed out\"));\n },\n Math.max(1, timeoutMs),\n ),\n };\n waiters.push(waiter);\n });\n },\n dispose() {\n rl.off(\"line\", onLine);\n rl.off(\"close\", onClose);\n while (waiters.length > 0) {\n const waiter = waiters.shift()!;\n clearTimeout(waiter.timer);\n }\n for (const bucket of responseWaitersById.values()) {\n for (const waiter of bucket) {\n clearTimeout(waiter.timer);\n }\n }\n responseWaitersById.clear();\n },\n };\n}\n\nfunction readThreadIdFromResult(result: unknown): string | null {\n if (!isRecord(result)) return null;\n const thread = isRecord(result.thread) ? result.thread : {};\n const value = asString(thread.id ?? result.threadId).trim();\n return value.length > 0 ? value : null;\n}\n\nfunction readTurnIdFromResult(result: unknown): string | null {\n if (!isRecord(result)) return null;\n const turn = isRecord(result.turn) ? result.turn : {};\n const value = asString(turn.id ?? result.turnId).trim();\n return value.length > 0 ? value : null;\n}\n\nfunction readTurnIdFromNotification(message: RpcMessage): string | null {\n if (!isRecord(message.params)) return null;\n const turn = isRecord(message.params.turn) ? message.params.turn : {};\n const value = asString(turn.id ?? message.params.turnId).trim();\n return value.length > 0 ? value : null;\n}\n\nfunction readTurnStatusFromNotification(message: RpcMessage): {\n status: string | null;\n reason: string | null;\n} {\n if (!isRecord(message.params)) {\n return { status: null, reason: null };\n }\n const turn = isRecord(message.params.turn) ? message.params.turn : {};\n const error = isRecord(turn.error) ? turn.error : null;\n return {\n status: asString(turn.status).trim() || null,\n reason: error ? asString(error.message).trim() || null : null,\n };\n}\n\nfunction parseTimestamp(value: unknown): number | null {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n return null;\n }\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\nfunction decodeJwtPayload(token: unknown): Record<string, unknown> | null {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n return null;\n }\n\n const segments = token.split(\".\");\n if (segments.length < 2) {\n return null;\n }\n\n try {\n const payloadRaw = Buffer.from(segments[1], \"base64url\").toString(\"utf8\");\n const payload = JSON.parse(payloadRaw);\n return payload && typeof payload === \"object\"\n ? (payload as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction extractJwtIssuedAtMs(token: unknown): number | null {\n const payload = decodeJwtPayload(token);\n if (!payload) {\n return null;\n }\n\n const issuedAt = payload[\"iat\"];\n if (typeof issuedAt !== \"number\" || !Number.isFinite(issuedAt)) {\n return null;\n }\n\n return issuedAt * 1000;\n}\n\nfunction parseAuthRecord(content: string): AuthRecord | null {\n try {\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === \"object\" ? (parsed as AuthRecord) : null;\n } catch {\n return null;\n }\n}\n\nfunction extractAuthRecencyMs(content: string): number | null {\n const parsed = parseAuthRecord(content);\n if (!parsed) {\n return null;\n }\n\n const rootLastRefresh = parseTimestamp(parsed.last_refresh);\n const nestedLastRefresh = parseTimestamp(parsed.tokens?.last_refresh);\n const rootAccessIssuedAt = extractJwtIssuedAtMs(parsed.access_token);\n const nestedAccessIssuedAt = extractJwtIssuedAtMs(\n parsed.tokens?.access_token,\n );\n const candidates = [\n rootLastRefresh,\n nestedLastRefresh,\n rootAccessIssuedAt,\n nestedAccessIssuedAt,\n ].filter(\n (value): value is number =>\n typeof value === \"number\" && Number.isFinite(value),\n );\n\n if (candidates.length === 0) {\n return null;\n }\n\n return Math.max(...candidates);\n}\n\nfunction shouldWriteBackAuth(\n initialSourceAuth: string | null,\n currentSourceAuth: string | null,\n updatedAuth: string,\n): boolean {\n if (updatedAuth.trim().length === 0) {\n return false;\n }\n\n if (!currentSourceAuth) {\n return true;\n }\n\n if (currentSourceAuth === updatedAuth) {\n return false;\n }\n\n if (currentSourceAuth === initialSourceAuth) {\n return true;\n }\n\n const currentRecency = extractAuthRecencyMs(currentSourceAuth);\n const updatedRecency = extractAuthRecencyMs(updatedAuth);\n\n if (\n typeof updatedRecency === \"number\" &&\n typeof currentRecency === \"number\"\n ) {\n return updatedRecency > currentRecency;\n }\n\n if (\n typeof updatedRecency === \"number\" &&\n typeof currentRecency !== \"number\"\n ) {\n return true;\n }\n\n return false;\n}\n\nasync function readAuthFileCached(filePath: string): Promise<string | null> {\n let stats;\n try {\n stats = await fs.stat(filePath);\n } catch {\n authFileCache.delete(filePath);\n return null;\n }\n\n const cached = authFileCache.get(filePath);\n if (\n cached &&\n cached.mtimeMs === stats.mtimeMs &&\n cached.size === stats.size\n ) {\n return cached.content;\n }\n\n const content = await fs.readFile(filePath, \"utf8\");\n authFileCache.set(filePath, {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n content,\n });\n return content;\n}\n\nasync function writeAuthFileCached(filePath: string, content: string): Promise<void> {\n await fs.writeFile(filePath, content, \"utf8\");\n try {\n const stats = await fs.stat(filePath);\n authFileCache.set(filePath, {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n content,\n });\n } catch {\n authFileCache.delete(filePath);\n }\n}\n\nfunction inferRefreshFailureHint(stderrOutput: string): string | null {\n if (!stderrOutput) {\n return null;\n }\n\n const normalized = stderrOutput.toLowerCase();\n if (normalized.includes(REFRESH_TOKEN_REDEEMED_SNIPPET)) {\n return REFRESH_TOKEN_REDEEMED_SNIPPET;\n }\n\n return null;\n}\n\nasync function sendPayload(\n child: ReturnType<typeof spawn>,\n payload: Record<string, unknown>,\n): Promise<void> {\n child.stdin?.write(JSON.stringify(payload));\n child.stdin?.write(\"\\n\");\n}\n\nfunction isRpcResponseForRequest(\n message: RpcMessage,\n requestId: number,\n): boolean {\n if (message.id !== requestId) {\n return false;\n }\n return (\n Object.prototype.hasOwnProperty.call(message, \"result\") ||\n Object.prototype.hasOwnProperty.call(message, \"error\")\n );\n}\n\nasync function readRpcResponseById(\n rl: readline.Interface,\n requestId: number,\n timeoutMs: number,\n): Promise<RpcMessage> {\n return new Promise<RpcMessage>((resolve, reject) => {\n const timer = setTimeout(\n () => {\n cleanup();\n reject(new Error(\"codex RPC timed out\"));\n },\n Math.max(1, timeoutMs),\n );\n\n const cleanup = () => {\n clearTimeout(timer);\n rl.off(\"line\", onLine);\n rl.off(\"close\", onClose);\n };\n\n const onClose = () => {\n cleanup();\n reject(new Error(\"codex RPC stream closed before response\"));\n };\n\n const onLine = (line: string) => {\n let parsed: RpcMessage;\n try {\n parsed = JSON.parse(line) as RpcMessage;\n } catch {\n cleanup();\n reject(new Error(\"codex RPC returned malformed JSON\"));\n return;\n }\n\n if (!isRpcResponseForRequest(parsed, requestId)) {\n return;\n }\n\n cleanup();\n resolve(parsed);\n };\n\n rl.on(\"line\", onLine);\n rl.on(\"close\", onClose);\n });\n}\n\nfunction formatRpcError(method: string, error: RpcError): string {\n const codeText =\n typeof error.code === \"number\" ? ` (code ${error.code})` : \"\";\n const message =\n typeof error.message === \"string\" && error.message.trim().length > 0\n ? error.message.trim()\n : \"Unknown RPC error\";\n return `${method} failed${codeText}: ${message}`;\n}\n\nfunction toWindow(\n rpc?: RpcRateLimitWindow | null,\n): RateLimitWindow | undefined {\n if (!rpc) return undefined;\n const usedPercent =\n typeof rpc.usedPercent === \"number\" && Number.isFinite(rpc.usedPercent)\n ? rpc.usedPercent\n : undefined;\n const windowMinutes =\n typeof rpc.windowDurationMins === \"number\" &&\n Number.isFinite(rpc.windowDurationMins)\n ? rpc.windowDurationMins\n : undefined;\n\n let resetsAt: string | undefined;\n let resetsInSeconds: number | undefined;\n if (typeof rpc.resetsAt === \"number\" && Number.isFinite(rpc.resetsAt)) {\n const ms =\n rpc.resetsAt > 10_000_000_000 ? rpc.resetsAt : rpc.resetsAt * 1000;\n resetsAt = new Date(ms).toISOString();\n resetsInSeconds = Math.max(0, Math.round((ms - Date.now()) / 1000));\n }\n\n if (\n typeof usedPercent === \"undefined\" &&\n typeof windowMinutes === \"undefined\" &&\n typeof resetsAt === \"undefined\"\n ) {\n return undefined;\n }\n\n const window: RateLimitWindow = {};\n if (typeof usedPercent === \"number\") {\n window.usedPercent = usedPercent;\n }\n if (typeof windowMinutes === \"number\") {\n window.windowMinutes = windowMinutes;\n }\n if (typeof resetsAt === \"string\") {\n window.resetsAt = resetsAt;\n }\n if (typeof resetsInSeconds === \"number\") {\n window.resetsInSeconds = resetsInSeconds;\n }\n return window;\n}\n\nfunction parseRateLimitSnapshotFromRpcMessage(\n message: RpcMessage,\n): RateLimitSnapshot | null {\n if (message.error) {\n throw new Error(formatRpcError(\"account/rateLimits/read\", message.error));\n }\n\n const result = message.result as\n | { rateLimits?: RpcRateLimitSnapshot }\n | undefined;\n const limits = result?.rateLimits;\n const primary = toWindow(limits?.primary ?? null);\n const secondary = toWindow(limits?.secondary ?? null);\n\n if (!primary && !secondary) {\n return null;\n }\n\n const snapshot: RateLimitSnapshot = {\n lastUpdated: new Date().toISOString(),\n source: \"codex-rpc\",\n };\n if (primary) {\n snapshot.primary = primary;\n }\n if (secondary) {\n snapshot.secondary = secondary;\n }\n return snapshot;\n}\n\nexport async function fetchRateLimitsViaRpc(\n envOverride?: NodeJS.ProcessEnv,\n options: { authPath?: string; codexPath?: string } = {},\n): Promise<RateLimitSnapshot | null> {\n const binaryPath = options.codexPath ?? (await requireCodexCli());\n const tempHome = await fs.mkdtemp(path.join(os.tmpdir(), \"codex-rpc-\"));\n const tempAuthPath = path.join(tempHome, \"auth.json\");\n let initialSourceAuth: string | null;\n\n const sourceAuthPath =\n options.authPath ??\n (envOverride?.CODEX_HOME\n ? path.join(envOverride.CODEX_HOME, \"auth.json\")\n : path.join(\n envOverride?.HOME ?? process.env.HOME ?? os.homedir(),\n \".codex\",\n \"auth.json\",\n ));\n\n try {\n initialSourceAuth = await readAuthFileCached(sourceAuthPath);\n if (!initialSourceAuth) {\n return null;\n }\n await fs.writeFile(tempAuthPath, initialSourceAuth, \"utf8\");\n } catch {\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n return null;\n }\n\n const childEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...(envOverride ?? {}),\n HOME: tempHome,\n CODEX_HOME: tempHome,\n CODEX_TELEMETRY_LABEL: \"codex-rpc\",\n ELECTRON_RUN_AS_NODE: \"1\",\n };\n const command = buildCodexCommand(\n binaryPath,\n [\"-s\", \"read-only\", \"-a\", \"untrusted\", \"app-server\"],\n childEnv,\n );\n const child = spawn(command.command, command.args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: childEnv,\n shell: command.shell,\n });\n\n const rl = readline.createInterface({\n input: child.stdout!,\n crlfDelay: Infinity,\n });\n let stderrOutput = \"\";\n const onStderrData = (chunk: Buffer): void => {\n if (stderrOutput.length >= MAX_STDERR_CAPTURE_CHARS) {\n return;\n }\n const text = chunk.toString(\"utf8\");\n const remaining = MAX_STDERR_CAPTURE_CHARS - stderrOutput.length;\n stderrOutput += text.slice(0, Math.max(0, remaining));\n };\n child.stderr?.on(\"data\", onStderrData);\n\n try {\n await sendPayload(child, {\n id: 1,\n method: \"initialize\",\n params: { clientInfo: { name: \"codexuse\", version: \"0.0.0\" } },\n });\n const initializeResponse = await readRpcResponseById(rl, 1, RPC_TIMEOUT_MS);\n if (initializeResponse.error) {\n throw new Error(formatRpcError(\"initialize\", initializeResponse.error));\n }\n\n await sendPayload(child, { method: \"initialized\", params: {} });\n\n await sendPayload(child, {\n id: 2,\n method: \"account/rateLimits/read\",\n params: {},\n });\n const message = await readRpcResponseById(rl, 2, RPC_TIMEOUT_MS);\n if (message.error) {\n const base = formatRpcError(\"account/rateLimits/read\", message.error);\n const hint = inferRefreshFailureHint(stderrOutput);\n if (hint && !base.toLowerCase().includes(hint)) {\n throw new Error(`${base}; ${hint}`);\n }\n throw new Error(base);\n }\n\n return parseRateLimitSnapshotFromRpcMessage(message);\n } finally {\n child.stderr?.off(\"data\", onStderrData);\n child.kill();\n rl.close();\n try {\n const updatedAuth = await fs.readFile(tempAuthPath, \"utf8\");\n if (updatedAuth.trim().length > 0) {\n const currentSourceAuth = await readAuthFileCached(sourceAuthPath);\n if (\n shouldWriteBackAuth(initialSourceAuth, currentSourceAuth, updatedAuth)\n ) {\n await writeAuthFileCached(sourceAuthPath, updatedAuth);\n } else if (\n currentSourceAuth &&\n currentSourceAuth !== updatedAuth &&\n currentSourceAuth !== initialSourceAuth\n ) {\n logWarn(\n \"Skipped stale auth sync-back after rate-limit probe; source auth changed in flight.\",\n {\n sourceAuthPath,\n currentRecencyMs: extractAuthRecencyMs(currentSourceAuth),\n updatedRecencyMs: extractAuthRecencyMs(updatedAuth),\n },\n );\n }\n }\n } catch {\n // Best effort: if auth sync-back fails, keep existing source auth.\n }\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n }\n}\n\nexport async function activateResetWindowViaRpc(\n envOverride?: NodeJS.ProcessEnv,\n options: { authPath?: string; codexPath?: string } = {},\n): Promise<CodexResetWindowActivationResult> {\n const binaryPath = options.codexPath ?? (await requireCodexCli());\n const tempHome = await fs.mkdtemp(\n path.join(os.tmpdir(), \"codex-activation-\"),\n );\n const tempAuthPath = path.join(tempHome, \"auth.json\");\n let initialSourceAuth: string | null;\n\n const sourceAuthPath =\n options.authPath ??\n (envOverride?.CODEX_HOME\n ? path.join(envOverride.CODEX_HOME, \"auth.json\")\n : path.join(\n envOverride?.HOME ?? process.env.HOME ?? os.homedir(),\n \".codex\",\n \"auth.json\",\n ));\n\n try {\n initialSourceAuth = await readAuthFileCached(sourceAuthPath);\n if (!initialSourceAuth) {\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n return { status: \"skipped\", reason: \"auth-missing\" };\n }\n await fs.writeFile(tempAuthPath, initialSourceAuth, \"utf8\");\n } catch {\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n return { status: \"skipped\", reason: \"auth-missing\" };\n }\n\n const childEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...(envOverride ?? {}),\n HOME: tempHome,\n CODEX_HOME: tempHome,\n CODEX_TELEMETRY_LABEL: \"codex-reset-activation\",\n ELECTRON_RUN_AS_NODE: \"1\",\n };\n const command = buildCodexCommand(\n binaryPath,\n [\"-s\", \"read-only\", \"-a\", \"untrusted\", \"app-server\"],\n childEnv,\n );\n const child = spawn(command.command, command.args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: childEnv,\n shell: command.shell,\n });\n\n const rl = readline.createInterface({\n input: child.stdout!,\n crlfDelay: Infinity,\n });\n const reader = createRpcMessageReader(rl);\n let stderrOutput = \"\";\n const onStderrData = (chunk: Buffer): void => {\n if (stderrOutput.length >= MAX_STDERR_CAPTURE_CHARS) {\n return;\n }\n const text = chunk.toString(\"utf8\");\n const remaining = MAX_STDERR_CAPTURE_CHARS - stderrOutput.length;\n stderrOutput += text.slice(0, Math.max(0, remaining));\n };\n child.stderr?.on(\"data\", onStderrData);\n\n try {\n await sendPayload(child, {\n id: 1,\n method: \"initialize\",\n params: { clientInfo: { name: \"codexuse\", version: \"0.0.0\" } },\n });\n const initializeResponse = await reader.readResponse(1, RPC_TIMEOUT_MS);\n if (initializeResponse.error) {\n throw new Error(formatRpcError(\"initialize\", initializeResponse.error));\n }\n\n await sendPayload(child, { method: \"initialized\", params: {} });\n\n await sendPayload(child, {\n id: 2,\n method: \"thread/start\",\n params: {\n cwd: tempHome,\n model: ACTIVATION_MODEL,\n approvalPolicy: \"untrusted\",\n sandbox: \"read-only\",\n experimentalRawEvents: false,\n },\n });\n const threadResponse = await reader.readResponse(2, RPC_TIMEOUT_MS);\n if (threadResponse.error) {\n throw new Error(formatRpcError(\"thread/start\", threadResponse.error));\n }\n const threadId = readThreadIdFromResult(threadResponse.result);\n if (!threadId) {\n throw new Error(\"thread/start response did not include a thread id.\");\n }\n\n await sendPayload(child, {\n id: 3,\n method: \"turn/start\",\n params: {\n threadId,\n model: ACTIVATION_MODEL,\n effort: \"low\",\n input: [\n {\n type: \"text\",\n text: ACTIVATION_PROMPT,\n text_elements: [],\n },\n ],\n },\n });\n const turnResponse = await reader.readResponse(3, RPC_TIMEOUT_MS);\n if (turnResponse.error) {\n const base = formatRpcError(\"turn/start\", turnResponse.error);\n const hint = inferRefreshFailureHint(stderrOutput);\n if (hint && !base.toLowerCase().includes(hint)) {\n throw new Error(`${base}; ${hint}`);\n }\n throw new Error(base);\n }\n const turnId = readTurnIdFromResult(turnResponse.result);\n if (!turnId) {\n throw new Error(\"turn/start response did not include a turn id.\");\n }\n\n const completed = await reader.read(\n (message) =>\n message.method === \"turn/completed\" &&\n readTurnIdFromNotification(message) === turnId,\n ACTIVATION_TURN_TIMEOUT_MS,\n );\n const turnStatus = readTurnStatusFromNotification(completed);\n if (turnStatus.status === \"failed\") {\n return {\n status: \"failed\",\n reason: turnStatus.reason ?? \"turn-failed\",\n threadId,\n turnId,\n };\n }\n\n return { status: \"completed\", reason: null, threadId, turnId };\n } finally {\n child.stderr?.off(\"data\", onStderrData);\n child.kill();\n reader.dispose();\n rl.close();\n try {\n const updatedAuth = await fs.readFile(tempAuthPath, \"utf8\");\n if (updatedAuth.trim().length > 0) {\n const currentSourceAuth = await readAuthFileCached(sourceAuthPath);\n if (\n shouldWriteBackAuth(initialSourceAuth, currentSourceAuth, updatedAuth)\n ) {\n await writeAuthFileCached(sourceAuthPath, updatedAuth);\n } else if (\n currentSourceAuth &&\n currentSourceAuth !== updatedAuth &&\n currentSourceAuth !== initialSourceAuth\n ) {\n logWarn(\n \"Skipped stale auth sync-back after reset-window activation; source auth changed in flight.\",\n {\n sourceAuthPath,\n currentRecencyMs: extractAuthRecencyMs(currentSourceAuth),\n updatedRecencyMs: extractAuthRecencyMs(updatedAuth),\n },\n );\n }\n }\n } catch {\n // Best effort: if auth sync-back fails, keep existing source auth.\n }\n await fs.rm(tempHome, { recursive: true, force: true }).catch(() => {});\n }\n}\n","import { promises as fs, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { CodexCliChannel, CodexCliInfoPayload, CodexCliStatusPayload } from \"@codexuse/contracts/desktop/ipc-types\";\n\ntype MutableStatus = CodexCliStatusPayload;\nconst STABLE_CHANNEL: CodexCliChannel = \"stable\";\nconst ENV_HINTS = [\"CODEX_BINARY\", \"CODEX_CLI_PATH\", \"CODEX_PATH\"] as const;\n\nlet cachedStatus: MutableStatus | null = null;\n\nfunction getPathHintEntries(): string[] {\n const homeDir = process.env.HOME ?? \"\";\n const homeEntries = homeDir\n ? [\n path.join(homeDir, \".local\", \"bin\"),\n path.join(homeDir, \".fnm\", \"aliases\", \"default\", \"bin\"),\n path.join(homeDir, \".fnm\", \"current\", \"bin\"),\n path.join(homeDir, \".volta\", \"bin\"),\n path.join(homeDir, \".asdf\", \"shims\"),\n path.join(homeDir, \".bun\", \"bin\"),\n ]\n : [];\n const configuredHints = (process.env.CODEX_PATH_HINTS ?? \"\")\n .split(path.delimiter)\n .map(entry => entry.trim())\n .filter(Boolean);\n\n return [\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n ...homeEntries,\n ...configuredHints,\n ];\n}\n\nfunction fileExists(candidate: string | undefined | null): string | null {\n if (!candidate) {\n return null;\n }\n\n const normalized = path.resolve(candidate);\n\n try {\n const stats = statSync(normalized);\n if (stats.isFile()) {\n return normalized;\n }\n } catch {\n // ignore missing paths\n }\n\n return null;\n}\n\nfunction resolveCodexFromEnv(): string | null {\n for (const key of ENV_HINTS) {\n const value = process.env[key];\n if (!value) {\n continue;\n }\n const resolved = fileExists(value);\n if (resolved) {\n return resolved;\n }\n }\n return null;\n}\n\nfunction resolveCodexFromPath(): string | null {\n const pathValue = process.env.PATH ?? \"\";\n const entries = Array.from(\n new Set(\n [\n ...getPathHintEntries(),\n ...pathValue\n .split(path.delimiter)\n .map(entry => entry.trim())\n .filter(Boolean),\n ].filter(Boolean),\n ),\n );\n for (const entry of entries) {\n const candidate = fileExists(path.join(entry, \"codex\"));\n if (candidate) {\n return candidate;\n }\n }\n return null;\n}\n\nfunction resolvePackageJsonPath(cliPath: string): string | null {\n const normalized = path.resolve(cliPath);\n const binDir = path.dirname(normalized);\n const packageDir = path.basename(binDir) === \"bin\" ? path.dirname(binDir) : path.dirname(normalized);\n const pkgPath = path.join(packageDir, \"package.json\");\n return fileExists(pkgPath);\n}\n\nasync function readCodexCliVersion(cliPath: string): Promise<string | null> {\n const packageJsonPath = resolvePackageJsonPath(cliPath);\n if (!packageJsonPath) {\n return null;\n }\n try {\n const raw = await fs.readFile(packageJsonPath, \"utf8\");\n const parsed = JSON.parse(raw) as { version?: unknown };\n if (typeof parsed?.version !== \"string\") {\n return null;\n }\n const normalized = parsed.version.trim();\n return normalized.length > 0 ? normalized : null;\n } catch {\n return null;\n }\n}\n\nfunction buildUnavailableStatus(reason?: string): MutableStatus {\n return {\n available: false,\n path: null,\n reason: reason ?? \"Codex CLI not found. Install @openai/codex on this machine or set CODEX_BINARY.\",\n source: null,\n channel: STABLE_CHANNEL,\n };\n}\n\nfunction evaluateExternalStatus(): MutableStatus {\n const envPath = resolveCodexFromEnv();\n if (envPath) {\n return {\n available: true,\n path: envPath,\n reason: null,\n source: \"env\",\n channel: STABLE_CHANNEL,\n };\n }\n\n const pathResolved = resolveCodexFromPath();\n if (pathResolved) {\n return {\n available: true,\n path: pathResolved,\n reason: null,\n source: \"path\",\n channel: STABLE_CHANNEL,\n };\n }\n\n return buildUnavailableStatus();\n}\n\nfunction evaluateCodexCliStatus(): MutableStatus {\n return evaluateExternalStatus();\n}\n\nexport async function refreshCodexStatus(): Promise<CodexCliStatusPayload> {\n cachedStatus = evaluateCodexCliStatus();\n return { ...cachedStatus };\n}\n\nasync function getCodexCliStatus(): Promise<CodexCliStatusPayload> {\n if (!cachedStatus) {\n return refreshCodexStatus();\n }\n return { ...cachedStatus };\n}\n\nexport async function getCodexCliInfo(): Promise<CodexCliInfoPayload> {\n const status = await getCodexCliStatus();\n const version =\n status.available && status.path\n ? await readCodexCliVersion(status.path)\n : null;\n return { ...status, version };\n}\n\nexport class CodexCliMissingError extends Error {\n readonly status: CodexCliStatusPayload;\n\n constructor(status: CodexCliStatusPayload, message?: string) {\n super(message ?? status.reason ?? \"Codex CLI is not available\");\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"CodexCliMissingError\";\n this.status = { ...status };\n }\n}\n\nexport async function requireCodexCli(): Promise<string> {\n const status = await refreshCodexStatus();\n if (!status.available || !status.path) {\n throw new CodexCliMissingError(status);\n }\n return status.path;\n}\n","import { spawnSync } from \"node:child_process\";\nimport path from \"node:path\";\n\nlet cachedNodeRuntime: string | null = null;\n\nfunction isJavaScriptEntrypoint(binaryPath: string): boolean {\n const normalized = binaryPath.trim().toLowerCase();\n return (\n normalized.endsWith(\".js\") ||\n normalized.endsWith(\".mjs\") ||\n normalized.endsWith(\".cjs\")\n );\n}\n\nfunction resolveNodeRuntime(env?: NodeJS.ProcessEnv): string {\n const override =\n env?.CODEX_NODE_RUNTIME?.trim() ||\n env?.CODEX_NODE_BIN?.trim() ||\n env?.CODEX_NODE?.trim() ||\n process.env.CODEX_NODE_RUNTIME?.trim() ||\n process.env.CODEX_NODE_BIN?.trim() ||\n process.env.CODEX_NODE?.trim() ||\n null;\n if (override) {\n return override;\n }\n\n if (cachedNodeRuntime) {\n return cachedNodeRuntime;\n }\n\n const runtimeEnv: NodeJS.ProcessEnv = { ...process.env, ...env };\n const homeDir = runtimeEnv.HOME ?? \"\";\n const pathHints = (runtimeEnv.CODEX_PATH_HINTS ?? process.env.CODEX_PATH_HINTS ?? \"\")\n .split(path.delimiter)\n .map(entry => entry.trim())\n .filter(Boolean);\n const extraPathEntries = [\n \"/usr/local/bin\",\n \"/opt/homebrew/bin\",\n path.join(homeDir, \".local\", \"bin\"),\n path.join(homeDir, \".fnm\", \"aliases\", \"default\", \"bin\"),\n path.join(homeDir, \".fnm\", \"current\", \"bin\"),\n ...pathHints,\n ].filter(Boolean);\n const currentPath = runtimeEnv.PATH ?? \"\";\n runtimeEnv.PATH = Array.from(\n new Set([...extraPathEntries, ...currentPath.split(path.delimiter).filter(Boolean)]),\n ).join(path.delimiter);\n\n const candidates = Array.from(\n new Set(\n [\n runtimeEnv.CODEX_NODE_RUNTIME?.trim(),\n runtimeEnv.CODEX_NODE_BIN?.trim(),\n runtimeEnv.CODEX_NODE?.trim(),\n \"/opt/homebrew/bin/node\",\n \"/usr/local/bin/node\",\n \"node\",\n ].filter((candidate): candidate is string => typeof candidate === \"string\" && candidate.length > 0),\n ),\n );\n\n for (const candidate of candidates) {\n const probe = spawnSync(candidate, [\"-v\"], { env: runtimeEnv, stdio: \"ignore\" });\n if (!probe.error && probe.status === 0) {\n cachedNodeRuntime = candidate;\n return candidate;\n }\n }\n\n cachedNodeRuntime = process.execPath;\n return process.execPath;\n}\n\nexport function buildCodexCommand(\n binaryPath: string,\n args: ReadonlyArray<string>,\n env?: NodeJS.ProcessEnv,\n): {\n command: string;\n args: string[];\n shell: boolean;\n} {\n if (isJavaScriptEntrypoint(binaryPath)) {\n return {\n command: resolveNodeRuntime(env),\n args: [binaryPath, ...args],\n shell: false,\n };\n }\n\n return {\n command: binaryPath,\n args: [...args],\n shell: false,\n };\n}\n","const isTestEnv =\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n process.env.VITEST === '1';\n\nfunction isMocked(fn: unknown): boolean {\n return Boolean(fn && typeof fn === 'function' && 'mock' in (fn as object));\n}\n\nexport function logWarn(...args: Parameters<typeof console.warn>): void {\n if (isTestEnv && !isMocked(console.warn)) {\n return;\n }\n console.warn(...args);\n}\n\nexport function logError(...args: Parameters<typeof console.error>): void {\n if (isTestEnv && !isMocked(console.error)) {\n return;\n }\n console.error(...args);\n}\n\nexport function logInfo(...args: Parameters<typeof console.info>): void {\n // eslint-disable-next-line no-console -- logger wrapper intentionally owns console.info\n if (isTestEnv && !isMocked(console.info)) {\n return;\n }\n // eslint-disable-next-line no-console -- logger wrapper intentionally owns console.info\n console.info(...args);\n}\n","export function printHelp(version: string): void {\n console.log(`CodexUse CLI v${version}\n\nUsage:\n codexuse doctor\n codexuse run --profile <name> -- <codex args>\n codexuse best [--dry-run] -- <codex args>\n\n codexuse account-pool status [--runtime=desktop] [--state-dir=/abs/path]\n codexuse account-pool quickstart\n codexuse account-pool enable\n codexuse account-pool disable\n codexuse account-pool routing <least-used|round-robin>\n codexuse account-pool profiles list\n codexuse account-pool profiles set <name> [more...]\n codexuse account-pool models list\n codexuse account-pool keys list [--runtime=desktop]\n codexuse account-pool keys create [--runtime=desktop]\n codexuse account-pool sessions list [--runtime=desktop]\n\n codexuse profile list [--no-usage] [--compact]\n codexuse profile current\n codexuse profile add <name> [--skip-login] [--device-auth] [--login=browser|device]\n codexuse profile refresh <name> [--skip-login] [--device-auth] [--login=browser|device]\n codexuse profile switch <name> [--activate-codex]\n codexuse profile autoroll [--switch-left=0-50] [--dry-run] [--watch] [--interval=seconds] [--activate-codex|--no-activate-codex]\n codexuse profile delete <name>\n codexuse profile rename <old> <new>\n\n codexuse license status [--refresh]\n codexuse license activate <license-key>\n\n codexuse sync status\n codexuse sync pull\n codexuse sync push\n\nFlags:\n -h, --help Show help\n -v, --version Show version\n --no-usage Skip rate-limit usage fetch\n --compact Names only\n --device-auth Use device auth for Codex login\n --login=MODE Login mode: browser | device\n --switch-left=NN Auto-roll switch threshold by percent left (0-50)\n --watch Keep checking and auto-switch when threshold is reached\n --interval=SEC Watch interval in seconds (default: 30)\n --dry-run Print planned switch without changing active profile\n --activate-codex Focus or launch official Codex after a profile switch\n --no-activate-codex Override saved auto-roll activation setting\n --profile=NAME Run Codex with one saved profile\n --runtime=NAME Accounts Pool runtime store: desktop\n --state-dir=PATH Override the runtime state dir for Accounts Pool inspection\nNote: profile autoroll requires Pro.\n`);\n}\n","import type { CodexLoginMode } from \"./codexCli\";\n\nexport const DEFAULT_AUTOROLL_INTERVAL_SECONDS = 30;\n\nexport function hasFlag(args: string[], flag: string): boolean {\n return args.includes(flag);\n}\n\nexport function stripFlags(args: string[]): string[] {\n return args.filter(arg => !arg.startsWith(\"-\"));\n}\n\nexport function parseLoginMode(flags: string[]): CodexLoginMode | null {\n if (flags.includes(\"--device-auth\")) return \"device\";\n const explicit = flags.find(flag => flag.startsWith(\"--login=\"));\n if (!explicit) return null;\n const value = explicit.split(\"=\")[1];\n if (value === \"browser\" || value === \"device\") {\n return value;\n }\n return null;\n}\n\nexport function parseNumericFlag(flags: string[], name: string): number | null {\n const explicit = flags.find(flag => flag.startsWith(`${name}=`));\n if (!explicit) {\n return null;\n }\n const raw = explicit.slice(`${name}=`.length);\n const value = Number.parseFloat(raw);\n return Number.isFinite(value) ? value : Number.NaN;\n}\n\nexport function parseIntegerFlag(flags: string[], name: string): number | null {\n const explicit = flags.find(flag => flag.startsWith(`${name}=`));\n if (!explicit) {\n return null;\n }\n const raw = explicit.slice(`${name}=`.length);\n const value = Number.parseInt(raw, 10);\n return Number.isFinite(value) ? value : Number.NaN;\n}\n\nexport function parseStringFlag(flags: string[], name: string): string | null {\n const explicit = flags.find(flag => flag.startsWith(`${name}=`));\n if (!explicit) {\n return null;\n }\n const value = explicit.slice(`${name}=`.length).trim();\n return value.length > 0 ? value : \"\";\n}\n","import { spawn } from \"node:child_process\";\nimport { maxUsedPercent } from \"@codexuse/runtime-profiles/profiles/rate-limit-notifier\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport type { Profile, RateLimitSnapshot } from \"@codexuse/contracts/profiles/types\";\nimport { readAccountPoolRuntimeSummary } from \"./accountPool\";\nimport { hasFlag } from \"../platform/args\";\nimport {\n buildCodexCommand,\n resolveCodexBinary,\n} from \"../platform/codexCli\";\n\ntype SplitCommandArgs = {\n flags: string[];\n codexArgs: string[];\n};\n\ntype CommandResult = {\n code: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n};\n\ntype BestProfileCandidate = {\n profile: Profile;\n usedPercent: number | null;\n resetSeconds: number | null;\n};\n\nconst DOCTOR_TIMEOUT_MS = 8_000;\n\nfunction splitCommandArgs(args: string[]): SplitCommandArgs {\n const delimiterIndex = args.indexOf(\"--\");\n const flags = delimiterIndex >= 0 ? args.slice(0, delimiterIndex) : args.slice();\n const codexArgs = delimiterIndex >= 0 ? args.slice(delimiterIndex + 1) : [];\n return { flags, codexArgs };\n}\n\nfunction readOption(flags: string[], longName: string, shortName?: string): string | null {\n for (let index = 0; index < flags.length; index += 1) {\n const flag = flags[index];\n if (flag === longName) {\n const next = flags[index + 1];\n return next && !next.startsWith(\"-\") ? next : \"\";\n }\n if (flag.startsWith(`${longName}=`)) {\n return flag.slice(longName.length + 1).trim();\n }\n if (shortName && flag === shortName) {\n const next = flags[index + 1];\n return next && !next.startsWith(\"-\") ? next : \"\";\n }\n }\n return null;\n}\n\nfunction firstLine(value: string): string | null {\n const line = value.split(/\\r?\\n/).map((entry) => entry.trim()).find(Boolean);\n return line ?? null;\n}\n\nfunction formatUsagePercent(value: number | null): string {\n return typeof value === \"number\" && Number.isFinite(value)\n ? `${Math.round(value)}%`\n : \"unknown\";\n}\n\nfunction snapshotResetSeconds(snapshot: RateLimitSnapshot | null): number | null {\n const values = [\n snapshot?.primary?.resetsInSeconds,\n snapshot?.secondary?.resetsInSeconds,\n ].filter((value): value is number => typeof value === \"number\" && Number.isFinite(value));\n return values.length > 0 ? Math.min(...values) : null;\n}\n\nfunction fallbackUsedPercent(profile: Profile): number | null {\n const cached = maxUsedPercent(profile.rateLimit ?? null);\n return typeof cached === \"number\" && Number.isFinite(cached) ? cached : null;\n}\n\nfunction compareCandidates(left: BestProfileCandidate, right: BestProfileCandidate): number {\n const leftUsage = left.usedPercent ?? Number.POSITIVE_INFINITY;\n const rightUsage = right.usedPercent ?? Number.POSITIVE_INFINITY;\n if (leftUsage !== rightUsage) {\n return leftUsage - rightUsage;\n }\n const leftReset = left.resetSeconds ?? Number.POSITIVE_INFINITY;\n const rightReset = right.resetSeconds ?? Number.POSITIVE_INFINITY;\n if (leftReset !== rightReset) {\n return leftReset - rightReset;\n }\n return left.profile.name.localeCompare(right.profile.name);\n}\n\nasync function runCommand(\n codexPath: string,\n args: string[],\n timeoutMs: number,\n): Promise<CommandResult> {\n const command = buildCodexCommand(codexPath, args);\n return new Promise((resolve) => {\n const child = spawn(command.command, command.args, {\n env: process.env,\n shell: command.shell,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n let settled = false;\n let timedOut = false;\n let timer: NodeJS.Timeout;\n const finish = (code: number | null) => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n };\n timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n finish(null);\n }, timeoutMs);\n child.stdout?.on(\"data\", (chunk) => {\n stdout = (stdout + String(chunk)).slice(-20_000);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr = (stderr + String(chunk)).slice(-20_000);\n });\n child.on(\"error\", () => finish(null));\n child.on(\"close\", (code) => finish(code));\n });\n}\n\nasync function selectBestProfile(\n manager: ProfileManager,\n profiles: Profile[],\n codexPath: string,\n): Promise<BestProfileCandidate | null> {\n const candidates: BestProfileCandidate[] = [];\n for (const profile of profiles) {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n continue;\n }\n try {\n const snapshot = await manager.readLiveRateLimits(profile.name, { codexPath });\n candidates.push({\n profile,\n usedPercent: typeof maxUsedPercent(snapshot) === \"number\"\n ? maxUsedPercent(snapshot)\n : fallbackUsedPercent(profile),\n resetSeconds: snapshotResetSeconds(snapshot),\n });\n } catch {\n candidates.push({\n profile,\n usedPercent: fallbackUsedPercent(profile),\n resetSeconds: snapshotResetSeconds(profile.rateLimit ?? null),\n });\n }\n }\n return candidates.sort(compareCandidates)[0] ?? null;\n}\n\nasync function runCodexWithProfile(\n manager: ProfileManager,\n profileName: string,\n codexArgs: string[],\n): Promise<void> {\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n throw new Error(\"Codex CLI not found. Install Codex CLI or set CODEX_BINARY.\");\n }\n const runtime = await manager.prepareProfileRuntime(profileName, {\n syncFromActiveAuthBeforeAction: false,\n });\n const command = buildCodexCommand(codexPath, codexArgs);\n try {\n const child = spawn(command.command, command.args, {\n env: runtime.env,\n shell: command.shell,\n stdio: \"inherit\",\n });\n const exitCode = await new Promise<number>((resolve) => {\n child.on(\"close\", (code) => resolve(code ?? 0));\n });\n process.exitCode = exitCode;\n } finally {\n await manager.syncProfileRuntime(profileName, runtime.profileHome).catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Warning: failed to sync profile runtime for '${profileName}': ${message}`);\n });\n }\n}\n\nexport async function handleDoctorCommand(args: string[]): Promise<void> {\n if (hasFlag(args, \"--help\") || hasFlag(args, \"-h\")) {\n console.log(`Usage:\n codexuse doctor\n\nChecks Codex CLI, auth, saved profiles, license, and Accounts Pool readiness.`);\n return;\n }\n\n const manager = new ProfileManager();\n const codexPath = resolveCodexBinary();\n const [profiles, current, license, accountPool] = await Promise.all([\n manager.listProfiles(),\n manager.getCurrentProfile(),\n licenseService.getStatus().catch(() => null),\n readAccountPoolRuntimeSummary().catch(() => null),\n ]);\n\n console.log(\"CodexUse Doctor\");\n if (!codexPath) {\n console.log(\"Codex CLI: missing\");\n } else {\n const version = await runCommand(codexPath, [\"--version\"], DOCTOR_TIMEOUT_MS);\n const versionText = firstLine(version.stdout) ?? firstLine(version.stderr);\n console.log(`Codex CLI: ${version.code === 0 ? \"ok\" : \"check\"} (${codexPath})`);\n console.log(`Version: ${versionText ?? (version.timedOut ? \"timed out\" : \"unknown\")}`);\n\n const auth = await runCommand(codexPath, [\"login\", \"status\"], DOCTOR_TIMEOUT_MS);\n const authText = firstLine(auth.stdout) ?? firstLine(auth.stderr);\n console.log(`Auth: ${auth.code === 0 ? \"ok\" : \"check\"}${authText ? ` (${authText})` : \"\"}`);\n }\n\n console.log(`Profiles: ${profiles.length}`);\n console.log(`Active profile: ${current.name ?? \"none\"}${current.trusted ? \"\" : \" (untrusted)\"}`);\n console.log(`License: ${license ? `${license.tier} (${license.state})` : \"unknown\"}`);\n if (accountPool) {\n console.log(\n `Accounts Pool: ${accountPool.enabled ? \"on\" : \"off\"} | keys ${accountPool.activeApiKeyCount} | sessions ${accountPool.activeSessionCount}`,\n );\n } else {\n console.log(\"Accounts Pool: unknown\");\n }\n\n const fixes: string[] = [];\n if (!codexPath) {\n fixes.push(\"Install Codex CLI or set CODEX_BINARY.\");\n }\n if (profiles.length === 0) {\n fixes.push(\"Add first profile: codexuse profile add personal\");\n }\n if (profiles.length === 1) {\n fixes.push(\"Add second profile: codexuse profile add work\");\n }\n if (!current.name && profiles.length > 0) {\n fixes.push(`Switch active profile: codexuse profile switch ${profiles[0]?.name}`);\n }\n if (accountPool && (!accountPool.enabled || accountPool.activeApiKeyCount === 0)) {\n fixes.push(\"Pool quickstart: codexuse account-pool quickstart\");\n }\n\n if (fixes.length > 0) {\n console.log(\"Fixes:\");\n for (const fix of fixes) {\n console.log(`- ${fix}`);\n }\n return;\n }\n console.log(\"Ready.\");\n}\n\nexport async function handleRunCommand(args: string[]): Promise<void> {\n const { flags, codexArgs } = splitCommandArgs(args);\n if (hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n console.log(`Usage:\n codexuse run --profile <name> -- <codex args>\n\nRuns Codex under one saved CodexUse profile.`);\n return;\n }\n const profileName = readOption(flags, \"--profile\", \"-p\");\n if (!profileName) {\n throw new Error(\"Profile is required. Use --profile <name>.\");\n }\n const manager = new ProfileManager();\n await runCodexWithProfile(manager, profileName, codexArgs);\n}\n\nexport async function handleBestCommand(args: string[]): Promise<void> {\n const { flags, codexArgs } = splitCommandArgs(args);\n if (hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n console.log(`Usage:\n codexuse best -- <codex args>\n\nPicks the healthiest saved profile, then runs Codex. Auto-run requires Pro.`);\n return;\n }\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n throw new Error(\"Codex CLI not found. Install Codex CLI or set CODEX_BINARY.\");\n }\n const manager = new ProfileManager();\n const profiles = await manager.listProfiles();\n const best = await selectBestProfile(manager, profiles, codexPath);\n if (!best) {\n throw new Error(\"No valid saved profiles found. Add one with `codexuse profile add <name>`.\");\n }\n\n const dryRun = hasFlag(flags, \"--dry-run\");\n const license = await licenseService.getStatus();\n const summary = `${best.profile.name} (${formatUsagePercent(best.usedPercent)} used)`;\n if (!license.isPro) {\n console.log(`Best profile: ${summary}`);\n console.log(\"Auto-run is Pro. Free path:\");\n console.log(` codexuse run --profile ${best.profile.name} -- ${codexArgs.join(\" \")}`.trimEnd());\n return;\n }\n if (dryRun) {\n console.log(`Would run with profile: ${summary}`);\n return;\n }\n console.error(`CodexUse best -> ${summary}`);\n await runCodexWithProfile(manager, best.profile.name, codexArgs);\n}\n","import type { RateLimitSnapshot } from \"@codexuse/contracts/profiles/types\";\n\nexport function maxUsedPercent(snapshot: RateLimitSnapshot | null | undefined): number | null {\n if (!snapshot) {\n return null;\n }\n\n const candidates = [\n snapshot.primary?.usedPercent,\n snapshot.secondary?.usedPercent,\n ].filter((value): value is number => typeof value === \"number\" && Number.isFinite(value));\n\n if (candidates.length === 0) {\n return null;\n }\n\n return Math.max(...candidates);\n}\n","import { spawn } from \"node:child_process\";\nimport { statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nconst ENV_HINTS = [\"CODEX_BINARY\", \"CODEX_CLI_PATH\", \"CODEX_PATH\"] as const;\n\nexport type CodexLoginMode = \"browser\" | \"device\";\n\nfunction fileExists(candidate: string | null | undefined): string | null {\n if (!candidate) return null;\n const resolved = path.resolve(candidate);\n try {\n const stat = statSync(resolved);\n if (stat.isFile()) return resolved;\n } catch {\n return null;\n }\n return null;\n}\n\nfunction resolveFromEnv(): string | null {\n for (const key of ENV_HINTS) {\n const value = process.env[key];\n if (!value) continue;\n const resolved = fileExists(value);\n if (resolved) return resolved;\n }\n return null;\n}\n\nfunction resolveFromPath(): string | null {\n const pathValue = process.env.PATH ?? \"\";\n const entries = pathValue.split(path.delimiter).filter(Boolean);\n\n for (const entry of entries) {\n const candidate = fileExists(path.join(entry, \"codex\"));\n if (candidate) return candidate;\n }\n\n return null;\n}\n\nexport function resolveCodexBinary(): string | null {\n return (\n resolveFromEnv() ||\n resolveFromPath()\n );\n}\n\nfunction requireCodexBinary(context?: string): string {\n const resolved = resolveCodexBinary();\n if (resolved) return resolved;\n const hint = \"Install Codex CLI (npm i -g @openai/codex) or set CODEX_BINARY.\";\n const message = context ? `${context} ${hint}` : hint;\n throw new Error(message);\n}\n\nexport function buildCodexCommand(codexPath: string, args: string[]): { command: string; args: string[]; shell: boolean } {\n const normalized = codexPath.toLowerCase();\n const isJs = normalized.endsWith(\".js\") || normalized.endsWith(\".mjs\") || normalized.endsWith(\".cjs\");\n if (isJs) {\n return { command: process.execPath, args: [codexPath, ...args], shell: false };\n }\n\n return { command: codexPath, args, shell: false };\n}\n\nfunction isHeadless(): boolean {\n if (process.env.CODEXUSE_HEADLESS === \"1\") return true;\n if (process.env.CI) return true;\n if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return true;\n return false;\n}\n\nexport function resolveLoginMode(preferred?: CodexLoginMode | null): CodexLoginMode {\n if (preferred === \"browser\" || preferred === \"device\") {\n return preferred;\n }\n const envMode = process.env.CODEXUSE_LOGIN_MODE;\n if (envMode === \"browser\" || envMode === \"device\") {\n return envMode;\n }\n return isHeadless() ? \"device\" : \"browser\";\n}\n\nexport async function runCodexLogin(mode?: CodexLoginMode | null): Promise<void> {\n const codexPath = requireCodexBinary(\"Codex CLI is required to login.\");\n const resolvedMode = resolveLoginMode(mode ?? null);\n const loginArgs = resolvedMode === \"device\"\n ? [\"login\", \"--device-auth\"]\n : [\"login\"];\n const { command, args, shell } = buildCodexCommand(codexPath, loginArgs);\n\n const child = spawn(command, args, {\n stdio: \"inherit\",\n env: process.env,\n shell,\n });\n\n const exitCode = await new Promise<number>((resolve) => {\n child.on(\"close\", (code) => resolve(code ?? 0));\n });\n\n if (exitCode !== 0) {\n throw new Error(`Codex CLI login failed (exit code ${exitCode}).`);\n }\n}\n","import { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { printHelp } from \"../app/help\";\nimport { hasFlag, stripFlags } from \"../platform/args\";\n\nexport async function handleLicense(args: string[], version: string): Promise<void> {\n const flags = args.filter(arg => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printHelp(version);\n return;\n }\n\n switch (sub) {\n case \"status\": {\n const forceRefresh = hasFlag(flags, \"--refresh\");\n const status = await licenseService.getStatus({ forceRefresh });\n console.log(`Tier: ${status.tier}`);\n console.log(`State: ${status.state}`);\n if (status.profileLimit !== null) {\n console.log(`Profile limit: ${status.profileLimit}`);\n }\n if (status.profilesRemaining !== null) {\n console.log(`Profiles remaining: ${status.profilesRemaining}`);\n }\n if (status.purchaseEmail) {\n console.log(`Email: ${status.purchaseEmail}`);\n }\n if (status.maskedLicenseKey) {\n console.log(`License: ${status.maskedLicenseKey}`);\n }\n if (status.message) {\n console.log(`Message: ${status.message}`);\n }\n if (status.error) {\n console.log(`Error: ${status.error}`);\n }\n return;\n }\n case \"activate\": {\n const key = params[1];\n if (!key) {\n throw new Error(\"License key is required.\");\n }\n const status = await licenseService.activate(key);\n console.log(status.message ?? \"License activated.\");\n return;\n }\n default:\n printHelp(version);\n }\n}\n","import { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\n\nexport async function assertProfileCreationAllowed(\n profileManager?: ProfileManager,\n): Promise<void> {\n const manager = profileManager ?? new ProfileManager();\n await manager.initialize();\n\n const license = await licenseService.getStatus();\n const profiles = await manager.listProfiles();\n const licenseWithCounts = licenseService.applyProfileCount(license, profiles.length);\n\n if (\n typeof licenseWithCounts.profileLimit === \"number\" &&\n licenseWithCounts.profilesRemaining !== null &&\n licenseWithCounts.profilesRemaining <= 0\n ) {\n throw new Error(\"CodexUse Free supports up to 2 profiles. Upgrade to CodexUse Pro for unlimited profiles.\");\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport net from \"node:net\";\nimport path from \"node:path\";\nimport type {\n AutoRollActivityEntry,\n OfficialCodexBridgeActivityState,\n AutoRollActivityKind,\n OfficialCodexBridgeCapabilitiesPayload,\n OfficialCodexPowerApplyResultPayload,\n OfficialCodexPowerSettingsPayload,\n OfficialCodexPowerStatusPayload,\n OfficialCodexQolStatusPayload,\n OfficialCodexRelayMode,\n OfficialCodexRelayStatusPayload,\n OfficialCodexBridgeStatus,\n OfficialCodexInstancesPayload,\n OfficialCodexProfileActionPayload,\n OfficialCodexProfileInstancePayload,\n OfficialCodexQolApplyResultPayload,\n OfficialCodexQolSettingsPayload,\n OfficialCodexSyncStatusPayload,\n OfficialCodexUnmanagedInstancePayload,\n} from \"@codexuse/contracts/desktop/ipc-types\";\nimport { findOfficialCodexThreadRecord } from \"./threadUsage\";\nimport {\n getAppState,\n patchAppState,\n updateAppState,\n type AppState,\n type OfficialCodexManagedInstanceState,\n} from \"@codexuse/runtime-app-state/app/state\";\n\nconst COMMAND_TIMEOUT_MS = 3_000;\nconst EXIT_WAIT_MS = 10_000;\nconst LAUNCH_WAIT_MS = 15_000;\nconst POLL_INTERVAL_MS = 250;\nconst PROCESS_EXIT_GRACE_MS = 15_000;\nconst POST_EXIT_SETTLE_MS = 3_000;\nconst GENERATING_EXIT_GRACE_MS = 45_000;\nconst GENERATING_EXIT_POLL_MS = 3_000;\nconst APP_DISCOVERY_CACHE_TTL_MS = 60_000;\nconst APP_DISCOVERY_MISS_CACHE_TTL_MS = 5_000;\nconst OFFICIAL_CODEX_ACTIVITY_LIMIT = 50;\nconst CODEX_CDP_HOST = \"127.0.0.1\";\nconst CODEX_CDP_REQUEST_TIMEOUT_MS = 2_500;\nconst CODEX_BRIDGE_PROBE_TTL_MS = 5_000;\n// A cold Codex relaunch can take well over 5s before its page target shows up\n// on the debug port; the post-launch waiters exit early once the bridge is\n// healthy, so a long deadline only costs time when the window is truly dead.\nconst CODEX_BRIDGE_LAUNCH_WAIT_MS = 30_000;\nconst CODEXUSE_BRIDGE_BINDING_NAME = \"__codexuseBridgeBinding\";\nconst CODEXUSE_BRIDGE_INSTALL_TTL_MS = 5_000;\nconst CODEXUSE_BRIDGE_VERSION = \"0.2.0\";\n\ntype CommandResult = {\n code: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n};\n\ntype OfficialCodexAppCandidate = {\n appPath: string;\n bundleId: string;\n executableName: string;\n version: string | null;\n};\n\ntype OfficialCodexAppTarget = {\n candidate: OfficialCodexAppCandidate | null;\n runningPids: number[];\n mainPids: number[];\n};\n\ntype CdpWebSocket = {\n send(data: string): void;\n close(): void;\n addEventListener(\n type: \"open\",\n listener: () => void,\n options?: { once?: boolean },\n ): void;\n addEventListener(\n type: \"error\",\n listener: (event: unknown) => void,\n options?: { once?: boolean },\n ): void;\n addEventListener(\n type: \"message\",\n listener: (event: { data: unknown }) => void,\n ): void;\n addEventListener(\n type: \"close\",\n listener: () => void,\n options?: { once?: boolean },\n ): void;\n};\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\ndeclare const WebSocket: {\n new (url: string): CdpWebSocket;\n};\n\ntype ProcessRow = {\n pid: number;\n ppid: number;\n startedAt: number | null;\n args: string;\n};\n\ntype OfficialCodexApplyRuntimeContext = {\n state: AppState;\n candidate: OfficialCodexAppCandidate | null;\n rows: ProcessRow[];\n};\n\ntype OfficialCodexProfileLaunchOptions = {\n profileName: string;\n profileKey: string | null;\n profileHome: string;\n desiredQolSettings?: OfficialCodexQolSettingsPayload | null;\n desiredPowerSettings?: OfficialCodexPowerSettingsPayload | null;\n};\n\ntype OfficialCodexBridgeState = Pick<\n OfficialCodexManagedInstanceState,\n | \"cdpPort\"\n | \"bridgeStatus\"\n | \"bridgeLastCheckedAt\"\n | \"bridgeError\"\n | \"bridgeVersion\"\n | \"bridgeRoute\"\n | \"bridgeDevToolsUrl\"\n | \"bridgeCapabilities\"\n | \"bridgeActiveThreadId\"\n | \"bridgeActiveThreadTitle\"\n | \"bridgeActiveThreadUpdatedAt\"\n | \"bridgeComposerText\"\n | \"bridgeWorkspacePath\"\n | \"bridgeModel\"\n | \"bridgeActivityState\"\n | \"bridgeQol\"\n | \"bridgePower\"\n | \"bridgeRelayStatus\"\n>;\n\ntype CdpTarget = {\n id?: string;\n type?: string;\n title?: string;\n url?: string;\n webSocketDebuggerUrl?: string;\n devtoolsFrontendUrl?: string;\n};\n\ntype CdpCommand = {\n method: string;\n params: Record<string, unknown>;\n optional?: boolean;\n};\n\nexport type OfficialCodexBridgeActionName =\n | \"continue\"\n | \"switch\"\n | \"auto-roll\"\n | \"setting\";\n\nexport type OfficialCodexBridgeSettingKey =\n | \"autoRoll\"\n | \"wideView\"\n | \"scrollRestore\"\n | \"conversationTimeline\"\n | \"handoffChip\";\n\nexport type OfficialCodexBridgeActionRequest = {\n id: string;\n action: OfficialCodexBridgeActionName;\n sourceProfileName: string;\n targetProfileName: string | null;\n targetProfileKey: string | null;\n targetProfileKeyHash: string | null;\n settingKey: OfficialCodexBridgeSettingKey | null;\n settingValue: boolean | null;\n cdpPort: number | null;\n route: string | null;\n activeThreadId: string | null;\n createdAt: number;\n};\n\ntype OfficialCodexBridgeActionHandler = (\n request: OfficialCodexBridgeActionRequest,\n) => void | Promise<void>;\n\nlet officialCodexBridgeActionHandler:\n | OfficialCodexBridgeActionHandler\n | null = null;\nconst bridgeActionListeners = new Map<string, CdpWebSocket>();\nconst handledBridgeActionIds: string[] = [];\nconst handledBridgeActionIdSet = new Set<string>();\n\nexport function configureOfficialCodexBridgeActionHandler(\n handler: OfficialCodexBridgeActionHandler | null,\n): void {\n officialCodexBridgeActionHandler = handler;\n}\n\n// Request/response over the binding: the overlay calls\n// `__codexuseBridgeV2.request(path, payload)` and the backend resolves the\n// promise by evaluating `resolveRequest(id, result)` back into the page.\nexport type OfficialCodexBridgeRequest = {\n path: string;\n payload: unknown;\n sourceProfileName: string;\n};\n\ntype OfficialCodexBridgeRequestHandler = (\n request: OfficialCodexBridgeRequest,\n) => Promise<unknown> | unknown;\n\nlet officialCodexBridgeRequestHandler:\n | OfficialCodexBridgeRequestHandler\n | null = null;\n\nexport function configureOfficialCodexBridgeRequestHandler(\n handler: OfficialCodexBridgeRequestHandler | null,\n): void {\n officialCodexBridgeRequestHandler = handler;\n}\n\n// Fire-and-forget diagnostics from the injected script; without this channel\n// renderer-side failures are invisible to backend logs.\nexport type OfficialCodexBridgeLogEntry = {\n event: string;\n context: Record<string, string | number | boolean | null> | null;\n sourceProfileName: string;\n route: string | null;\n};\n\ntype OfficialCodexBridgeLogHandler = (\n entry: OfficialCodexBridgeLogEntry,\n) => void;\n\nlet officialCodexBridgeLogHandler: OfficialCodexBridgeLogHandler | null = null;\n\nexport function configureOfficialCodexBridgeLogHandler(\n handler: OfficialCodexBridgeLogHandler | null,\n): void {\n officialCodexBridgeLogHandler = handler;\n}\n\nfunction sanitizeBridgeLogContext(\n value: unknown,\n): Record<string, string | number | boolean | null> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n const context: Record<string, string | number | boolean | null> = {};\n let keys = 0;\n for (const [key, entry] of Object.entries(value)) {\n if (keys >= 16) {\n break;\n }\n const safeKey = key.replace(/[^A-Za-z0-9_.-]/g, \"_\").slice(0, 48);\n if (!safeKey) {\n continue;\n }\n if (typeof entry === \"string\") {\n context[safeKey] = entry.slice(0, 200);\n } else if (\n typeof entry === \"number\" ||\n typeof entry === \"boolean\" ||\n entry === null\n ) {\n context[safeKey] = entry;\n } else {\n continue;\n }\n keys += 1;\n }\n return keys > 0 ? context : null;\n}\n\nfunction rememberBridgeActionId(id: string): boolean {\n if (handledBridgeActionIdSet.has(id)) {\n return false;\n }\n handledBridgeActionIdSet.add(id);\n handledBridgeActionIds.push(id);\n while (handledBridgeActionIds.length > 200) {\n const stale = handledBridgeActionIds.shift();\n if (stale) {\n handledBridgeActionIdSet.delete(stale);\n }\n }\n return true;\n}\n\nfunction sanitizeBridgeActionRoute(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const route = value.replace(/\\s+/g, \" \").trim();\n if (!route || /^(?:https?|file|blob):/i.test(route)) {\n return null;\n }\n return route\n .replace(/local(?::|%3A)[A-Za-z0-9_.-]{8,128}/gi, \"local:[redacted-thread]\")\n .slice(0, 180);\n}\n\ntype OfficialCodexBridgeSnapshot = {\n version: string | null;\n route: string | null;\n devToolsUrl: string | null;\n capabilities: OfficialCodexBridgeCapabilitiesPayload | null;\n activeThreadId: string | null;\n activeThreadTitle: string | null;\n activeThreadUpdatedAt: number | null;\n composerText: string | null;\n workspacePath: string | null;\n model: string | null;\n activityState: OfficialCodexBridgeActivityState;\n qol: OfficialCodexQolStatusPayload | null;\n power: OfficialCodexPowerStatusPayload | null;\n relayStatus: OfficialCodexRelayStatusPayload | null;\n};\n\nexport type OfficialCodexDraftPromptInsertionResult = {\n status: \"inserted\" | \"not-found\" | \"unavailable\" | \"failed\";\n reason: string | null;\n route: string | null;\n};\n\ntype OfficialCodexQolScriptResult = {\n status: \"applied\" | \"failed\";\n reason: string | null;\n route: string | null;\n wideViewEnabled: boolean;\n wideViewMaxWidth: number | null;\n scrollRestoreEnabled: boolean;\n conversationTimelineEnabled: boolean;\n inCodexStatusEnabled: boolean;\n qolStatus: OfficialCodexQolStatusPayload | null;\n};\n\ntype OfficialCodexPowerScriptResult = {\n status: \"applied\" | \"failed\";\n reason: string | null;\n route: string | null;\n activeThreadId: string | null;\n powerStatus: OfficialCodexPowerStatusPayload | null;\n reloadRequired: boolean;\n};\n\ntype OfficialCodexActivityInput = {\n kind: AutoRollActivityKind;\n status: string;\n reason?: string | null;\n decisionId?: string | null;\n profileName?: string | null;\n sourceProfileName?: string | null;\n targetProfileName?: string | null;\n remainingPercent?: number | null;\n threshold?: number | null;\n snapshotAgeMs?: number | null;\n snapshotSource?: string | null;\n phase?: string | null;\n pid?: number | null;\n profileKey?: string | null;\n profileKeyHash?: string | null;\n switchVerified?: boolean | null;\n activationRequested?: boolean | null;\n activationResult?: string | null;\n restartRequested?: boolean | null;\n restartResult?: string | null;\n observedProfileName?: string | null;\n observedProfileKey?: string | null;\n observedProfileKeyHash?: string | null;\n observedProfileMatchSource?: AutoRollActivityEntry[\"observedProfileMatchSource\"];\n};\n\ntype OfficialCodexBridgeTarget = {\n instance: OfficialCodexManagedInstanceState;\n runtime: {\n running: boolean;\n appServerPid: number | null;\n startedAt: number | null;\n };\n managed: boolean;\n};\n\nlet profileActionLock: Promise<void> = Promise.resolve();\nlet appDiscoveryCache: {\n envPath: string | null;\n expiresAt: number;\n candidates: OfficialCodexAppCandidate[];\n} | null = null;\nlet bridgeInstallCache = new Map<\n string,\n { expiresAt: number; newDocumentScriptId: string | null }\n>();\n\nfunction hashProfileKey(profileKey?: string | null): string | null {\n if (!profileKey) {\n return null;\n }\n return createHash(\"sha256\").update(profileKey).digest(\"hex\").slice(0, 12);\n}\n\nexport type OfficialCodexOverlayRendererTarget = {\n profileKeyHash: string;\n label: string;\n detail: string;\n current: boolean;\n eligible: boolean;\n};\n\n// Shape the overlay consumes: profileKey is replaced by its hash so the page\n// never sees raw account identifiers. Used both when embedding targets in the\n// QOL expression and when answering the overlay's live \"overlay-targets\"\n// bridge request.\nexport function sanitizeOfficialCodexOverlayActionTargetsForRenderer(\n targets: OfficialCodexQolSettingsPayload[\"actionTargets\"],\n): OfficialCodexOverlayRendererTarget[] {\n const sanitized: OfficialCodexOverlayRendererTarget[] = [];\n for (const target of targets ?? []) {\n const profileKeyHash = hashProfileKey(target.profileKey);\n if (!profileKeyHash) {\n continue;\n }\n sanitized.push({\n profileKeyHash,\n label:\n typeof target.label === \"string\" && target.label.trim()\n ? target.label.trim()\n : \"Account\",\n detail:\n typeof target.detail === \"string\" && target.detail.trim()\n ? target.detail.trim()\n : target.eligible === false\n ? \"Sign-in needed\"\n : \"Ready\",\n current: target.current === true,\n eligible: target.eligible !== false,\n });\n }\n return sanitized;\n}\n\nfunction bridgeCapabilitiesUnavailable(): OfficialCodexBridgeCapabilitiesPayload {\n return {\n health: false,\n snapshot: false,\n draft: false,\n qol: false,\n power: false,\n modelWhitelist: false,\n pluginMarketplace: false,\n forcePluginInstall: false,\n };\n}\n\nfunction bridgeFeatureStatus(\n enabled: boolean,\n applied: boolean,\n version: string | null,\n error: string | null = null,\n) {\n return {\n enabled,\n applied,\n status: !enabled ? \"disabled\" : applied ? \"applied\" : \"degraded\",\n version,\n error: sanitizeUserFacingError(error),\n } as const;\n}\n\nfunction bridgeQolStatusDisabled(): OfficialCodexQolStatusPayload {\n return {\n wideView: bridgeFeatureStatus(false, false, null),\n scrollRestore: bridgeFeatureStatus(false, false, null),\n conversationTimeline: bridgeFeatureStatus(false, false, null),\n inCodexStatus: bridgeFeatureStatus(false, false, null),\n appliedAt: null,\n };\n}\n\nfunction relayStatusDisabled(): OfficialCodexRelayStatusPayload {\n return {\n mode: \"off\",\n profileId: null,\n status: \"off\",\n error: null,\n };\n}\n\nfunction bridgePowerStatusDisabled(): OfficialCodexPowerStatusPayload {\n return {\n modelWhitelistUnlock: bridgeFeatureStatus(false, false, null),\n pluginMarketplaceUnlock: bridgeFeatureStatus(false, false, null),\n forcePluginInstall: bridgeFeatureStatus(false, false, null),\n relay: relayStatusDisabled(),\n appliedAt: null,\n };\n}\n\nfunction sanitizeUserFacingError(value: unknown): string | null {\n const raw =\n value instanceof Error\n ? value.message\n : typeof value === \"string\"\n ? value\n : value === null || value === undefined\n ? \"\"\n : String(value);\n const compacted = raw.replace(/\\s+/g, \" \").trim();\n if (!compacted) {\n return null;\n }\n const sanitized = compacted\n .replace(/\\/Users\\/[^/\\s]+(?:\\/[^\\s\"'`),;]*)?/g, \"~\")\n .replace(/\\b(?:file|blob):\\/\\/[^\\s<>\"')]+/gi, \"[redacted-url]\")\n .replace(/\\bhttps?:\\/\\/[^\\s<>\"')]+/gi, \"[redacted-url]\")\n .replace(/\\blocal(?::|%3A)[A-Za-z0-9_-]{12,}\\b/gi, \"local:[redacted-thread]\")\n .replace(/\\brollout-[A-Za-z0-9_-]{12,}\\.(?:jsonl?|ndjson)\\b/g, \"rollout-[redacted]\")\n .replace(\n /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi,\n \"[redacted-id]\",\n )\n .replace(/\\bBearer\\s+[A-Za-z0-9._~+/=-]{8,}/gi, \"Bearer [redacted]\")\n .replace(/\\b(?:rk|sess|sk)-[A-Za-z0-9_-]{12,}\\b/g, \"[redacted-key]\")\n .replace(\n /\\b(api[_-]?key|token|authorization)([\"'\\s:=]+)([^,\\s\"']{8,})/gi,\n \"$1$2[redacted]\",\n );\n return sanitized.slice(0, 180);\n}\n\nfunction bridgeStateUnavailable(): OfficialCodexBridgeState {\n return {\n cdpPort: null,\n bridgeStatus: \"not-configured\",\n bridgeLastCheckedAt: null,\n bridgeError: null,\n bridgeVersion: null,\n bridgeRoute: null,\n bridgeDevToolsUrl: null,\n bridgeCapabilities: bridgeCapabilitiesUnavailable(),\n bridgeActiveThreadId: null,\n bridgeActiveThreadTitle: null,\n bridgeActiveThreadUpdatedAt: null,\n bridgeComposerText: null,\n bridgeWorkspacePath: null,\n bridgeModel: null,\n bridgeActivityState: \"unknown\",\n bridgeQol: bridgeQolStatusDisabled(),\n bridgePower: bridgePowerStatusDisabled(),\n bridgeRelayStatus: relayStatusDisabled(),\n };\n}\n\nfunction bridgeStateUnattached(\n cdpPort: number,\n checkedAt: number,\n): OfficialCodexBridgeState {\n return {\n cdpPort,\n bridgeStatus: \"unattached\",\n bridgeLastCheckedAt: checkedAt,\n bridgeError: null,\n bridgeVersion: null,\n bridgeRoute: null,\n bridgeDevToolsUrl: null,\n bridgeCapabilities: bridgeCapabilitiesUnavailable(),\n bridgeActiveThreadId: null,\n bridgeActiveThreadTitle: null,\n bridgeActiveThreadUpdatedAt: null,\n bridgeComposerText: null,\n bridgeWorkspacePath: null,\n bridgeModel: null,\n bridgeActivityState: \"unknown\",\n bridgeQol: bridgeQolStatusDisabled(),\n bridgePower: bridgePowerStatusDisabled(),\n bridgeRelayStatus: relayStatusDisabled(),\n };\n}\n\nfunction bridgeStateHealthy(\n cdpPort: number,\n checkedAt: number,\n snapshot: OfficialCodexBridgeSnapshot,\n): OfficialCodexBridgeState {\n return {\n cdpPort,\n bridgeStatus: \"healthy\",\n bridgeLastCheckedAt: checkedAt,\n bridgeError: null,\n bridgeVersion: snapshot.version,\n bridgeRoute: snapshot.route,\n bridgeDevToolsUrl: snapshot.devToolsUrl,\n bridgeCapabilities: snapshot.capabilities,\n bridgeActiveThreadId: snapshot.activeThreadId,\n bridgeActiveThreadTitle: snapshot.activeThreadTitle,\n bridgeActiveThreadUpdatedAt: snapshot.activeThreadUpdatedAt,\n bridgeComposerText: snapshot.composerText,\n bridgeWorkspacePath: snapshot.workspacePath,\n bridgeModel: snapshot.model,\n bridgeActivityState: snapshot.activityState,\n bridgeQol: snapshot.qol,\n bridgePower: snapshot.power,\n bridgeRelayStatus: snapshot.relayStatus,\n };\n}\n\nfunction bridgeStateUnhealthy(\n cdpPort: number,\n checkedAt: number,\n error: string,\n): OfficialCodexBridgeState {\n return {\n cdpPort,\n bridgeStatus: \"unhealthy\",\n bridgeLastCheckedAt: checkedAt,\n bridgeError: sanitizeUserFacingError(error),\n bridgeVersion: null,\n bridgeRoute: null,\n bridgeDevToolsUrl: null,\n bridgeCapabilities: bridgeCapabilitiesUnavailable(),\n bridgeActiveThreadId: null,\n bridgeActiveThreadTitle: null,\n bridgeActiveThreadUpdatedAt: null,\n bridgeComposerText: null,\n bridgeWorkspacePath: null,\n bridgeModel: null,\n bridgeActivityState: \"unknown\",\n bridgeQol: bridgeQolStatusDisabled(),\n bridgePower: bridgePowerStatusDisabled(),\n bridgeRelayStatus: relayStatusDisabled(),\n };\n}\n\nfunction bridgeStateForStoredInstance(\n instance: OfficialCodexManagedInstanceState,\n running: boolean,\n checkedAt: number | null = instance.bridgeLastCheckedAt,\n): OfficialCodexBridgeState {\n if (!running || !instance.cdpPort) {\n return bridgeStateUnavailable();\n }\n const bridgeStatus: OfficialCodexBridgeStatus =\n instance.bridgeStatus === \"not-configured\"\n ? \"unattached\"\n : instance.bridgeStatus;\n return {\n cdpPort: instance.cdpPort,\n bridgeStatus,\n bridgeLastCheckedAt: checkedAt,\n bridgeError:\n bridgeStatus === \"unhealthy\"\n ? sanitizeUserFacingError(instance.bridgeError)\n : null,\n bridgeVersion: instance.bridgeVersion,\n bridgeRoute: instance.bridgeRoute,\n bridgeDevToolsUrl: instance.bridgeDevToolsUrl,\n bridgeCapabilities:\n instance.bridgeCapabilities ?? bridgeCapabilitiesUnavailable(),\n bridgeActiveThreadId: instance.bridgeActiveThreadId,\n bridgeActiveThreadTitle: instance.bridgeActiveThreadTitle,\n bridgeActiveThreadUpdatedAt: instance.bridgeActiveThreadUpdatedAt,\n bridgeComposerText: instance.bridgeComposerText,\n bridgeWorkspacePath: instance.bridgeWorkspacePath,\n bridgeModel: instance.bridgeModel,\n bridgeActivityState: instance.bridgeActivityState,\n bridgeQol: instance.bridgeQol ?? bridgeQolStatusDisabled(),\n bridgePower: instance.bridgePower ?? bridgePowerStatusDisabled(),\n bridgeRelayStatus: instance.bridgeRelayStatus ?? relayStatusDisabled(),\n };\n}\n\nasync function reserveLoopbackPort(): Promise<number> {\n return await new Promise<number>((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, CODEX_CDP_HOST, () => {\n const address = server.address();\n const port =\n typeof address === \"object\" && address !== null ? address.port : null;\n server.close(() => {\n if (typeof port === \"number\" && Number.isFinite(port)) {\n resolve(port);\n return;\n }\n reject(new Error(\"missing-cdp-port\"));\n });\n });\n });\n}\n\nasync function fetchCdpJson(url: string): Promise<unknown> {\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n CODEX_CDP_REQUEST_TIMEOUT_MS,\n );\n try {\n const response = await fetch(url, { signal: controller.signal });\n if (!response.ok) {\n throw new Error(`cdp-http-${response.status}`);\n }\n return await response.json();\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function readCdpTargets(port: number): Promise<CdpTarget[]> {\n const urls = [\n `http://${CODEX_CDP_HOST}:${port}/json/list`,\n `http://${CODEX_CDP_HOST}:${port}/json`,\n ];\n let lastError: unknown = null;\n for (const url of urls) {\n try {\n const value = await fetchCdpJson(url);\n return Array.isArray(value) ? (value as CdpTarget[]) : [];\n } catch (error) {\n lastError = error;\n }\n }\n throw lastError instanceof Error ? lastError : new Error(\"cdp-list-failed\");\n}\n\nfunction pickCodexCdpTarget(targets: CdpTarget[]): CdpTarget | null {\n const pages = targets.filter(\n (target) =>\n target.webSocketDebuggerUrl &&\n (target.type === \"page\" || target.type === \"webview\" || !target.type),\n );\n return (\n pages.find((target) =>\n `${target.title ?? \"\"} ${target.url ?? \"\"}`\n .toLowerCase()\n .includes(\"codex\"),\n ) ??\n pages[0] ??\n null\n );\n}\n\nfunction buildCdpDevToolsUrl(port: number, target: CdpTarget): string | null {\n const frontendUrl = target.devtoolsFrontendUrl?.trim();\n if (frontendUrl?.startsWith(\"/\")) {\n return `http://${CODEX_CDP_HOST}:${port}${frontendUrl}`;\n }\n if (\n frontendUrl?.startsWith(\"http://\") ||\n frontendUrl?.startsWith(\"https://\") ||\n frontendUrl?.startsWith(\"devtools://\")\n ) {\n return frontendUrl;\n }\n if (!target.id) {\n return null;\n }\n return `http://${CODEX_CDP_HOST}:${port}/devtools/inspector.html?ws=${CODEX_CDP_HOST}:${port}/devtools/page/${target.id}`;\n}\n\nfunction createBridgeSnapshotExpression(): string {\n return `(() => {\n const version = ${JSON.stringify(CODEXUSE_BRIDGE_VERSION)};\n const now = Date.now();\n const readText = (value) => typeof value === \"string\" ? value.trim() : \"\";\n const route = window.location.pathname + window.location.search + window.location.hash;\n const source = [window.location.pathname, window.location.search, window.location.hash, window.location.href].join(\" \");\n const visible = (element) => {\n if (!element || !(element instanceof HTMLElement)) return false;\n const style = window.getComputedStyle(element);\n const rect = element.getBoundingClientRect();\n return style.visibility !== \"hidden\" &&\n style.display !== \"none\" &&\n rect.width > 0 &&\n rect.height > 0 &&\n !element.hasAttribute(\"disabled\") &&\n element.getAttribute(\"aria-disabled\") !== \"true\";\n };\n const composerSelectors = [\n \"textarea\",\n \"input[type='text']\",\n \"[contenteditable='true']\",\n \"[role='textbox']\"\n ];\n const composerCandidates = composerSelectors.flatMap((selector) =>\n Array.from(document.querySelectorAll(selector))\n ).filter(visible);\n const composer = composerCandidates.find((element) => {\n const value = element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement\n ? element.value\n : element.textContent;\n return String(value ?? \"\").trim();\n }) ?? composerCandidates[0] ?? null;\n const rawComposerText = composer\n ? composer instanceof HTMLTextAreaElement || composer instanceof HTMLInputElement\n ? composer.value\n : composer.textContent\n : null;\n const composerText = typeof rawComposerText === \"string\"\n ? rawComposerText.trim().slice(0, 4000)\n : null;\n const compact = (value, max = 240) => {\n const text = readText(value).replace(/\\\\s+/g, \" \").trim();\n return text ? text.slice(0, max) : \"\";\n };\n const elementLabel = (element) => compact([\n element.getAttribute(\"aria-label\"),\n element.getAttribute(\"title\"),\n element.getAttribute(\"data-testid\"),\n element.getAttribute(\"data-test-id\"),\n element instanceof HTMLSelectElement\n ? element.options[element.selectedIndex]?.textContent\n : element.textContent\n ].map(readText).filter(Boolean).join(\" | \"));\n const metadataCandidates = Array.from(document.querySelectorAll([\n \"button\",\n \"select\",\n \"[role='button']\",\n \"[role='combobox']\",\n \"[aria-label]\",\n \"[title]\",\n \"[data-testid]\",\n \"[data-test-id]\"\n ].join(\",\"))).filter(visible);\n const cleanLabeledValue = (text, keywords) => {\n let value = compact(text);\n for (const keyword of keywords) {\n const index = value.toLowerCase().indexOf(keyword);\n if (index >= 0) {\n value = value.slice(0, index) + value.slice(index + keyword.length);\n }\n }\n value = value.replace(/^\\\\s*[:=\\\\u2013-]\\\\s*/g, \"\");\n value = value.replace(/\\\\s*\\\\|\\\\s*/g, \" \").replace(/\\\\s+/g, \" \").trim();\n return value || null;\n };\n const detectLabeledValue = (keywords) => {\n for (const element of metadataCandidates) {\n const label = elementLabel(element);\n const lower = label.toLowerCase();\n if (keywords.some((keyword) => lower.includes(keyword))) {\n const cleaned = cleanLabeledValue(label, keywords);\n if (cleaned) return cleaned;\n }\n }\n return null;\n };\n const workspaceCandidates = metadataCandidates.filter((element) => {\n const attrs = [\n element.getAttribute(\"aria-label\"),\n element.getAttribute(\"title\"),\n element.getAttribute(\"data-testid\"),\n element.getAttribute(\"data-test-id\")\n ].map(readText).join(\" \").toLowerCase();\n return /workspace|cwd|directory|folder|path/.test(attrs);\n });\n let workspacePath = null;\n for (const element of workspaceCandidates) {\n const label = elementLabel(element);\n const match = label.match(/(?:~|\\\\/Users\\\\/|\\\\/[A-Za-z0-9._-])[A-Za-z0-9._~@%+\\\\-/ ]{2,240}/);\n const cleaned = match?.[0] ? compact(match[0], 240) : cleanLabeledValue(label, [\"workspace\", \"cwd\", \"directory\", \"folder\", \"path\"]);\n if (cleaned) {\n workspacePath = cleaned;\n break;\n }\n }\n const model = detectLabeledValue([\"model\"]);\n const normalizeThreadId = (value) => {\n let id = String(value || \"\").trim();\n try { id = decodeURIComponent(id); } catch {}\n if (id.toLowerCase().startsWith(\"local:\")) id = id.slice(6);\n if (!id || id === \"__proto__\" || id === \"prototype\" || id === \"constructor\") return null;\n return /^[A-Za-z0-9_.-]{8,128}$/.test(id) ? id : null;\n };\n const normalizeRelayProfileId = (value) => {\n const id = String(value || \"\").trim();\n return /^[A-Za-z0-9][A-Za-z0-9_-]{2,79}$/.test(id) ? id : null;\n };\n const threadIdFromRow = (row) => {\n if (!row) return null;\n const href = row.getAttribute(\"href\") || row.querySelector(\"a\")?.getAttribute(\"href\") || \"\";\n const hrefMatch = href.match(/(?:sessions?|conversations?|threads?)(?:\\\\/|=|:|-)((?:local(?::|%3A))?[A-Za-z0-9_.-]+)/i)\n || href.match(/((?:local(?::|%3A))?[A-Za-z0-9_.-]{8,128})$/i);\n return normalizeThreadId(row.getAttribute(\"data-app-action-sidebar-thread-id\"))\n || normalizeThreadId(hrefMatch?.[1])\n || normalizeThreadId(row.getAttribute(\"data-session-id\"));\n };\n const activeThreadIdFromDocument = () => {\n const rows = Array.from(document.querySelectorAll(\"[data-app-action-sidebar-thread-id]\"));\n const activeRow = rows.find((row) =>\n row.getAttribute(\"data-app-action-sidebar-thread-active\") === \"true\"\n || row.getAttribute(\"aria-current\") === \"page\"\n || row.getAttribute(\"aria-current\") === \"true\"\n );\n const rowId = threadIdFromRow(activeRow);\n if (rowId) return rowId;\n const patterns = [\n /(?:sessions?|conversations?|threads?)(?:\\\\/|=|:|-)((?:local(?::|%3A))?[A-Za-z0-9_.-]+)/i,\n /(?:threadId|sessionId|conversationId)=((?:local(?::|%3A))?[A-Za-z0-9_.-]+)/i,\n /local(?::|%3A)([A-Za-z0-9_.-]{8,128})/i,\n /\\\\/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})(?:[/?#]|$)/,\n /\\\\/([A-Za-z0-9_-]{24,})(?:[/?#]|$)/\n ];\n for (const pattern of patterns) {\n const match = source.match(pattern);\n const id = normalizeThreadId(match?.[1] || \"\");\n if (id) return id;\n }\n return null;\n };\n const activeThreadId = activeThreadIdFromDocument();\n const controls = Array.from(document.querySelectorAll(\"button,[role='button']\"));\n const isGenerating = controls.some((element) => {\n const label = [\n element.getAttribute(\"aria-label\"),\n element.getAttribute(\"title\"),\n element.textContent\n ].map(readText).join(\" \").toLowerCase();\n return /\\\\b(stop|cancel|interrupt)\\\\b/.test(label) &&\n /\\\\b(generat|response|task|run|codex)\\\\b/.test(label);\n });\n const featureStatus = (enabled, applied, versionValue, error) => ({\n enabled: enabled === true,\n applied: applied === true,\n status: enabled === true ? (applied === true ? \"applied\" : \"degraded\") : \"disabled\",\n version: typeof versionValue === \"string\" ? versionValue : null,\n error: typeof error === \"string\" && error ? error.slice(0, 180) : null\n });\n const readFeatureStatus = (sourceValue, enabledFallback = false) => {\n const source = sourceValue && typeof sourceValue === \"object\" ? sourceValue : {};\n return featureStatus(\n source.enabled === true || enabledFallback === true,\n source.applied === true,\n source.version,\n source.error\n );\n };\n const qolRuntime = window.__codexuseQol && typeof window.__codexuseQol === \"object\"\n ? window.__codexuseQol\n : {};\n const powerRuntime = window.__codexusePower && typeof window.__codexusePower === \"object\"\n ? window.__codexusePower\n : {};\n const relayRuntime = powerRuntime.relay && typeof powerRuntime.relay === \"object\"\n ? powerRuntime.relay\n : {};\n const qol = {\n wideView: readFeatureStatus(qolRuntime.features?.wideView, qolRuntime.wideViewEnabled === true),\n scrollRestore: readFeatureStatus(qolRuntime.features?.scrollRestore, qolRuntime.scrollRestoreEnabled === true),\n conversationTimeline: readFeatureStatus(qolRuntime.features?.conversationTimeline, qolRuntime.conversationTimelineEnabled === true),\n inCodexStatus: readFeatureStatus(qolRuntime.features?.inCodexStatus, qolRuntime.inCodexStatusEnabled === true),\n appliedAt: typeof qolRuntime.appliedAtIso === \"string\" ? qolRuntime.appliedAtIso : null\n };\n const relayMode = [\"official\", \"responses\", \"chat-completions\"].includes(relayRuntime.mode)\n ? relayRuntime.mode\n : \"off\";\n const relayProfileId = relayMode === \"responses\" || relayMode === \"chat-completions\"\n ? normalizeRelayProfileId(relayRuntime.profileId)\n : null;\n const relayStatus = {\n mode: relayMode,\n profileId: relayProfileId,\n status: [\"configured\", \"missing-key\", \"degraded\"].includes(relayRuntime.status)\n ? relayRuntime.status\n : \"off\",\n error: typeof relayRuntime.error === \"string\" && relayRuntime.error ? relayRuntime.error.slice(0, 180) : null\n };\n const power = {\n modelWhitelistUnlock: readFeatureStatus(powerRuntime.features?.modelWhitelistUnlock),\n pluginMarketplaceUnlock: readFeatureStatus(powerRuntime.features?.pluginMarketplaceUnlock),\n forcePluginInstall: readFeatureStatus(powerRuntime.features?.forcePluginInstall),\n relay: relayStatus,\n appliedAt: typeof powerRuntime.appliedAtIso === \"string\" ? powerRuntime.appliedAtIso : null\n };\n const activeThreadTitle = activeThreadId ? \"Active conversation\" : null;\n const bridgeHealth = typeof window.__codexuseBridgeV2?.health === \"function\"\n ? window.__codexuseBridgeV2.health()\n : null;\n const healthReady = bridgeHealth?.status === \"ok\" && bridgeHealth?.bindingAvailable === true;\n const bridgeRuntime = window.__codexuseBridgeV2;\n const bridgeCommands = bridgeRuntime?.commands && typeof bridgeRuntime.commands === \"object\"\n ? bridgeRuntime.commands\n : {};\n const commandReady = (name) =>\n healthReady &&\n typeof bridgeRuntime?.run === \"function\" &&\n bridgeCommands[name] === true;\n const snapshot = {\n version,\n route,\n capabilities: {\n health: healthReady,\n snapshot: commandReady(\"snapshot\"),\n draft: commandReady(\"setDraft\"),\n qol: commandReady(\"applyQol\"),\n power: commandReady(\"applyPower\"),\n modelWhitelist: commandReady(\"applyPower\"),\n pluginMarketplace: commandReady(\"applyPower\"),\n forcePluginInstall: commandReady(\"applyPower\")\n },\n activeThreadId,\n activeThreadTitle,\n activeThreadUpdatedAt: null,\n composerText,\n workspacePath,\n model,\n activityState: isGenerating ? \"generating\" : \"idle\",\n qol,\n power,\n relayStatus,\n checkedAt: now\n };\n window.__codexuseBridge = {\n version,\n installedAt: window.__codexuseBridge?.installedAt ?? now,\n snapshot\n };\n return snapshot;\n })()`;\n}\n\nfunction createBridgeSetDraftPromptExpression(prompt: string): string {\n return `(() => {\n const prompt = ${JSON.stringify(prompt)};\n const visible = (element) => {\n if (!element || !(element instanceof HTMLElement)) return false;\n const style = window.getComputedStyle(element);\n const rect = element.getBoundingClientRect();\n return style.visibility !== \"hidden\" &&\n style.display !== \"none\" &&\n rect.width > 0 &&\n rect.height > 0 &&\n !element.hasAttribute(\"disabled\") &&\n element.getAttribute(\"aria-disabled\") !== \"true\";\n };\n const dispatchInput = (element) => {\n try {\n element.dispatchEvent(new InputEvent(\"input\", {\n bubbles: true,\n cancelable: true,\n inputType: \"insertText\",\n data: prompt\n }));\n } catch {\n element.dispatchEvent(new Event(\"input\", { bubbles: true }));\n }\n element.dispatchEvent(new Event(\"change\", { bubbles: true }));\n };\n const setNativeValue = (element, value) => {\n const proto = Object.getPrototypeOf(element);\n const descriptor = proto ? Object.getOwnPropertyDescriptor(proto, \"value\") : null;\n if (descriptor?.set) {\n descriptor.set.call(element, value);\n } else {\n element.value = value;\n }\n };\n const selectors = [\n \"textarea\",\n \"input[type='text']\",\n \"[contenteditable='true']\",\n \"[role='textbox']\"\n ];\n const candidates = selectors.flatMap((selector) =>\n Array.from(document.querySelectorAll(selector))\n ).filter(visible);\n const emptyPreferred = candidates.find((element) => {\n const value = element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement\n ? element.value\n : element.textContent;\n return !String(value ?? \"\").trim();\n });\n const target = emptyPreferred ?? candidates[0] ?? null;\n if (!target) {\n return {\n status: \"not-found\",\n reason: \"composer-not-found\",\n route: window.location.pathname + window.location.search + window.location.hash\n };\n }\n target.focus();\n if (target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement) {\n setNativeValue(target, prompt);\n dispatchInput(target);\n return {\n status: \"inserted\",\n reason: null,\n route: window.location.pathname + window.location.search + window.location.hash\n };\n }\n const selection = window.getSelection();\n if (selection) {\n const range = document.createRange();\n range.selectNodeContents(target);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n const inserted = document.execCommand?.(\"insertText\", false, prompt);\n if (!inserted) {\n target.textContent = prompt;\n }\n dispatchInput(target);\n return {\n status: \"inserted\",\n reason: null,\n route: window.location.pathname + window.location.search + window.location.hash\n };\n })()`;\n}\n\nfunction createBridgeSendMessageExpression(text: string): string {\n return `(async () => {\n const text = ${JSON.stringify(text)};\n const route = () => window.location.pathname + window.location.search + window.location.hash;\n const visible = (element) => {\n if (!element || !(element instanceof HTMLElement)) return false;\n const style = window.getComputedStyle(element);\n const rect = element.getBoundingClientRect();\n return style.visibility !== \"hidden\" &&\n style.display !== \"none\" &&\n rect.width > 0 &&\n rect.height > 0 &&\n !element.hasAttribute(\"disabled\") &&\n element.getAttribute(\"aria-disabled\") !== \"true\";\n };\n const dispatchInput = (element) => {\n try {\n element.dispatchEvent(new InputEvent(\"input\", {\n bubbles: true,\n cancelable: true,\n inputType: \"insertText\",\n data: text\n }));\n } catch {\n element.dispatchEvent(new Event(\"input\", { bubbles: true }));\n }\n element.dispatchEvent(new Event(\"change\", { bubbles: true }));\n };\n const setNativeValue = (element, value) => {\n const proto = Object.getPrototypeOf(element);\n const descriptor = proto ? Object.getOwnPropertyDescriptor(proto, \"value\") : null;\n if (descriptor?.set) {\n descriptor.set.call(element, value);\n } else {\n element.value = value;\n }\n };\n const selectors = [\n \"textarea\",\n \"input[type='text']\",\n \"[contenteditable='true']\",\n \"[role='textbox']\"\n ];\n const candidates = selectors.flatMap((selector) =>\n Array.from(document.querySelectorAll(selector))\n ).filter(visible);\n const emptyPreferred = candidates.find((element) => {\n const value = element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement\n ? element.value\n : element.textContent;\n return !String(value ?? \"\").trim();\n });\n const target = emptyPreferred ?? candidates[0] ?? null;\n if (!target) {\n return { status: \"not-found\", reason: \"composer-not-found\", route: route() };\n }\n target.focus();\n if (target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement) {\n setNativeValue(target, text);\n dispatchInput(target);\n } else {\n const selection = window.getSelection();\n if (selection) {\n const range = document.createRange();\n range.selectNodeContents(target);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n const inserted = document.execCommand?.(\"insertText\", false, text);\n if (!inserted) {\n target.textContent = text;\n }\n dispatchInput(target);\n }\n // Give the app's state a beat to register the inserted text so the send\n // control enables before we submit.\n await new Promise((resolve) => setTimeout(resolve, 150));\n try {\n const form = target.closest(\"form\");\n const findSendButton = () => {\n const scope = form ||\n target.closest(\"[class*='composer'],[data-testid*='composer']\") ||\n document;\n const buttons = Array.from(scope.querySelectorAll(\"button\"));\n const usable = (button) => visible(button) && !button.disabled;\n return buttons.find((button) => usable(button) && /send/i.test(button.getAttribute(\"data-testid\") || \"\")) ||\n buttons.find((button) => usable(button) && /send/i.test(button.getAttribute(\"aria-label\") || \"\")) ||\n buttons.find((button) => usable(button) && button.type === \"submit\") ||\n null;\n };\n const sendButton = findSendButton();\n if (sendButton) {\n sendButton.click();\n return { status: \"sent\", reason: null, route: route() };\n }\n if (form && typeof form.requestSubmit === \"function\") {\n form.requestSubmit();\n return { status: \"sent\", reason: null, route: route() };\n }\n const keyInit = {\n key: \"Enter\",\n code: \"Enter\",\n keyCode: 13,\n which: 13,\n bubbles: true,\n cancelable: true\n };\n target.dispatchEvent(new KeyboardEvent(\"keydown\", keyInit));\n target.dispatchEvent(new KeyboardEvent(\"keypress\", keyInit));\n target.dispatchEvent(new KeyboardEvent(\"keyup\", keyInit));\n return { status: \"sent\", reason: null, route: route() };\n } catch (error) {\n return { status: \"failed\", reason: String(error?.message || error || \"submit-failed\"), route: route() };\n }\n })()`;\n}\n\nfunction createBridgeReadComposerExpression(): string {\n return `(() => {\n const visible = (element) => {\n if (!element || !(element instanceof HTMLElement)) return false;\n const style = window.getComputedStyle(element);\n const rect = element.getBoundingClientRect();\n return style.visibility !== \"hidden\" && style.display !== \"none\" && rect.width > 0 && rect.height > 0;\n };\n const valueOf = (element) =>\n element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement\n ? element.value\n : element.textContent;\n const candidates = [\"textarea\", \"input[type='text']\", \"[contenteditable='true']\", \"[role='textbox']\"]\n .flatMap((selector) => Array.from(document.querySelectorAll(selector)))\n .filter(visible);\n const filled = candidates.find((element) => String(valueOf(element) ?? \"\").trim());\n const target = filled ?? candidates[0] ?? null;\n return { text: target ? String(valueOf(target) ?? \"\") : \"\" };\n })()`;\n}\n\n// Overlay chrome follows the host app's own theme: renderStatus copies the\n// Codex window's body background/foreground into --cu-bg/--cu-fg on each\n// overlay root, and every other color is mixed from those two, so the overlay\n// matches the official app's design tokens in light and dark themes alike.\nfunction buildInCodexStatusOverlayCssRules(): string[] {\n const id = \"#codexuse-status-pill\";\n const chip = \"#codexuse-handoff-chip\";\n const picker = \"#codexuse-handoff-picker\";\n const palette =\n \"--cu-surface:color-mix(in srgb,var(--cu-bg,#202123) 94%,var(--cu-fg,#ececf1) 6%);--cu-popover:color-mix(in srgb,var(--cu-bg,#202123) 97%,var(--cu-fg,#ececf1) 3%);--cu-border:color-mix(in srgb,var(--cu-fg,#ececf1) 16%,transparent);--cu-muted:color-mix(in srgb,var(--cu-fg,#ececf1) 60%,var(--cu-bg,#202123) 40%);--cu-hover:color-mix(in srgb,var(--cu-fg,#ececf1) 7%,var(--cu-bg,#202123) 93%);\";\n return [\n `${id}{${palette}position:fixed;right:16px;bottom:16px;z-index:2147483001;border:1px solid var(--cu-border);border-radius:12px;background:var(--cu-surface);color:var(--cu-fg,#ececf1);font-family:inherit;font-size:12px;line-height:1.4;box-shadow:0 8px 28px rgba(0,0,0,.28);pointer-events:auto;user-select:none;-webkit-user-select:none;}`,\n `${id}[data-codexuse-qol-status='degraded']{border-color:color-mix(in srgb,#d97706 55%,var(--cu-border));}`,\n `${id}[data-codexuse-qol-status='degraded'] .codexuse-status-chip{color:#d97706;border-color:color-mix(in srgb,#d97706 40%,transparent);}`,\n `${id}[data-collapsed='true']{display:flex;width:18px;height:18px;align-items:center;justify-content:center;border-radius:50%;opacity:.5;cursor:pointer;font-size:10px;color:var(--cu-muted);transition:opacity 120ms ease-out;}`,\n `${id}[data-collapsed='true']:hover{opacity:1;}`,\n `${id} button{font:inherit;font-family:inherit;color:inherit;border:0;background:transparent;}`,\n `${id} .codexuse-status-trigger{display:flex;width:100%;align-items:center;gap:8px;padding:8px 10px;cursor:pointer;border-radius:12px;}`,\n `${id} .codexuse-status-label{max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600;}`,\n `${id} .codexuse-status-chip{display:inline-flex;align-items:center;border-radius:999px;border:1px solid var(--cu-border);padding:1px 7px;font-size:10px;font-weight:600;color:var(--cu-muted);white-space:nowrap;}`,\n `${id} .codexuse-status-chevron{flex-shrink:0;color:var(--cu-muted);font-size:10px;line-height:1;transition:transform 150ms ease-out;}`,\n `${id}[data-open='true'] .codexuse-status-chevron{transform:rotate(180deg);}`,\n // Closed pill stays out of the way: compact, translucent, quota chip\n // hidden. Hover (or opening the menu) restores the full pill.\n `${id}[data-open='false']:not([data-collapsed='true']){opacity:.5;box-shadow:0 2px 10px rgba(0,0,0,.16);transition:opacity 140ms ease-out;}`,\n `${id}[data-open='false']:not([data-collapsed='true']):hover{opacity:1;box-shadow:0 8px 28px rgba(0,0,0,.28);}`,\n `${id}[data-open='false']:not([data-collapsed='true']) .codexuse-status-trigger{padding:4px 9px;gap:6px;}`,\n `${id}[data-open='false']:not([data-collapsed='true']) .codexuse-status-label{max-width:120px;font-size:11px;}`,\n `${id}[data-open='false']:not([data-collapsed='true']) .codexuse-status-chip{display:none;}`,\n `${id}[data-open='false']:not([data-collapsed='true']):hover .codexuse-status-trigger{padding:8px 10px;gap:8px;}`,\n `${id}[data-open='false']:not([data-collapsed='true']):hover .codexuse-status-label{max-width:160px;font-size:12px;}`,\n `${id}[data-open='false']:not([data-collapsed='true']):hover .codexuse-status-chip{display:inline-flex;}`,\n `${id} .codexuse-action-menu{display:none;position:absolute;right:0;bottom:calc(100% + 8px);width:min(280px,calc(100vw - 24px));border:1px solid var(--cu-border);border-radius:12px;background:var(--cu-popover);padding:6px;box-shadow:0 12px 36px rgba(0,0,0,.32);}`,\n `${id}[data-drop='down'] .codexuse-action-menu{bottom:auto;top:calc(100% + 8px);}`,\n `${id}[data-open='true'] .codexuse-action-menu{display:flex;flex-direction:column;gap:2px;}`,\n `${id} .codexuse-target-list{display:flex;max-height:210px;flex-direction:column;gap:2px;overflow-y:auto;}`,\n `${id} .codexuse-target-row{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;padding:7px 9px;border-radius:8px;cursor:pointer;text-align:left;transition:background 120ms ease-out;}`,\n `${id} .codexuse-target-row:hover{background:var(--cu-hover);}`,\n `${id} .codexuse-target-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;}`,\n `${id} .codexuse-target-detail{flex-shrink:0;color:var(--cu-muted);font-size:10px;white-space:nowrap;}`,\n `${id} .codexuse-action-empty{margin:0;padding:7px 9px;color:var(--cu-muted);font-size:11px;}`,\n `${id} .codexuse-menu-divider{height:1px;margin:4px 2px;background:var(--cu-border);}`,\n `${id} .codexuse-setting-row{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;padding:6px 9px;border-radius:8px;cursor:pointer;text-align:left;transition:background 120ms ease-out;}`,\n `${id} .codexuse-setting-row:hover{background:var(--cu-hover);}`,\n `${id} .codexuse-toggle{position:relative;flex-shrink:0;width:26px;height:15px;border-radius:999px;background:var(--cu-border);transition:background 120ms ease-out;}`,\n `${id} .codexuse-toggle::after{content:'';position:absolute;left:2px;top:2px;width:11px;height:11px;border-radius:50%;background:var(--cu-fg,#ececf1);transition:transform 120ms ease-out;}`,\n `${id} .codexuse-setting-row[data-on='true'] .codexuse-toggle{background:color-mix(in srgb,#10a37f 75%,var(--cu-bg,#202123));}`,\n `${id} .codexuse-setting-row[data-on='true'] .codexuse-toggle::after{transform:translateX(11px);}`,\n `${id} .codexuse-menu-footer{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:4px 9px 2px;}`,\n `${id} .codexuse-action-status{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--cu-muted);font-size:10px;}`,\n `${id} .codexuse-overlay-hide{flex-shrink:0;padding:2px 6px;border-radius:6px;color:var(--cu-muted);font-size:10px;cursor:pointer;}`,\n `${id} .codexuse-overlay-hide:hover{background:var(--cu-hover);color:var(--cu-fg,#ececf1);}`,\n `${chip}{${palette}position:fixed;z-index:2147483001;display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:999px;border:1px solid var(--cu-border);background:var(--cu-surface);color:var(--cu-fg,#ececf1);font-family:inherit;font-size:11px;font-weight:600;line-height:1.2;cursor:pointer;box-shadow:0 4px 16px rgba(0,0,0,.2);transition:background 120ms ease-out;}`,\n `${chip}:hover{background:var(--cu-hover);}`,\n `${chip}:disabled{opacity:.6;cursor:default;}`,\n // Hand-off account picker is a standalone body child (not inside the pill),\n // so the pill-scoped popover rules don't reach it — give it its own palette\n // + popover styling, mirroring the chip.\n `${picker}{${palette}position:fixed;z-index:2147483001;display:flex;flex-direction:column;gap:2px;width:min(280px,calc(100vw - 24px));max-height:240px;overflow-y:auto;border:1px solid var(--cu-border);border-radius:12px;background:var(--cu-popover);color:var(--cu-fg,#ececf1);font-family:inherit;font-size:12px;line-height:1.4;padding:6px;box-shadow:0 12px 36px rgba(0,0,0,.32);}`,\n `${picker} button{font:inherit;font-family:inherit;color:inherit;border:0;background:transparent;}`,\n `${picker} .codexuse-target-list{display:flex;flex-direction:column;gap:2px;}`,\n `${picker} .codexuse-target-row{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;padding:7px 9px;border-radius:8px;cursor:pointer;text-align:left;transition:background 120ms ease-out;}`,\n `${picker} .codexuse-target-row:hover{background:var(--cu-hover);}`,\n `${picker} .codexuse-target-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;}`,\n `${picker} .codexuse-target-detail{flex-shrink:0;color:var(--cu-muted);font-size:10px;white-space:nowrap;}`,\n ];\n}\n\nfunction createBridgeApplyQolExpression(\n settings: OfficialCodexQolSettingsPayload,\n): string {\n return `(async () => {\n const wideViewEnabled = ${JSON.stringify(settings.wideViewEnabled === true)};\n const wideViewMaxWidth = ${JSON.stringify(\n typeof settings.wideViewMaxWidth === \"number\" &&\n Number.isFinite(settings.wideViewMaxWidth)\n ? Math.max(640, Math.min(2400, settings.wideViewMaxWidth))\n : 1480,\n )};\n const scrollRestoreEnabled = ${JSON.stringify(settings.scrollRestoreEnabled === true)};\n const conversationTimelineEnabled = ${JSON.stringify(settings.conversationTimelineEnabled === true)};\n const inCodexStatusEnabled = ${JSON.stringify(settings.inCodexStatusEnabled === true)};\n const handoffChipEnabled = ${JSON.stringify(settings.handoffChipEnabled !== false)};\n const actionTargets = ${JSON.stringify(\n sanitizeOfficialCodexOverlayActionTargetsForRenderer(\n settings.actionTargets,\n ),\n )};\n const overlayAutoRollEnabled = ${JSON.stringify(\n typeof settings.overlayAutoRollEnabled === \"boolean\"\n ? settings.overlayAutoRollEnabled\n : null,\n )};\n const versions = {\n wideView: \"3\",\n scrollRestore: \"5\",\n conversationTimeline: \"1\",\n inCodexStatus: \"3\"\n };\n const styleId = \"codexuse-qol-style\";\n const timelineClass = \"codexuse-conversation-timeline\";\n const timelineTargetClass = \"codexuse-conversation-timeline-target\";\n const statusId = \"codexuse-status-pill\";\n // Codex desktop is a SPA whose URL never changes per thread; key scroll\n // state by the open conversation id so each chat restores independently.\n const route = () => {\n const composer = document.querySelector(\"[data-above-composer-conversation-id]\");\n const conversationId = composer?.getAttribute(\"data-above-composer-conversation-id\")?.trim();\n const base = window.location.pathname + window.location.search + window.location.hash;\n return conversationId ? base + \"::\" + conversationId : base;\n };\n const getDocumentScroller = () => document.scrollingElement || document.documentElement || document.body;\n const looksScrollable = (element) => {\n if (!element) return false;\n const style = getComputedStyle(element);\n return /(auto|scroll)/.test(style.overflowY) && element.scrollHeight > element.clientHeight;\n };\n const getScroller = () => {\n const explicit = document.querySelector(\".thread-scroll-container\");\n if (looksScrollable(explicit)) return explicit;\n const candidates = Array.from(document.querySelectorAll([\n \"[data-testid*='conversation']\",\n \"[data-testid*='thread']\",\n \"[class*='conversation']\",\n \"[class*='thread']\",\n \"main\",\n \"[role='main']\"\n ].join(\",\")));\n const scroller = candidates.find(looksScrollable);\n return scroller || getDocumentScroller();\n };\n const storageKey = () => \"codexuse:qol:scroll:\" + route();\n const readScrollTop = () => {\n const scroller = getScroller();\n return Number(scroller?.scrollTop ?? window.scrollY ?? 0);\n };\n const writeScrollTop = (value) => {\n const y = Number(value);\n if (!Number.isFinite(y) || y < 0) return;\n const scroller = getScroller();\n if (scroller) scroller.scrollTop = y;\n if (scroller === getDocumentScroller()) window.scrollTo(0, y);\n };\n let state = window.__codexuseQol;\n if (!state || typeof state !== \"object\") state = {};\n const appliedAtIso = new Date().toISOString();\n const feature = (enabled, applied, version, error = null) => ({\n enabled: enabled === true,\n applied: applied === true,\n status: enabled === true ? (applied === true ? \"applied\" : \"degraded\") : \"disabled\",\n version,\n error\n });\n\n if (wideViewEnabled || conversationTimelineEnabled || inCodexStatusEnabled) {\n let style = document.getElementById(styleId);\n if (!style) {\n style = document.createElement(\"style\");\n style.id = styleId;\n document.head.appendChild(style);\n }\n style.textContent = [\n wideViewEnabled ? \"[class*='max-w-(--thread-content-max-width)']{--thread-content-max-width:min(\" + wideViewMaxWidth + \"px,100%)!important;}\" : \"\",\n wideViewEnabled ? \".thread-scroll-container > div:has([class*='max-w-(--thread-content-max-width)']){transform:none!important;}\" : \"\",\n conversationTimelineEnabled ? \".\" + timelineClass + \"{position:fixed;right:10px;top:18%;bottom:18%;z-index:2147483000;width:22px;pointer-events:none;}\" : \"\",\n conversationTimelineEnabled ? \".\" + timelineClass + \"::before{content:'';position:absolute;left:10px;top:0;bottom:0;width:2px;border-radius:2px;background:rgba(127,127,127,.35);}\" : \"\",\n conversationTimelineEnabled ? \".\" + timelineClass + \" button{position:absolute;left:4px;width:14px;height:14px;border-radius:50%;border:1px solid rgba(16,163,127,.7);background:#10a37f;box-shadow:0 2px 10px rgba(0,0,0,.24);pointer-events:auto;padding:0;}\" : \"\",\n conversationTimelineEnabled ? \".\" + timelineClass + \" button span{position:absolute;right:18px;top:50%;transform:translateY(-50%);display:none;max-width:220px;border-radius:6px;background:rgba(24,24,27,.96);color:white;font:12px/1.35 system-ui,sans-serif;padding:5px 7px;text-align:left;white-space:normal;}\" : \"\",\n conversationTimelineEnabled ? \".\" + timelineClass + \" button:hover span,.\" + timelineClass + \" button:focus-visible span{display:block;}\" : \"\",\n conversationTimelineEnabled ? \".\" + timelineTargetClass + \"{animation:codexuse-conversation-timeline-pulse 1.2s ease-out;}\" : \"\",\n conversationTimelineEnabled ? \"@keyframes codexuse-conversation-timeline-pulse{0%{box-shadow:0 0 0 0 rgba(16,163,127,.45);}100%{box-shadow:0 0 0 14px rgba(16,163,127,0);}}\" : \"\",\n ...(inCodexStatusEnabled ? ${JSON.stringify(buildInCodexStatusOverlayCssRules())} : [])\n ].filter(Boolean).join(\"\\\\n\");\n } else {\n document.getElementById(styleId)?.remove();\n }\n\n const visibleElement = (element) => {\n if (!(element instanceof HTMLElement) || !element.isConnected) return false;\n const rect = element.getBoundingClientRect();\n return rect.width > 0 && rect.height > 0;\n };\n // Wide view is pure CSS now: widen the --thread-content-max-width\n // consumers and neutralize Codex's window-centering transform (it is\n // computed for the narrow width and would shift wide content under the\n // sidebar). A previous version aligned elements with inline styles; its\n // cleanup closure (if still installed) restores them.\n if (typeof state.cleanupWideView === \"function\") {\n state.cleanupWideView();\n state.cleanupWideView = null;\n }\n let wideViewApplied = wideViewEnabled;\n if (wideViewEnabled) {\n state.wideViewInstalled = true;\n state.wideViewVersion = versions.wideView;\n } else {\n state.wideViewInstalled = false;\n state.wideViewVersion = null;\n }\n\n if (scrollRestoreEnabled) {\n if (state.scrollRestoreInstalled && state.scrollRestoreVersion !== versions.scrollRestore) {\n if (typeof state.cleanupScrollRestore === \"function\") state.cleanupScrollRestore();\n state.scrollRestoreInstalled = false;\n state.cleanupScrollRestore = null;\n }\n if (!state.scrollRestoreInstalled) {\n let frame = 0;\n let restoreTimers = [];\n let lastRouteKey = route();\n const clearRestoreTimers = () => {\n restoreTimers.forEach((timer) => window.clearTimeout(timer));\n restoreTimers = [];\n };\n const save = () => {\n frame = 0;\n const key = route();\n if (key !== lastRouteKey) {\n // The thread changed under us (SPA swap); restore instead of\n // saving the transient scroll position into the new thread's slot.\n lastRouteKey = key;\n scheduleRestore();\n return;\n }\n if (restoreTimers.length > 0) return;\n try {\n sessionStorage.setItem(storageKey(), String(readScrollTop()));\n } catch {\n // Session storage can be unavailable in some webview states.\n }\n };\n const onScroll = () => {\n if (frame) return;\n frame = window.requestAnimationFrame(save);\n };\n const onAnyScroll = (event) => {\n const scroller = getScroller();\n if (event.target === document || event.target === window || event.target === scroller) onScroll();\n };\n const restore = () => {\n let saved = null;\n try {\n saved = sessionStorage.getItem(storageKey());\n } catch {\n saved = null;\n }\n if (!saved) return;\n window.requestAnimationFrame(() => writeScrollTop(saved));\n };\n const scheduleRestore = () => {\n clearRestoreTimers();\n restoreTimers = [0, 80, 220, 500, 1000, 1800, 2800].map((delay) => window.setTimeout(restore, delay));\n // While restore timers are pending, save() is suppressed; resume\n // saving once the restore window has passed.\n restoreTimers.push(window.setTimeout(clearRestoreTimers, 3200));\n };\n const onRouteChange = () => scheduleRestore();\n // The SPA swaps threads without touching the URL or history, so poll\n // the conversation-aware route key to catch thread changes.\n const routeWatchTimer = window.setInterval(() => {\n const key = route();\n if (key === lastRouteKey) return;\n lastRouteKey = key;\n scheduleRestore();\n }, 300);\n const historyOriginals = {};\n const historyPatched = {};\n [\"pushState\", \"replaceState\"].forEach((method) => {\n const original = history[method];\n if (typeof original !== \"function\") return;\n const patched = function codexuseQolHistoryRoute(...args) {\n save();\n const result = original.apply(this, args);\n scheduleRestore();\n return result;\n };\n historyOriginals[method] = original;\n historyPatched[method] = patched;\n history[method] = patched;\n });\n window.addEventListener(\"scroll\", onAnyScroll, { capture: true, passive: true });\n window.addEventListener(\"hashchange\", onRouteChange);\n window.addEventListener(\"popstate\", onRouteChange);\n document.addEventListener(\"visibilitychange\", save, true);\n state.cleanupScrollRestore = () => {\n window.clearInterval(routeWatchTimer);\n window.removeEventListener(\"scroll\", onAnyScroll, true);\n window.removeEventListener(\"hashchange\", onRouteChange);\n window.removeEventListener(\"popstate\", onRouteChange);\n document.removeEventListener(\"visibilitychange\", save, true);\n Object.keys(historyOriginals).forEach((method) => {\n if (history[method] === historyPatched[method]) {\n history[method] = historyOriginals[method];\n }\n });\n if (frame) window.cancelAnimationFrame(frame);\n clearRestoreTimers();\n };\n state.scrollRestoreInstalled = true;\n state.scrollRestoreVersion = versions.scrollRestore;\n scheduleRestore();\n }\n } else if (typeof state.cleanupScrollRestore === \"function\") {\n state.cleanupScrollRestore();\n state.scrollRestoreInstalled = false;\n state.cleanupScrollRestore = null;\n state.scrollRestoreVersion = null;\n }\n\n const textOf = (node) => String(node?.textContent || \"\").replace(/\\\\s+/g, \" \").trim();\n const timelineMinTopPercent = 2;\n const timelineMaxTopPercent = 98;\n const timelineMaxMarkerGapPercent = 3.5;\n const timelineRoot = () => document.querySelector(\".thread-scroll-container\") || document.querySelector(\"main\") || document.querySelector(\"[role='main']\") || document.body;\n const userMessageNodes = () => {\n const root = timelineRoot();\n const candidates = Array.from(root.querySelectorAll([\n \"[data-user-message-bubble]\",\n \"[data-message-author-role='user']\",\n \"[data-testid='conversation-turn'][data-message-author-role='user']\",\n \"[data-testid='conversation-turn'] [data-message-author-role='user']\",\n \"[class*='user-message']\",\n \"[class*='UserMessage']\"\n ].join(\",\")));\n const seen = new Set();\n return candidates.flatMap((node) => {\n const target = node.closest(\"[data-turn-key]\") || node.closest(\"[data-testid='conversation-turn']\") || node;\n if (seen.has(target) || target.closest(\"[data-app-action-sidebar-thread-id]\")) return [];\n seen.add(target);\n const text = textOf(node).slice(0, 80);\n return text ? [{ node: target, text }] : [];\n }).slice(0, 60);\n };\n const nearestScroller = (node) => {\n for (let current = node?.parentElement; current; current = current.parentElement) {\n const style = getComputedStyle(current);\n if (/(auto|scroll)/.test(style.overflowY) && current.scrollHeight > current.clientHeight) return current;\n }\n return getScroller();\n };\n const timelineScrollerViewportTop = (scroller) =>\n scroller === document.scrollingElement || scroller === document.documentElement || scroller === document.body\n ? 0\n : scroller.getBoundingClientRect().top;\n const timelineRawMarkerTop = (message, scroller) => {\n const rect = message.node.getBoundingClientRect();\n const scrollableHeight = Math.max(1, scroller.scrollHeight - scroller.clientHeight);\n const scrollOffset = scroller.scrollTop + rect.top - timelineScrollerViewportTop(scroller);\n const percent = (scrollOffset / scrollableHeight) * 100;\n return Math.max(timelineMinTopPercent, Math.min(timelineMaxTopPercent, percent));\n };\n const timelineMarkerTops = (messages, scroller) => {\n if (messages.length <= 1) return [50];\n const minGap = Math.min(\n timelineMaxMarkerGapPercent,\n (timelineMaxTopPercent - timelineMinTopPercent) / Math.max(messages.length - 1, 1),\n );\n const tops = messages.map((message) => timelineRawMarkerTop(message, scroller));\n for (let index = 1; index < tops.length; index += 1) {\n tops[index] = Math.max(tops[index], tops[index - 1] + minGap);\n }\n for (let index = tops.length - 1; index >= 0; index -= 1) {\n const maxForIndex = timelineMaxTopPercent - ((tops.length - 1 - index) * minGap);\n tops[index] = Math.min(tops[index], maxForIndex);\n }\n return tops.map((top) => Math.max(timelineMinTopPercent, Math.min(timelineMaxTopPercent, top)));\n };\n const scrollTimelineTarget = (node) => {\n const scroller = nearestScroller(node);\n const rect = node.getBoundingClientRect();\n const nextTop = scroller.scrollTop + rect.top - timelineScrollerViewportTop(scroller) - (scroller.clientHeight / 2) + (rect.height / 2);\n if (typeof scroller.scrollTo === \"function\") {\n scroller.scrollTo({ top: nextTop, behavior: \"smooth\" });\n } else {\n scroller.scrollTop = nextTop;\n }\n };\n const highlightTimelineTarget = (node) => {\n node.classList.remove(timelineTargetClass);\n void node.offsetWidth;\n node.classList.add(timelineTargetClass);\n clearTimeout(node.__codexuseTimelineHighlightTimer);\n node.__codexuseTimelineHighlightTimer = setTimeout(() => {\n node.classList.remove(timelineTargetClass);\n }, 1300);\n };\n const clearTimelineTargets = () => {\n document.querySelectorAll(\".\" + timelineTargetClass).forEach((node) => {\n clearTimeout(node.__codexuseTimelineHighlightTimer);\n node.classList.remove(timelineTargetClass);\n });\n };\n const renderTimeline = () => {\n document.querySelectorAll(\".\" + timelineClass).forEach((node) => node.remove());\n if (!conversationTimelineEnabled) return false;\n const messages = userMessageNodes();\n if (messages.length === 0) return true;\n const scroller = nearestScroller(messages[0].node);\n const markerTops = timelineMarkerTops(messages, scroller);\n const rail = document.createElement(\"div\");\n rail.className = timelineClass;\n rail.dataset.codexuseTimelineMarkerCount = String(messages.length);\n messages.forEach((message, index) => {\n const top = markerTops[index] ?? timelineMinTopPercent;\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.style.top = top.toFixed(2) + \"%\";\n button.setAttribute(\"aria-label\", \"Jump to user message\");\n const label = document.createElement(\"span\");\n label.textContent = message.text;\n button.appendChild(label);\n const activateMarker = (event) => {\n event.preventDefault();\n event.stopPropagation();\n event.stopImmediatePropagation?.();\n scrollTimelineTarget(message.node);\n highlightTimelineTarget(message.node);\n };\n button.addEventListener(\"click\", activateMarker, true);\n button.addEventListener(\"pointerup\", activateMarker, true);\n button.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\" || event.key === \" \") activateMarker(event);\n }, true);\n rail.appendChild(button);\n });\n document.body.appendChild(rail);\n return true;\n };\n const handoffId = \"codexuse-handoff-chip\";\n const handoffPickerId = \"codexuse-handoff-picker\";\n const overlayHiddenKey = \"codexuse:overlay:hidden\";\n const overlayIntroKey = \"codexuse:overlay:intro-shown\";\n const overlayPosKey = \"codexuse:overlay:pos\";\n const readOverlayStore = (key) => {\n try {\n return window.localStorage.getItem(key);\n } catch {\n return null;\n }\n };\n const writeOverlayStore = (key, value) => {\n try {\n if (value === null) window.localStorage.removeItem(key);\n else window.localStorage.setItem(key, value);\n } catch {\n // Storage can be unavailable in some webview states.\n }\n };\n // Mirror the host app's theme onto the overlay roots; all overlay colors\n // are color-mixed from these two variables.\n const parseColorChannels = (value) => {\n const match = /rgba?\\\\(([^)]+)\\\\)/.exec(value || \"\");\n if (!match) return null;\n const parts = match[1].split(\",\").map((part) => parseFloat(part.trim()));\n if (parts.length < 3 || parts.slice(0, 3).some((part) => Number.isNaN(part))) return null;\n return { r: parts[0], g: parts[1], b: parts[2], a: parts.length > 3 && !Number.isNaN(parts[3]) ? parts[3] : 1 };\n };\n const applyOverlayTheme = (element) => {\n const fg = getComputedStyle(document.body).color || \"#ececf1\";\n // Electron windows often keep body/html transparent for vibrancy, so probe\n // real surfaces before falling back.\n const candidates = [\n document.body,\n document.querySelector(\"main\"),\n document.getElementById(\"root\"),\n document.body.firstElementChild,\n document.documentElement\n ];\n let bg = null;\n for (const candidate of candidates) {\n if (!candidate) continue;\n const channels = parseColorChannels(getComputedStyle(candidate).backgroundColor);\n if (channels && channels.a > 0.5) {\n bg = getComputedStyle(candidate).backgroundColor;\n break;\n }\n }\n if (!bg) {\n // No opaque surface found — fall back to the app's declared color\n // scheme (Codex sets html.electron-light/dark + color-scheme), then to\n // text-color luminance, so we never pair a dark fallback background\n // with dark adopted text.\n const scheme = (getComputedStyle(document.documentElement).colorScheme || \"\") +\n \" \" + document.documentElement.className;\n if (/dark/i.test(scheme)) bg = \"#202123\";\n else if (/light/i.test(scheme)) bg = \"#ffffff\";\n else {\n const channels = parseColorChannels(fg);\n const luminance = channels\n ? (0.299 * channels.r + 0.587 * channels.g + 0.114 * channels.b) / 255\n : 1;\n bg = luminance < 0.5 ? \"#ffffff\" : \"#202123\";\n }\n }\n element.style.setProperty(\"--cu-bg\", bg);\n element.style.setProperty(\"--cu-fg\", fg);\n };\n const clampOverlayXY = (pill, x, y) => {\n const rect = pill.getBoundingClientRect();\n return {\n x: Math.min(Math.max(8, x), Math.max(8, window.innerWidth - rect.width - 8)),\n y: Math.min(Math.max(8, y), Math.max(8, window.innerHeight - rect.height - 8))\n };\n };\n const placeOverlay = (pill, x, y) => {\n const next = clampOverlayXY(pill, x, y);\n pill.style.left = next.x + \"px\";\n pill.style.top = next.y + \"px\";\n pill.style.right = \"auto\";\n pill.style.bottom = \"auto\";\n const rect = pill.getBoundingClientRect();\n pill.dataset.drop = rect.top + rect.height / 2 < window.innerHeight / 2 ? \"down\" : \"up\";\n };\n const applyStoredOverlayPosition = (pill) => {\n const raw = readOverlayStore(overlayPosKey);\n if (!raw) return;\n try {\n const pos = JSON.parse(raw);\n if (typeof pos?.x === \"number\" && typeof pos?.y === \"number\") {\n placeOverlay(pill, pos.x, pos.y);\n }\n } catch {\n // Drop corrupt stored positions.\n }\n };\n const placeInitialOverlayPosition = (pill) => {\n const rect = pill.getBoundingClientRect();\n const x = Math.round((window.innerWidth - rect.width) / 2);\n const y = Math.max(72, Math.min(140, Math.round(window.innerHeight * 0.16)));\n placeOverlay(pill, x, y);\n };\n const setOverlayMessage = (value) => {\n const node = document.querySelector(\"#\" + statusId + \" [data-codexuse-action-status]\");\n if (node) node.textContent = value || \"\";\n };\n // Read the open conversation id from the DOM at action time — the bridge\n // snapshot can be a poll-interval stale.\n const domActiveThreadId = () => {\n const composerHost = document.querySelector(\"[data-above-composer-conversation-id]\");\n const composerId = composerHost?.getAttribute(\"data-above-composer-conversation-id\");\n if (composerId) return composerId;\n const row = document.querySelector(\"[data-app-action-sidebar-thread-id][data-app-action-sidebar-thread-active='true']\") ||\n document.querySelector(\"[data-app-action-sidebar-thread-id][aria-current='page']\");\n return row?.getAttribute(\"data-app-action-sidebar-thread-id\") || null;\n };\n const requestAction = (action, target = null, setting = null) => {\n const bridge = window.__codexuseBridgeV2 && typeof window.__codexuseBridgeV2 === \"object\"\n ? window.__codexuseBridgeV2\n : {};\n const bindingName = typeof bridge.bindingName === \"string\" && bridge.bindingName\n ? bridge.bindingName\n : \"__codexuseBridgeBinding\";\n const binding = window[bindingName];\n if (typeof binding !== \"function\") {\n setOverlayMessage(\"Reconnecting…\");\n return;\n }\n const payload = {\n type: \"codexuse-action-request\",\n id: \"codexuse-\" + Date.now().toString(36) + \"-\" + Math.random().toString(36).slice(2, 8),\n action,\n targetProfileKeyHash: target && typeof target.profileKeyHash === \"string\" ? target.profileKeyHash : null,\n settingKey: setting && typeof setting.key === \"string\" ? setting.key : null,\n settingValue: setting && typeof setting.value === \"boolean\" ? setting.value : null,\n route: route(),\n activeThreadId: domActiveThreadId() || window.__codexuseBridge?.snapshot?.activeThreadId || null,\n createdAt: Date.now()\n };\n try {\n binding(JSON.stringify(payload));\n state.lastActionRequest = payload;\n setOverlayMessage(\n action === \"switch\" ? \"Switching…\"\n : action === \"continue\" ? \"Handing off…\"\n : action === \"setting\" ? \"Saving…\"\n : \"Requested\"\n );\n } catch {\n setOverlayMessage(\"Failed\");\n }\n };\n const cuLog = (event, context = null) => {\n const bridge = window.__codexuseBridgeV2;\n if (bridge && typeof bridge.log === \"function\") {\n try { bridge.log(event, context); } catch { /* diagnostics must never break the overlay */ }\n }\n };\n let allTargets = [];\n let activeTarget = null;\n let switchable = [];\n const setTargets = (targets) => {\n allTargets = Array.isArray(targets)\n ? targets.filter((target) => target && typeof target.profileKeyHash === \"string\" && target.profileKeyHash)\n : [];\n activeTarget = allTargets.find((target) => target.current === true) || null;\n switchable = allTargets.filter((target) => target.current !== true && target.eligible !== false).slice(0, 6);\n };\n setTargets(actionTargets);\n // Quotas/eligibility embedded at apply time go stale; pull fresh targets\n // from the backend whenever the menu or hand-off picker opens.\n let refreshingTargets = false;\n const refreshTargetsLive = (onUpdated = null) => {\n const bridge = window.__codexuseBridgeV2;\n if (refreshingTargets || !bridge || typeof bridge.request !== \"function\") return;\n refreshingTargets = true;\n Promise.resolve(bridge.request(\"overlay-targets\")).then((result) => {\n refreshingTargets = false;\n if (!result || result.status !== \"ok\" || !Array.isArray(result.actionTargets)) {\n if (result && result.status !== \"ok\") {\n cuLog(\"overlay.targets-refresh-failed\", { reason: typeof result.reason === \"string\" ? result.reason : \"unknown\" });\n }\n return;\n }\n setTargets(result.actionTargets);\n renderStatus();\n if (typeof onUpdated === \"function\") onUpdated();\n }).catch(() => {\n refreshingTargets = false;\n });\n };\n const renderStatus = () => {\n const previous = document.getElementById(statusId);\n if (previous?.dataset.dragging === \"true\") return true;\n // Re-applies rebuild the pill from scratch (cleanupVisuals already\n // removed it), so the open flag must survive in qol state.\n const wasOpen = previous ? previous.dataset.open === \"true\" : state.overlayMenuOpen === true;\n previous?.remove();\n if (!inCodexStatusEnabled) return false;\n const overlayHidden = readOverlayStore(overlayHiddenKey) === \"1\";\n const hasStoredPosition = Boolean(readOverlayStore(overlayPosKey));\n const shouldShowIntro =\n !previous &&\n !overlayHidden &&\n !hasStoredPosition &&\n readOverlayStore(overlayIntroKey) !== \"1\";\n const pill = document.createElement(\"div\");\n pill.id = statusId;\n applyOverlayTheme(pill);\n if (overlayHidden) {\n pill.dataset.collapsed = \"true\";\n pill.title = \"Show CodexUse\";\n pill.textContent = \"●\";\n pill.addEventListener(\"click\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n writeOverlayStore(overlayHiddenKey, null);\n renderStatus();\n renderHandoff();\n }, true);\n document.body.appendChild(pill);\n applyStoredOverlayPosition(pill);\n return true;\n }\n pill.dataset.open = wasOpen || shouldShowIntro ? \"true\" : \"false\";\n state.overlayMenuOpen = pill.dataset.open === \"true\";\n const trigger = document.createElement(\"button\");\n trigger.type = \"button\";\n trigger.className = \"codexuse-status-trigger\";\n trigger.setAttribute(\"aria-label\", \"CodexUse\");\n const triggerLabel = document.createElement(\"span\");\n triggerLabel.className = \"codexuse-status-label\";\n triggerLabel.setAttribute(\"data-codexuse-status-label\", \"true\");\n triggerLabel.textContent = activeTarget?.label?.trim() || \"CodexUse\";\n trigger.appendChild(triggerLabel);\n const triggerDetailText = activeTarget?.detail?.trim() || \"\";\n const triggerDetail = document.createElement(\"span\");\n triggerDetail.className = \"codexuse-status-chip\";\n triggerDetail.setAttribute(\"data-codexuse-status-detail\", \"true\");\n triggerDetail.textContent = triggerDetailText;\n if (triggerDetailText) trigger.appendChild(triggerDetail);\n const triggerChevron = document.createElement(\"span\");\n triggerChevron.className = \"codexuse-status-chevron\";\n triggerChevron.setAttribute(\"aria-hidden\", \"true\");\n triggerChevron.innerHTML = \"▾\";\n trigger.appendChild(triggerChevron);\n // Drag-to-move on the trigger; a real click (under 4px travel) toggles.\n let dragMoved = false;\n trigger.addEventListener(\"pointerdown\", (event) => {\n if (event.button !== 0) return;\n const startX = event.clientX;\n const startY = event.clientY;\n const startRect = pill.getBoundingClientRect();\n const offsetX = startX - startRect.left;\n const offsetY = startY - startRect.top;\n dragMoved = false;\n const onMove = (moveEvent) => {\n if (!dragMoved && Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY) < 4) return;\n dragMoved = true;\n pill.dataset.dragging = \"true\";\n placeOverlay(pill, moveEvent.clientX - offsetX, moveEvent.clientY - offsetY);\n };\n const onUp = () => {\n window.removeEventListener(\"pointermove\", onMove, true);\n window.removeEventListener(\"pointerup\", onUp, true);\n if (pill.dataset.dragging === \"true\") {\n delete pill.dataset.dragging;\n const rect = pill.getBoundingClientRect();\n writeOverlayStore(overlayPosKey, JSON.stringify({ x: rect.left, y: rect.top }));\n }\n };\n window.addEventListener(\"pointermove\", onMove, true);\n window.addEventListener(\"pointerup\", onUp, true);\n }, true);\n trigger.addEventListener(\"click\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n if (dragMoved) {\n dragMoved = false;\n return;\n }\n pill.dataset.open = pill.dataset.open === \"true\" ? \"false\" : \"true\";\n state.overlayMenuOpen = pill.dataset.open === \"true\";\n // renderStatus rebuilds the open menu in place with the fresh rows.\n if (state.overlayMenuOpen) refreshTargetsLive();\n }, true);\n const menu = document.createElement(\"div\");\n menu.className = \"codexuse-action-menu\";\n if (switchable.length > 0) {\n const list = document.createElement(\"div\");\n list.className = \"codexuse-target-list\";\n switchable.forEach((target) => {\n const row = document.createElement(\"button\");\n row.type = \"button\";\n row.className = \"codexuse-target-row\";\n row.title = \"Switch to \" + (target.label || \"account\");\n const label = document.createElement(\"span\");\n label.className = \"codexuse-target-label\";\n label.textContent = typeof target.label === \"string\" && target.label.trim() ? target.label.trim() : \"Account\";\n row.appendChild(label);\n if (typeof target.detail === \"string\" && target.detail.trim()) {\n const detail = document.createElement(\"span\");\n detail.className = \"codexuse-target-detail\";\n detail.textContent = target.detail.trim();\n row.appendChild(detail);\n }\n row.addEventListener(\"click\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n pill.dataset.open = \"false\";\n state.overlayMenuOpen = false;\n requestAction(\"switch\", target);\n }, true);\n list.appendChild(row);\n });\n menu.appendChild(list);\n } else {\n const empty = document.createElement(\"p\");\n empty.className = \"codexuse-action-empty\";\n empty.textContent = \"No other account ready\";\n menu.appendChild(empty);\n }\n const settingToggles = [\n [\"Auto-roll\", \"autoRoll\", overlayAutoRollEnabled],\n [\"Wide view\", \"wideView\", wideViewEnabled],\n [\"Scroll memory\", \"scrollRestore\", scrollRestoreEnabled],\n [\"Timeline\", \"conversationTimeline\", conversationTimelineEnabled],\n [\"Hand off\", \"handoffChip\", handoffChipEnabled]\n ].filter((entry) => typeof entry[2] === \"boolean\");\n if (settingToggles.length > 0) {\n const divider = document.createElement(\"div\");\n divider.className = \"codexuse-menu-divider\";\n menu.appendChild(divider);\n settingToggles.forEach(([labelText, key, value]) => {\n const row = document.createElement(\"button\");\n row.type = \"button\";\n row.className = \"codexuse-setting-row\";\n row.dataset.on = value === true ? \"true\" : \"false\";\n const label = document.createElement(\"span\");\n label.textContent = labelText;\n const toggle = document.createElement(\"span\");\n toggle.className = \"codexuse-toggle\";\n row.appendChild(label);\n row.appendChild(toggle);\n row.addEventListener(\"click\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n const next = row.dataset.on !== \"true\";\n row.dataset.on = next ? \"true\" : \"false\";\n requestAction(\"setting\", null, { key, value: next });\n }, true);\n menu.appendChild(row);\n });\n }\n const footer = document.createElement(\"div\");\n footer.className = \"codexuse-menu-footer\";\n const actionStatus = document.createElement(\"span\");\n actionStatus.className = \"codexuse-action-status\";\n actionStatus.setAttribute(\"data-codexuse-action-status\", \"true\");\n footer.appendChild(actionStatus);\n const hide = document.createElement(\"button\");\n hide.type = \"button\";\n hide.className = \"codexuse-overlay-hide\";\n hide.textContent = \"Hide\";\n hide.addEventListener(\"click\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n writeOverlayStore(overlayHiddenKey, \"1\");\n state.overlayMenuOpen = false;\n renderStatus();\n renderHandoff();\n }, true);\n footer.appendChild(hide);\n menu.appendChild(footer);\n pill.appendChild(trigger);\n pill.appendChild(menu);\n document.body.appendChild(pill);\n if (shouldShowIntro) {\n placeInitialOverlayPosition(pill);\n writeOverlayStore(overlayIntroKey, \"1\");\n } else {\n applyStoredOverlayPosition(pill);\n }\n return true;\n };\n // Thread-scoped hand-off control: pinned to the composer, only shown when\n // a conversation is on screen and another account is ready to take over.\n // Log the hand-off chip's visibility gate only when it CHANGES — this runs\n // on every mutation tick, and the reason is the first question every\n // \"chip is missing\" report needs answered.\n const reportHandoff = (reason) => {\n if (state.lastHandoffReason === reason) return;\n state.lastHandoffReason = reason;\n cuLog(\"handoff.render\", { reason, targets: switchable.length });\n };\n const renderHandoff = () => {\n document.getElementById(handoffId)?.remove();\n document.getElementById(handoffPickerId)?.remove();\n if (!inCodexStatusEnabled || !handoffChipEnabled) {\n reportHandoff(\"disabled\");\n return false;\n }\n if (readOverlayStore(overlayHiddenKey) === \"1\") {\n reportHandoff(\"overlay-hidden\");\n return false;\n }\n // Codex desktop marks turns with data-turn-key / data-user-message-bubble;\n // the ChatGPT-style selectors are kept as a fallback.\n const inThread = Boolean(domActiveThreadId() || document.querySelector(\n \"[data-turn-key],[data-user-message-bubble],[data-message-author-role='user'],[data-testid='conversation-turn']\"\n ));\n if (!inThread) {\n reportHandoff(\"no-thread\");\n return false;\n }\n const textbox = Array.from(document.querySelectorAll(\n \"textarea,[contenteditable='true'],[role='textbox']\"\n )).find(visibleElement);\n if (!textbox) {\n reportHandoff(\"no-composer\");\n return false;\n }\n const composer = textbox.closest(\"form,[class*='composer'],[data-testid*='composer']\") || textbox;\n const rect = composer.getBoundingClientRect();\n if (rect.width <= 0 || rect.height <= 0) {\n reportHandoff(\"composer-hidden\");\n return false;\n }\n const chipTop = Math.max(8, rect.top - 36);\n const chipRight = Math.max(8, window.innerWidth - rect.right);\n const chip = document.createElement(\"button\");\n chip.type = \"button\";\n chip.id = handoffId;\n applyOverlayTheme(chip);\n chip.textContent = \"Hand off\";\n chip.title = \"Continue this thread on another account\";\n chip.style.top = chipTop + \"px\";\n chip.style.right = chipRight + \"px\";\n // Hand off needs BOTH a thread (this chip only shows in-thread) and a\n // target account. Clicking opens a picker of ready accounts; the chosen\n // account becomes the explicit continue target (the request also carries\n // the active thread id, so the new account reopens this same thread and\n // the \"continue\" message is auto-sent there).\n const closePicker = () => {\n document.getElementById(handoffPickerId)?.remove();\n chip.dataset.open = \"false\";\n };\n const handOffTo = (target) => {\n closePicker();\n chip.disabled = true;\n chip.textContent = \"Handing off…\";\n requestAction(\"continue\", target);\n };\n const openPicker = (skipRefresh = false) => {\n document.getElementById(handoffPickerId)?.remove();\n const picker = document.createElement(\"div\");\n picker.id = handoffPickerId;\n picker.className = \"codexuse-action-menu\";\n applyOverlayTheme(picker);\n picker.style.position = \"fixed\";\n picker.style.right = chipRight + \"px\";\n picker.style.bottom = Math.max(8, window.innerHeight - chipTop + 4) + \"px\";\n picker.style.maxHeight = \"240px\";\n picker.style.overflowY = \"auto\";\n picker.style.zIndex = \"2147483647\";\n const list = document.createElement(\"div\");\n list.className = \"codexuse-target-list\";\n if (switchable.length === 0) {\n const empty = document.createElement(\"p\");\n empty.className = \"codexuse-action-empty\";\n empty.textContent = \"No other account ready\";\n list.appendChild(empty);\n }\n switchable.forEach((target) => {\n const row = document.createElement(\"button\");\n row.type = \"button\";\n row.className = \"codexuse-target-row\";\n row.title = \"Continue this thread on \" + (target.label || \"account\");\n const label = document.createElement(\"span\");\n label.className = \"codexuse-target-label\";\n label.textContent = typeof target.label === \"string\" && target.label.trim() ? target.label.trim() : \"Account\";\n row.appendChild(label);\n if (typeof target.detail === \"string\" && target.detail.trim()) {\n const detail = document.createElement(\"span\");\n detail.className = \"codexuse-target-detail\";\n detail.textContent = target.detail.trim();\n row.appendChild(detail);\n }\n row.addEventListener(\"click\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n handOffTo(target);\n }, true);\n list.appendChild(row);\n });\n picker.appendChild(list);\n document.body.appendChild(picker);\n chip.dataset.open = \"true\";\n // Rebuild the open picker once fresh targets arrive; skipRefresh stops\n // the rebuilt picker from requesting again in a loop.\n if (!skipRefresh) {\n refreshTargetsLive(() => {\n if (document.getElementById(handoffPickerId)) openPicker(true);\n });\n }\n const onDocPointer = (event) => {\n if (picker.contains(event.target) || chip.contains(event.target)) return;\n document.removeEventListener(\"pointerdown\", onDocPointer, true);\n closePicker();\n };\n document.addEventListener(\"pointerdown\", onDocPointer, true);\n };\n chip.addEventListener(\"click\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n // Always make the user pick the destination account explicitly — never\n // auto-hand-off to a server-chosen account (which could be out of quota).\n if (chip.dataset.open === \"true\") {\n closePicker();\n } else {\n openPicker();\n }\n }, true);\n document.body.appendChild(chip);\n reportHandoff(\"rendered\");\n return true;\n };\n if (typeof state.cleanupVisuals === \"function\") {\n state.cleanupVisuals();\n state.cleanupVisuals = null;\n }\n let timelineApplied = renderTimeline();\n let statusApplied = renderStatus();\n renderHandoff();\n if (conversationTimelineEnabled || inCodexStatusEnabled) {\n let frame = 0;\n const refreshVisuals = () => {\n frame = 0;\n timelineApplied = renderTimeline();\n statusApplied = renderStatus();\n renderHandoff();\n };\n const scheduleVisuals = () => {\n if (frame) return;\n frame = window.requestAnimationFrame(refreshVisuals);\n };\n const isVisualNode = (node, target) => {\n if (!node) return false;\n const element = node.nodeType === Node.ELEMENT_NODE\n ? node\n : node.parentElement || (target?.nodeType === Node.ELEMENT_NODE ? target : target?.parentElement);\n return element?.id === statusId ||\n element?.id === handoffId ||\n element?.id === handoffPickerId ||\n element?.classList?.contains(timelineClass) ||\n Boolean(element?.closest?.(\".\" + timelineClass + \",#\" + statusId + \",#\" + handoffId + \",#\" + handoffPickerId));\n };\n const isVisualOnlyMutation = (mutation) => {\n const nodes = [...mutation.addedNodes, ...mutation.removedNodes];\n return nodes.length > 0 && nodes.every((node) => isVisualNode(node, mutation.target));\n };\n const observer = new MutationObserver((mutations) => {\n if (mutations.length > 0 && mutations.every(isVisualOnlyMutation)) return;\n scheduleVisuals();\n });\n observer.observe(document.body, { childList: true, subtree: true });\n window.addEventListener(\"resize\", scheduleVisuals);\n state.cleanupVisuals = () => {\n observer.disconnect();\n window.removeEventListener(\"resize\", scheduleVisuals);\n if (frame) window.cancelAnimationFrame(frame);\n document.querySelectorAll(\".\" + timelineClass).forEach((node) => node.remove());\n clearTimelineTargets();\n document.getElementById(statusId)?.remove();\n document.getElementById(handoffId)?.remove();\n };\n } else {\n document.querySelectorAll(\".\" + timelineClass).forEach((node) => node.remove());\n clearTimelineTargets();\n document.getElementById(statusId)?.remove();\n document.getElementById(handoffId)?.remove();\n }\n\n state.wideViewEnabled = wideViewEnabled;\n state.wideViewMaxWidth = wideViewMaxWidth;\n state.scrollRestoreEnabled = scrollRestoreEnabled;\n state.conversationTimelineEnabled = conversationTimelineEnabled;\n state.inCodexStatusEnabled = inCodexStatusEnabled;\n state.actionTargets = actionTargets;\n state.appliedAt = Date.now();\n state.appliedAtIso = appliedAtIso;\n const styleText = String(document.getElementById(styleId)?.textContent || \"\");\n wideViewApplied = wideViewEnabled && (wideViewApplied || styleText.includes(\"--thread-content-max-width\"));\n const scrollRestoreApplied = scrollRestoreEnabled && state.scrollRestoreInstalled === true && typeof state.cleanupScrollRestore === \"function\";\n state.features = {\n wideView: feature(wideViewEnabled, wideViewApplied, versions.wideView, wideViewEnabled && !wideViewApplied ? \"wide-style-missing\" : null),\n scrollRestore: feature(scrollRestoreEnabled, scrollRestoreApplied, versions.scrollRestore, scrollRestoreEnabled && !scrollRestoreApplied ? \"scroll-restore-not-installed\" : null),\n conversationTimeline: feature(conversationTimelineEnabled, timelineApplied, versions.conversationTimeline),\n inCodexStatus: feature(inCodexStatusEnabled, statusApplied, versions.inCodexStatus)\n };\n if (inCodexStatusEnabled) {\n const enabledFeatures = [\n [\"wide\", state.features.wideView],\n [\"scroll\", state.features.scrollRestore],\n [\"timeline\", state.features.conversationTimeline],\n [\"status\", state.features.inCodexStatus]\n ].filter((entry) => entry[1]?.enabled === true);\n const degradedFeatures = enabledFeatures.filter((entry) => entry[1]?.applied !== true);\n const status = degradedFeatures.length > 0\n ? \"degraded\"\n : enabledFeatures.length > 0\n ? \"applied\"\n : \"disabled\";\n const pill = document.getElementById(statusId);\n if (pill) {\n const detail = enabledFeatures.length > 0\n ? enabledFeatures.map((entry) => entry[0] + \":\" + entry[1].status).join(\" / \")\n : \"no active conversation controls\";\n pill.setAttribute(\"data-codexuse-qol-status\", status);\n pill.setAttribute(\"title\", detail);\n if (status === \"degraded\") {\n const statusDetail = pill.querySelector(\"[data-codexuse-status-detail]\");\n if (statusDetail) {\n statusDetail.textContent = \"Reconnect\";\n }\n }\n }\n state.features.inCodexStatus = feature(inCodexStatusEnabled, Boolean(pill), versions.inCodexStatus, pill ? null : \"status-pill-missing\");\n }\n window.__codexuseQol = state;\n cuLog(\"qol.applied\", {\n wideView: state.features.wideView?.status || \"off\",\n scrollRestore: state.features.scrollRestore?.status || \"off\",\n timeline: state.features.conversationTimeline?.status || \"off\",\n inCodexStatus: state.features.inCodexStatus?.status || \"off\",\n targets: allTargets.length\n });\n const qolStatus = {\n wideView: state.features.wideView,\n scrollRestore: state.features.scrollRestore,\n conversationTimeline: state.features.conversationTimeline,\n inCodexStatus: state.features.inCodexStatus,\n appliedAt: appliedAtIso\n };\n return {\n status: \"applied\",\n reason: null,\n route: route(),\n wideViewEnabled,\n wideViewMaxWidth,\n scrollRestoreEnabled,\n conversationTimelineEnabled,\n inCodexStatusEnabled,\n qolStatus\n };\n })()`;\n}\n\nfunction createBridgeApplyPowerExpression(\n settings: OfficialCodexPowerSettingsPayload,\n settingsExpression?: string,\n): string {\n return `(async () => {\n const settings = ${settingsExpression ?? JSON.stringify(settings)};\n const versions = {\n modelWhitelistUnlock: \"1\",\n pluginMarketplaceUnlock: \"1\",\n forcePluginInstall: \"1\"\n };\n const route = () => window.location.pathname + window.location.search + window.location.hash;\n const sanitizeError = (value, fallback = null) => {\n const raw = String(value?.message || value || \"\").replace(/\\\\s+/g, \" \").trim();\n if (!raw) return fallback;\n return raw\n .replace(/\\\\/Users\\\\/[^/\\\\s]+(?:\\\\/[^\\\\s\"'),;]*)?/g, \"~\")\n .replace(/\\\\b(?:file|blob):\\\\/\\\\/[^\\\\s<>\"')]+/gi, \"[redacted-url]\")\n .replace(/\\\\bhttps?:\\\\/\\\\/[^\\\\s<>\"')]+/gi, \"[redacted-url]\")\n .replace(/\\\\blocal(?::|%3A)[A-Za-z0-9_-]{12,}\\\\b/gi, \"local:[redacted-thread]\")\n .replace(/\\\\brollout-[A-Za-z0-9_-]{12,}\\\\.(?:jsonl?|ndjson)\\\\b/g, \"rollout-[redacted]\")\n .replace(/\\\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\\\b/gi, \"[redacted-id]\")\n .replace(/\\\\bBearer\\\\s+[A-Za-z0-9._~+/=-]{8,}/gi, \"Bearer [redacted]\")\n .replace(/\\\\b(?:rk|sess|sk)-[A-Za-z0-9_-]{12,}\\\\b/g, \"[redacted-key]\")\n .replace(/\\\\b(api[_-]?key|token|authorization)([\"'\\\\s:=]+)([^,\\\\s\"']{8,})/gi, \"$1$2[redacted]\")\n .slice(0, 180);\n };\n const normalizeThreadId = (value) => {\n let id = String(value || \"\").trim();\n try { id = decodeURIComponent(id); } catch {}\n if (id.toLowerCase().startsWith(\"local:\")) id = id.slice(6);\n if (!id || id === \"__proto__\" || id === \"prototype\" || id === \"constructor\") return null;\n return /^[A-Za-z0-9_.-]{8,128}$/.test(id) ? id : null;\n };\n const normalizeRelayProfileId = (value) => {\n const id = String(value || \"\").trim();\n return /^[A-Za-z0-9][A-Za-z0-9_-]{2,79}$/.test(id) ? id : null;\n };\n const threadIdFromRow = (row) => {\n if (!row) return null;\n const href = row.getAttribute(\"href\") || row.querySelector(\"a\")?.getAttribute(\"href\") || \"\";\n const hrefMatch = href.match(/(?:sessions?|conversations?|threads?)(?:\\\\/|=|:|-)((?:local(?::|%3A))?[A-Za-z0-9_.-]+)/i)\n || href.match(/((?:local(?::|%3A))?[A-Za-z0-9_.-]{8,128})$/i);\n return normalizeThreadId(row.getAttribute(\"data-app-action-sidebar-thread-id\"))\n || normalizeThreadId(hrefMatch?.[1])\n || normalizeThreadId(row.getAttribute(\"data-session-id\"));\n };\n const activeThreadIdFromRoute = () => {\n const source = window.location.href + \" \" + route();\n const rows = Array.from(document.querySelectorAll(\"[data-app-action-sidebar-thread-id]\"));\n const activeRow = rows.find((row) =>\n row.getAttribute(\"data-app-action-sidebar-thread-active\") === \"true\"\n || row.getAttribute(\"aria-current\") === \"page\"\n || row.getAttribute(\"aria-current\") === \"true\"\n );\n const rowId = threadIdFromRow(activeRow);\n if (rowId) return rowId;\n const patterns = [\n /(?:sessions?|conversations?|threads?)(?:\\\\/|=|:|-)((?:local(?::|%3A))?[A-Za-z0-9_.-]+)/i,\n /(?:threadId|sessionId|conversationId)=((?:local(?::|%3A))?[A-Za-z0-9_.-]+)/i,\n /local(?::|%3A)([A-Za-z0-9_.-]{8,128})/i,\n /\\\\/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})(?:[/?#]|$)/,\n /\\\\/([A-Za-z0-9_-]{24,})(?:[/?#]|$)/\n ];\n for (const pattern of patterns) {\n const match = source.match(pattern);\n const id = normalizeThreadId(match?.[1] || \"\");\n if (id) return id;\n }\n return null;\n };\n const enabled = {\n modelWhitelistUnlock: settings.modelWhitelistUnlockEnabled === true,\n pluginMarketplaceUnlock: settings.pluginMarketplaceUnlockEnabled === true,\n forcePluginInstall: settings.forcePluginInstallEnabled === true\n };\n const modelWhitelistModels = Array.isArray(settings.modelWhitelistModels)\n ? Array.from(new Set(settings.modelWhitelistModels\n .map((model) => typeof model === \"string\" ? model.trim() : \"\")\n .filter(Boolean)))\n .slice(0, 50)\n : [];\n const feature = (name, applied, error = null) => ({\n enabled: enabled[name] === true,\n applied: applied === true,\n status: enabled[name] === true ? (applied === true ? \"applied\" : \"degraded\") : \"disabled\",\n version: versions[name] || null,\n error: sanitizeError(error)\n });\n const relayMode = [\"official\", \"responses\", \"chat-completions\"].includes(settings.relayMode) ? settings.relayMode : \"off\";\n const relayProfileId = relayMode === \"responses\" || relayMode === \"chat-completions\"\n ? normalizeRelayProfileId(settings.relayProfileId)\n : null;\n let state = window.__codexusePower;\n if (!state || typeof state !== \"object\") state = {};\n const previousSettings = state.settings && typeof state.settings === \"object\" ? state.settings : {};\n const previousFeatures = state.features && typeof state.features === \"object\" ? state.features : {};\n const previousPatchOwners = state.pluginMarketplacePatchOwners && typeof state.pluginMarketplacePatchOwners === \"object\"\n ? state.pluginMarketplacePatchOwners\n : {};\n const previousSettingKnown = (key) => Object.prototype.hasOwnProperty.call(previousSettings, key);\n const previousEnabled = {\n modelWhitelistUnlock: previousFeatures.modelWhitelistUnlock?.enabled === true || previousSettings.modelWhitelistUnlockEnabled === true,\n pluginMarketplaceUnlock: previousFeatures.pluginMarketplaceUnlock?.enabled === true || previousSettings.pluginMarketplaceUnlockEnabled === true\n };\n const clientPatchActive = state.pluginMarketplaceClientPatchInstalled === \"1\";\n const previousModelRuntimeActive = previousEnabled.modelWhitelistUnlock\n || previousPatchOwners.modelWhitelistUnlock === true\n || (clientPatchActive && !previousSettingKnown(\"modelWhitelistUnlockEnabled\") && previousPatchOwners.modelWhitelistUnlock !== false);\n const previousPluginRuntimeActive = previousEnabled.pluginMarketplaceUnlock\n || previousPatchOwners.pluginMarketplaceUnlock === true\n || state.pluginMarketplaceFilterPatchInstalled === \"1\"\n || (clientPatchActive && !previousSettingKnown(\"pluginMarketplaceUnlockEnabled\") && previousPatchOwners.pluginMarketplaceUnlock !== false);\n const reloadRequired = (previousModelRuntimeActive && !enabled.modelWhitelistUnlock)\n || (previousPluginRuntimeActive && !enabled.pluginMarketplaceUnlock);\n state.settings = settings;\n const activeThreadId = activeThreadIdFromRoute();\n state.modulePromises = state.modulePromises && typeof state.modulePromises === \"object\"\n ? state.modulePromises\n : {};\n const codexAppAssetUrl = (namePart) => {\n const urls = [\n ...Array.from(document.scripts || []).map((script) => script.src),\n ...Array.from(document.querySelectorAll(\"link[href]\") || []).map((link) => link.href),\n ...performance.getEntriesByType(\"resource\").map((entry) => entry.name)\n ].filter(Boolean);\n return urls.find((url) => url.includes(\"/assets/\") && url.includes(namePart) && url.split(\"?\")[0].endsWith(\".js\")) || \"\";\n };\n const loadCodexAppModule = async (namePart) => {\n if (!state.modulePromises[namePart]) {\n state.modulePromises[namePart] = Promise.resolve().then(async () => {\n const url = codexAppAssetUrl(namePart);\n if (!url) throw new Error(\"Codex App asset not found: \" + namePart);\n return await import(url);\n }).catch((error) => {\n delete state.modulePromises[namePart];\n throw error;\n });\n }\n return await state.modulePromises[namePart];\n };\n const patchModelListRequestParams = (params) => {\n if (!enabled.modelWhitelistUnlock) return params;\n if (params && typeof params === \"object\" && params.includeHidden === true) return params;\n return {\n ...(params && typeof params === \"object\" && !Array.isArray(params) ? params : {}),\n includeHidden: true\n };\n };\n const patchModelListRequest = (request) => {\n if (!enabled.modelWhitelistUnlock || !request || typeof request !== \"object\") return request;\n if (String(request.method || \"\") !== \"model/list\") return request;\n const params = patchModelListRequestParams(request.params);\n return params === request.params ? request : { ...request, params };\n };\n const patchRequestMessage = (message) => {\n if (!message || typeof message !== \"object\") return message;\n let next = message;\n if (enabled.modelWhitelistUnlock) {\n next = patchModelListRequest(next);\n if (next.params && typeof next.params === \"object\" && String(next.params.method || \"\") === \"model/list\") {\n const params = patchModelListRequestParams(next.params.params);\n if (params !== next.params.params) {\n next = { ...next, params: { ...next.params, params } };\n }\n }\n if (next.request && typeof next.request === \"object\") {\n const request = patchModelListRequest(next.request);\n if (request !== next.request) next = { ...next, request };\n }\n }\n return next;\n };\n const patchModelContainer = (value, visited = new WeakSet(), depth = 0) => {\n if (!enabled.modelWhitelistUnlock || !value || typeof value !== \"object\" || visited.has(value) || depth > 5) return false;\n visited.add(value);\n let changed = false;\n const modelDescriptor = (model) => ({\n model,\n id: model,\n slug: model,\n name: model,\n displayName: model,\n title: model,\n description: \"CodexUse relay model\",\n hidden: false,\n disabled: false\n });\n const unhideArray = (items) => {\n if (!Array.isArray(items)) return;\n for (const item of items) {\n if (!item || typeof item !== \"object\") continue;\n if (\"hidden\" in item && item.hidden !== false) {\n item.hidden = false;\n changed = true;\n }\n if (\"disabled\" in item && item.disabled === true) {\n item.disabled = false;\n changed = true;\n }\n }\n };\n const stringArrayLooksPatchable = (items) =>\n Array.isArray(items) && items.every((item) => typeof item === \"string\");\n const objectArrayLooksPatchable = (items, allowEmpty = false) =>\n Array.isArray(items)\n && (allowEmpty || items.length > 0)\n && items.every((item) =>\n item && typeof item === \"object\" && (\n typeof item.model === \"string\"\n || typeof item.id === \"string\"\n || typeof item.slug === \"string\"\n || typeof item.name === \"string\"\n )\n );\n const patchModelArray = (items, allowEmpty = false) => {\n if (!Array.isArray(items)) return false;\n let localChanged = false;\n unhideArray(items);\n if (stringArrayLooksPatchable(items)) {\n for (const model of modelWhitelistModels) {\n if (!items.includes(model)) {\n items.push(model);\n localChanged = true;\n }\n }\n return localChanged;\n }\n if (objectArrayLooksPatchable(items, allowEmpty)) {\n const existing = new Set();\n for (const item of items) {\n existing.add(String(item.model || item.id || item.slug || item.name || \"\"));\n }\n for (const model of modelWhitelistModels) {\n if (!existing.has(model)) {\n items.push(modelDescriptor(model));\n localChanged = true;\n }\n }\n }\n return localChanged;\n };\n if (patchModelArray(value.models, \"defaultModel\" in value || \"availableModels\" in value)) changed = true;\n if (patchModelArray(value.data)) changed = true;\n if (patchModelArray(value.result)) changed = true;\n if (patchModelArray(value.availableModels, true)) changed = true;\n if (patchModelArray(value.available_models, true)) changed = true;\n if (value.available_models instanceof Set) {\n for (const model of modelWhitelistModels) {\n if (!value.available_models.has(model)) {\n value.available_models.add(model);\n changed = true;\n }\n }\n }\n if (value.availableModels instanceof Set) {\n for (const model of modelWhitelistModels) {\n if (!value.availableModels.has(model)) {\n value.availableModels.add(model);\n changed = true;\n }\n }\n }\n if (Array.isArray(value.hiddenModels)) {\n const nextHidden = value.hiddenModels.filter((model) => !modelWhitelistModels.includes(String(model)));\n if (nextHidden.length !== value.hiddenModels.length) {\n value.hiddenModels = nextHidden;\n changed = true;\n }\n }\n if (Array.isArray(value.hidden_models)) {\n const nextHidden = value.hidden_models.filter((model) => !modelWhitelistModels.includes(String(model)));\n if (nextHidden.length !== value.hidden_models.length) {\n value.hidden_models = nextHidden;\n changed = true;\n }\n }\n for (const key of Object.keys(value)) {\n if (patchModelContainer(value[key], visited, depth + 1)) changed = true;\n }\n return changed;\n };\n const patchStatsigModelDynamicConfig = (config) => {\n const value = config?.value;\n if (!enabled.modelWhitelistUnlock || !modelWhitelistModels.length || !value || typeof value !== \"object\") return false;\n const availableModels = Array.isArray(value.available_models) ? [...value.available_models] : [];\n let changed = false;\n for (const model of modelWhitelistModels) {\n if (!availableModels.includes(model)) {\n availableModels.push(model);\n changed = true;\n }\n }\n const nextValue = {\n ...value,\n available_models: availableModels,\n default_model: modelWhitelistModels[0] || value.default_model\n };\n if (!changed && nextValue.default_model === value.default_model) return false;\n try {\n config.value = nextValue;\n } catch {\n return false;\n }\n return true;\n };\n const statsigClients = () => {\n const root = window.__STATSIG__ || globalThis.__STATSIG__;\n if (!root || typeof root !== \"object\") return [];\n const clients = [root.firstInstance, typeof root.instance === \"function\" ? root.instance() : null];\n if (root.instances && typeof root.instances === \"object\") clients.push(...Object.values(root.instances));\n return clients.filter((client, index, array) => client && typeof client === \"object\" && array.indexOf(client) === index);\n };\n const patchStatsigModelWhitelist = () => {\n if (!enabled.modelWhitelistUnlock) return false;\n try {\n let touched = false;\n for (const client of statsigClients()) {\n if (typeof client.getDynamicConfig !== \"function\") continue;\n if (!client.__codexuseModelWhitelistOriginalGetDynamicConfig) {\n const originalGetDynamicConfig = client.getDynamicConfig.bind(client);\n client.__codexuseModelWhitelistOriginalGetDynamicConfig = originalGetDynamicConfig;\n client.getDynamicConfig = (name, options) => {\n const result = originalGetDynamicConfig(name, options);\n patchStatsigModelDynamicConfig(result);\n return result;\n };\n }\n try {\n if (patchStatsigModelDynamicConfig(client.getDynamicConfig(\"107580212\", { disableExposureLog: true }))) {\n touched = true;\n }\n } catch {\n }\n touched = true;\n }\n state.modelStatsigPatchInstalled = touched ? \"1\" : null;\n state.modelStatsigPatchError = null;\n return touched;\n } catch (error) {\n state.modelStatsigPatchInstalled = null;\n state.modelStatsigPatchError = sanitizeError(error, \"model-statsig-patch-failed\");\n return false;\n }\n };\n const patchObjectGraphForModels = (root, visited = new WeakSet(), depth = 0) => {\n if (!enabled.modelWhitelistUnlock || !root || typeof root !== \"object\" || visited.has(root) || depth > 5) return false;\n let changed = patchModelContainer(root);\n visited.add(root);\n if (root instanceof Element || root === window || root === document || root === document.body || root === document.documentElement) return changed;\n for (const key of Object.keys(root)) {\n if (key === \"ownerDocument\" || key === \"parentElement\" || key === \"parentNode\" || key === \"children\" || key === \"childNodes\") continue;\n try {\n const value = root[key];\n if (value && typeof value === \"object\" && patchObjectGraphForModels(value, visited, depth + 1)) changed = true;\n } catch {\n }\n }\n return changed;\n };\n const reactFiberKeys = (element) => Object.keys(element || {}).filter((key) => key.startsWith(\"__reactFiber\") || key.startsWith(\"__reactInternalInstance\") || key.startsWith(\"__reactProps\"));\n const patchReactModelState = () => {\n if (!enabled.modelWhitelistUnlock) return false;\n try {\n const visited = new WeakSet();\n const nodes = [document.body, ...Array.from(document.querySelectorAll(\"button,[role='menu'],[role='dialog'],[data-radix-popper-content-wrapper]\"))].filter(Boolean);\n let changed = false;\n for (const node of nodes.slice(0, 220)) {\n for (const key of reactFiberKeys(node)) {\n if (patchObjectGraphForModels(node[key], visited)) changed = true;\n }\n }\n state.modelReactStatePatchedAt = changed ? Date.now() : state.modelReactStatePatchedAt || null;\n state.modelReactStatePatchError = null;\n return changed;\n } catch (error) {\n state.modelReactStatePatchError = sanitizeError(error, \"model-react-state-patch-failed\");\n return false;\n }\n };\n const patchPluginContainer = (value, visited = new WeakSet(), depth = 0, inheritedMarketplaceName = null) => {\n if (!enabled.pluginMarketplaceUnlock || !value || typeof value !== \"object\" || visited.has(value) || depth > 4) return false;\n visited.add(value);\n let changed = false;\n const unhideRecord = (record, marketplaceName = null) => {\n if (!record || typeof record !== \"object\") return false;\n const recordMarketplaceName = marketplaceName || record.marketplaceName || record.remoteMarketplaceName || record.name || null;\n if (!codexPluginOfficialMarketplaceName(recordMarketplaceName)) return false;\n let localChanged = false;\n if (\"hidden\" in record && record.hidden !== false) {\n record.hidden = false;\n localChanged = true;\n }\n if (\"disabled\" in record && record.disabled === true) {\n record.disabled = false;\n localChanged = true;\n }\n return localChanged;\n };\n if (unhideRecord(value, inheritedMarketplaceName)) changed = true;\n if (Array.isArray(value.marketplaces)) {\n for (const marketplace of value.marketplaces) {\n if (!marketplace || typeof marketplace !== \"object\") continue;\n const marketplaceName = marketplace.name || marketplace.marketplaceName || marketplace.remoteMarketplaceName || null;\n if (unhideRecord(marketplace, marketplaceName)) changed = true;\n if (Array.isArray(marketplace.plugins)) {\n for (const plugin of marketplace.plugins) {\n if (unhideRecord(plugin, marketplaceName)) changed = true;\n }\n }\n }\n }\n for (const key of Object.keys(value)) {\n const childMarketplaceName =\n key === \"plugins\" || key === \"plugin\" || key === \"items\"\n ? (value.marketplaceName || value.remoteMarketplaceName || value.name || inheritedMarketplaceName)\n : inheritedMarketplaceName;\n if (patchPluginContainer(value[key], visited, depth + 1, childMarketplaceName)) changed = true;\n }\n return changed;\n };\n const pluginRequestMethod = (method, params) => {\n if (method === \"send-cli-request-for-host\" && params?.method) {\n return String(params.method);\n }\n return String(method || \"\");\n };\n const restorePluginMarketplaceName = (name) => {\n if (name === \"codexuse-openai-bundled\") return \"openai-bundled\";\n if (name === \"codexuse-openai-curated\") return \"openai-curated\";\n if (name === \"codexuse-openai-primary-runtime\") return \"openai-primary-runtime\";\n return name;\n };\n const restorePluginMarketplaceKind = (name) => {\n if (typeof name !== \"string\") return name;\n if (name === \"remote:openai-curated\") return \"openai-curated\";\n if (name.startsWith(\"remote:\")) {\n return \"remote:\" + restorePluginMarketplaceName(name.slice(\"remote:\".length));\n }\n return restorePluginMarketplaceName(name);\n };\n const codexPluginOfficialMarketplaceName = (name) => {\n const restored = restorePluginMarketplaceName(name);\n return restored === \"openai-bundled\" || restored === \"openai-curated\" || restored === \"openai-primary-runtime\";\n };\n const isCodexPluginBuildFlavorFilter = (callback, sample) => {\n if (!Array.isArray(sample) || sample.length === 0 || typeof callback !== \"function\") return false;\n let source = \"\";\n try {\n source = Function.prototype.toString.call(callback);\n } catch {\n return false;\n }\n if (!source.includes(\"!u(e.marketplaceName)||e.marketplaceName===r\")) return false;\n if (!sample.some((plugin) => codexPluginOfficialMarketplaceName(plugin?.marketplaceName))) return false;\n return sample.some((plugin) => codexPluginOfficialMarketplaceName(plugin?.marketplaceName) && !callback(plugin));\n };\n const isCodexPluginMarketplaceHiddenFilter = (callback, sample) => {\n if (!Array.isArray(sample) || sample.length === 0 || typeof callback !== \"function\") return false;\n let source = \"\";\n try {\n source = Function.prototype.toString.call(callback);\n } catch {\n return false;\n }\n if (!source.includes(\"!t.includes(e.name)\")) return false;\n if (!sample.some((marketplace) => codexPluginOfficialMarketplaceName(marketplace?.name))) return false;\n return sample.some((marketplace) => codexPluginOfficialMarketplaceName(marketplace?.name) && !callback(marketplace));\n };\n const restorePluginMarketplaceFilterPatch = () => {\n try {\n if (\n state.pluginMarketplaceFilterOriginal &&\n Array.prototype.filter === state.pluginMarketplaceFilterPatched\n ) {\n Array.prototype.filter = state.pluginMarketplaceFilterOriginal;\n }\n } catch {\n }\n state.pluginMarketplaceFilterOriginal = null;\n state.pluginMarketplaceFilterPatched = null;\n state.pluginMarketplaceFilterPatchInstalled = null;\n state.pluginMarketplaceFilterPatchError = null;\n };\n const installPluginMarketplaceFilterPatch = () => {\n if (!enabled.pluginMarketplaceUnlock) {\n restorePluginMarketplaceFilterPatch();\n return false;\n }\n if (state.pluginMarketplaceFilterPatchInstalled === \"1\") {\n restorePluginMarketplaceFilterPatch();\n }\n try {\n const originalFilter = Array.prototype.filter;\n const patchedFilter = function codexusePluginMarketplaceFilterPatch(callback, thisArg) {\n try {\n if (\n isCodexPluginBuildFlavorFilter(callback, this) ||\n isCodexPluginMarketplaceHiddenFilter(callback, this)\n ) {\n return Array.from(this);\n }\n } catch {\n }\n return originalFilter.call(this, callback, thisArg);\n };\n state.pluginMarketplaceFilterOriginal = originalFilter;\n state.pluginMarketplaceFilterPatched = patchedFilter;\n Array.prototype.filter = patchedFilter;\n state.pluginMarketplaceFilterPatchInstalled = \"1\";\n state.pluginMarketplaceFilterPatchError = null;\n return true;\n } catch (error) {\n state.pluginMarketplaceFilterPatchInstalled = null;\n state.pluginMarketplaceFilterPatchError = sanitizeError(error, \"plugin-filter-patch-failed\");\n return false;\n }\n };\n const restorePluginMarketplaceRequestParams = (params, method = \"\") => {\n if (!params || typeof params !== \"object\") return params;\n let next = params;\n if (Array.isArray(params.marketplaceKinds)) {\n const nextKinds = params.marketplaceKinds.map(restorePluginMarketplaceKind);\n if (nextKinds.some((kind, index) => kind !== params.marketplaceKinds[index])) {\n next = { ...next, marketplaceKinds: Array.from(new Set(nextKinds)) };\n }\n }\n if (method === \"install-plugin\") {\n next = next === params ? { ...params } : { ...next };\n if (typeof next.remoteMarketplaceName === \"string\") {\n next.remoteMarketplaceName = restorePluginMarketplaceName(next.remoteMarketplaceName);\n }\n if (typeof next.marketplacePath === \"string\" && next.marketplacePath.startsWith(\"remote:\")) {\n const remoteMarketplaceName = next.marketplacePath.slice(\"remote:\".length);\n delete next.marketplacePath;\n next.remoteMarketplaceName = restorePluginMarketplaceName(remoteMarketplaceName);\n }\n }\n return next;\n };\n const patchPluginMarketplaceRequestParams = (method, params) => {\n const restoredParams = restorePluginMarketplaceRequestParams(params, method);\n if (!restoredParams || typeof restoredParams !== \"object\") return restoredParams;\n let next = restoredParams;\n if (method === \"list-plugins\") {\n next = { ...restoredParams };\n delete next.marketplaceKinds;\n }\n return next;\n };\n const patchPluginMarketplaceResult = (method, result) => {\n if (method === \"list-plugins\") {\n patchPluginContainer(result);\n }\n return result;\n };\n const patchAppServerModelResult = (method, result) => {\n if (method !== \"list-models-for-host\" && method !== \"model/list\") return result;\n try {\n if (Array.isArray(result)) patchModelContainer(result);\n if (Array.isArray(result?.data)) patchModelContainer(result.data);\n if (Array.isArray(result?.models)) patchModelContainer(result.models);\n patchModelContainer(result);\n } catch (error) {\n state.modelRequestClientPatchError = sanitizeError(error, \"model-client-patch-failed\");\n }\n return result;\n };\n const patchPluginMarketplaceRequestClient = (client) => {\n if (!client || typeof client.sendRequest !== \"function\") return false;\n if (client.__codexusePluginMarketplaceOriginalSendRequest) return true;\n const originalSendRequest = client.sendRequest.bind(client);\n client.__codexusePluginMarketplaceOriginalSendRequest = originalSendRequest;\n client.sendRequest = async function codexusePluginMarketplaceSendRequest(method, params, options) {\n const requestMethod = pluginRequestMethod(String(method || \"\"), params);\n const requestParams = enabled.pluginMarketplaceUnlock\n ? patchPluginMarketplaceRequestParams(requestMethod, params)\n : params;\n const result = await originalSendRequest(method, requestParams, options);\n const modelResult = enabled.modelWhitelistUnlock\n ? patchAppServerModelResult(requestMethod, result)\n : result;\n return enabled.pluginMarketplaceUnlock\n ? patchPluginMarketplaceResult(requestMethod, modelResult)\n : modelResult;\n };\n state.pluginMarketplacePatchTargets = Array.isArray(state.pluginMarketplacePatchTargets)\n ? state.pluginMarketplacePatchTargets\n : [];\n state.pluginMarketplacePatchTargets.push(client);\n return true;\n };\n const restorePluginMarketplaceClientPatch = () => {\n const targets = Array.isArray(state.pluginMarketplacePatchTargets)\n ? state.pluginMarketplacePatchTargets\n : [];\n for (const client of targets) {\n try {\n if (client?.__codexusePluginMarketplaceOriginalSendRequest) {\n client.sendRequest = client.__codexusePluginMarketplaceOriginalSendRequest;\n delete client.__codexusePluginMarketplaceOriginalSendRequest;\n }\n } catch {\n }\n }\n state.pluginMarketplacePatchTargets = [];\n state.pluginMarketplaceClientPatchInstalled = null;\n state.pluginMarketplaceClientPatchError = null;\n state.modelRequestClientPatchError = null;\n state.pluginMarketplacePatchOwners = {};\n };\n const installPluginMarketplaceClientPatch = async () => {\n if (!enabled.pluginMarketplaceUnlock && !enabled.modelWhitelistUnlock) {\n restorePluginMarketplaceClientPatch();\n return false;\n }\n if (state.pluginMarketplaceClientPatchInstalled === \"1\") {\n restorePluginMarketplaceClientPatch();\n }\n try {\n const module = await loadCodexAppModule(\"app-server-manager-signals-\");\n const candidates = Object.values(module || {}).filter((value) => value && typeof value === \"object\");\n let patchedCount = 0;\n for (const candidate of candidates) {\n if (patchPluginMarketplaceRequestClient(candidate)) patchedCount += 1;\n if (typeof candidate.sendRequest !== \"function\" && typeof candidate.get === \"function\") {\n try {\n if (patchPluginMarketplaceRequestClient(candidate.get())) patchedCount += 1;\n } catch {\n }\n }\n }\n if (patchedCount === 0) throw new Error(\"app-server-request-client-not-found\");\n state.pluginMarketplaceClientPatchInstalled = \"1\";\n state.pluginMarketplaceClientPatchError = null;\n state.modelRequestClientPatchError = null;\n return true;\n } catch (error) {\n state.pluginMarketplaceClientPatchInstalled = null;\n state.pluginMarketplaceClientPatchError = sanitizeError(error, \"plugin-client-patch-failed\");\n return false;\n }\n };\n const patchResponsePayload = (payload) => {\n try {\n patchModelContainer(payload);\n patchPluginContainer(payload);\n } catch (error) {\n state.lastPatchError = sanitizeError(error, \"response-patch-failed\");\n }\n return payload;\n };\n const installRequestPatches = () => {\n if (state.requestPatchInstalled === \"1\") {\n restoreRequestPatches();\n }\n state.originals = state.originals || {};\n const originals = state.originals;\n originals.fetch = originals.fetch || window.fetch;\n if (typeof originals.fetch === \"function\") {\n const patchJsonBodyText = (bodyText) => {\n if (typeof bodyText !== \"string\" || !bodyText.trim().startsWith(\"{\")) {\n return { changed: false, body: bodyText };\n }\n const parsed = JSON.parse(bodyText);\n const patched = patchRequestMessage(parsed);\n const patchedBody = JSON.stringify(patched);\n return {\n changed: patched !== parsed || patchedBody !== bodyText,\n body: patchedBody\n };\n };\n window.fetch = async function codexusePowerFetch(input, init) {\n let nextInput = input;\n let nextInit = init;\n try {\n const body = init?.body;\n if (typeof body === \"string\") {\n const patched = patchJsonBodyText(body);\n if (patched.changed) {\n nextInit = { ...(init || {}), body: patched.body };\n }\n } else if (!body && typeof Request !== \"undefined\" && input instanceof Request) {\n const method = String(input.method || \"\").toUpperCase();\n if (method !== \"GET\" && method !== \"HEAD\") {\n const text = await input.clone().text();\n const patched = patchJsonBodyText(text);\n if (patched.changed) {\n nextInput = new Request(input, { body: patched.body });\n }\n }\n }\n } catch {\n }\n return originals.fetch.call(this, nextInput, nextInit);\n };\n }\n originals.responseJson = originals.responseJson || Response.prototype.json;\n if (typeof originals.responseJson === \"function\") {\n Response.prototype.json = async function codexusePowerResponseJson(...args) {\n const payload = await originals.responseJson.apply(this, args);\n return patchResponsePayload(payload);\n };\n }\n originals.webSocketSend = originals.webSocketSend || WebSocket.prototype.send;\n if (typeof originals.webSocketSend === \"function\") {\n WebSocket.prototype.send = function codexusePowerWebSocketSend(data) {\n let nextData = data;\n try {\n if (typeof data === \"string\" && data.trim().startsWith(\"{\")) {\n nextData = JSON.stringify(patchRequestMessage(JSON.parse(data)));\n }\n } catch {\n nextData = data;\n }\n return originals.webSocketSend.call(this, nextData);\n };\n }\n originals.dispatchEvent = originals.dispatchEvent || window.dispatchEvent;\n if (typeof originals.dispatchEvent === \"function\") {\n window.dispatchEvent = function codexusePowerDispatchEvent(event) {\n try {\n const detail = event?.detail;\n if (detail && typeof detail === \"object\") {\n if (detail.request) detail.request = patchRequestMessage(detail.request);\n if (detail.message) detail.message = patchRequestMessage(detail.message);\n }\n } catch {\n }\n return originals.dispatchEvent.call(this, event);\n };\n }\n state.requestPatchInstalled = \"1\";\n return true;\n };\n const restoreRequestPatches = () => {\n const originals = state.originals || {};\n if (originals.fetch) window.fetch = originals.fetch;\n if (originals.responseJson) Response.prototype.json = originals.responseJson;\n if (originals.webSocketSend) WebSocket.prototype.send = originals.webSocketSend;\n if (originals.dispatchEvent) window.dispatchEvent = originals.dispatchEvent;\n state.originals = {};\n state.requestPatchInstalled = null;\n };\n const disabledInstallSelector = [\n \"button:disabled\",\n \"button[aria-disabled='true']\",\n \"button[data-disabled]\",\n \"[role='button'][aria-disabled='true']\",\n \"[role='button'][data-disabled]\",\n \"button.cursor-not-allowed\",\n \"[role='button'].cursor-not-allowed\",\n \"button.pointer-events-none\",\n \"[role='button'].pointer-events-none\"\n ].join(\",\");\n const installButtonCandidates = () => Array.from(new Set(\n Array.from(document.querySelectorAll(disabledInstallSelector))\n .map((node) => node.closest?.(\"button,[role='button']\") || node)\n ));\n const looksInstall = (node) => {\n const text = [\n node?.textContent,\n node?.getAttribute?.(\"aria-label\"),\n node?.getAttribute?.(\"title\"),\n node?.getAttribute?.(\"data-testid\"),\n node?.getAttribute?.(\"data-test-id\")\n ].filter(Boolean).join(\" \");\n return /^\\\\s*(安装|强制安装)/.test(text) || /\\\\b(install|add plugin|enable)\\\\b/i.test(text);\n };\n const installButtonUnlockNodes = (button) => {\n const nodes = [button];\n button.querySelectorAll?.(disabledInstallSelector).forEach((node) => nodes.push(node));\n let parent = button.parentElement;\n for (let depth = 0; parent && depth < 3; depth += 1, parent = parent.parentElement) {\n if (parent.matches?.(disabledInstallSelector)) nodes.push(parent);\n }\n return Array.from(new Set(nodes));\n };\n const patchReactDisabledProps = (node) => {\n try {\n Object.keys(node)\n .filter((key) => key.startsWith(\"__reactProps\"))\n .forEach((key) => {\n const props = node[key];\n if (!props || typeof props !== \"object\") return;\n props.disabled = false;\n props[\"aria-disabled\"] = false;\n props[\"data-disabled\"] = undefined;\n });\n } catch {\n }\n };\n const unlockInstallNode = (node) => {\n if (!(node instanceof HTMLElement)) return false;\n if (node.dataset.codexuseForcePluginInstall !== \"true\") {\n node.dataset.codexuseOriginalDisabled = \"disabled\" in node && node.disabled ? \"true\" : \"false\";\n node.dataset.codexuseOriginalAriaDisabledPresent = node.hasAttribute(\"aria-disabled\") ? \"true\" : \"false\";\n node.dataset.codexuseOriginalAriaDisabled = node.getAttribute(\"aria-disabled\") || \"\";\n node.dataset.codexuseOriginalDataDisabledPresent = node.hasAttribute(\"data-disabled\") ? \"true\" : \"false\";\n node.dataset.codexuseOriginalDataDisabled = node.getAttribute(\"data-disabled\") || \"\";\n node.dataset.codexuseOriginalInertPresent = node.hasAttribute(\"inert\") ? \"true\" : \"false\";\n node.dataset.codexuseOriginalInert = node.getAttribute(\"inert\") || \"\";\n node.dataset.codexuseOriginalClassName = node.getAttribute(\"class\") || \"\";\n node.dataset.codexuseOriginalPointerEvents = node.style.pointerEvents || \"\";\n node.dataset.codexuseOriginalCursor = node.style.cursor || \"\";\n node.dataset.codexuseOriginalOpacity = node.style.opacity || \"\";\n node.dataset.codexuseOriginalTabIndexPresent = node.hasAttribute(\"tabindex\") ? \"true\" : \"false\";\n node.dataset.codexuseOriginalTabIndex = node.getAttribute(\"tabindex\") || \"\";\n }\n if (\"disabled\" in node) node.disabled = false;\n if (\"inert\" in node) node.inert = false;\n node.removeAttribute(\"disabled\");\n node.removeAttribute(\"aria-disabled\");\n node.removeAttribute(\"data-disabled\");\n node.removeAttribute(\"inert\");\n node.classList.remove(\"disabled\", \"cursor-not-allowed\", \"pointer-events-none\", \"opacity-50\");\n node.style.pointerEvents = \"auto\";\n node.style.cursor = \"pointer\";\n node.style.opacity = \"\";\n node.tabIndex = 0;\n patchReactDisabledProps(node);\n node.dataset.codexuseForcePluginInstall = \"true\";\n return true;\n };\n const unlockInstallButtons = () => {\n if (!enabled.forcePluginInstall) return false;\n let changed = false;\n for (const button of installButtonCandidates()) {\n if (!(button instanceof HTMLElement) || !looksInstall(button)) continue;\n for (const node of installButtonUnlockNodes(button)) {\n changed = unlockInstallNode(node) || changed;\n }\n }\n return changed;\n };\n if (typeof state.cleanupForcePluginInstall === \"function\") {\n state.cleanupForcePluginInstall();\n state.cleanupForcePluginInstall = null;\n }\n let forcePluginApplied = false;\n if (enabled.forcePluginInstall) {\n forcePluginApplied = unlockInstallButtons();\n let frame = 0;\n const scheduleUnlock = () => {\n if (frame) return;\n frame = requestAnimationFrame(() => {\n frame = 0;\n forcePluginApplied = unlockInstallButtons() || forcePluginApplied;\n });\n };\n const observer = new MutationObserver(scheduleUnlock);\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n attributeFilter: [\"disabled\", \"aria-disabled\", \"data-disabled\", \"class\", \"style\"]\n });\n state.cleanupForcePluginInstall = () => {\n observer.disconnect();\n if (frame) cancelAnimationFrame(frame);\n document.querySelectorAll(\"[data-codexuse-force-plugin-install='true']\").forEach((node) => {\n if (node instanceof HTMLElement) {\n if (node.dataset.codexuseOriginalDisabled === \"true\") {\n if (\"disabled\" in node) node.disabled = true;\n node.setAttribute(\"disabled\", \"\");\n } else {\n if (\"disabled\" in node) node.disabled = false;\n node.removeAttribute(\"disabled\");\n }\n if (node.dataset.codexuseOriginalAriaDisabledPresent === \"true\") {\n node.setAttribute(\"aria-disabled\", node.dataset.codexuseOriginalAriaDisabled);\n } else {\n node.removeAttribute(\"aria-disabled\");\n }\n if (node.dataset.codexuseOriginalDataDisabledPresent === \"true\") {\n node.setAttribute(\"data-disabled\", node.dataset.codexuseOriginalDataDisabled);\n } else {\n node.removeAttribute(\"data-disabled\");\n }\n if (node.dataset.codexuseOriginalInertPresent === \"true\") {\n node.setAttribute(\"inert\", node.dataset.codexuseOriginalInert);\n if (\"inert\" in node) node.inert = true;\n } else {\n node.removeAttribute(\"inert\");\n if (\"inert\" in node) node.inert = false;\n }\n node.setAttribute(\"class\", node.dataset.codexuseOriginalClassName || \"\");\n node.style.pointerEvents = node.dataset.codexuseOriginalPointerEvents || \"\";\n node.style.cursor = node.dataset.codexuseOriginalCursor || \"\";\n node.style.opacity = node.dataset.codexuseOriginalOpacity || \"\";\n if (node.dataset.codexuseOriginalTabIndexPresent === \"true\") {\n node.setAttribute(\"tabindex\", node.dataset.codexuseOriginalTabIndex);\n } else {\n node.removeAttribute(\"tabindex\");\n }\n delete node.dataset.codexuseOriginalDisabled;\n delete node.dataset.codexuseOriginalAriaDisabledPresent;\n delete node.dataset.codexuseOriginalAriaDisabled;\n delete node.dataset.codexuseOriginalDataDisabledPresent;\n delete node.dataset.codexuseOriginalDataDisabled;\n delete node.dataset.codexuseOriginalInertPresent;\n delete node.dataset.codexuseOriginalInert;\n delete node.dataset.codexuseOriginalClassName;\n delete node.dataset.codexuseOriginalPointerEvents;\n delete node.dataset.codexuseOriginalCursor;\n delete node.dataset.codexuseOriginalOpacity;\n delete node.dataset.codexuseOriginalTabIndexPresent;\n delete node.dataset.codexuseOriginalTabIndex;\n }\n delete node.dataset.codexuseForcePluginInstall;\n });\n };\n }\n const anyRequestPatch = enabled.modelWhitelistUnlock || enabled.pluginMarketplaceUnlock;\n const requestPatchApplied = anyRequestPatch ? installRequestPatches() : false;\n if (!anyRequestPatch && state.requestPatchInstalled === \"1\") restoreRequestPatches();\n const pluginClientPatchApplied = enabled.pluginMarketplaceUnlock || enabled.modelWhitelistUnlock\n ? await installPluginMarketplaceClientPatch()\n : false;\n const modelStatsigPatchApplied = enabled.modelWhitelistUnlock\n ? patchStatsigModelWhitelist()\n : false;\n const modelReactStatePatched = enabled.modelWhitelistUnlock\n ? patchReactModelState()\n : false;\n const pluginFilterPatchApplied = enabled.pluginMarketplaceUnlock\n ? installPluginMarketplaceFilterPatch()\n : false;\n if (!enabled.modelWhitelistUnlock) {\n state.modelStatsigPatchInstalled = null;\n state.modelStatsigPatchError = null;\n state.modelReactStatePatchError = null;\n }\n state.modelStatsigPatchApplied = modelStatsigPatchApplied === true;\n state.modelReactStatePatched = modelReactStatePatched === true;\n if (\n !enabled.pluginMarketplaceUnlock &&\n !enabled.modelWhitelistUnlock &&\n state.pluginMarketplaceClientPatchInstalled === \"1\"\n ) {\n restorePluginMarketplaceClientPatch();\n }\n if (!enabled.pluginMarketplaceUnlock && state.pluginMarketplaceFilterPatchInstalled === \"1\") {\n restorePluginMarketplaceFilterPatch();\n }\n state.pluginMarketplacePatchOwners = pluginClientPatchApplied\n ? {\n modelWhitelistUnlock: enabled.modelWhitelistUnlock,\n pluginMarketplaceUnlock: enabled.pluginMarketplaceUnlock\n }\n : {};\n const appliedAtIso = new Date().toISOString();\n const relay = {\n mode: relayMode,\n profileId: relayProfileId,\n status: relayMode === \"off\" ? \"off\" : relayMode === \"official\" ? \"configured\" : relayProfileId ? \"configured\" : \"missing-key\",\n error: relayMode !== \"off\" && relayMode !== \"official\" && !relayProfileId ? \"relay-profile-missing\" : null\n };\n state.relay = relay;\n state.appliedAt = Date.now();\n state.appliedAtIso = appliedAtIso;\n state.features = {\n modelWhitelistUnlock: feature(\n \"modelWhitelistUnlock\",\n enabled.modelWhitelistUnlock\n ? requestPatchApplied && pluginClientPatchApplied\n : false,\n enabled.modelWhitelistUnlock && !pluginClientPatchApplied\n ? state.pluginMarketplaceClientPatchError || state.modelRequestClientPatchError\n : enabled.modelWhitelistUnlock && state.modelStatsigPatchError\n ? state.modelStatsigPatchError\n : enabled.modelWhitelistUnlock && state.modelReactStatePatchError\n ? state.modelReactStatePatchError\n : null\n ),\n pluginMarketplaceUnlock: feature(\n \"pluginMarketplaceUnlock\",\n enabled.pluginMarketplaceUnlock\n ? requestPatchApplied && pluginClientPatchApplied && pluginFilterPatchApplied\n : false,\n enabled.pluginMarketplaceUnlock && !pluginClientPatchApplied\n ? state.pluginMarketplaceClientPatchError\n : enabled.pluginMarketplaceUnlock && !pluginFilterPatchApplied\n ? state.pluginMarketplaceFilterPatchError\n : null\n ),\n forcePluginInstall: feature(\"forcePluginInstall\", enabled.forcePluginInstall ? forcePluginApplied || !!state.cleanupForcePluginInstall : false)\n };\n window.__codexusePower = state;\n return {\n status: \"applied\",\n reason: null,\n route: route(),\n activeThreadId,\n powerStatus: {\n modelWhitelistUnlock: state.features.modelWhitelistUnlock,\n pluginMarketplaceUnlock: state.features.pluginMarketplaceUnlock,\n forcePluginInstall: state.features.forcePluginInstall,\n relay,\n appliedAt: appliedAtIso\n },\n reloadRequired\n };\n })()`;\n}\n\nfunction normalizeBridgeSnapshot(value: unknown): OfficialCodexBridgeSnapshot {\n if (!value || typeof value !== \"object\") {\n return {\n version: null,\n route: null,\n devToolsUrl: null,\n capabilities: bridgeCapabilitiesUnavailable(),\n activeThreadId: null,\n activeThreadTitle: null,\n activeThreadUpdatedAt: null,\n composerText: null,\n workspacePath: null,\n model: null,\n activityState: \"unknown\",\n qol: bridgeQolStatusDisabled(),\n power: bridgePowerStatusDisabled(),\n relayStatus: relayStatusDisabled(),\n };\n }\n const record = value as Record<string, unknown>;\n const activityState: OfficialCodexBridgeActivityState =\n record.activityState === \"idle\" || record.activityState === \"generating\"\n ? record.activityState\n : \"unknown\";\n const normalizeFeatureStatus = (input: unknown) => {\n if (!input || typeof input !== \"object\") {\n return bridgeFeatureStatus(false, false, null);\n }\n const item = input as Record<string, unknown>;\n return bridgeFeatureStatus(\n item.enabled === true,\n item.applied === true,\n typeof item.version === \"string\" ? item.version : null,\n sanitizeUserFacingError(item.error),\n );\n };\n const normalizeQolStatus = (\n input: unknown,\n ): OfficialCodexQolStatusPayload => {\n if (!input || typeof input !== \"object\") {\n return bridgeQolStatusDisabled();\n }\n const item = input as Record<string, unknown>;\n return {\n wideView: normalizeFeatureStatus(item.wideView),\n scrollRestore: normalizeFeatureStatus(item.scrollRestore),\n conversationTimeline: normalizeFeatureStatus(item.conversationTimeline),\n inCodexStatus: normalizeFeatureStatus(item.inCodexStatus),\n appliedAt: typeof item.appliedAt === \"string\" ? item.appliedAt : null,\n };\n };\n const normalizeRelayStatus = (\n input: unknown,\n ): OfficialCodexRelayStatusPayload => {\n if (!input || typeof input !== \"object\") {\n return relayStatusDisabled();\n }\n const item = input as Record<string, unknown>;\n const mode: OfficialCodexRelayMode =\n item.mode === \"official\" ||\n item.mode === \"responses\" ||\n item.mode === \"chat-completions\"\n ? item.mode\n : \"off\";\n const profileId = normalizeOfficialCodexRelayProfileId(item.profileId);\n return {\n mode,\n profileId:\n mode === \"responses\" || mode === \"chat-completions\" ? profileId : null,\n status:\n item.status === \"configured\" ||\n item.status === \"missing-key\" ||\n item.status === \"degraded\"\n ? item.status\n : \"off\",\n error: sanitizeUserFacingError(item.error),\n };\n };\n const normalizePowerStatus = (\n input: unknown,\n ): OfficialCodexPowerStatusPayload => {\n if (!input || typeof input !== \"object\") {\n return bridgePowerStatusDisabled();\n }\n const item = input as Record<string, unknown>;\n return {\n modelWhitelistUnlock: normalizeFeatureStatus(item.modelWhitelistUnlock),\n pluginMarketplaceUnlock: normalizeFeatureStatus(\n item.pluginMarketplaceUnlock,\n ),\n forcePluginInstall: normalizeFeatureStatus(item.forcePluginInstall),\n relay: normalizeRelayStatus(item.relay),\n appliedAt: typeof item.appliedAt === \"string\" ? item.appliedAt : null,\n };\n };\n const normalizeCapabilities = (\n input: unknown,\n ): OfficialCodexBridgeCapabilitiesPayload => {\n if (!input || typeof input !== \"object\") {\n return bridgeCapabilitiesUnavailable();\n }\n const item = input as Record<string, unknown>;\n return {\n health: item.health === true,\n snapshot: item.snapshot === true,\n draft: item.draft === true,\n qol: item.qol === true,\n power: item.power === true,\n modelWhitelist: item.modelWhitelist === true,\n pluginMarketplace: item.pluginMarketplace === true,\n forcePluginInstall: item.forcePluginInstall === true,\n };\n };\n return {\n version: typeof record.version === \"string\" ? record.version : null,\n route: typeof record.route === \"string\" ? record.route : null,\n devToolsUrl:\n typeof record.devToolsUrl === \"string\" ? record.devToolsUrl : null,\n capabilities: normalizeCapabilities(record.capabilities),\n activeThreadId: normalizeOfficialCodexThreadId(record.activeThreadId),\n activeThreadTitle:\n typeof record.activeThreadTitle === \"string\"\n ? record.activeThreadTitle\n : null,\n activeThreadUpdatedAt:\n typeof record.activeThreadUpdatedAt === \"number\" &&\n Number.isFinite(record.activeThreadUpdatedAt)\n ? record.activeThreadUpdatedAt\n : null,\n composerText:\n typeof record.composerText === \"string\" ? record.composerText : null,\n workspacePath:\n typeof record.workspacePath === \"string\" ? record.workspacePath : null,\n model: typeof record.model === \"string\" ? record.model : null,\n activityState,\n qol: normalizeQolStatus(record.qol),\n power: normalizePowerStatus(record.power),\n relayStatus: normalizeRelayStatus(record.relayStatus),\n };\n}\n\nfunction normalizeDraftPromptInsertionResult(\n value: unknown,\n): OfficialCodexDraftPromptInsertionResult {\n if (!value || typeof value !== \"object\") {\n return {\n status: \"failed\",\n reason: \"invalid-bridge-result\",\n route: null,\n };\n }\n const record = value as Record<string, unknown>;\n const status =\n record.status === \"inserted\" ||\n record.status === \"not-found\" ||\n record.status === \"unavailable\" ||\n record.status === \"failed\"\n ? record.status\n : \"failed\";\n return {\n status,\n reason: sanitizeUserFacingError(record.reason),\n route: typeof record.route === \"string\" ? record.route : null,\n };\n}\n\nfunction normalizeQolScriptResult(\n value: unknown,\n settings: OfficialCodexQolSettingsPayload,\n): OfficialCodexQolScriptResult {\n if (!value || typeof value !== \"object\") {\n return {\n status: \"failed\",\n reason: \"invalid-bridge-result\",\n route: null,\n wideViewEnabled: settings.wideViewEnabled === true,\n wideViewMaxWidth:\n typeof settings.wideViewMaxWidth === \"number\"\n ? settings.wideViewMaxWidth\n : null,\n scrollRestoreEnabled: settings.scrollRestoreEnabled === true,\n conversationTimelineEnabled:\n settings.conversationTimelineEnabled === true,\n inCodexStatusEnabled: settings.inCodexStatusEnabled === true,\n qolStatus: null,\n };\n }\n const record = value as Record<string, unknown>;\n const qolStatus =\n normalizeBridgeSnapshot({ qol: record.qolStatus }).qol ??\n bridgeQolStatusDisabled();\n const degradedFeature = [\n qolStatus.wideView,\n qolStatus.scrollRestore,\n qolStatus.conversationTimeline,\n qolStatus.inCodexStatus,\n ].find((feature) => feature.enabled && feature.applied !== true);\n const status =\n record.status === \"applied\" && !degradedFeature ? \"applied\" : \"failed\";\n return {\n status,\n reason:\n sanitizeUserFacingError(record.reason) ??\n (degradedFeature ? degradedFeature.error ?? \"qol-feature-degraded\" : null),\n route: typeof record.route === \"string\" ? record.route : null,\n wideViewEnabled: record.wideViewEnabled === true,\n wideViewMaxWidth:\n typeof record.wideViewMaxWidth === \"number\" &&\n Number.isFinite(record.wideViewMaxWidth)\n ? record.wideViewMaxWidth\n : null,\n scrollRestoreEnabled: record.scrollRestoreEnabled === true,\n conversationTimelineEnabled: record.conversationTimelineEnabled === true,\n inCodexStatusEnabled: record.inCodexStatusEnabled === true,\n qolStatus,\n };\n}\n\nfunction normalizePowerScriptResult(\n value: unknown,\n): OfficialCodexPowerScriptResult {\n if (!value || typeof value !== \"object\") {\n return {\n status: \"failed\",\n reason: \"invalid-bridge-result\",\n route: null,\n activeThreadId: null,\n powerStatus: null,\n reloadRequired: false,\n };\n }\n const record = value as Record<string, unknown>;\n const powerStatus =\n normalizeBridgeSnapshot({\n power: record.powerStatus,\n }).power ?? bridgePowerStatusDisabled();\n const degradedFeature = [\n powerStatus.modelWhitelistUnlock,\n powerStatus.pluginMarketplaceUnlock,\n powerStatus.forcePluginInstall,\n ].find((feature) => feature.enabled && feature.applied !== true);\n const relayDegraded =\n powerStatus.relay.mode !== \"off\" &&\n powerStatus.relay.status !== \"configured\"\n ? powerStatus.relay\n : null;\n const status =\n record.status === \"applied\" && !degradedFeature && !relayDegraded\n ? \"applied\"\n : \"failed\";\n return {\n status,\n reason:\n sanitizeUserFacingError(record.reason) ??\n degradedFeature?.error ??\n (degradedFeature ? \"power-feature-degraded\" : null) ??\n relayDegraded?.error ??\n (relayDegraded ? `relay-${relayDegraded.status}` : null),\n route: typeof record.route === \"string\" ? record.route : null,\n activeThreadId: normalizeOfficialCodexThreadId(record.activeThreadId),\n powerStatus,\n reloadRequired: record.reloadRequired === true,\n };\n}\n\nfunction normalizeOfficialCodexRelayMode(value: unknown): OfficialCodexRelayMode {\n return value === \"official\" ||\n value === \"responses\" ||\n value === \"chat-completions\"\n ? value\n : \"off\";\n}\n\nfunction normalizeOfficialCodexRelayProfileId(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const relayProfileId = value.trim();\n return /^[A-Za-z0-9][A-Za-z0-9_-]{2,79}$/.test(relayProfileId)\n ? relayProfileId\n : null;\n}\n\nfunction normalizeOfficialCodexPowerSettings(\n value: OfficialCodexPowerSettingsPayload,\n): OfficialCodexPowerSettingsPayload {\n const relayMode = normalizeOfficialCodexRelayMode(value.relayMode);\n const relayProfileId = normalizeOfficialCodexRelayProfileId(\n value.relayProfileId,\n );\n return {\n relayMode,\n relayProfileId:\n (relayMode === \"responses\" || relayMode === \"chat-completions\") &&\n relayProfileId\n ? relayProfileId\n : null,\n modelWhitelistUnlockEnabled: value.modelWhitelistUnlockEnabled === true,\n pluginMarketplaceUnlockEnabled:\n value.pluginMarketplaceUnlockEnabled === true,\n forcePluginInstallEnabled: value.forcePluginInstallEnabled === true,\n };\n}\n\nfunction normalizeOfficialCodexQolSettings(\n value: OfficialCodexQolSettingsPayload,\n): OfficialCodexQolSettingsPayload {\n const actionTargets = Array.isArray(value.actionTargets)\n ? value.actionTargets\n .map((target) => ({\n profileKey:\n typeof target.profileKey === \"string\"\n ? target.profileKey.trim().slice(0, 200)\n : \"\",\n label:\n typeof target.label === \"string\"\n ? target.label.trim().slice(0, 80)\n : \"Account\",\n detail:\n typeof target.detail === \"string\" && target.detail.trim()\n ? target.detail.trim().slice(0, 120)\n : null,\n current: target.current === true,\n eligible: target.eligible !== false,\n }))\n .filter((target) => target.profileKey.length > 0)\n .slice(0, 8)\n : [];\n return {\n wideViewEnabled: value.wideViewEnabled === true,\n wideViewMaxWidth:\n typeof value.wideViewMaxWidth === \"number\" &&\n Number.isFinite(value.wideViewMaxWidth)\n ? Math.max(640, Math.min(2400, value.wideViewMaxWidth))\n : null,\n scrollRestoreEnabled: value.scrollRestoreEnabled === true,\n conversationTimelineEnabled: value.conversationTimelineEnabled === true,\n inCodexStatusEnabled: value.inCodexStatusEnabled !== false,\n handoffChipEnabled: value.handoffChipEnabled !== false,\n actionTargets,\n overlayAutoRollEnabled:\n typeof value.overlayAutoRollEnabled === \"boolean\"\n ? value.overlayAutoRollEnabled\n : null,\n };\n}\n\nfunction hasActiveQolSettings(settings: OfficialCodexQolSettingsPayload): boolean {\n return (\n settings.wideViewEnabled ||\n settings.scrollRestoreEnabled ||\n settings.conversationTimelineEnabled ||\n settings.inCodexStatusEnabled ||\n settings.handoffChipEnabled === false\n );\n}\n\nfunction hasActivePowerSettings(\n settings: OfficialCodexPowerSettingsPayload,\n): boolean {\n return (\n settings.relayMode !== \"off\" ||\n settings.modelWhitelistUnlockEnabled ||\n settings.pluginMarketplaceUnlockEnabled ||\n settings.forcePluginInstallEnabled\n );\n}\n\nfunction hasEnabledBridgePowerRuntime(\n power: OfficialCodexPowerStatusPayload | null | undefined,\n): boolean {\n return (\n power?.modelWhitelistUnlock.enabled === true ||\n power?.pluginMarketplaceUnlock.enabled === true ||\n power?.forcePluginInstall.enabled === true ||\n power?.relay.mode === \"official\" ||\n power?.relay.mode === \"responses\" ||\n power?.relay.mode === \"chat-completions\"\n );\n}\n\nfunction defaultPowerSettings(): OfficialCodexPowerSettingsPayload {\n return {\n relayMode: \"off\",\n relayProfileId: null,\n modelWhitelistUnlockEnabled: false,\n pluginMarketplaceUnlockEnabled: false,\n forcePluginInstallEnabled: false,\n };\n}\n\nfunction normalizeOfficialCodexThreadId(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n let threadId = value.trim();\n try {\n threadId = decodeURIComponent(threadId);\n } catch {\n // Keep raw value if it is not URI encoded.\n }\n if (threadId.toLowerCase().startsWith(\"local:\")) {\n threadId = threadId.slice(\"local:\".length);\n }\n if (\n !threadId ||\n threadId === \"__proto__\" ||\n threadId === \"prototype\" ||\n threadId === \"constructor\" ||\n !/^[A-Za-z0-9_.-]{8,128}$/.test(threadId)\n ) {\n return null;\n }\n return threadId;\n}\n\nfunction resolvePowerModelWhitelistModels(args: {\n settings: OfficialCodexPowerSettingsPayload;\n state: AppState;\n}): string[] {\n if (args.settings.modelWhitelistUnlockEnabled !== true) {\n return [];\n }\n const models = new Set<string>();\n const addModel = (value: unknown): void => {\n if (typeof value !== \"string\") {\n return;\n }\n const model = value.trim();\n if (model) {\n models.add(model);\n }\n };\n if (\n args.settings.relayProfileId &&\n (args.settings.relayMode === \"responses\" ||\n args.settings.relayMode === \"chat-completions\")\n ) {\n addModel(\n args.state.officialCodex.relayProfilesById[args.settings.relayProfileId]\n ?.model,\n );\n }\n return Array.from(models).slice(0, 50);\n}\n\nfunction createBridgePowerSettingsExpression(args: {\n settings: OfficialCodexPowerSettingsPayload;\n modelWhitelistModels: string[];\n}): string {\n const settings = normalizeOfficialCodexPowerSettings(args.settings);\n return JSON.stringify({\n ...settings,\n modelWhitelistModels: args.modelWhitelistModels,\n });\n}\n\nfunction resolveDesiredQolSettings(args: {\n requested?: OfficialCodexQolSettingsPayload | null;\n existing?: OfficialCodexQolSettingsPayload | null;\n}): OfficialCodexQolSettingsPayload | null {\n if (args.requested === undefined) {\n return args.existing ?? null;\n }\n return args.requested && hasActiveQolSettings(args.requested)\n ? normalizeOfficialCodexQolSettings(args.requested)\n : null;\n}\n\nfunction resolveDesiredPowerSettings(args: {\n requested?: OfficialCodexPowerSettingsPayload | null;\n existing?: OfficialCodexPowerSettingsPayload | null;\n}): OfficialCodexPowerSettingsPayload | null {\n if (args.requested === undefined) {\n return args.existing ?? null;\n }\n return args.requested && hasActivePowerSettings(args.requested)\n ? normalizeOfficialCodexPowerSettings(args.requested)\n : null;\n}\n\nfunction createBridgeInstallExpression(): string {\n return `(() => {\n const version = ${JSON.stringify(CODEXUSE_BRIDGE_VERSION)};\n const bindingName = ${JSON.stringify(CODEXUSE_BRIDGE_BINDING_NAME)};\n const now = Date.now();\n const route = () => window.location.pathname + window.location.search + window.location.hash;\n const sanitizeError = (value, fallback = null) => {\n const raw = String(value?.message || value || \"\").replace(/\\\\s+/g, \" \").trim();\n if (!raw) return fallback;\n return raw\n .replace(/\\\\/Users\\\\/[^/\\\\s]+(?:\\\\/[^\\\\s\"'),;]*)?/g, \"~\")\n .replace(/\\\\b(?:file|blob):\\\\/\\\\/[^\\\\s<>\"')]+/gi, \"[redacted-url]\")\n .replace(/\\\\bhttps?:\\\\/\\\\/[^\\\\s<>\"')]+/gi, \"[redacted-url]\")\n .replace(/\\\\blocal(?::|%3A)[A-Za-z0-9_-]{12,}\\\\b/gi, \"local:[redacted-thread]\")\n .replace(/\\\\brollout-[A-Za-z0-9_-]{12,}\\\\.(?:jsonl?|ndjson)\\\\b/g, \"rollout-[redacted]\")\n .replace(/\\\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\\\b/gi, \"[redacted-id]\")\n .replace(/\\\\bBearer\\\\s+[A-Za-z0-9._~+/=-]{8,}/gi, \"Bearer [redacted]\")\n .replace(/\\\\b(?:rk|sess|sk)-[A-Za-z0-9_-]{12,}\\\\b/g, \"[redacted-key]\")\n .replace(/\\\\b(api[_-]?key|token|authorization)([\"'\\\\s:=]+)([^,\\\\s\"']{8,})/gi, \"$1$2[redacted]\")\n .slice(0, 180);\n };\n const previous = window.__codexuseBridgeV2 && typeof window.__codexuseBridgeV2 === \"object\"\n ? window.__codexuseBridgeV2\n : {};\n const state = previous;\n state.version = version;\n state.bindingName = bindingName;\n state.installedAt = typeof state.installedAt === \"number\" ? state.installedAt : now;\n state.lastInstalledAt = now;\n state.commandCounts = state.commandCounts && typeof state.commandCounts === \"object\"\n ? state.commandCounts\n : {};\n state.commands = {\n health: true,\n snapshot: true,\n setDraft: true,\n sendMessage: true,\n applyQol: true,\n applyPower: true\n };\n state.bindingAvailable = typeof window[bindingName] === \"function\";\n state.health = () => ({\n status: typeof window[bindingName] === \"function\" ? \"ok\" : \"degraded\",\n version,\n route: route(),\n\t bindingAvailable: typeof window[bindingName] === \"function\",\n\t installedAt: state.installedAt,\n\t lastInstalledAt: state.lastInstalledAt\n\t });\n\t document.querySelectorAll(\"[data-codexuse-thread-action-hidden='true']\").forEach((node) => {\n\t node.removeAttribute(\"data-codexuse-thread-action-hidden\");\n\t node.removeAttribute(\"aria-hidden\");\n\t });\n\t document.getElementById(\"codexuse-thread-action-safety-style\")?.remove();\n\t state.run = async (command, operation) => {\n const name = typeof command === \"string\" && command ? command : \"unknown\";\n state.lastCommand = name;\n state.lastCommandAt = Date.now();\n state.commandCounts[name] = (Number(state.commandCounts[name]) || 0) + 1;\n try {\n const result = await operation();\n state.lastCommandStatus = result && typeof result === \"object\" && typeof result.status === \"string\"\n ? result.status\n : \"ok\";\n state.lastError = null;\n return result;\n } catch (error) {\n const reason = sanitizeError(error, \"bridge-command-failed\");\n state.lastCommandStatus = \"failed\";\n state.lastError = reason;\n return {\n status: \"failed\",\n reason,\n route: route()\n };\n }\n };\n state.pendingRequests = state.pendingRequests instanceof Map ? state.pendingRequests : new Map();\n state.requestSeq = typeof state.requestSeq === \"number\" ? state.requestSeq : 0;\n state.resolveRequest = (id, result) => {\n const pending = state.pendingRequests.get(id);\n if (!pending) return false;\n state.pendingRequests.delete(id);\n clearTimeout(pending.timer);\n pending.resolve(result === undefined ? null : result);\n return true;\n };\n state.request = (path, payload = null, timeoutMs = 5000) => {\n if (typeof window[bindingName] !== \"function\") {\n return Promise.resolve({ status: \"failed\", reason: \"binding-missing\" });\n }\n const id = \"codexuse-req-\" + Date.now().toString(36) + \"-\" + (++state.requestSeq).toString(36);\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n state.pendingRequests.delete(id);\n resolve({ status: \"failed\", reason: \"request-timeout\" });\n }, timeoutMs);\n state.pendingRequests.set(id, { resolve, timer });\n try {\n window[bindingName](JSON.stringify({\n type: \"codexuse-bridge-request\",\n id,\n path: String(path || \"\"),\n payload: payload === undefined ? null : payload,\n route: route(),\n createdAt: Date.now()\n }));\n } catch (error) {\n state.pendingRequests.delete(id);\n clearTimeout(timer);\n resolve({ status: \"failed\", reason: sanitizeError(error, \"request-send-failed\") });\n }\n });\n };\n state.log = (event, context = null) => {\n if (typeof window[bindingName] !== \"function\") return false;\n try {\n window[bindingName](JSON.stringify({\n type: \"codexuse-log\",\n event: String(event || \"event\").slice(0, 64),\n context: context && typeof context === \"object\" && !Array.isArray(context) ? context : null,\n route: route(),\n createdAt: Date.now()\n }));\n return true;\n } catch {\n return false;\n }\n };\n window.__codexuseBridgeV2 = state;\n window.__codexuseBridge = {\n ...(window.__codexuseBridge && typeof window.__codexuseBridge === \"object\" ? window.__codexuseBridge : {}),\n version,\n installedAt: state.installedAt,\n lastInstalledAt: state.lastInstalledAt,\n bindingAvailable: state.bindingAvailable\n };\n return state.health();\n })()`;\n}\n\nfunction createBridgeHealthExpression(): string {\n return `(() => {\n const bridge = window.__codexuseBridgeV2;\n if (!bridge || typeof bridge.health !== \"function\") {\n return {\n status: \"failed\",\n reason: \"bridge-health-missing\",\n route: window.location.pathname + window.location.search + window.location.hash,\n bindingAvailable: false\n };\n }\n return bridge.health();\n })()`;\n}\n\nfunction createBridgeCommandExpression(\n command:\n | \"health\"\n | \"snapshot\"\n | \"setDraft\"\n | \"sendMessage\"\n | \"openThread\"\n | \"applyQol\"\n | \"applyPower\",\n expression: string,\n): string {\n return `(async () => {\n const operation = async () => await (${expression});\n const bridge = window.__codexuseBridgeV2;\n if (!bridge || typeof bridge.run !== \"function\") {\n return {\n status: \"failed\",\n reason: \"bridge-command-runtime-missing\",\n route: window.location.pathname + window.location.search + window.location.hash\n };\n }\n const health = typeof bridge.health === \"function\" ? bridge.health() : null;\n if (!health || health.status !== \"ok\" || health.bindingAvailable !== true) {\n return {\n status: \"failed\",\n reason: health?.bindingAvailable === true ? \"bridge-health-degraded\" : \"bridge-binding-missing\",\n route: window.location.pathname + window.location.search + window.location.hash\n };\n }\n return await bridge.run(${JSON.stringify(command)}, operation);\n })()`;\n}\n\nfunction cdpRemoteObjectValue(response: unknown): unknown {\n if (!response || typeof response !== \"object\") {\n return null;\n }\n const result = (response as Record<string, unknown>).result;\n const remoteObject =\n result && typeof result === \"object\"\n ? (result as Record<string, unknown>).result\n : null;\n const exceptionDetails =\n result && typeof result === \"object\"\n ? (result as Record<string, unknown>).exceptionDetails\n : null;\n if (exceptionDetails && typeof exceptionDetails === \"object\") {\n const exception = (exceptionDetails as Record<string, unknown>).exception;\n const text = (exceptionDetails as Record<string, unknown>).text;\n const description =\n exception && typeof exception === \"object\"\n ? (exception as Record<string, unknown>).description\n : null;\n throw new Error(\n sanitizeUserFacingError(description ?? text) ?? \"bridge-script-error\",\n );\n }\n if (\n remoteObject &&\n typeof remoteObject === \"object\" &&\n (remoteObject as Record<string, unknown>).subtype === \"error\"\n ) {\n throw new Error(\n sanitizeUserFacingError(\n (remoteObject as Record<string, unknown>).description ??\n (remoteObject as Record<string, unknown>).value,\n ) ?? \"bridge-script-error\",\n );\n }\n return remoteObject && typeof remoteObject === \"object\"\n ? ((remoteObject as Record<string, unknown>).value ?? null)\n : null;\n}\n\nfunction normalizeBridgeHealth(value: unknown): {\n ok: boolean;\n reason: string | null;\n} {\n if (!value || typeof value !== \"object\") {\n return { ok: false, reason: \"invalid-bridge-health\" };\n }\n const record = value as Record<string, unknown>;\n const status = typeof record.status === \"string\" ? record.status : \"failed\";\n const bindingAvailable = record.bindingAvailable === true;\n if (status === \"ok\" && bindingAvailable) {\n return { ok: true, reason: null };\n }\n return {\n ok: false,\n reason:\n sanitizeUserFacingError(record.reason) ??\n (bindingAvailable ? `bridge-health-${status}` : \"bridge-binding-missing\"),\n };\n}\n\nfunction isBridgeInstallDrift(value: unknown): boolean {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const reason = (value as Record<string, unknown>).reason;\n return (\n reason === \"bridge-command-runtime-missing\" ||\n reason === \"bridge-health-missing\" ||\n reason === \"bridge-health-degraded\" ||\n reason === \"bridge-binding-missing\"\n );\n}\n\nasync function runCdpCommandSequence(\n debuggerUrl: string,\n commands: CdpCommand[],\n timeoutMs = CODEX_CDP_REQUEST_TIMEOUT_MS,\n): Promise<unknown[]> {\n return await new Promise<unknown[]>((resolve, reject) => {\n const ws = new WebSocket(debuggerUrl);\n const results: unknown[] = [];\n let commandIndex = 0;\n let requestId = 0;\n let currentCommand: CdpCommand | null = null;\n const timeout = setTimeout(() => {\n ws.close();\n reject(new Error(\"cdp-command-timeout\"));\n }, timeoutMs);\n const settle = (fn: () => void) => {\n clearTimeout(timeout);\n try {\n ws.close();\n } catch {\n // Ignore close failures after a completed CDP request.\n }\n fn();\n };\n const sendNext = () => {\n currentCommand = commands[commandIndex] ?? null;\n if (!currentCommand) {\n settle(() => resolve(results));\n return;\n }\n requestId += 1;\n ws.send(\n JSON.stringify({\n id: requestId,\n method: currentCommand.method,\n params: currentCommand.params,\n }),\n );\n };\n\n ws.addEventListener(\"open\", () => {\n sendNext();\n }, { once: true });\n ws.addEventListener(\"error\", () => {\n settle(() => reject(new Error(\"cdp-websocket-error\")));\n }, { once: true });\n ws.addEventListener(\"message\", (event) => {\n let message: Record<string, unknown>;\n try {\n const text =\n typeof event.data === \"string\"\n ? event.data\n : event.data && typeof event.data === \"object\"\n ? String(event.data)\n : \"\";\n if (!text) {\n return;\n }\n message = JSON.parse(text) as Record<string, unknown>;\n } catch {\n return;\n }\n if (message.id !== requestId) {\n return;\n }\n if (message.error && !currentCommand?.optional) {\n settle(() =>\n reject(new Error(`cdp-${currentCommand?.method ?? \"command\"}-error`)),\n );\n return;\n }\n results.push(message);\n commandIndex += 1;\n sendNext();\n });\n });\n}\n\nasync function verifyCdpBindingRoundTrip(\n debuggerUrl: string,\n): Promise<boolean> {\n const nonce = randomUUID();\n const expression = `(() => {\n const binding = window[${JSON.stringify(CODEXUSE_BRIDGE_BINDING_NAME)}];\n if (typeof binding !== \"function\") return false;\n binding(${JSON.stringify(\n JSON.stringify({ type: \"codexuse-health-echo\", id: nonce }),\n )});\n return true;\n })()`;\n return await new Promise<boolean>((resolve) => {\n const ws = new WebSocket(debuggerUrl);\n let settled = false;\n let evaluateSent = false;\n const timeout = setTimeout(() => {\n settle(false);\n }, CODEX_CDP_REQUEST_TIMEOUT_MS);\n const settle = (ok: boolean) => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timeout);\n try {\n ws.close();\n } catch {\n // Ignore close failures after probe completion.\n }\n resolve(ok);\n };\n const send = (id: number, method: string, params: Record<string, unknown>) => {\n ws.send(JSON.stringify({ id, method, params }));\n };\n ws.addEventListener(\n \"open\",\n () => {\n send(1, \"Runtime.enable\", {});\n },\n { once: true },\n );\n ws.addEventListener(\n \"error\",\n () => {\n settle(false);\n },\n { once: true },\n );\n ws.addEventListener(\"message\", (event) => {\n let message: Record<string, unknown>;\n try {\n const text =\n typeof event.data === \"string\" ? event.data : String(event.data ?? \"\");\n if (!text) {\n return;\n }\n message = JSON.parse(text) as Record<string, unknown>;\n } catch {\n return;\n }\n if (message.id === 1) {\n send(2, \"Runtime.removeBinding\", {\n name: CODEXUSE_BRIDGE_BINDING_NAME,\n });\n return;\n }\n if (message.id === 2) {\n send(3, \"Runtime.addBinding\", {\n name: CODEXUSE_BRIDGE_BINDING_NAME,\n });\n return;\n }\n if (message.id === 3 && !evaluateSent) {\n evaluateSent = true;\n send(4, \"Runtime.evaluate\", {\n expression,\n returnByValue: true,\n awaitPromise: true,\n allowUnsafeEvalBlockedByCSP: true,\n });\n return;\n }\n if (message.id === 4) {\n let value: unknown;\n try {\n value = cdpRemoteObjectValue(message);\n } catch {\n settle(false);\n return;\n }\n if (value !== true) {\n settle(false);\n }\n return;\n }\n if (message.method !== \"Runtime.bindingCalled\") {\n return;\n }\n const params =\n message.params && typeof message.params === \"object\"\n ? (message.params as Record<string, unknown>)\n : {};\n if (params.name !== CODEXUSE_BRIDGE_BINDING_NAME) {\n return;\n }\n try {\n const payload =\n typeof params.payload === \"string\"\n ? (JSON.parse(params.payload) as Record<string, unknown>)\n : {};\n if (payload.id === nonce) {\n settle(true);\n }\n } catch {\n // Ignore unrelated binding payloads.\n }\n });\n });\n}\n\nasync function evaluateCdpExpression(\n debuggerUrl: string,\n expression: string,\n): Promise<unknown> {\n const [response] = await runCdpCommandSequence(debuggerUrl, [\n {\n method: \"Runtime.evaluate\",\n params: {\n expression,\n returnByValue: true,\n awaitPromise: true,\n allowUnsafeEvalBlockedByCSP: true,\n },\n },\n ]);\n return cdpRemoteObjectValue(response);\n}\n\nasync function readCurrentBridgeNewDocumentScriptId(\n debuggerUrl: string,\n): Promise<string | null> {\n try {\n const value = await evaluateCdpExpression(\n debuggerUrl,\n `(() => {\n const id = window.__codexuseBridgeV2?.cdpNewDocumentScriptId;\n return typeof id === \"string\" && id ? id : null;\n })()`,\n );\n return typeof value === \"string\" && value ? value : null;\n } catch {\n return null;\n }\n}\n\nasync function rememberCurrentBridgeNewDocumentScriptId(\n debuggerUrl: string,\n newDocumentScriptId: string | null,\n): Promise<void> {\n if (!newDocumentScriptId) {\n return;\n }\n try {\n await evaluateCdpExpression(\n debuggerUrl,\n `(() => {\n const bridge = window.__codexuseBridgeV2;\n if (bridge && typeof bridge === \"object\") {\n bridge.cdpNewDocumentScriptId = ${JSON.stringify(newDocumentScriptId)};\n }\n return true;\n })()`,\n );\n } catch {\n // Cache still covers this backend process; page memory is only restart recovery.\n }\n}\n\nconst qolNewDocumentScriptIds = new Map<string, string>();\n\nasync function readCurrentQolNewDocumentScriptId(\n debuggerUrl: string,\n): Promise<string | null> {\n try {\n const value = await evaluateCdpExpression(\n debuggerUrl,\n `(() => {\n const id = window.__codexuseQol?.cdpNewDocumentScriptId;\n return typeof id === \"string\" && id ? id : null;\n })()`,\n );\n return typeof value === \"string\" && value ? value : null;\n } catch {\n return null;\n }\n}\n\n// Re-run the QOL expression at document start so the overlay reappears as\n// soon as a page loads, instead of staying gone until the next backend poll.\nasync function registerQolNewDocumentScript(\n debuggerUrl: string,\n expression: string,\n): Promise<void> {\n try {\n const staleId =\n qolNewDocumentScriptIds.get(debuggerUrl) ??\n (await readCurrentQolNewDocumentScriptId(debuggerUrl));\n const source = `(() => {\n let attempts = 0;\n const run = () => {\n if (!document.body && attempts < 120) {\n attempts += 1;\n requestAnimationFrame(run);\n return;\n }\n ${expression}\n };\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", run, { once: true });\n } else {\n run();\n }\n })();`;\n const commands: CdpCommand[] = [\n { method: \"Page.enable\", params: {}, optional: true },\n ];\n if (staleId) {\n commands.push({\n method: \"Page.removeScriptToEvaluateOnNewDocument\",\n params: { identifier: staleId },\n optional: true,\n });\n }\n commands.push({\n method: \"Page.addScriptToEvaluateOnNewDocument\",\n params: { source },\n });\n commands.push({\n method: \"Runtime.evaluate\",\n params: {\n expression: source,\n returnByValue: true,\n awaitPromise: true,\n allowUnsafeEvalBlockedByCSP: true,\n },\n optional: true,\n });\n const results = await runCdpCommandSequence(\n debuggerUrl,\n commands,\n CODEX_CDP_REQUEST_TIMEOUT_MS,\n );\n let identifier: string | null = null;\n for (const response of results) {\n const result =\n response && typeof response === \"object\"\n ? (response as Record<string, unknown>).result\n : null;\n if (result && typeof result === \"object\") {\n const id = (result as Record<string, unknown>).identifier;\n if (typeof id === \"string\" && id) {\n identifier = id;\n }\n }\n }\n if (identifier) {\n qolNewDocumentScriptIds.set(debuggerUrl, identifier);\n await evaluateCdpExpression(\n debuggerUrl,\n `(() => {\n const state = window.__codexuseQol;\n if (state && typeof state === \"object\") {\n state.cdpNewDocumentScriptId = ${JSON.stringify(identifier)};\n }\n return true;\n })()`,\n );\n }\n } catch {\n // Best effort; the regular evaluate path still applies the overlay.\n }\n}\n\nasync function ensureOfficialCodexBridgeInstalled(\n debuggerUrl: string,\n force = false,\n): Promise<void> {\n const cached = bridgeInstallCache.get(debuggerUrl);\n if (!force && cached && cached.expiresAt > Date.now()) {\n return;\n }\n const staleNewDocumentScriptId =\n cached?.newDocumentScriptId ??\n (await readCurrentBridgeNewDocumentScriptId(debuggerUrl));\n const source = createBridgeInstallExpression();\n const commands: CdpCommand[] = [\n { method: \"Runtime.enable\", params: {} },\n { method: \"Page.enable\", params: {}, optional: true },\n ];\n if (staleNewDocumentScriptId) {\n commands.push({\n method: \"Page.removeScriptToEvaluateOnNewDocument\",\n params: { identifier: staleNewDocumentScriptId },\n optional: true,\n });\n }\n commands.push(\n {\n method: \"Runtime.removeBinding\",\n params: { name: CODEXUSE_BRIDGE_BINDING_NAME },\n optional: true,\n },\n {\n method: \"Runtime.addBinding\",\n params: { name: CODEXUSE_BRIDGE_BINDING_NAME },\n },\n {\n method: \"Page.addScriptToEvaluateOnNewDocument\",\n params: { source },\n },\n {\n method: \"Runtime.evaluate\",\n params: {\n expression: source,\n returnByValue: true,\n awaitPromise: true,\n allowUnsafeEvalBlockedByCSP: true,\n },\n },\n );\n const results = await runCdpCommandSequence(\n debuggerUrl,\n commands,\n CODEX_CDP_REQUEST_TIMEOUT_MS * 2,\n );\n const installHealth = normalizeBridgeHealth(\n cdpRemoteObjectValue(results[results.length - 1]),\n );\n if (!installHealth.ok) {\n bridgeInstallCache.delete(debuggerUrl);\n throw new Error(installHealth.reason ?? \"bridge-install-health-failed\");\n }\n let newDocumentScriptId: string | null = null;\n for (const response of results) {\n const result =\n response && typeof response === \"object\"\n ? (response as Record<string, unknown>).result\n : null;\n if (result && typeof result === \"object\") {\n const identifier = (result as Record<string, unknown>).identifier;\n if (typeof identifier === \"string\" && identifier) {\n newDocumentScriptId = identifier;\n }\n }\n }\n bridgeInstallCache.set(debuggerUrl, {\n expiresAt: Date.now() + CODEXUSE_BRIDGE_INSTALL_TTL_MS,\n newDocumentScriptId,\n });\n await rememberCurrentBridgeNewDocumentScriptId(\n debuggerUrl,\n newDocumentScriptId,\n );\n}\n\nasync function evaluateOfficialCodexBridgeCommand(\n debuggerUrl: string,\n command: Parameters<typeof createBridgeCommandExpression>[0],\n expression: string,\n forceInstall = false,\n): Promise<unknown> {\n await ensureOfficialCodexBridgeInstalled(debuggerUrl, forceInstall);\n const value = await evaluateCdpExpression(\n debuggerUrl,\n createBridgeCommandExpression(command, expression),\n );\n if (!forceInstall && isBridgeInstallDrift(value)) {\n bridgeInstallCache.delete(debuggerUrl);\n await ensureOfficialCodexBridgeInstalled(debuggerUrl, true);\n return await evaluateCdpExpression(\n debuggerUrl,\n createBridgeCommandExpression(command, expression),\n );\n }\n return value;\n}\n\nfunction startOfficialCodexBridgeActionListener(args: {\n profileName: string;\n cdpPort: number | null;\n debuggerUrl: string;\n}): void {\n const profileName = args.profileName.trim();\n if (!profileName || bridgeActionListeners.has(args.debuggerUrl)) {\n return;\n }\n let ws: CdpWebSocket;\n try {\n ws = new WebSocket(args.debuggerUrl);\n } catch {\n return;\n }\n bridgeActionListeners.set(args.debuggerUrl, ws);\n let nextId = 1;\n const close = () => {\n if (bridgeActionListeners.get(args.debuggerUrl) === ws) {\n bridgeActionListeners.delete(args.debuggerUrl);\n }\n };\n const send = (method: string, params: Record<string, unknown>) => {\n try {\n ws.send(JSON.stringify({ id: nextId++, method, params }));\n } catch {\n close();\n }\n };\n ws.addEventListener(\n \"open\",\n () => {\n send(\"Runtime.enable\", {});\n send(\"Runtime.removeBinding\", {\n name: CODEXUSE_BRIDGE_BINDING_NAME,\n });\n send(\"Runtime.addBinding\", {\n name: CODEXUSE_BRIDGE_BINDING_NAME,\n });\n },\n { once: true },\n );\n ws.addEventListener(\"error\", close, { once: true });\n ws.addEventListener(\"close\", close, { once: true });\n ws.addEventListener(\"message\", (event) => {\n let message: Record<string, unknown>;\n try {\n const text =\n typeof event.data === \"string\" ? event.data : String(event.data ?? \"\");\n if (!text) {\n return;\n }\n message = JSON.parse(text) as Record<string, unknown>;\n } catch {\n return;\n }\n if (message.method !== \"Runtime.bindingCalled\") {\n return;\n }\n const params =\n message.params && typeof message.params === \"object\"\n ? (message.params as Record<string, unknown>)\n : {};\n if (params.name !== CODEXUSE_BRIDGE_BINDING_NAME) {\n return;\n }\n try {\n const payload =\n typeof params.payload === \"string\"\n ? (JSON.parse(params.payload) as Record<string, unknown>)\n : {};\n if (payload.type === \"codexuse-log\") {\n const logHandler = officialCodexBridgeLogHandler;\n if (!logHandler) {\n return;\n }\n const event =\n typeof payload.event === \"string\" && payload.event.trim()\n ? payload.event.trim().slice(0, 64)\n : \"event\";\n logHandler({\n event,\n context: sanitizeBridgeLogContext(payload.context),\n sourceProfileName: profileName,\n route:\n typeof payload.route === \"string\"\n ? sanitizeBridgeActionRoute(payload.route)\n : null,\n });\n return;\n }\n if (payload.type === \"codexuse-bridge-request\") {\n const requestId =\n typeof payload.id === \"string\" && payload.id.trim()\n ? payload.id.trim().slice(0, 96)\n : \"\";\n if (!requestId || !rememberBridgeActionId(requestId)) {\n return;\n }\n const path =\n typeof payload.path === \"string\"\n ? payload.path.trim().slice(0, 64)\n : \"\";\n const requestHandler = officialCodexBridgeRequestHandler;\n void (async () => {\n let result: unknown;\n if (!path) {\n result = { status: \"failed\", reason: \"missing-path\" };\n } else if (!requestHandler) {\n result = { status: \"failed\", reason: \"no-request-handler\" };\n } else {\n try {\n result = await requestHandler({\n path,\n payload: payload.payload ?? null,\n sourceProfileName: profileName,\n });\n } catch (error) {\n result = {\n status: \"failed\",\n reason: sanitizeUserFacingError(error) ?? \"request-failed\",\n };\n }\n }\n let serialized: string;\n try {\n serialized = JSON.stringify(result ?? null) ?? \"null\";\n } catch {\n serialized = JSON.stringify({\n status: \"failed\",\n reason: \"unserializable-result\",\n });\n }\n send(\"Runtime.evaluate\", {\n expression:\n \"window.__codexuseBridgeV2 && typeof window.__codexuseBridgeV2.resolveRequest === \\\"function\\\" && window.__codexuseBridgeV2.resolveRequest(\" +\n JSON.stringify(requestId) +\n \", \" +\n serialized +\n \")\",\n returnByValue: true,\n });\n })();\n return;\n }\n if (payload.type !== \"codexuse-action-request\") {\n return;\n }\n const id =\n typeof payload.id === \"string\" && payload.id.trim()\n ? payload.id.trim().slice(0, 96)\n : \"\";\n if (!id || !rememberBridgeActionId(id)) {\n return;\n }\n const action: OfficialCodexBridgeActionName | null =\n payload.action === \"continue\" ||\n payload.action === \"switch\" ||\n payload.action === \"auto-roll\" ||\n payload.action === \"setting\"\n ? payload.action\n : null;\n if (!action) {\n return;\n }\n const settingKey: OfficialCodexBridgeSettingKey | null =\n payload.settingKey === \"autoRoll\" ||\n payload.settingKey === \"wideView\" ||\n payload.settingKey === \"scrollRestore\" ||\n payload.settingKey === \"conversationTimeline\" ||\n payload.settingKey === \"handoffChip\"\n ? payload.settingKey\n : null;\n const settingValue =\n typeof payload.settingValue === \"boolean\"\n ? payload.settingValue\n : null;\n if (action === \"setting\" && (!settingKey || settingValue === null)) {\n return;\n }\n const targetProfileName =\n typeof payload.targetProfileName === \"string\" &&\n payload.targetProfileName.trim()\n ? payload.targetProfileName.trim().slice(0, 160)\n : null;\n const targetProfileKey =\n typeof payload.targetProfileKey === \"string\" &&\n payload.targetProfileKey.trim()\n ? payload.targetProfileKey.trim().slice(0, 200)\n : null;\n const targetProfileKeyHash =\n typeof payload.targetProfileKeyHash === \"string\" &&\n payload.targetProfileKeyHash.trim()\n ? payload.targetProfileKeyHash.trim().slice(0, 24)\n : null;\n const request: OfficialCodexBridgeActionRequest = {\n id,\n action,\n sourceProfileName: profileName,\n targetProfileName,\n targetProfileKey,\n targetProfileKeyHash,\n settingKey,\n settingValue,\n cdpPort: args.cdpPort,\n route:\n typeof payload.route === \"string\"\n ? sanitizeBridgeActionRoute(payload.route)\n : null,\n activeThreadId: normalizeOfficialCodexThreadId(payload.activeThreadId),\n createdAt:\n typeof payload.createdAt === \"number\" &&\n Number.isFinite(payload.createdAt)\n ? payload.createdAt\n : Date.now(),\n };\n const handler = officialCodexBridgeActionHandler;\n if (!handler) {\n return;\n }\n void Promise.resolve(handler(request)).catch((error) => {\n console.warn(\"[official-codex-bridge-action] Handler failed.\", {\n action: request.action,\n error: sanitizeUserFacingError(error) ?? \"handler-failed\",\n });\n });\n } catch {\n // Ignore malformed page-side action payloads.\n }\n });\n}\n\nasync function reloadOfficialCodexBridgePage(\n debuggerUrl: string,\n): Promise<boolean> {\n try {\n await evaluateCdpExpression(\n debuggerUrl,\n \"window.setTimeout(() => window.location.reload(), 0); true\",\n );\n bridgeInstallCache.delete(debuggerUrl);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function probeOfficialCodexBridge(\n instance: OfficialCodexManagedInstanceState,\n forceInstall = false,\n): Promise<OfficialCodexBridgeState> {\n const checkedAt = Date.now();\n if (!instance.cdpPort) {\n return bridgeStateUnavailable();\n }\n try {\n const targets = await readCdpTargets(instance.cdpPort);\n const target = pickCodexCdpTarget(targets);\n if (!target?.webSocketDebuggerUrl) {\n return bridgeStateUnhealthy(\n instance.cdpPort,\n checkedAt,\n \"cdp-target-not-found\",\n );\n }\n const healthValue = await evaluateOfficialCodexBridgeCommand(\n target.webSocketDebuggerUrl,\n \"health\",\n createBridgeHealthExpression(),\n forceInstall,\n );\n const health = normalizeBridgeHealth(healthValue);\n if (!health.ok) {\n return bridgeStateUnhealthy(\n instance.cdpPort,\n checkedAt,\n health.reason ?? \"bridge-health-failed\",\n );\n }\n if (!(await verifyCdpBindingRoundTrip(target.webSocketDebuggerUrl))) {\n bridgeInstallCache.delete(target.webSocketDebuggerUrl);\n return bridgeStateUnhealthy(\n instance.cdpPort,\n checkedAt,\n \"bridge-binding-roundtrip-failed\",\n );\n }\n startOfficialCodexBridgeActionListener({\n profileName: instance.profileName,\n cdpPort: instance.cdpPort,\n debuggerUrl: target.webSocketDebuggerUrl,\n });\n const value = await evaluateOfficialCodexBridgeCommand(\n target.webSocketDebuggerUrl,\n \"snapshot\",\n createBridgeSnapshotExpression(),\n false,\n );\n const snapshot = normalizeBridgeSnapshot(value);\n snapshot.devToolsUrl = buildCdpDevToolsUrl(instance.cdpPort, target);\n const threadRecord =\n instance.profileHome && snapshot.activeThreadId\n ? await findOfficialCodexThreadRecord(\n instance.profileHome,\n snapshot.activeThreadId,\n )\n : null;\n if (threadRecord?.title) {\n snapshot.activeThreadTitle = \"Active conversation\";\n }\n if (threadRecord?.cwd) {\n snapshot.workspacePath = threadRecord.cwd;\n }\n if (\n threadRecord?.updatedAtMs !== null &&\n threadRecord?.updatedAtMs !== undefined\n ) {\n snapshot.activeThreadUpdatedAt = threadRecord.updatedAtMs;\n } else if (threadRecord?.updatedAt) {\n const recordUpdatedAtMs = Date.parse(threadRecord.updatedAt);\n if (Number.isFinite(recordUpdatedAtMs)) {\n snapshot.activeThreadUpdatedAt = recordUpdatedAtMs;\n }\n }\n return bridgeStateHealthy(instance.cdpPort, checkedAt, snapshot);\n } catch (error) {\n return bridgeStateUnhealthy(\n instance.cdpPort,\n checkedAt,\n sanitizeUserFacingError(error) ?? \"bridge-probe-failed\",\n );\n }\n}\n\nasync function reapplyDesiredBridgeSettings(\n instance: OfficialCodexManagedInstanceState,\n bridge: OfficialCodexBridgeState,\n): Promise<OfficialCodexBridgeState> {\n const shouldClearPowerRuntime =\n !instance.desiredPowerSettings &&\n hasEnabledBridgePowerRuntime(bridge.bridgePower);\n if (\n bridge.bridgeStatus !== \"healthy\" ||\n !instance.cdpPort ||\n (!instance.desiredQolSettings &&\n !instance.desiredPowerSettings &&\n !shouldClearPowerRuntime)\n ) {\n return bridge;\n }\n try {\n const targets = await readCdpTargets(instance.cdpPort);\n const target = pickCodexCdpTarget(targets);\n if (!target?.webSocketDebuggerUrl) {\n return bridge;\n }\n let next = { ...bridge };\n if (instance.desiredQolSettings) {\n const qolSettings = normalizeOfficialCodexQolSettings(\n instance.desiredQolSettings,\n );\n const qolExpression = createBridgeApplyQolExpression(qolSettings);\n const qolValue = await evaluateOfficialCodexBridgeCommand(\n target.webSocketDebuggerUrl,\n \"applyQol\",\n qolExpression,\n false,\n );\n await registerQolNewDocumentScript(\n target.webSocketDebuggerUrl,\n qolExpression,\n );\n const qolResult = normalizeQolScriptResult(qolValue, qolSettings);\n if (qolResult.qolStatus) {\n next = {\n ...next,\n bridgeQol: qolResult.qolStatus,\n };\n }\n }\n if (instance.desiredPowerSettings || shouldClearPowerRuntime) {\n const powerSettings = normalizeOfficialCodexPowerSettings(\n instance.desiredPowerSettings ?? defaultPowerSettings(),\n );\n const state = await getAppState();\n const modelWhitelistModels = resolvePowerModelWhitelistModels({\n settings: powerSettings,\n state,\n });\n const powerValue = await evaluateOfficialCodexBridgeCommand(\n target.webSocketDebuggerUrl,\n \"applyPower\",\n createBridgeApplyPowerExpression(\n powerSettings,\n createBridgePowerSettingsExpression({\n settings: powerSettings,\n modelWhitelistModels,\n }),\n ),\n false,\n );\n const powerResult = normalizePowerScriptResult(powerValue);\n if (powerResult.powerStatus) {\n next = {\n ...next,\n bridgePower: powerResult.powerStatus,\n bridgeRelayStatus: powerResult.powerStatus.relay,\n };\n }\n if (powerResult.reloadRequired) {\n const reloadStarted = await reloadOfficialCodexBridgePage(\n target.webSocketDebuggerUrl,\n );\n if (reloadStarted) {\n const reloaded = await waitForBridgeStateAfterReload({\n ...instance,\n ...next,\n });\n next = {\n ...next,\n ...reloaded,\n };\n } else {\n next = {\n ...next,\n bridgeError: \"bridge-reload-failed\",\n };\n }\n }\n }\n return next;\n } catch (error) {\n return {\n ...bridge,\n bridgeError: sanitizeUserFacingError(error) ?? \"bridge-reapply-failed\",\n };\n }\n}\n\nasync function refreshBridgeStateIfNeeded(\n instance: OfficialCodexManagedInstanceState,\n running: boolean,\n force = false,\n reapplyDesired = false,\n): Promise<OfficialCodexBridgeState> {\n if (!running || !instance.cdpPort) {\n return bridgeStateUnavailable();\n }\n const checkedAt = instance.bridgeLastCheckedAt;\n if (\n !force &&\n checkedAt &&\n Date.now() - checkedAt < CODEX_BRIDGE_PROBE_TTL_MS\n ) {\n return bridgeStateForStoredInstance(instance, true);\n }\n const bridge = await probeOfficialCodexBridge(instance, force);\n return reapplyDesired\n ? await reapplyDesiredBridgeSettings(instance, bridge)\n : bridge;\n}\n\nasync function waitForBridgeStateAfterLaunch(\n instance: OfficialCodexManagedInstanceState,\n): Promise<OfficialCodexBridgeState> {\n const deadline = Date.now() + CODEX_BRIDGE_LAUNCH_WAIT_MS;\n let latest = await refreshBridgeStateIfNeeded(instance, true, true, true);\n // A freshly relaunched window's CDP port is not listening immediately, so the\n // first probe fails with a connection error (not \"cdp-target-not-found\"). Keep\n // polling until the bridge is healthy or the deadline passes — otherwise the\n // post-launch handoff (reopen thread + auto-send) runs before the window is up.\n while (latest.bridgeStatus !== \"healthy\" && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n latest = await refreshBridgeStateIfNeeded(\n {\n ...instance,\n ...latest,\n },\n true,\n true,\n true,\n );\n }\n return latest;\n}\n\n// Poll a freshly launched window's CDP endpoint until a page target is\n// reachable. readCdpTargets throws ConnectionRefused until the new process binds\n// its debug port, so swallow errors and retry until the deadline.\nasync function waitForCdpTargetAfterLaunch(\n cdpPort: number,\n): Promise<ReturnType<typeof pickCodexCdpTarget>> {\n const deadline = Date.now() + CODEX_BRIDGE_LAUNCH_WAIT_MS;\n for (;;) {\n try {\n const target = pickCodexCdpTarget(await readCdpTargets(cdpPort));\n if (target?.webSocketDebuggerUrl) {\n return target;\n }\n } catch {\n // CDP port not listening yet; keep polling until the deadline.\n }\n if (Date.now() >= deadline) {\n return null;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n}\n\nasync function waitForBridgeStateAfterReload(\n instance: OfficialCodexManagedInstanceState,\n): Promise<OfficialCodexBridgeState> {\n const deadline = Date.now() + CODEX_BRIDGE_LAUNCH_WAIT_MS;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n let latest = await refreshBridgeStateIfNeeded(instance, true, true, true);\n while (latest.bridgeStatus !== \"healthy\" && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n latest = await refreshBridgeStateIfNeeded(\n {\n ...instance,\n ...latest,\n },\n true,\n true,\n true,\n );\n }\n return latest;\n}\n\nexport async function recordOfficialCodexActivity(\n input: OfficialCodexActivityInput,\n): Promise<void> {\n const now = new Date();\n const entry: AutoRollActivityEntry = {\n id: `${now.getTime().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,\n at: now.toISOString(),\n kind: input.kind,\n status: input.status,\n reason: input.reason ?? null,\n decisionId: input.decisionId ?? null,\n profileName: input.profileName ?? null,\n sourceProfileName: input.sourceProfileName ?? null,\n targetProfileName: input.targetProfileName ?? null,\n remainingPercent: input.remainingPercent ?? null,\n threshold: input.threshold ?? null,\n snapshotAgeMs: input.snapshotAgeMs ?? null,\n snapshotSource: input.snapshotSource ?? null,\n phase: input.phase ?? null,\n pid: input.pid ?? null,\n profileKeyHash: input.profileKeyHash ?? hashProfileKey(input.profileKey),\n switchVerified: input.switchVerified ?? null,\n activationRequested: input.activationRequested ?? null,\n activationResult: input.activationResult ?? null,\n restartRequested: input.restartRequested ?? null,\n restartResult: input.restartResult ?? null,\n observedProfileName: input.observedProfileName ?? null,\n observedProfileKeyHash:\n input.observedProfileKeyHash ?? hashProfileKey(input.observedProfileKey),\n observedProfileMatchSource: input.observedProfileMatchSource ?? null,\n };\n try {\n await updateAppState((state) => ({\n officialCodex: {\n activity: [...state.officialCodex.activity, entry].slice(\n -OFFICIAL_CODEX_ACTIVITY_LIMIT,\n ),\n },\n }));\n } catch (error) {\n console.warn(\"[official-codex-activity] Failed to record activity.\", {\n kind: entry.kind,\n status: entry.status,\n profileKeyHash: entry.profileKeyHash,\n error: sanitizeUserFacingError(error) ?? \"activity-record-failed\",\n });\n }\n}\n\nfunction runCommand(\n command: string,\n args: string[],\n timeoutMs = COMMAND_TIMEOUT_MS,\n): Promise<CommandResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, timeoutMs);\n\n child.stdout?.on(\"data\", (chunk) => {\n stdout += String(chunk);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += String(chunk);\n });\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n resolve({\n code: -1,\n stdout,\n stderr: error instanceof Error ? error.message : String(error),\n timedOut,\n });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\nfunction enqueueProfileAction<T>(work: () => Promise<T>): Promise<T> {\n const run = profileActionLock.then(work, work);\n profileActionLock = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n}\n\nasync function readProcessRows(): Promise<ProcessRow[]> {\n const result = await runCommand(\n \"/bin/ps\",\n [\"-axo\", \"pid=,ppid=,lstart=,args=\"],\n 2_000,\n );\n if (result.code !== 0) {\n return [];\n }\n\n return result.stdout.split(/\\r?\\n/).flatMap((line) => {\n const match = line.match(\n /^\\s*(\\d+)\\s+(\\d+)\\s+([A-Z][a-z]{2}\\s+[A-Z][a-z]{2}\\s+\\d+\\s+\\d+:\\d+:\\d+\\s+\\d{4})\\s+(.+)$/,\n );\n if (!match) {\n return [];\n }\n const pid = Number(match[1]);\n const ppid = Number(match[2]);\n const parsedStartedAt = Date.parse(match[3] ?? \"\");\n const startedAt = Number.isFinite(parsedStartedAt) ? parsedStartedAt : null;\n const args = match[4] ?? \"\";\n if (!Number.isInteger(pid) || !Number.isInteger(ppid) || !args) {\n return [];\n }\n return [{ pid, ppid, startedAt, args }];\n });\n}\n\nfunction getMainExecutablePath(candidate: OfficialCodexAppCandidate): string {\n return path.join(candidate.appPath, \"Contents\", \"MacOS\", candidate.executableName);\n}\n\nfunction isMainProcessRow(\n row: ProcessRow,\n candidate: OfficialCodexAppCandidate,\n): boolean {\n return row.args.includes(getMainExecutablePath(candidate));\n}\n\nfunction findAppServerPid(rows: ProcessRow[], mainPid: number): number | null {\n return (\n rows.find(\n (row) =>\n row.ppid === mainPid &&\n row.args.includes(\"/Contents/Resources/codex app-server\"),\n )?.pid ?? null\n );\n}\n\nasync function processMatchesProfileHome(\n pid: number,\n profileHome: string,\n): Promise<boolean> {\n const result = await runCommand(\n \"/bin/ps\",\n [\"eww\", \"-p\", String(pid), \"-o\", \"command=\"],\n 2_000,\n );\n if (result.code !== 0) {\n return false;\n }\n return (\n result.stdout.includes(`CODEX_HOME=${profileHome}`) ||\n result.stdout.includes(profileHome)\n );\n}\n\nasync function findAppServerPidForProfile(\n rows: ProcessRow[],\n mainPid: number,\n profileHome: string,\n): Promise<number | null> {\n const candidates = rows.filter(\n (row) =>\n row.ppid === mainPid &&\n row.args.includes(\"/Contents/Resources/codex app-server\"),\n );\n for (const row of candidates) {\n if (\n row.args.includes(profileHome) ||\n (await processMatchesProfileHome(row.pid, profileHome))\n ) {\n return row.pid;\n }\n }\n return null;\n}\n\nfunction parseRemoteDebuggingPort(args: string): number | null {\n const match = args.match(/--remote-debugging-port(?:=|\\s+)(\\d{2,5})\\b/);\n const port = Number(match?.[1]);\n return Number.isInteger(port) && port > 0 && port < 65536 ? port : null;\n}\n\nasync function describeUnmanagedProfileHint(\n appServerPid: number | null,\n): Promise<Pick<\n OfficialCodexUnmanagedInstancePayload,\n \"profileName\" | \"profileMatchSource\"\n>> {\n if (!appServerPid) {\n return {};\n }\n const result = await runCommand(\n \"/bin/ps\",\n [\"eww\", \"-p\", String(appServerPid), \"-o\", \"command=\"],\n 2_000,\n );\n if (result.code !== 0) {\n return {};\n }\n const telemetryMatch = result.stdout.match(\n /CODEX_TELEMETRY_LABEL=codexuse-profile-([^\\s]+)/,\n );\n if (telemetryMatch?.[1]) {\n const encodedProfileName = telemetryMatch[1];\n let profileName: string;\n try {\n profileName = decodeURIComponent(encodedProfileName);\n } catch {\n profileName = encodedProfileName;\n }\n return {\n profileName,\n profileMatchSource: \"telemetry-label\",\n };\n }\n const profileHomeMatch = result.stdout.match(/profile-homes\\/([^\\s]+)/);\n if (profileHomeMatch?.[1]) {\n return {\n profileName: profileHomeMatch[1],\n profileMatchSource: \"profile-home\",\n };\n }\n return {};\n}\n\nfunction getDescendantPids(rootPid: number, rows: ProcessRow[]): number[] {\n const descendants: number[] = [];\n const queue = [rootPid];\n const seen = new Set<number>();\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (seen.has(current)) {\n continue;\n }\n seen.add(current);\n for (const row of rows) {\n if (row.ppid !== current || seen.has(row.pid)) {\n continue;\n }\n descendants.push(row.pid);\n queue.push(row.pid);\n }\n }\n\n return descendants;\n}\n\nasync function waitForNewMainPid(\n candidate: OfficialCodexAppCandidate,\n previousPids: ReadonlySet<number>,\n): Promise<number | null> {\n const deadline = Date.now() + LAUNCH_WAIT_MS;\n while (Date.now() < deadline) {\n const rows = await readProcessRows();\n const pid =\n rows.find((row) => isMainProcessRow(row, candidate) && !previousPids.has(row.pid))\n ?.pid ?? null;\n if (pid !== null) {\n return pid;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return null;\n}\n\nasync function waitForMainPid(\n candidate: OfficialCodexAppCandidate,\n pid: number,\n timeoutMs: number,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const rows = await readProcessRows();\n if (rows.some((row) => row.pid === pid && isMainProcessRow(row, candidate))) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return false;\n}\n\nasync function waitForAppServerPid(\n mainPid: number,\n profileHome: string,\n): Promise<number | null> {\n const deadline = Date.now() + LAUNCH_WAIT_MS;\n while (Date.now() < deadline) {\n const pid = await findAppServerPidForProfile(\n await readProcessRows(),\n mainPid,\n profileHome,\n );\n if (pid !== null) {\n return pid;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return null;\n}\n\nasync function waitForMainPidExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const rows = await readProcessRows();\n if (!rows.some((row) => row.pid === pid)) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return false;\n}\n\nasync function focusMainPid(pid: number): Promise<boolean> {\n const result = await runCommand(\"/usr/bin/osascript\", [\n \"-e\",\n `tell application \"System Events\" to repeat with proc in (processes whose unix id is ${pid})`,\n \"-e\",\n \"set frontmost of proc to true\",\n \"-e\",\n \"end repeat\",\n ], 5_000);\n return result.code === 0;\n}\n\nfunction managedInstanceToPayload(\n instance: OfficialCodexManagedInstanceState,\n running: boolean,\n appServerPid: number | null = instance.appServerPid,\n startedAt: number | null = null,\n): OfficialCodexProfileInstancePayload {\n const runningStartedAt = startedAt ?? instance.launchedAt;\n const bridge = bridgeStateForStoredInstance(instance, running);\n return {\n profileName: instance.profileName,\n profileKey: instance.profileKey,\n appPath: instance.appPath,\n bundleId: instance.bundleId,\n pid: running ? instance.pid : null,\n appServerPid: running ? appServerPid : null,\n cdpPort: bridge.cdpPort,\n bridgeStatus: bridge.bridgeStatus,\n bridgeLastCheckedAt: toIso(bridge.bridgeLastCheckedAt),\n bridgeError: sanitizeUserFacingError(bridge.bridgeError),\n bridgeVersion: bridge.bridgeVersion,\n bridgeRoute: bridge.bridgeRoute,\n bridgeDevToolsUrl: bridge.bridgeDevToolsUrl,\n bridgeCapabilities: bridge.bridgeCapabilities,\n bridgeActiveThreadId: bridge.bridgeActiveThreadId,\n bridgeActiveThreadTitle: bridge.bridgeActiveThreadTitle,\n bridgeActiveThreadUpdatedAt: toIso(bridge.bridgeActiveThreadUpdatedAt),\n bridgeComposerText: bridge.bridgeComposerText,\n bridgeWorkspacePath: bridge.bridgeWorkspacePath,\n bridgeModel: bridge.bridgeModel,\n bridgeActivityState: bridge.bridgeActivityState,\n bridgeQol: bridge.bridgeQol,\n bridgePower: bridge.bridgePower,\n bridgeRelayStatus: bridge.bridgeRelayStatus,\n desiredQolSettings: instance.desiredQolSettings ?? null,\n desiredPowerSettings: instance.desiredPowerSettings ?? null,\n running,\n startedAt: running ? toIso(runningStartedAt) : null,\n uptimeMs:\n running && typeof runningStartedAt === \"number\"\n ? Math.max(0, Date.now() - runningStartedAt)\n : null,\n launchedAt: toIso(instance.launchedAt),\n lastVerifiedAt: toIso(instance.lastVerifiedAt),\n lastStatus: instance.lastStatus,\n lastError: sanitizeUserFacingError(instance.lastError),\n };\n}\n\nasync function patchManagedInstance(\n instance: OfficialCodexManagedInstanceState,\n): Promise<void> {\n await patchAppState({\n officialCodex: {\n instancesByProfileName: {\n [instance.profileName]: instance,\n },\n },\n });\n}\n\nasync function readManagedInstance(\n profileName: string,\n): Promise<OfficialCodexManagedInstanceState | null> {\n const state = await getAppState();\n return state.officialCodex.instancesByProfileName[profileName] ?? null;\n}\n\nasync function resolveInstanceRuntimeState(args: {\n instance: OfficialCodexManagedInstanceState;\n candidate: OfficialCodexAppCandidate;\n rows: ProcessRow[];\n}): Promise<{\n running: boolean;\n appServerPid: number | null;\n startedAt: number | null;\n}> {\n const pid = args.instance.pid;\n if (!pid) {\n return { running: false, appServerPid: null, startedAt: null };\n }\n const mainRow = args.rows.find((row) => row.pid === pid);\n if (!mainRow || !isMainProcessRow(mainRow, args.candidate)) {\n return { running: false, appServerPid: null, startedAt: null };\n }\n const appServerPid = args.instance.profileHome\n ? await findAppServerPidForProfile(args.rows, pid, args.instance.profileHome)\n : findAppServerPid(args.rows, pid);\n if (args.instance.profileHome && appServerPid === null) {\n const profileMainPid =\n mainRow.args.includes(args.instance.profileHome) ||\n (await processMatchesProfileHome(pid, args.instance.profileHome));\n if (!profileMainPid) {\n return { running: false, appServerPid: null, startedAt: null };\n }\n }\n return {\n running: true,\n appServerPid,\n startedAt: mainRow.startedAt,\n };\n}\n\nasync function resolveOfficialCodexBridgeTarget(args: {\n profileName: string;\n state: AppState;\n candidate: OfficialCodexAppCandidate;\n rows: ProcessRow[];\n}): Promise<OfficialCodexBridgeTarget | null> {\n const existing =\n args.state.officialCodex.instancesByProfileName[args.profileName] ?? null;\n if (existing) {\n const runtime = await resolveInstanceRuntimeState({\n instance: existing,\n candidate: args.candidate,\n rows: args.rows,\n });\n if (runtime.running && existing.cdpPort) {\n return { instance: existing, runtime, managed: true };\n }\n }\n\n const runningManagedPids = new Set<number>();\n for (const instance of Object.values(\n args.state.officialCodex.instancesByProfileName,\n )) {\n const runtime = await resolveInstanceRuntimeState({\n instance,\n candidate: args.candidate,\n rows: args.rows,\n });\n if (runtime.running && instance.pid) {\n runningManagedPids.add(instance.pid);\n }\n }\n\n const candidates = [];\n for (const row of args.rows) {\n if (!isMainProcessRow(row, args.candidate) || runningManagedPids.has(row.pid)) {\n continue;\n }\n const cdpPort = parseRemoteDebuggingPort(row.args);\n if (!cdpPort) {\n continue;\n }\n const appServerPid = findAppServerPid(args.rows, row.pid);\n candidates.push({\n row,\n cdpPort,\n appServerPid,\n hint: await describeUnmanagedProfileHint(appServerPid),\n });\n }\n\n const target =\n candidates.find((entry) => entry.hint.profileName === args.profileName) ??\n (candidates.length === 1 ? candidates[0] : null);\n if (!target) {\n return null;\n }\n\n const now = Date.now();\n const bridge = bridgeStateUnattached(target.cdpPort, now);\n return {\n managed: false,\n runtime: {\n running: true,\n appServerPid: target.appServerPid,\n startedAt: target.row.startedAt,\n },\n instance: {\n profileName: args.profileName,\n profileKey: existing?.profileKey ?? null,\n profileHome: existing?.profileHome ?? null,\n appPath: args.candidate.appPath,\n bundleId: args.candidate.bundleId,\n pid: target.row.pid,\n appServerPid: target.appServerPid,\n launchedAt: target.row.startedAt,\n lastVerifiedAt: now,\n lastStatus: \"observed-unmanaged\",\n lastError: null,\n ...bridge,\n bridgeStatus: existing?.bridgeStatus ?? bridge.bridgeStatus,\n bridgeLastCheckedAt: existing?.bridgeLastCheckedAt ?? bridge.bridgeLastCheckedAt,\n bridgeError: existing?.bridgeError ?? bridge.bridgeError,\n bridgeVersion: existing?.bridgeVersion ?? bridge.bridgeVersion,\n bridgeRoute: existing?.bridgeRoute ?? bridge.bridgeRoute,\n bridgeDevToolsUrl: existing?.bridgeDevToolsUrl ?? bridge.bridgeDevToolsUrl,\n bridgeCapabilities: existing?.bridgeCapabilities ?? bridge.bridgeCapabilities,\n bridgeActiveThreadId:\n existing?.bridgeActiveThreadId ?? bridge.bridgeActiveThreadId,\n bridgeActiveThreadTitle:\n existing?.bridgeActiveThreadTitle ?? bridge.bridgeActiveThreadTitle,\n bridgeActiveThreadUpdatedAt:\n existing?.bridgeActiveThreadUpdatedAt ?? bridge.bridgeActiveThreadUpdatedAt,\n bridgeComposerText: existing?.bridgeComposerText ?? bridge.bridgeComposerText,\n bridgeWorkspacePath: existing?.bridgeWorkspacePath ?? bridge.bridgeWorkspacePath,\n bridgeModel: existing?.bridgeModel ?? bridge.bridgeModel,\n bridgeActivityState:\n existing?.bridgeActivityState ?? bridge.bridgeActivityState,\n bridgeQol: existing?.bridgeQol ?? bridge.bridgeQol,\n bridgePower: existing?.bridgePower ?? bridge.bridgePower,\n bridgeRelayStatus: existing?.bridgeRelayStatus ?? bridge.bridgeRelayStatus,\n desiredQolSettings: existing?.desiredQolSettings ?? null,\n desiredPowerSettings: existing?.desiredPowerSettings ?? null,\n },\n };\n}\n\nasync function openCodexWithProfileHome(\n candidate: OfficialCodexAppCandidate,\n profileHome: string,\n profileName: string,\n cdpPort: number,\n previousPids: ReadonlySet<number>,\n options: { useDefaultUserData?: boolean } = {},\n): Promise<{ opened: boolean; pid: number | null }> {\n const executablePath = getMainExecutablePath(candidate);\n if (!existsSync(executablePath)) {\n return { opened: false, pid: null };\n }\n const telemetryLabel = `codexuse-profile-${encodeURIComponent(profileName)}`;\n // Shared-home launches keep the app's default Electron userData so the\n // window carries the user's real Codex state; per-profile launches isolate\n // userData so multiple windows can run side by side.\n const appUserDataDir = options.useDefaultUserData\n ? null\n : path.join(profileHome, \"codex-app-user-data\");\n let child: ReturnType<typeof spawn>;\n try {\n if (appUserDataDir) {\n mkdirSync(appUserDataDir, { recursive: true });\n }\n child = spawn(\n executablePath,\n [\n ...(appUserDataDir ? [`--user-data-dir=${appUserDataDir}`] : []),\n `--remote-debugging-port=${cdpPort}`,\n `--remote-debugging-address=${CODEX_CDP_HOST}`,\n `--remote-allow-origins=http://${CODEX_CDP_HOST}:${cdpPort}`,\n ],\n {\n detached: true,\n env: {\n ...process.env,\n CODEX_HOME: profileHome,\n CODEX_TELEMETRY_LABEL: telemetryLabel,\n },\n stdio: \"ignore\",\n },\n );\n } catch {\n return { opened: false, pid: null };\n }\n\n const childPid = child.pid ?? null;\n child.unref();\n const spawnError = await new Promise<boolean>((resolve) => {\n let settled = false;\n const settle = (failed: boolean) => {\n if (settled) {\n return;\n }\n settled = true;\n resolve(failed);\n };\n child.once(\"error\", () => settle(true));\n setTimeout(() => settle(false), POLL_INTERVAL_MS);\n });\n if (spawnError) {\n return { opened: false, pid: null };\n }\n\n if (childPid !== null) {\n const verified = await waitForMainPid(candidate, childPid, 2_000);\n if (verified) {\n return { opened: true, pid: childPid };\n }\n }\n\n return {\n opened: true,\n pid: await waitForNewMainPid(candidate, previousPids),\n };\n}\n\nasync function readBundleString(\n appPath: string,\n key: \"CFBundleIdentifier\" | \"CFBundleExecutable\" | \"CFBundleShortVersionString\",\n): Promise<string | null> {\n const plistPath = path.join(appPath, \"Contents\", \"Info.plist\");\n if (!existsSync(plistPath)) {\n return null;\n }\n\n const result = await runCommand(\"/usr/bin/plutil\", [\n \"-extract\",\n key,\n \"raw\",\n \"-o\",\n \"-\",\n plistPath,\n ]);\n if (result.code !== 0) {\n return null;\n }\n\n const bundleId = result.stdout.trim();\n return bundleId.length > 0 ? bundleId : null;\n}\n\nasync function collectCodexAppCandidates(\n rawPaths: ReadonlySet<string>,\n): Promise<OfficialCodexAppCandidate[]> {\n const candidates: OfficialCodexAppCandidate[] = [];\n for (const appPath of rawPaths) {\n if (!existsSync(appPath) || path.basename(appPath) !== \"Codex.app\") {\n continue;\n }\n\n const bundleId = await readBundleString(appPath, \"CFBundleIdentifier\");\n if (!bundleId || bundleId.toLowerCase().includes(\"codexuse\")) {\n continue;\n }\n candidates.push({\n appPath,\n bundleId,\n version: await readBundleString(appPath, \"CFBundleShortVersionString\"),\n executableName:\n (await readBundleString(appPath, \"CFBundleExecutable\")) ?? \"Codex\",\n });\n }\n return candidates.sort((a, b) => a.appPath.localeCompare(b.appPath));\n}\n\nasync function discoverCodexAppCandidates(): Promise<OfficialCodexAppCandidate[]> {\n const now = Date.now();\n const envPath = process.env.CODEXUSE_OFFICIAL_CODEX_APP_PATH?.trim() || null;\n if (\n appDiscoveryCache &&\n appDiscoveryCache.envPath === envPath &&\n appDiscoveryCache.expiresAt > now\n ) {\n return appDiscoveryCache.candidates;\n }\n\n const rawPaths = new Set<string>();\n if (envPath) {\n rawPaths.add(envPath);\n }\n rawPaths.add(\"/Applications/Codex.app\");\n rawPaths.add(path.join(homedir(), \"Applications\", \"Codex.app\"));\n\n const sorted = await collectCodexAppCandidates(rawPaths);\n appDiscoveryCache = {\n envPath,\n expiresAt:\n now +\n (sorted.length > 0 ? APP_DISCOVERY_CACHE_TTL_MS : APP_DISCOVERY_MISS_CACHE_TTL_MS),\n candidates: sorted,\n };\n return sorted;\n}\n\nexport async function warmOfficialCodexAppDiscoveryCache(): Promise<void> {\n const envPath = process.env.CODEXUSE_OFFICIAL_CODEX_APP_PATH?.trim() || null;\n const rawPaths = new Set<string>();\n if (envPath) {\n rawPaths.add(envPath);\n }\n rawPaths.add(\"/Applications/Codex.app\");\n rawPaths.add(path.join(homedir(), \"Applications\", \"Codex.app\"));\n\n const mdfind = await runCommand(\n \"/usr/bin/mdfind\",\n [\"kMDItemFSName == 'Codex.app'\"],\n 1_500,\n );\n if (mdfind.code === 0) {\n for (const line of mdfind.stdout.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.endsWith(\"/Codex.app\")) {\n rawPaths.add(trimmed);\n }\n }\n }\n\n const sorted = await collectCodexAppCandidates(rawPaths);\n appDiscoveryCache = {\n envPath,\n expiresAt:\n Date.now() +\n (sorted.length > 0 ? APP_DISCOVERY_CACHE_TTL_MS : APP_DISCOVERY_MISS_CACHE_TTL_MS),\n candidates: sorted,\n };\n}\n\nfunction getRunningCodexPidsFromRows(\n candidate: OfficialCodexAppCandidate,\n rows: ProcessRow[],\n): number[] {\n const pids = new Set<number>();\n const appContentsRoot = `${path.join(candidate.appPath, \"Contents\")}${path.sep}`;\n for (const row of rows) {\n if (row.args.includes(appContentsRoot)) {\n pids.add(row.pid);\n }\n }\n\n return Array.from(pids).sort((a, b) => a - b);\n}\n\nfunction getRunningCodexMainPidsFromRows(\n candidate: OfficialCodexAppCandidate,\n rows: ProcessRow[],\n): number[] {\n const pids = new Set<number>();\n const executablePath = path.join(\n candidate.appPath,\n \"Contents\",\n \"MacOS\",\n candidate.executableName,\n );\n for (const row of rows) {\n if (row.args.includes(executablePath)) {\n pids.add(row.pid);\n }\n }\n\n return Array.from(pids).sort((a, b) => a - b);\n}\n\nasync function resolveCodexAppTarget(): Promise<OfficialCodexAppTarget> {\n const candidates = await discoverCodexAppCandidates();\n const fallback = candidates[0] ?? null;\n if (!fallback) {\n return { candidate: null, runningPids: [], mainPids: [] };\n }\n\n const rows = await readProcessRows();\n for (const candidate of candidates) {\n const runningPids = getRunningCodexPidsFromRows(candidate, rows);\n const mainPids = getRunningCodexMainPidsFromRows(candidate, rows);\n if (mainPids.length > 0) {\n return { candidate, runningPids, mainPids };\n }\n }\n\n const runningPids = getRunningCodexPidsFromRows(fallback, rows);\n const mainPids = getRunningCodexMainPidsFromRows(fallback, rows);\n return { candidate: fallback, runningPids, mainPids };\n}\n\nasync function signalPids(\n pids: number[],\n signal: NodeJS.Signals,\n): Promise<number[]> {\n const signaled: number[] = [];\n for (const pid of pids) {\n try {\n process.kill(pid, signal);\n signaled.push(pid);\n } catch {\n // Process may have already exited.\n }\n }\n return signaled;\n}\n\nconst SHARED_CODEX_HOME = path.join(homedir(), \".codex\");\n\nlet sharedHomeCdpWindow: { pid: number; cdpPort: number } | null = null;\n\nexport type OfficialCodexLiveAccountSwitchResult = {\n status: \"reloaded\" | \"launched\" | \"skipped\" | \"failed\";\n reason: string | null;\n pid: number | null;\n};\n\nexport type OfficialCodexLiveAccountSwitchOptions = {\n carryDraft?: boolean;\n continueMessage?: string | null;\n // Thread the hand-off started from; reopened before the continue message is\n // sent so it lands in the right conversation.\n continueThreadId?: string | null;\n profileName?: string;\n profileKey?: string | null;\n desiredQolSettings?: OfficialCodexQolSettingsPayload | null;\n desiredPowerSettings?: OfficialCodexPowerSettingsPayload | null;\n // The signed-in account lives in the app's `codex app-server` child process,\n // so an auth.json change only takes effect after a full app relaunch. When\n // false, an already-managed window is kept as-is (no reload flicker).\n accountChanged?: boolean;\n // Switching accounts must not cold-launch Codex: users who gate Codex behind\n // a VPN switch it while the app is closed and expect it to stay closed.\n launchIfNotRunning?: boolean;\n // Auto-roll at exhaustion may kill a generating window after a grace wait;\n // callers that can't tolerate that (manual switches) gate before calling.\n forceAfterGrace?: boolean;\n};\n\n// Register the shared-home window as the managed instance for the profile it\n// now shows, so instance polling sees it (window state, bridge action\n// listener, tweak reapply). Entries for other profiles that pointed at the\n// same window are dropped — the shared window only ever shows one account.\nasync function adoptSharedManagedWindow(args: {\n candidate: OfficialCodexAppCandidate;\n pid: number;\n cdpPort: number;\n profileName: string;\n profileKey?: string | null;\n desiredQolSettings?: OfficialCodexQolSettingsPayload | null;\n desiredPowerSettings?: OfficialCodexPowerSettingsPayload | null;\n}): Promise<void> {\n const now = Date.now();\n await updateAppState(\n (state) => {\n const instances = state.officialCodex.instancesByProfileName;\n const previous =\n Object.values(instances).find((entry) => entry.pid === args.pid) ??\n instances[args.profileName] ??\n null;\n for (const [key, entry] of Object.entries(instances)) {\n if (key !== args.profileName && entry.pid === args.pid) {\n delete instances[key];\n }\n }\n const desiredQolSettings = resolveDesiredQolSettings({\n requested: args.desiredQolSettings,\n existing: previous?.desiredQolSettings,\n });\n const desiredPowerSettings = resolveDesiredPowerSettings({\n requested: args.desiredPowerSettings,\n existing: previous?.desiredPowerSettings,\n });\n instances[args.profileName] = {\n profileName: args.profileName,\n profileKey: args.profileKey ?? previous?.profileKey ?? null,\n profileHome: null,\n appPath: args.candidate.appPath,\n bundleId: args.candidate.bundleId,\n pid: args.pid,\n appServerPid: null,\n launchedAt: previous?.pid === args.pid ? previous.launchedAt : now,\n lastVerifiedAt: now,\n lastStatus: \"shared-window\",\n lastError: null,\n ...bridgeStateUnattached(args.cdpPort, now),\n // Saved settings carry no overlay targets; keep the last applied ones\n // so the in-window account switcher survives the switch.\n desiredQolSettings:\n desiredQolSettings &&\n (desiredQolSettings.actionTargets?.length ?? 0) === 0 &&\n previous?.desiredQolSettings?.actionTargets?.length\n ? {\n ...desiredQolSettings,\n actionTargets: previous.desiredQolSettings.actionTargets,\n }\n : desiredQolSettings,\n desiredPowerSettings,\n };\n return state;\n },\n { mode: \"replace\" },\n );\n}\n\n// After the shared window reloads or launches into the new account, bring the\n// bridge back up and reapply the saved in-app tweaks (a reload wipes them).\nasync function refreshAdoptedSharedWindow(profileName: string): Promise<void> {\n const instance = await readManagedInstance(profileName);\n if (!instance) {\n return;\n }\n const bridge = await waitForBridgeStateAfterLaunch(instance);\n await patchManagedInstance({\n ...instance,\n ...bridge,\n lastVerifiedAt: bridge.bridgeLastCheckedAt ?? instance.lastVerifiedAt,\n lastStatus:\n bridge.bridgeStatus === \"healthy\" ? \"bridged\" : \"running-unbridged\",\n });\n}\n\n// Read the current composer draft from a shared-home window (before reload), so\n// a \"hand off\" can carry the in-progress prompt into the next account.\nasync function readSharedComposerDraft(debuggerUrl: string): Promise<string> {\n try {\n const value = await evaluateCdpExpression(\n debuggerUrl,\n createBridgeReadComposerExpression(),\n );\n const text =\n value && typeof value === \"object\" && \"text\" in value\n ? (value as { text?: unknown }).text\n : null;\n return typeof text === \"string\" ? text : \"\";\n } catch {\n return \"\";\n }\n}\n\n// Re-insert a carried draft after the window has reloaded into the new account.\n// The composer takes a moment to mount post-reload, so retry a few times.\nasync function restoreSharedComposerDraft(\n debuggerUrl: string,\n prompt: string,\n): Promise<void> {\n if (!prompt.trim()) {\n return;\n }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n await new Promise((resolve) => setTimeout(resolve, 400));\n try {\n const result = await evaluateOfficialCodexBridgeCommand(\n debuggerUrl,\n \"setDraft\",\n createBridgeSetDraftPromptExpression(prompt),\n false,\n );\n const status =\n result && typeof result === \"object\" && \"status\" in result\n ? (result as { status?: unknown }).status\n : null;\n if (status === \"inserted\") {\n return;\n }\n } catch {\n // Composer may not be mounted yet; retry.\n }\n }\n}\n\n// Click the sidebar row for a given thread id so a hand-off lands back in the\n// conversation it started from. Codex marks rows with\n// data-app-action-sidebar-thread-id and the open conversation with\n// data-above-composer-conversation-id; ids may differ by a local:/URI-encoded\n// prefix, so matching is suffix-tolerant.\nfunction createBridgeOpenThreadExpression(threadId: string): string {\n return `(() => {\n const wanted = ${JSON.stringify(threadId)};\n const normalize = (value) => {\n let id = typeof value === \"string\" ? value.trim() : \"\";\n try { id = decodeURIComponent(id); } catch {\n // Keep raw value if it is not URI encoded.\n }\n if (id.toLowerCase().startsWith(\"local:\")) id = id.slice(\"local:\".length);\n return id;\n };\n const matches = (value) => {\n const id = normalize(value);\n return Boolean(id) && (id === wanted || id.endsWith(wanted) || wanted.endsWith(id));\n };\n const composerHost = document.querySelector(\"[data-above-composer-conversation-id]\");\n if (matches(composerHost?.getAttribute(\"data-above-composer-conversation-id\"))) {\n return { status: \"active\" };\n }\n const rows = Array.from(document.querySelectorAll(\"[data-app-action-sidebar-thread-id]\"));\n const row = rows.find((node) => matches(node.getAttribute(\"data-app-action-sidebar-thread-id\")));\n if (!row) {\n return { status: \"not-found\" };\n }\n if (row.getAttribute(\"data-app-action-sidebar-thread-active\") === \"true\") {\n return { status: \"active\" };\n }\n // The row itself is the navigation target (role=button div); its inner\n // <button>s are per-row actions, so never fall back to them. A bare click\n // event is ignored — the full pointer sequence is required.\n row.scrollIntoView({ block: \"center\" });\n const rect = row.getBoundingClientRect();\n const eventInit = {\n bubbles: true,\n cancelable: true,\n clientX: rect.left + rect.width / 2,\n clientY: rect.top + rect.height / 2,\n button: 0,\n pointerId: 1,\n isPrimary: true\n };\n row.dispatchEvent(new PointerEvent(\"pointerdown\", eventInit));\n row.dispatchEvent(new MouseEvent(\"mousedown\", eventInit));\n row.dispatchEvent(new PointerEvent(\"pointerup\", eventInit));\n row.dispatchEvent(new MouseEvent(\"mouseup\", eventInit));\n row.dispatchEvent(new MouseEvent(\"click\", eventInit));\n return { status: \"clicked\" };\n })()`;\n}\n\n// Reopen a specific thread after a hand-off relaunch. The sidebar mounts a\n// moment after launch, so poll like the composer helpers; \"clicked\" keeps\n// polling until a later pass confirms the thread is active.\nasync function openSharedThreadById(\n debuggerUrl: string,\n threadId: string,\n): Promise<boolean> {\n const normalized = normalizeOfficialCodexThreadId(threadId);\n if (!normalized) {\n return false;\n }\n for (let attempt = 0; attempt < 12; attempt += 1) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n try {\n const result = await evaluateOfficialCodexBridgeCommand(\n debuggerUrl,\n \"openThread\",\n createBridgeOpenThreadExpression(normalized),\n false,\n );\n const status =\n result && typeof result === \"object\" && \"status\" in result\n ? (result as { status?: unknown }).status\n : null;\n if (status === \"active\") {\n return true;\n }\n } catch {\n // Sidebar may not be mounted yet; retry.\n }\n }\n return false;\n}\n\n// Auto-send a continue message after the window has reloaded or launched into\n// the new account. Same retry shape as restoreSharedComposerDraft: the\n// composer takes a moment to mount, so poll until the bridge reports \"sent\".\nasync function sendSharedComposerMessage(\n debuggerUrl: string,\n text: string,\n): Promise<void> {\n if (!text.trim()) {\n return;\n }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n await new Promise((resolve) => setTimeout(resolve, 400));\n try {\n const result = await evaluateOfficialCodexBridgeCommand(\n debuggerUrl,\n \"sendMessage\",\n createBridgeSendMessageExpression(text),\n false,\n );\n const status =\n result && typeof result === \"object\" && \"status\" in result\n ? (result as { status?: unknown }).status\n : null;\n if (status === \"sent\") {\n return;\n }\n } catch {\n // Composer may not be mounted yet; retry.\n }\n }\n}\n\nexport type SharedWindowActivityState =\n | OfficialCodexBridgeActivityState\n | \"plain-running\"\n | \"not-running\";\n\nfunction isSharedHomeMainProcessRow(\n row: ProcessRow,\n candidate: OfficialCodexAppCandidate,\n): boolean {\n return isMainProcessRow(row, candidate) && !row.args.includes(\"profile-homes\");\n}\n\nfunction findSharedHomeDebugWindow(\n rows: ProcessRow[],\n candidate: OfficialCodexAppCandidate,\n): { pid: number; cdpPort: number } | null {\n if (\n sharedHomeCdpWindow &&\n rows.some((row) => row.pid === sharedHomeCdpWindow?.pid)\n ) {\n return sharedHomeCdpWindow;\n }\n for (const row of rows) {\n if (!isSharedHomeMainProcessRow(row, candidate)) {\n continue;\n }\n const cdpPort = parseRemoteDebuggingPort(row.args);\n if (cdpPort !== null) {\n return { pid: row.pid, cdpPort };\n }\n }\n return null;\n}\n\nfunction findPlainSharedHomeRows(\n rows: ProcessRow[],\n candidate: OfficialCodexAppCandidate,\n): ProcessRow[] {\n return rows.filter(\n (row) =>\n isSharedHomeMainProcessRow(row, candidate) &&\n parseRemoteDebuggingPort(row.args) === null,\n );\n}\n\nasync function readSharedBridgeSnapshot(\n debuggerUrl: string,\n): Promise<OfficialCodexBridgeSnapshot | null> {\n try {\n const value = await evaluateOfficialCodexBridgeCommand(\n debuggerUrl,\n \"snapshot\",\n createBridgeSnapshotExpression(),\n false,\n );\n return normalizeBridgeSnapshot(value);\n } catch {\n return null;\n }\n}\n\nasync function readSharedWindowActivityStateForTarget(\n target: { cdpPort: number },\n): Promise<OfficialCodexBridgeActivityState> {\n const cdpTarget = pickCodexCdpTarget(await readCdpTargets(target.cdpPort));\n if (!cdpTarget?.webSocketDebuggerUrl) {\n return \"unknown\";\n }\n const snapshot = await readSharedBridgeSnapshot(cdpTarget.webSocketDebuggerUrl);\n return snapshot?.activityState ?? \"unknown\";\n}\n\nexport async function readSharedWindowActivityState(): Promise<SharedWindowActivityState> {\n if (process.platform !== \"darwin\") {\n return \"not-running\";\n }\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return \"not-running\";\n }\n const rows = await readProcessRows();\n const target = findSharedHomeDebugWindow(rows, candidate);\n if (target) {\n return await readSharedWindowActivityStateForTarget(target);\n }\n return findPlainSharedHomeRows(rows, candidate).length > 0\n ? \"plain-running\"\n : \"not-running\";\n}\n\nasync function waitForSharedWindowToStopGenerating(\n debuggerUrl: string,\n): Promise<OfficialCodexBridgeActivityState> {\n const deadline = Date.now() + GENERATING_EXIT_GRACE_MS;\n while (Date.now() < deadline) {\n const snapshot = await readSharedBridgeSnapshot(debuggerUrl);\n const state = snapshot?.activityState ?? \"unknown\";\n if (state !== \"generating\") {\n return state;\n }\n await sleep(GENERATING_EXIT_POLL_MS);\n }\n return \"generating\";\n}\n\n// Apply the active ~/.codex/auth.json account to a running shared-home Official\n// Codex window without a full process restart. Reloads the renderer of a\n// CodexUse-managed shared-home window (re-reads auth.json -> shows the new\n// account live). If no such window exists, takes over: stops any plain\n// (no-debug) shared-home instance and launches a debug-enabled shared-home\n// window that boots straight into the new account. Per-profile windows\n// (profile-homes/<name>) are never touched.\nasync function applyOfficialCodexLiveAccountSwitchOnce(\n options: OfficialCodexLiveAccountSwitchOptions = {},\n): Promise<OfficialCodexLiveAccountSwitchResult> {\n if (process.platform !== \"darwin\") {\n return { status: \"skipped\", reason: \"unsupported-platform\", pid: null };\n }\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"skipped\",\n reason: \"official-codex-app-not-found\",\n pid: null,\n };\n }\n let rows = await readProcessRows();\n\n let driveTarget = findSharedHomeDebugWindow(rows, candidate);\n const killedMainPids = new Set<number>();\n let plainSharedRows = findPlainSharedHomeRows(rows, candidate);\n if (\n !driveTarget &&\n plainSharedRows.length === 0 &&\n options.launchIfNotRunning !== true\n ) {\n return {\n status: \"skipped\",\n reason: \"official-codex-not-running\",\n pid: null,\n };\n }\n\n let carriedDraft = \"\";\n let capturedThreadId: string | null = null;\n if (driveTarget) {\n if (options.accountChanged !== true) {\n // Same account: keep the managed window untouched — adopt it and make\n // sure the bridge/overlay are current, but skip any reload flicker.\n sharedHomeCdpWindow = driveTarget;\n const target = pickCodexCdpTarget(\n await readCdpTargets(driveTarget.cdpPort),\n );\n if (target?.webSocketDebuggerUrl) {\n const debuggerUrl = target.webSocketDebuggerUrl;\n try {\n await ensureOfficialCodexBridgeInstalled(debuggerUrl, false);\n } catch {\n // Best effort; adoption below re-applies the bridge.\n }\n if (options.profileName) {\n await adoptSharedManagedWindow({\n candidate,\n pid: driveTarget.pid,\n cdpPort: driveTarget.cdpPort,\n profileName: options.profileName,\n profileKey: options.profileKey,\n desiredQolSettings: options.desiredQolSettings,\n desiredPowerSettings: options.desiredPowerSettings,\n });\n await refreshAdoptedSharedWindow(options.profileName);\n }\n if (options.continueMessage?.trim()) {\n if (options.continueThreadId) {\n await openSharedThreadById(debuggerUrl, options.continueThreadId);\n }\n await sendSharedComposerMessage(debuggerUrl, options.continueMessage);\n }\n return { status: \"reloaded\", reason: null, pid: driveTarget.pid };\n }\n sharedHomeCdpWindow = null;\n } else {\n // Account changed: the running app-server keeps the old session, so a\n // renderer reload is not enough — relaunch the whole app below.\n const target = pickCodexCdpTarget(\n await readCdpTargets(driveTarget.cdpPort),\n );\n const debuggerUrl = target?.webSocketDebuggerUrl ?? null;\n const snapshot = debuggerUrl\n ? await readSharedBridgeSnapshot(debuggerUrl)\n : null;\n capturedThreadId = snapshot?.activeThreadId ?? null;\n if (snapshot?.activityState === \"generating\") {\n if (!options.forceAfterGrace) {\n return {\n status: \"skipped\",\n reason: \"source-generating\",\n pid: driveTarget.pid,\n };\n }\n await waitForSharedWindowToStopGenerating(debuggerUrl!);\n }\n if (options.carryDraft && target?.webSocketDebuggerUrl) {\n carriedDraft = await readSharedComposerDraft(\n target.webSocketDebuggerUrl,\n );\n }\n const tree = [driveTarget.pid, ...getDescendantPids(driveTarget.pid, rows)]\n .filter((pid, index, all) => all.indexOf(pid) === index)\n .sort((a, b) => b - a);\n killedMainPids.add(driveTarget.pid);\n await signalPids(tree, \"SIGTERM\");\n if (!(await waitForMainPidExit(driveTarget.pid, PROCESS_EXIT_GRACE_MS))) {\n await signalPids(tree, \"SIGKILL\");\n await waitForMainPidExit(driveTarget.pid, EXIT_WAIT_MS);\n }\n sharedHomeCdpWindow = null;\n rows = await readProcessRows();\n plainSharedRows = findPlainSharedHomeRows(rows, candidate);\n }\n }\n\n for (const row of plainSharedRows) {\n const tree = [row.pid, ...getDescendantPids(row.pid, rows)]\n .filter((pid, index, all) => all.indexOf(pid) === index)\n .sort((a, b) => b - a);\n killedMainPids.add(row.pid);\n await signalPids(tree, \"SIGTERM\");\n if (!(await waitForMainPidExit(row.pid, PROCESS_EXIT_GRACE_MS))) {\n await signalPids(tree, \"SIGKILL\");\n await waitForMainPidExit(row.pid, EXIT_WAIT_MS);\n }\n }\n\n if (killedMainPids.size > 0) {\n rows = await readProcessRows();\n if (\n rows.some(\n (row) => killedMainPids.has(row.pid) && isMainProcessRow(row, candidate),\n )\n ) {\n return {\n status: \"failed\",\n reason: \"previous-instance-still-running\",\n pid: null,\n };\n }\n await sleep(POST_EXIT_SETTLE_MS);\n }\n\n let cdpPort: number;\n try {\n cdpPort = await reserveLoopbackPort();\n } catch {\n return { status: \"failed\", reason: \"cdp-port-unavailable\", pid: null };\n }\n rows = await readProcessRows();\n const launch = await openCodexWithProfileHome(\n candidate,\n SHARED_CODEX_HOME,\n options.profileName ?? \"shared\",\n cdpPort,\n new Set(rows.map((row) => row.pid)),\n { useDefaultUserData: true },\n );\n if (!launch.opened || launch.pid === null) {\n return { status: \"failed\", reason: \"shared-home-launch-failed\", pid: null };\n }\n sharedHomeCdpWindow = { pid: launch.pid, cdpPort };\n if (options.profileName) {\n await adoptSharedManagedWindow({\n candidate,\n pid: launch.pid,\n cdpPort,\n profileName: options.profileName,\n profileKey: options.profileKey,\n desiredQolSettings: options.desiredQolSettings,\n desiredPowerSettings: options.desiredPowerSettings,\n });\n await refreshAdoptedSharedWindow(options.profileName);\n }\n const threadToReopen = options.continueThreadId ?? capturedThreadId;\n if (\n carriedDraft.trim() ||\n options.continueMessage?.trim() ||\n threadToReopen\n ) {\n const launchedTarget = await waitForCdpTargetAfterLaunch(cdpPort);\n if (launchedTarget?.webSocketDebuggerUrl) {\n if (carriedDraft.trim()) {\n await restoreSharedComposerDraft(\n launchedTarget.webSocketDebuggerUrl,\n carriedDraft,\n );\n }\n if (!options.continueMessage?.trim() && threadToReopen) {\n await openSharedThreadById(\n launchedTarget.webSocketDebuggerUrl,\n threadToReopen,\n );\n }\n if (options.continueMessage?.trim()) {\n if (threadToReopen) {\n await openSharedThreadById(\n launchedTarget.webSocketDebuggerUrl,\n threadToReopen,\n );\n }\n await sendSharedComposerMessage(\n launchedTarget.webSocketDebuggerUrl,\n options.continueMessage,\n );\n }\n }\n }\n return { status: \"launched\", reason: null, pid: launch.pid };\n}\n\nexport function applyOfficialCodexLiveAccountSwitch(\n options: OfficialCodexLiveAccountSwitchOptions = {},\n): Promise<OfficialCodexLiveAccountSwitchResult> {\n return enqueueProfileAction(() =>\n applyOfficialCodexLiveAccountSwitchOnce(options),\n );\n}\n\nfunction toIso(value: number | null | undefined): string | null {\n return typeof value === \"number\" && Number.isFinite(value)\n ? new Date(value).toISOString()\n : null;\n}\n\nasync function rememberProfileSwitch(profileKey: string | null): Promise<void> {\n await patchAppState({\n officialCodex: {\n lastProfileSwitchAt: Date.now(),\n lastProfileSwitchProfileKey: profileKey,\n },\n });\n}\n\nasync function rememberActivationResult(args: {\n status: string;\n reason?: string | null;\n profileKey?: string | null;\n pid?: number | null;\n}): Promise<void> {\n const now = Date.now();\n const verified = args.status === \"restarted\" || args.status === \"started\";\n await patchAppState({\n officialCodex: {\n lastVerifiedLaunchAt: verified ? now : undefined,\n lastVerifiedLaunchProfileKey: verified ? (args.profileKey ?? null) : undefined,\n lastObservedPid: verified ? (args.pid ?? null) : undefined,\n lastActivationStatus: args.status,\n lastActivationReason: args.reason ?? null,\n },\n });\n}\n\nexport async function recordOfficialCodexProfileObservation(\n profileKey: string | null,\n pid: number | null,\n): Promise<void> {\n if (!profileKey || !pid) {\n return;\n }\n await patchAppState({\n officialCodex: {\n lastVerifiedLaunchProfileKey: profileKey,\n lastObservedPid: pid,\n },\n });\n}\n\nexport function recordOfficialCodexActivationResult(args: {\n status: string;\n reason?: string | null;\n profileKey?: string | null;\n pid?: number | null;\n}): Promise<void> {\n return rememberActivationResult(args);\n}\n\nexport async function getOfficialCodexSyncStatus(\n currentProfileKey: string | null,\n): Promise<OfficialCodexSyncStatusPayload> {\n const state = await getAppState();\n const stored = state.officialCodex;\n const base = {\n runningPids: [],\n lastProfileSwitchAt: toIso(stored.lastProfileSwitchAt),\n lastVerifiedLaunchAt: toIso(stored.lastVerifiedLaunchAt),\n lastActivationStatus: stored.lastActivationStatus,\n lastActivationReason: stored.lastActivationReason,\n activity: stored.activity,\n };\n\n if (process.platform !== \"darwin\") {\n return {\n ...base,\n state: \"unsupported\",\n };\n }\n\n const { candidate, mainPids } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n ...base,\n state: \"not-found\",\n };\n }\n\n if (mainPids.length === 0) {\n return {\n ...base,\n state: \"not-running\",\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n runningPids: mainPids,\n };\n }\n\n const lastSwitchAt = stored.lastProfileSwitchAt;\n const lastLaunchAt = stored.lastVerifiedLaunchAt;\n const lastLaunchProfileKey = stored.lastVerifiedLaunchProfileKey;\n const lastObservedPid = stored.lastObservedPid;\n const observedSynced = Boolean(\n currentProfileKey &&\n lastLaunchProfileKey === currentProfileKey &&\n lastObservedPid &&\n mainPids.includes(lastObservedPid),\n );\n const stale = Boolean(\n !observedSynced &&\n currentProfileKey &&\n lastSwitchAt &&\n (!lastLaunchAt ||\n lastLaunchAt < lastSwitchAt ||\n lastLaunchProfileKey !== currentProfileKey),\n );\n\n return {\n ...base,\n state: observedSynced\n ? \"synced\"\n : stale\n ? \"stale\"\n : \"unknown\",\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n runningPids: mainPids,\n };\n}\n\nexport function recordOfficialCodexProfileSwitch(\n profileKey: string | null,\n): Promise<void> {\n return rememberProfileSwitch(profileKey);\n}\n\nasync function ensureBridgeActionListenerForInstance(\n instance: OfficialCodexManagedInstanceState,\n): Promise<void> {\n const profileName = instance.profileName.trim();\n if (!profileName || !instance.cdpPort) {\n return;\n }\n try {\n const targets = await readCdpTargets(instance.cdpPort);\n const target = pickCodexCdpTarget(targets);\n if (!target?.webSocketDebuggerUrl) {\n return;\n }\n startOfficialCodexBridgeActionListener({\n profileName,\n cdpPort: instance.cdpPort,\n debuggerUrl: target.webSocketDebuggerUrl,\n });\n } catch {\n // Listener attach is best-effort; bridge health remains the source of truth.\n }\n}\n\nexport async function getOfficialCodexProfileInstances(\n options: { forceBridgeRefresh?: boolean; profileNames?: string[] } = {},\n): Promise<OfficialCodexInstancesPayload> {\n if (process.platform !== \"darwin\") {\n return {\n state: \"unsupported\",\n appPath: null,\n bundleId: null,\n version: null,\n instances: [],\n unmanaged: [],\n };\n }\n\n const { candidate, mainPids } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n state: \"not-found\",\n appPath: null,\n bundleId: null,\n version: null,\n instances: [],\n unmanaged: [],\n };\n }\n\n const [state, rows] = await Promise.all([getAppState(), readProcessRows()]);\n const allowedProfileNames = options.profileNames\n ? new Set(options.profileNames.map((name) => name.trim()).filter(Boolean))\n : null;\n const managed: OfficialCodexProfileInstancePayload[] = [];\n const managedPids = new Set<number>();\n for (const instance of Object.values(state.officialCodex.instancesByProfileName)) {\n const runtime = await resolveInstanceRuntimeState({ instance, candidate, rows });\n if (runtime.running && instance.pid) {\n managedPids.add(instance.pid);\n }\n if (allowedProfileNames && !allowedProfileNames.has(instance.profileName)) {\n continue;\n }\n let current = instance;\n if (runtime.running && options.forceBridgeRefresh === true) {\n const bridge = await refreshBridgeStateIfNeeded(\n {\n ...instance,\n appServerPid: runtime.appServerPid,\n },\n true,\n true,\n true,\n );\n current = {\n ...instance,\n appServerPid: runtime.appServerPid,\n ...bridge,\n lastVerifiedAt: bridge.bridgeLastCheckedAt ?? instance.lastVerifiedAt,\n lastStatus:\n bridge.bridgeStatus === \"healthy\" ? \"bridged\" : \"running-unbridged\",\n lastError: null,\n };\n if (bridge.bridgeLastCheckedAt !== instance.bridgeLastCheckedAt) {\n await patchManagedInstance(current);\n }\n }\n if (runtime.running) {\n await ensureBridgeActionListenerForInstance(current);\n }\n managed.push(\n managedInstanceToPayload(\n current,\n runtime.running,\n runtime.appServerPid,\n runtime.startedAt,\n ),\n );\n }\n managed.sort((a, b) => a.profileName.localeCompare(b.profileName));\n\n const unmanaged: OfficialCodexUnmanagedInstancePayload[] = [];\n const unmanagedPids = mainPids.filter((entry) => !managedPids.has(entry));\n const allowedFallbackProfileName =\n allowedProfileNames?.size === 1 ? Array.from(allowedProfileNames)[0] : null;\n for (const pid of unmanagedPids) {\n const mainRow = rows.find((row) => row.pid === pid) ?? null;\n const appServerPid = findAppServerPid(rows, pid);\n const startedAt = mainRow?.startedAt ?? null;\n const hint = await describeUnmanagedProfileHint(appServerPid);\n const observedProfileName =\n hint.profileName ??\n (unmanagedPids.length === 1 ? allowedFallbackProfileName : null);\n const observedCdpPort = mainRow ? parseRemoteDebuggingPort(mainRow.args) : null;\n if (\n observedProfileName &&\n observedCdpPort &&\n (!allowedProfileNames || allowedProfileNames.has(observedProfileName))\n ) {\n const existing =\n state.officialCodex.instancesByProfileName[observedProfileName] ?? null;\n let current: OfficialCodexManagedInstanceState = {\n profileName: observedProfileName,\n profileKey: existing?.profileKey ?? null,\n profileHome: existing?.profileHome ?? null,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid,\n appServerPid,\n launchedAt: startedAt,\n lastVerifiedAt: Date.now(),\n lastStatus: \"observed-unmanaged\",\n lastError: null,\n ...bridgeStateUnattached(observedCdpPort, Date.now()),\n desiredQolSettings: existing?.desiredQolSettings ?? null,\n desiredPowerSettings: existing?.desiredPowerSettings ?? null,\n };\n if (options.forceBridgeRefresh === true) {\n const bridge = await refreshBridgeStateIfNeeded(\n current,\n true,\n true,\n true,\n );\n current = {\n ...current,\n ...bridge,\n lastVerifiedAt: bridge.bridgeLastCheckedAt ?? current.lastVerifiedAt,\n lastStatus:\n bridge.bridgeStatus === \"healthy\" ? \"observed-bridged\" : \"observed-unbridged\",\n lastError: null,\n };\n }\n await ensureBridgeActionListenerForInstance(current);\n managed.push(\n managedInstanceToPayload(current, true, appServerPid, startedAt),\n );\n continue;\n }\n unmanaged.push({\n pid,\n appServerPid,\n startedAt: toIso(startedAt),\n uptimeMs:\n typeof startedAt === \"number\" ? Math.max(0, Date.now() - startedAt) : null,\n ...hint,\n });\n }\n\n return {\n state: \"found\",\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n version: candidate.version,\n instances: managed,\n unmanaged,\n };\n}\n\nexport async function setOfficialCodexProfileDraftPrompt(\n profileName: string,\n prompt: string,\n): Promise<OfficialCodexDraftPromptInsertionResult> {\n const normalizedProfileName = profileName.trim();\n const normalizedPrompt = prompt.trim();\n if (!normalizedProfileName || !normalizedPrompt) {\n return {\n status: \"unavailable\",\n reason: \"missing-profile-or-prompt\",\n route: null,\n };\n }\n if (process.platform !== \"darwin\") {\n return {\n status: \"unavailable\",\n reason: \"unsupported-platform\",\n route: null,\n };\n }\n try {\n const [state, { candidate }, rows] = await Promise.all([\n getAppState(),\n resolveCodexAppTarget(),\n readProcessRows(),\n ]);\n if (!candidate) {\n return {\n status: \"unavailable\",\n reason: \"codex-app-not-found\",\n route: null,\n };\n }\n const bridgeTarget = await resolveOfficialCodexBridgeTarget({\n profileName: normalizedProfileName,\n state,\n candidate,\n rows,\n });\n if (!bridgeTarget?.instance.cdpPort) {\n return {\n status: \"unavailable\",\n reason: \"target-instance-not-running\",\n route: null,\n };\n }\n const targets = await readCdpTargets(bridgeTarget.instance.cdpPort);\n const target = pickCodexCdpTarget(targets);\n if (!target?.webSocketDebuggerUrl) {\n return {\n status: \"unavailable\",\n reason: \"cdp-target-not-found\",\n route: null,\n };\n }\n startOfficialCodexBridgeActionListener({\n profileName: normalizedProfileName,\n cdpPort: bridgeTarget.instance.cdpPort,\n debuggerUrl: target.webSocketDebuggerUrl,\n });\n const result = await evaluateOfficialCodexBridgeCommand(\n target.webSocketDebuggerUrl,\n \"setDraft\",\n createBridgeSetDraftPromptExpression(normalizedPrompt),\n false,\n );\n return normalizeDraftPromptInsertionResult(result);\n } catch (error) {\n return {\n status: \"failed\",\n reason:\n sanitizeUserFacingError(error) ?? \"draft-insertion-failed\",\n route: null,\n };\n }\n}\n\nexport async function readOfficialCodexApplyRuntimeContext(): Promise<OfficialCodexApplyRuntimeContext> {\n const [state, { candidate }, rows] = await Promise.all([\n getAppState(),\n resolveCodexAppTarget(),\n readProcessRows(),\n ]);\n return { state, candidate, rows };\n}\n\nexport async function applyOfficialCodexProfileQol(\n profileName: string,\n settings: OfficialCodexQolSettingsPayload,\n runtimeContext?: OfficialCodexApplyRuntimeContext,\n): Promise<OfficialCodexQolApplyResultPayload> {\n const normalizedProfileName = profileName.trim();\n const normalizedSettings = normalizeOfficialCodexQolSettings(settings);\n const base = (\n fields: Partial<OfficialCodexQolApplyResultPayload>,\n ): OfficialCodexQolApplyResultPayload => ({\n status: fields.status ?? \"failed\",\n profileName: normalizedProfileName,\n reason: fields.reason ?? null,\n route: fields.route ?? null,\n wideViewEnabled: normalizedSettings.wideViewEnabled,\n wideViewMaxWidth: normalizedSettings.wideViewMaxWidth,\n scrollRestoreEnabled: normalizedSettings.scrollRestoreEnabled,\n conversationTimelineEnabled:\n normalizedSettings.conversationTimelineEnabled,\n inCodexStatusEnabled: normalizedSettings.inCodexStatusEnabled,\n qolStatus: fields.qolStatus ?? null,\n });\n if (!normalizedProfileName) {\n return base({ status: \"skipped\", reason: \"missing-profile\" });\n }\n if (process.platform !== \"darwin\") {\n return base({ status: \"skipped\", reason: \"unsupported-platform\" });\n }\n try {\n const { state, candidate, rows } =\n runtimeContext ?? (await readOfficialCodexApplyRuntimeContext());\n if (!candidate) {\n return base({ status: \"skipped\", reason: \"codex-app-not-found\" });\n }\n const bridgeTarget = await resolveOfficialCodexBridgeTarget({\n profileName: normalizedProfileName,\n state,\n candidate,\n rows,\n });\n if (!bridgeTarget?.instance.cdpPort) {\n return base({ status: \"skipped\", reason: \"target-instance-not-running\" });\n }\n const instance = bridgeTarget.instance;\n const cdpPort = bridgeTarget.instance.cdpPort;\n const targets = await readCdpTargets(cdpPort);\n const target = pickCodexCdpTarget(targets);\n if (!target?.webSocketDebuggerUrl) {\n return base({ status: \"failed\", reason: \"cdp-target-not-found\" });\n }\n startOfficialCodexBridgeActionListener({\n profileName: normalizedProfileName,\n cdpPort,\n debuggerUrl: target.webSocketDebuggerUrl,\n });\n const qolExpression = createBridgeApplyQolExpression(normalizedSettings);\n const value = await evaluateOfficialCodexBridgeCommand(\n target.webSocketDebuggerUrl,\n \"applyQol\",\n qolExpression,\n true,\n );\n await registerQolNewDocumentScript(\n target.webSocketDebuggerUrl,\n qolExpression,\n );\n const result = normalizeQolScriptResult(value, normalizedSettings);\n const payload = {\n ...base({\n status: result.status,\n reason: result.reason,\n route: result.route,\n qolStatus: result.qolStatus,\n }),\n wideViewEnabled: result.wideViewEnabled,\n wideViewMaxWidth: result.wideViewMaxWidth,\n scrollRestoreEnabled: result.scrollRestoreEnabled,\n conversationTimelineEnabled: result.conversationTimelineEnabled,\n inCodexStatusEnabled: result.inCodexStatusEnabled,\n qolStatus: result.qolStatus,\n };\n // Persist the user's DESIRED qol to the managed instance whenever the bridge\n // responded (we got here = the window was reachable), even if a feature\n // reports degraded. Gating this on status === \"applied\" froze the cache when\n // any single feature degraded (e.g. timeline can't bind off-thread), so the\n // instance poll kept re-applying stale toggle values — reverting overlay\n // toggles like Hand off immediately after the user changed them.\n if (bridgeTarget.managed) {\n const applied = result.status === \"applied\";\n await patchManagedInstance({\n ...instance,\n appServerPid: bridgeTarget.runtime.appServerPid,\n bridgeQol: result.qolStatus ?? instance.bridgeQol,\n desiredQolSettings: hasActiveQolSettings(normalizedSettings)\n ? normalizedSettings\n : null,\n lastVerifiedAt: Date.now(),\n lastStatus: applied ? \"qol-applied\" : instance.lastStatus,\n lastError: applied ? null : result.reason ?? instance.lastError,\n });\n }\n return payload;\n } catch (error) {\n return base({\n status: \"failed\",\n reason: sanitizeUserFacingError(error) ?? \"qol-apply-failed\",\n });\n }\n}\n\nexport async function applyOfficialCodexProfilePower(\n profileName: string,\n settings: OfficialCodexPowerSettingsPayload,\n runtimeContext?: OfficialCodexApplyRuntimeContext,\n): Promise<OfficialCodexPowerApplyResultPayload> {\n const normalizedProfileName = profileName.trim();\n const normalizedSettings = normalizeOfficialCodexPowerSettings(settings);\n const base = (\n fields: Partial<OfficialCodexPowerApplyResultPayload>,\n ): OfficialCodexPowerApplyResultPayload => ({\n status: fields.status ?? \"failed\",\n profileName: normalizedProfileName,\n reason: fields.reason ?? null,\n route: fields.route ?? null,\n settings: normalizedSettings,\n powerStatus: fields.powerStatus ?? null,\n reloadRequired: fields.reloadRequired ?? false,\n reloadStatus:\n fields.reloadStatus ?? (fields.reloadRequired ? \"failed\" : \"not-needed\"),\n });\n if (!normalizedProfileName) {\n return base({ status: \"skipped\", reason: \"missing-profile\" });\n }\n if (process.platform !== \"darwin\") {\n return base({ status: \"skipped\", reason: \"unsupported-platform\" });\n }\n try {\n const { state, candidate, rows } =\n runtimeContext ?? (await readOfficialCodexApplyRuntimeContext());\n if (!candidate) {\n return base({ status: \"skipped\", reason: \"codex-app-not-found\" });\n }\n const bridgeTarget = await resolveOfficialCodexBridgeTarget({\n profileName: normalizedProfileName,\n state,\n candidate,\n rows,\n });\n if (!bridgeTarget?.instance.cdpPort) {\n return base({ status: \"skipped\", reason: \"target-instance-not-running\" });\n }\n const instance = bridgeTarget.instance;\n const cdpPort = bridgeTarget.instance.cdpPort;\n const targets = await readCdpTargets(cdpPort);\n const target = pickCodexCdpTarget(targets);\n if (!target?.webSocketDebuggerUrl) {\n return base({ status: \"failed\", reason: \"cdp-target-not-found\" });\n }\n startOfficialCodexBridgeActionListener({\n profileName: normalizedProfileName,\n cdpPort,\n debuggerUrl: target.webSocketDebuggerUrl,\n });\n const modelWhitelistModels = resolvePowerModelWhitelistModels({\n settings: normalizedSettings,\n state,\n });\n const value = await evaluateOfficialCodexBridgeCommand(\n target.webSocketDebuggerUrl,\n \"applyPower\",\n createBridgeApplyPowerExpression(\n normalizedSettings,\n createBridgePowerSettingsExpression({\n settings: normalizedSettings,\n modelWhitelistModels,\n }),\n ),\n true,\n );\n const result = normalizePowerScriptResult(value);\n if (result.status === \"applied\") {\n const nextDesiredPowerSettings = hasActivePowerSettings(\n normalizedSettings,\n )\n ? normalizedSettings\n : null;\n const nextInstance = {\n ...instance,\n appServerPid: bridgeTarget.runtime.appServerPid,\n bridgePower: result.powerStatus ?? instance.bridgePower,\n bridgeRelayStatus:\n result.powerStatus?.relay ?? instance.bridgeRelayStatus,\n desiredPowerSettings: nextDesiredPowerSettings,\n lastVerifiedAt: Date.now(),\n lastStatus: \"power-applied\",\n lastError: null,\n };\n if (bridgeTarget.managed) {\n await patchManagedInstance(nextInstance);\n }\n let reloadStatus: OfficialCodexPowerApplyResultPayload[\"reloadStatus\"] =\n \"not-needed\";\n let finalPowerStatus = result.powerStatus;\n if (result.reloadRequired) {\n reloadStatus = \"failed\";\n const reloadStarted = await reloadOfficialCodexBridgePage(\n target.webSocketDebuggerUrl,\n );\n if (reloadStarted) {\n const reloadedBridge = await waitForBridgeStateAfterReload(\n nextInstance,\n );\n if (reloadedBridge.bridgeStatus === \"healthy\") {\n finalPowerStatus = reloadedBridge.bridgePower;\n if (bridgeTarget.managed) {\n await patchManagedInstance({\n ...nextInstance,\n ...reloadedBridge,\n lastVerifiedAt: Date.now(),\n lastStatus: \"power-reloaded\",\n lastError: null,\n });\n }\n reloadStatus = \"reloaded\";\n } else {\n if (bridgeTarget.managed) {\n await patchManagedInstance({\n ...nextInstance,\n ...reloadedBridge,\n lastVerifiedAt: Date.now(),\n lastStatus: \"power-reload-failed\",\n lastError:\n sanitizeUserFacingError(reloadedBridge.bridgeError) ??\n \"bridge-reload-reapply-failed\",\n });\n }\n }\n }\n }\n return base({\n status: result.status,\n reason: result.reason,\n route: result.route,\n powerStatus: finalPowerStatus,\n reloadRequired: result.reloadRequired,\n reloadStatus,\n });\n }\n return base({\n status: result.status,\n reason: result.reason,\n route: result.route,\n powerStatus: result.powerStatus,\n reloadRequired: result.reloadRequired,\n });\n } catch (error) {\n return base({\n status: \"failed\",\n reason: sanitizeUserFacingError(error) ?? \"power-apply-failed\",\n });\n }\n}\n\nexport function launchOfficialCodexProfileInstance(\n options: OfficialCodexProfileLaunchOptions,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(() => launchOfficialCodexProfileInstanceOnce(options));\n}\n\nasync function launchOfficialCodexProfileInstanceOnce(\n options: OfficialCodexProfileLaunchOptions,\n): Promise<OfficialCodexProfileActionPayload> {\n if (process.platform !== \"darwin\") {\n return {\n status: \"skipped\",\n profileName: options.profileName,\n instance: null,\n reason: \"unsupported-platform\",\n };\n }\n\n const { candidate, mainPids } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"skipped\",\n profileName: options.profileName,\n instance: null,\n reason: \"official-codex-app-not-found\",\n };\n }\n\n const existing = await readManagedInstance(options.profileName);\n const desiredQolSettings = resolveDesiredQolSettings({\n requested: options.desiredQolSettings,\n existing: existing?.desiredQolSettings,\n });\n const desiredPowerSettings = resolveDesiredPowerSettings({\n requested: options.desiredPowerSettings,\n existing: existing?.desiredPowerSettings,\n });\n if (existing) {\n const rows = await readProcessRows();\n const runtime = await resolveInstanceRuntimeState({ instance: existing, candidate, rows });\n if (runtime.running) {\n const verifiedAt = Date.now();\n const bridge = await refreshBridgeStateIfNeeded(\n {\n ...existing,\n profileHome: existing.profileHome ?? options.profileHome,\n desiredQolSettings,\n desiredPowerSettings,\n appServerPid: runtime.appServerPid,\n },\n true,\n true,\n true,\n );\n const verified: OfficialCodexManagedInstanceState = {\n ...existing,\n profileHome: existing.profileHome ?? options.profileHome,\n appServerPid: runtime.appServerPid,\n ...bridge,\n desiredQolSettings,\n desiredPowerSettings,\n lastVerifiedAt: verifiedAt,\n lastStatus:\n bridge.bridgeStatus === \"healthy\"\n ? \"already-running-bridged\"\n : \"already-running-unbridged\",\n lastError: null,\n };\n await patchManagedInstance(verified);\n return {\n status: \"already-running\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(\n verified,\n true,\n runtime.appServerPid,\n runtime.startedAt,\n ),\n reason: null,\n };\n }\n }\n\n let cdpPort: number;\n try {\n cdpPort = await reserveLoopbackPort();\n } catch {\n const failed: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: null,\n appServerPid: null,\n ...bridgeStateUnavailable(),\n desiredQolSettings,\n desiredPowerSettings,\n launchedAt: null,\n lastVerifiedAt: null,\n lastStatus: \"failed\",\n lastError: \"cdp-port-unavailable\",\n };\n await patchManagedInstance(failed);\n return {\n status: \"failed\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(failed, false),\n reason: \"cdp-port-unavailable\",\n };\n }\n\n const launch = await openCodexWithProfileHome(\n candidate,\n options.profileHome,\n options.profileName,\n cdpPort,\n new Set(mainPids),\n );\n if (!launch.opened) {\n const failed: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: null,\n appServerPid: null,\n ...bridgeStateUnavailable(),\n desiredQolSettings,\n desiredPowerSettings,\n launchedAt: null,\n lastVerifiedAt: null,\n lastStatus: \"failed\",\n lastError: \"open-failed\",\n };\n await patchManagedInstance(failed);\n return {\n status: \"failed\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(failed, false),\n reason: \"open-failed\",\n };\n }\n\n const launchedPid = launch.pid;\n if (launchedPid === null) {\n const failed: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: null,\n appServerPid: null,\n ...bridgeStateUnavailable(),\n desiredQolSettings,\n desiredPowerSettings,\n launchedAt: null,\n lastVerifiedAt: null,\n lastStatus: \"failed\",\n lastError: \"launch-timeout\",\n };\n await patchManagedInstance(failed);\n return {\n status: \"failed\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(failed, false),\n reason: \"launch-timeout\",\n };\n }\n\n const appServerPid = await waitForAppServerPid(\n launchedPid,\n options.profileHome,\n );\n if (appServerPid === null) {\n const failed: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: null,\n appServerPid: null,\n ...bridgeStateUnavailable(),\n desiredQolSettings,\n desiredPowerSettings,\n launchedAt: null,\n lastVerifiedAt: Date.now(),\n lastStatus: \"failed\",\n lastError: \"app-server-not-verified\",\n };\n await patchManagedInstance(failed);\n return {\n status: \"failed\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(failed, false),\n reason: \"app-server-not-verified\",\n };\n }\n const now = Date.now();\n const baseInstance: OfficialCodexManagedInstanceState = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: options.profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: launchedPid,\n appServerPid,\n ...bridgeStateUnattached(cdpPort, now),\n desiredQolSettings,\n desiredPowerSettings,\n launchedAt: now,\n lastVerifiedAt: now,\n lastStatus: \"started\",\n lastError: null,\n };\n const bridge = await waitForBridgeStateAfterLaunch(baseInstance);\n const instance: OfficialCodexManagedInstanceState = {\n ...baseInstance,\n ...bridge,\n lastStatus:\n bridge.bridgeStatus === \"healthy\" ? \"started-bridged\" : \"started-unbridged\",\n lastError: null,\n };\n await patchManagedInstance(instance);\n return {\n status: \"started\",\n profileName: options.profileName,\n instance: managedInstanceToPayload(instance, true, appServerPid),\n reason: null,\n };\n}\n\nexport function stopOfficialCodexProfileInstance(\n profileName: string,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(() => stopOfficialCodexProfileInstanceOnce(profileName));\n}\n\nasync function stopOfficialCodexProfileInstanceOnce(\n profileName: string,\n): Promise<OfficialCodexProfileActionPayload> {\n const existing = await readManagedInstance(profileName);\n if (!existing) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"not-managed\",\n };\n }\n\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n const verifiedAt = Date.now();\n const stopped: OfficialCodexManagedInstanceState = {\n ...existing,\n pid: null,\n appServerPid: null,\n ...bridgeStateUnavailable(),\n lastVerifiedAt: verifiedAt,\n lastStatus: \"not-running\",\n lastError: \"official-codex-app-not-found\",\n };\n await patchManagedInstance(stopped);\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(stopped, false),\n reason: \"official-codex-app-not-found\",\n };\n }\n\n const rows = await readProcessRows();\n const runtime = await resolveInstanceRuntimeState({ instance: existing, candidate, rows });\n if (!runtime.running || !existing.pid) {\n const verifiedAt = Date.now();\n const stopped: OfficialCodexManagedInstanceState = {\n ...existing,\n pid: null,\n appServerPid: null,\n ...bridgeStateUnavailable(),\n lastVerifiedAt: verifiedAt,\n lastStatus: \"not-running\",\n lastError: null,\n };\n await patchManagedInstance(stopped);\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(stopped, false),\n reason: null,\n };\n }\n\n const tree = [existing.pid, ...getDescendantPids(existing.pid, rows)]\n .filter((pid, index, all) => all.indexOf(pid) === index)\n .sort((a, b) => b - a);\n await signalPids(tree, \"SIGTERM\");\n const exited = await waitForMainPidExit(existing.pid, PROCESS_EXIT_GRACE_MS);\n if (!exited) {\n await signalPids(tree, \"SIGKILL\");\n await waitForMainPidExit(existing.pid, EXIT_WAIT_MS);\n }\n\n const stillRunning = (await readProcessRows()).some((row) => row.pid === existing.pid);\n const verifiedAt = Date.now();\n const stopped: OfficialCodexManagedInstanceState = {\n ...existing,\n pid: stillRunning ? existing.pid : null,\n appServerPid: stillRunning ? runtime.appServerPid : null,\n ...(stillRunning\n ? bridgeStateForStoredInstance(existing, true, verifiedAt)\n : bridgeStateUnavailable()),\n lastVerifiedAt: verifiedAt,\n lastStatus: stillRunning ? \"failed\" : \"stopped\",\n lastError: stillRunning ? \"stop-timeout\" : null,\n };\n await patchManagedInstance(stopped);\n return {\n status: stillRunning ? \"failed\" : \"stopped\",\n profileName,\n instance: managedInstanceToPayload(\n stopped,\n stillRunning,\n stopped.appServerPid,\n runtime.startedAt,\n ),\n reason: stillRunning ? \"stop-timeout\" : null,\n };\n}\n\nexport function focusOfficialCodexProfileInstance(\n profileName: string,\n desiredSettings?: {\n qol?: OfficialCodexQolSettingsPayload | null;\n power?: OfficialCodexPowerSettingsPayload | null;\n },\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const existing = await readManagedInstance(profileName);\n if (!existing) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"not-managed\",\n };\n }\n const desiredQolSettings = resolveDesiredQolSettings({\n requested: desiredSettings?.qol,\n existing: existing.desiredQolSettings,\n });\n const desiredPowerSettings = resolveDesiredPowerSettings({\n requested: desiredSettings?.power,\n existing: existing.desiredPowerSettings,\n });\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(existing, false),\n reason: \"official-codex-app-not-found\",\n };\n }\n const rows = await readProcessRows();\n const runtime = await resolveInstanceRuntimeState({ instance: existing, candidate, rows });\n if (!runtime.running || !existing.pid) {\n return {\n status: \"not-running\",\n profileName,\n instance: managedInstanceToPayload(existing, false),\n reason: null,\n };\n }\n const focused = await focusMainPid(existing.pid);\n const verifiedAt = Date.now();\n const bridge = await refreshBridgeStateIfNeeded(\n {\n ...existing,\n desiredQolSettings,\n desiredPowerSettings,\n appServerPid: runtime.appServerPid,\n },\n true,\n true,\n true,\n );\n const verified: OfficialCodexManagedInstanceState = {\n ...existing,\n appServerPid: runtime.appServerPid,\n ...bridge,\n desiredQolSettings,\n desiredPowerSettings,\n lastVerifiedAt: verifiedAt,\n lastStatus: focused ? \"focused\" : \"focus-unknown\",\n lastError: focused ? null : \"focus-unknown\",\n };\n await patchManagedInstance(verified);\n return {\n status: focused ? \"focused\" : \"focus-unknown\",\n profileName,\n instance: managedInstanceToPayload(\n verified,\n true,\n runtime.appServerPid,\n runtime.startedAt,\n ),\n reason: focused ? null : \"focus-unknown\",\n };\n });\n}\n\nexport function focusOfficialCodexObservedProfileInstance(\n profileName: string,\n pid: number,\n appServerPid: number | null,\n desiredSettings?: {\n profileKey?: string | null;\n profileHome?: string | null;\n qol?: OfficialCodexQolSettingsPayload | null;\n power?: OfficialCodexPowerSettingsPayload | null;\n },\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"official-codex-app-not-found\",\n };\n }\n const rows = await readProcessRows();\n const mainRow = rows.find((row) => row.pid === pid);\n if (!mainRow || !isMainProcessRow(mainRow, candidate)) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: null,\n };\n }\n\n const runtimeAppServerPid = findAppServerPid(rows, pid) ?? appServerPid;\n const focused = await focusMainPid(pid);\n const cdpPort = parseRemoteDebuggingPort(mainRow.args);\n const checkedAt = Date.now();\n const existing = await readManagedInstance(profileName);\n const profileKey =\n desiredSettings?.profileKey ?? existing?.profileKey ?? null;\n const profileHome =\n desiredSettings?.profileHome ?? existing?.profileHome ?? null;\n const desiredQolSettings = resolveDesiredQolSettings({\n requested: desiredSettings?.qol,\n existing: existing?.desiredQolSettings,\n });\n const desiredPowerSettings = resolveDesiredPowerSettings({\n requested: desiredSettings?.power,\n existing: existing?.desiredPowerSettings,\n });\n const bridge =\n cdpPort !== null\n ? await refreshBridgeStateIfNeeded(\n {\n profileName,\n profileKey,\n profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid,\n appServerPid: runtimeAppServerPid,\n ...bridgeStateUnattached(cdpPort, checkedAt),\n desiredQolSettings,\n desiredPowerSettings,\n launchedAt: null,\n lastVerifiedAt: checkedAt,\n lastStatus: focused ? \"focused\" : \"focus-unknown\",\n lastError: focused ? null : \"focus-unknown\",\n },\n true,\n true,\n true,\n )\n : bridgeStateUnavailable();\n const instance: OfficialCodexManagedInstanceState = {\n profileName,\n profileKey,\n profileHome,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid,\n appServerPid: runtimeAppServerPid,\n ...bridge,\n desiredQolSettings,\n desiredPowerSettings,\n launchedAt: null,\n lastVerifiedAt: checkedAt,\n lastStatus: focused ? \"focused\" : \"focus-unknown\",\n lastError: focused ? null : \"focus-unknown\",\n };\n await patchManagedInstance(instance);\n return {\n status: focused ? \"focused\" : \"focus-unknown\",\n profileName,\n instance: managedInstanceToPayload(\n instance,\n true,\n runtimeAppServerPid,\n mainRow.startedAt,\n ),\n reason: focused ? null : \"focus-unknown\",\n };\n });\n}\n\nexport function stopOfficialCodexObservedProfileInstance(\n profileName: string,\n pid: number,\n appServerPid: number | null,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const { candidate } = await resolveCodexAppTarget();\n if (!candidate) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: \"official-codex-app-not-found\",\n };\n }\n const rows = await readProcessRows();\n const mainRow = rows.find((row) => row.pid === pid);\n if (!mainRow || !isMainProcessRow(mainRow, candidate)) {\n return {\n status: \"not-running\",\n profileName,\n instance: null,\n reason: null,\n };\n }\n\n const runtimeAppServerPid = findAppServerPid(rows, pid) ?? appServerPid;\n const tree = [pid, ...getDescendantPids(pid, rows)]\n .filter((entry, index, all) => all.indexOf(entry) === index)\n .sort((a, b) => b - a);\n await signalPids(tree, \"SIGTERM\");\n const exited = await waitForMainPidExit(pid, PROCESS_EXIT_GRACE_MS);\n if (!exited) {\n await signalPids(tree, \"SIGKILL\");\n await waitForMainPidExit(pid, EXIT_WAIT_MS);\n }\n\n const stillRunning = (await readProcessRows()).some((row) => row.pid === pid);\n const bridge = bridgeStateUnavailable();\n const instance: OfficialCodexProfileInstancePayload = {\n profileName,\n profileKey: null,\n appPath: candidate.appPath,\n bundleId: candidate.bundleId,\n pid: stillRunning ? pid : null,\n appServerPid: stillRunning ? runtimeAppServerPid : null,\n cdpPort: bridge.cdpPort,\n bridgeStatus: bridge.bridgeStatus,\n bridgeLastCheckedAt: toIso(bridge.bridgeLastCheckedAt),\n bridgeError: sanitizeUserFacingError(bridge.bridgeError),\n bridgeVersion: bridge.bridgeVersion,\n bridgeRoute: bridge.bridgeRoute,\n bridgeDevToolsUrl: bridge.bridgeDevToolsUrl,\n bridgeCapabilities: bridge.bridgeCapabilities,\n bridgeActiveThreadId: bridge.bridgeActiveThreadId,\n bridgeActiveThreadTitle: bridge.bridgeActiveThreadTitle,\n bridgeActiveThreadUpdatedAt: toIso(bridge.bridgeActiveThreadUpdatedAt),\n bridgeComposerText: bridge.bridgeComposerText,\n bridgeWorkspacePath: bridge.bridgeWorkspacePath,\n bridgeModel: bridge.bridgeModel,\n bridgeActivityState: bridge.bridgeActivityState,\n bridgeQol: bridge.bridgeQol,\n bridgePower: bridge.bridgePower,\n bridgeRelayStatus: bridge.bridgeRelayStatus,\n running: stillRunning,\n startedAt: stillRunning ? toIso(mainRow.startedAt) : null,\n uptimeMs:\n stillRunning && typeof mainRow.startedAt === \"number\"\n ? Math.max(0, Date.now() - mainRow.startedAt)\n : null,\n launchedAt: null,\n lastVerifiedAt: new Date().toISOString(),\n lastStatus: stillRunning ? \"failed\" : \"stopped\",\n lastError: stillRunning ? \"stop-timeout\" : null,\n };\n return {\n status: stillRunning ? \"failed\" : \"stopped\",\n profileName,\n instance,\n reason: stillRunning ? \"stop-timeout\" : null,\n };\n });\n}\n\nexport async function restartOfficialCodexProfileInstance(\n options: OfficialCodexProfileLaunchOptions,\n): Promise<OfficialCodexProfileActionPayload> {\n return enqueueProfileAction(async () => {\n const stopped = await stopOfficialCodexProfileInstanceOnce(options.profileName);\n if (stopped.status === \"failed\") {\n return stopped;\n }\n if (stopped.status === \"stopped\") {\n await sleep(POST_EXIT_SETTLE_MS);\n }\n const launched = await launchOfficialCodexProfileInstanceOnce(options);\n return {\n ...launched,\n status: launched.status === \"started\" ? \"restarted\" : launched.status,\n };\n });\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nconst ROLLOUT_DIRS = [\"sessions\", \"archived_sessions\"] as const;\n\ntype JsonRecord = Record<string, unknown>;\ntype RolloutDirent = {\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n};\ntype RolloutMatch = {\n path: string;\n updatedAtMs: number | null;\n};\ntype StatementLike = {\n all: (...params: unknown[]) => unknown[];\n};\ntype DatabaseLike = {\n prepare: (sql: string) => StatementLike;\n close: () => unknown;\n};\nexport type OfficialCodexThreadRecord = {\n rolloutPath: string | null;\n title: string | null;\n cwd: string | null;\n updatedAt: string | null;\n updatedAtMs: number | null;\n};\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nasync function collectRolloutFiles(root: string): Promise<string[]> {\n const files: string[] = [];\n async function visit(dir: string): Promise<void> {\n let entries: RolloutDirent[];\n try {\n entries = await fs.readdir(dir, {\n withFileTypes: true,\n encoding: \"utf8\",\n });\n } catch {\n return;\n }\n const childVisits: Array<Promise<void>> = [];\n for (const entry of entries) {\n const entryName = String(entry.name);\n const entryPath = path.join(dir, entryName);\n if (entry.isDirectory()) {\n childVisits.push(visit(entryPath));\n continue;\n }\n if (\n entry.isFile() &&\n entryName.startsWith(\"rollout-\") &&\n entryName.endsWith(\".jsonl\")\n ) {\n files.push(entryPath);\n }\n }\n await Promise.all(childVisits);\n }\n await visit(root);\n files.sort();\n return files;\n}\n\nasync function findRolloutFileByScan(\n profileHome: string,\n threadId: string,\n): Promise<RolloutMatch | null> {\n let best: RolloutMatch | null = null;\n const variants = threadIdVariants(threadId);\n for (const dirname of ROLLOUT_DIRS) {\n const root = path.join(profileHome, dirname);\n const files = await collectRolloutFiles(root);\n for (const file of files) {\n const basename = path.basename(file);\n if (!variants.some((variant) => basename.includes(variant))) {\n continue;\n }\n const stat = await fs.stat(file).catch(() => null);\n const updatedAtMs =\n stat && Number.isFinite(stat.mtimeMs) ? stat.mtimeMs : null;\n if (\n !best ||\n (updatedAtMs ?? 0) > (best.updatedAtMs ?? 0) ||\n ((updatedAtMs ?? 0) === (best.updatedAtMs ?? 0) && file > best.path)\n ) {\n best = { path: file, updatedAtMs };\n }\n }\n }\n return best;\n}\n\nasync function openReadonlyDatabase(dbPath: string): Promise<DatabaseLike> {\n if (process.versions.bun !== undefined) {\n const sqlite = await (Function(\"return import('bun:sqlite')\")() as Promise<any>);\n const database = new sqlite.Database(dbPath, { readonly: true, create: false });\n return {\n prepare: database.prepare.bind(database),\n close: database.close.bind(database),\n };\n }\n const sqlite = await (Function(\"return import('node:sqlite')\")() as Promise<any>);\n const database = new sqlite.DatabaseSync(dbPath, { readOnly: true });\n return {\n prepare: database.prepare.bind(database),\n close: database.close.bind(database),\n };\n}\n\nfunction threadIdVariants(threadId: string): string[] {\n const trimmed = threadId.trim();\n let decoded = trimmed;\n try {\n decoded = decodeURIComponent(trimmed).trim();\n } catch {\n // Keep raw value if it is not URI encoded.\n }\n const bare = decoded.toLowerCase().startsWith(\"local:\")\n ? decoded.slice(\"local:\".length)\n : decoded;\n return Array.from(\n new Set(\n [trimmed, decoded, bare, `local:${bare}`, `local%3A${bare}`].filter(Boolean),\n ),\n );\n}\n\nfunction recordString(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction recordNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === \"bigint\") {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value.trim());\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n}\n\nfunction normalizeTimestampMs(value: unknown): number | null {\n const numeric = recordNumber(value);\n if (numeric !== null) {\n return numeric > 1_000_000_000_000 ? numeric : numeric * 1_000;\n }\n const text = recordString(value);\n if (!text) {\n return null;\n }\n const parsed = Date.parse(text);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction resolveRolloutPath(\n profileHome: string,\n rolloutPath: string | null,\n): string | null {\n if (!rolloutPath) {\n return null;\n }\n return path.isAbsolute(rolloutPath)\n ? rolloutPath\n : path.join(profileHome, rolloutPath);\n}\n\nasync function readThreadRecordFromStateDb(\n profileHome: string,\n threadId: string,\n): Promise<OfficialCodexThreadRecord | null> {\n const dbPath = path.join(profileHome, \"state_5.sqlite\");\n try {\n await fs.access(dbPath);\n } catch {\n return null;\n }\n let db: DatabaseLike | null = null;\n try {\n db = await openReadonlyDatabase(dbPath);\n const columns = new Set(\n db\n .prepare(\"PRAGMA table_info(threads)\")\n .all()\n .map((row) => (isRecord(row) ? recordString(row.name) : null))\n .filter((name): name is string => Boolean(name)),\n );\n const idColumn = columns.has(\"id\")\n ? \"id\"\n : columns.has(\"thread_id\")\n ? \"thread_id\"\n : null;\n if (!idColumn) {\n return null;\n }\n const variants = threadIdVariants(threadId);\n const placeholders = variants.map(() => \"?\").join(\", \");\n const select = [\n columns.has(\"rollout_path\")\n ? \"rollout_path AS rollout_path\"\n : \"NULL AS rollout_path\",\n columns.has(\"title\") ? \"title AS title\" : \"NULL AS title\",\n columns.has(\"cwd\") ? \"cwd AS cwd\" : \"NULL AS cwd\",\n columns.has(\"updated_at\")\n ? \"updated_at AS updated_at\"\n : \"NULL AS updated_at\",\n columns.has(\"updated_at_ms\")\n ? \"updated_at_ms AS updated_at_ms\"\n : \"NULL AS updated_at_ms\",\n columns.has(\"created_at_ms\")\n ? \"created_at_ms AS created_at_ms\"\n : \"NULL AS created_at_ms\",\n ].join(\", \");\n const orderByColumn = columns.has(\"updated_at_ms\")\n ? \"updated_at_ms\"\n : columns.has(\"updated_at\")\n ? \"updated_at\"\n : columns.has(\"created_at_ms\")\n ? \"created_at_ms\"\n : null;\n const orderBy = orderByColumn\n ? ` ORDER BY ${orderByColumn} DESC, ${idColumn} DESC`\n : ` ORDER BY ${idColumn} DESC`;\n const rows = db\n .prepare(\n `SELECT ${select} FROM threads WHERE ${idColumn} IN (${placeholders})${orderBy} LIMIT 1`,\n )\n .all(...variants);\n const row = rows.find(isRecord);\n if (!row) {\n return null;\n }\n return {\n rolloutPath: resolveRolloutPath(\n profileHome,\n recordString(row.rollout_path),\n ),\n title: recordString(row.title),\n cwd: recordString(row.cwd),\n updatedAt: recordString(row.updated_at),\n updatedAtMs:\n normalizeTimestampMs(row.updated_at_ms) ??\n normalizeTimestampMs(row.updated_at) ??\n normalizeTimestampMs(row.created_at_ms),\n };\n } catch {\n return null;\n } finally {\n db?.close();\n }\n}\n\nexport async function findOfficialCodexThreadRecord(\n profileHome: string,\n threadId: string,\n): Promise<OfficialCodexThreadRecord | null> {\n const stateRecord = await readThreadRecordFromStateDb(profileHome, threadId);\n if (stateRecord) {\n return stateRecord;\n }\n const rolloutMatch = await findRolloutFileByScan(profileHome, threadId);\n if (!rolloutMatch) {\n return null;\n }\n const updatedAt =\n rolloutMatch.updatedAtMs === null\n ? null\n : new Date(rolloutMatch.updatedAtMs).toISOString();\n return {\n rolloutPath: rolloutMatch.path,\n title: null,\n cwd: null,\n updatedAt,\n updatedAtMs: rolloutMatch.updatedAtMs,\n };\n}\n\nexport async function findOfficialCodexRolloutFile(\n profileHome: string,\n threadId: string,\n): Promise<string | null> {\n const threadRecord = await findOfficialCodexThreadRecord(profileHome, threadId);\n if (threadRecord?.rolloutPath) {\n try {\n await fs.access(threadRecord.rolloutPath);\n return threadRecord.rolloutPath;\n } catch {\n // Fall back to rollout filename scan when sqlite points at a stale path.\n }\n }\n return (await findRolloutFileByScan(profileHome, threadId))?.path ?? null;\n}\n","import { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { assertProfileCreationAllowed } from \"@codexuse/runtime-profiles/license/guard\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { maxUsedPercent } from \"@codexuse/runtime-profiles/profiles/rate-limit-notifier\";\nimport { getStoredAutoRollSettings } from \"@codexuse/runtime-codex/codex/settings\";\nimport {\n focusOfficialCodexObservedProfileInstance,\n focusOfficialCodexProfileInstance,\n getOfficialCodexProfileInstances,\n launchOfficialCodexProfileInstance,\n recordOfficialCodexActivity,\n recordOfficialCodexActivationResult,\n recordOfficialCodexProfileSwitch,\n} from \"@codexuse/runtime-codex/codex/officialAppRestart\";\nimport type {\n OfficialCodexInstancesPayload,\n OfficialCodexProfileActionPayload,\n OfficialCodexUnmanagedInstancePayload,\n} from \"@codexuse/contracts/desktop/ipc-types\";\nimport type {\n OrganizationInfo,\n Profile,\n RateLimitSnapshot,\n RateLimitWindow,\n} from \"@codexuse/contracts/profiles/types\";\nimport { resolveProfileIdentityKeyFromProfile } from \"@codexuse/contracts/profiles/identity\";\nimport {\n AUTO_ROLL_SWITCH_REMAINING_MAX,\n AUTO_ROLL_SWITCH_REMAINING_MIN,\n DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD,\n DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD,\n sanitizeAutoRollRearmRemainingThreshold,\n sanitizeAutoRollSwitchRemainingThreshold,\n} from \"@codexuse/contracts/settings/auto-roll\";\nimport {\n DEFAULT_AUTOROLL_INTERVAL_SECONDS,\n hasFlag,\n parseIntegerFlag,\n parseLoginMode,\n parseNumericFlag,\n stripFlags,\n} from \"../platform/args\";\nimport {\n resolveCodexBinary,\n resolveLoginMode,\n runCodexLogin,\n} from \"../platform/codexCli\";\nimport { printHelp } from \"../app/help\";\n\nfunction formatProfileLabel(name: string, displayName?: string | null): string {\n if (displayName && displayName.trim() && displayName !== name) {\n return `${displayName} (${name})`;\n }\n return name;\n}\n\nfunction profileRateLimitKey(profile: Profile): string {\n return resolveProfileIdentityKeyFromProfile(profile);\n}\n\nfunction toTitleCase(value: string): string {\n return value.replace(/\\w\\S*/g, word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());\n}\n\nfunction formatShortDate(value?: string | null): string | null {\n if (!value) return null;\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return null;\n if (typeof Intl !== \"undefined\" && Intl.DateTimeFormat) {\n return new Intl.DateTimeFormat(undefined, { month: \"short\", day: \"numeric\" }).format(date);\n }\n return date.toLocaleDateString();\n}\n\nfunction formatRelativeTime(value?: string | null): string | null {\n if (!value) return null;\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) return null;\n const diffMs = parsed - Date.now();\n const absMs = Math.abs(diffMs);\n if (absMs < 60_000) {\n return null;\n }\n const minutes = Math.round(absMs / 60_000);\n if (minutes < 60) {\n return diffMs >= 0 ? `in ${minutes}m` : `${minutes}m ago`;\n }\n const hours = Math.round(minutes / 60);\n if (hours < 24) {\n return diffMs >= 0 ? `in ${hours}h` : `${hours}h ago`;\n }\n const days = Math.round(hours / 24);\n return diffMs >= 0 ? `in ${days}d` : `${days}d ago`;\n}\n\nfunction formatOrganizations(organizations?: OrganizationInfo[]): string | null {\n if (!organizations || !Array.isArray(organizations) || organizations.length === 0) {\n return null;\n }\n const parts = organizations\n .map(org => {\n if (!org) return null;\n const name = org.title || org.id;\n if (!name) return null;\n return org.role ? `${name} (${org.role})` : name;\n })\n .filter((value): value is string => Boolean(value));\n return parts.length > 0 ? parts.join(\", \") : null;\n}\n\nfunction formatWindowLabel(windowMinutes?: number): string | null {\n if (typeof windowMinutes !== \"number\" || Number.isNaN(windowMinutes)) {\n return null;\n }\n if (windowMinutes >= 2880) {\n const days = windowMinutes / 1440;\n const rounded = Math.round(days * 10) / 10;\n const display = Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1);\n return `${display.replace(/\\.0$/, \"\")}d window`;\n }\n if (windowMinutes >= 60) {\n const hours = windowMinutes / 60;\n const rounded = Math.round(hours * 10) / 10;\n const display = Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1);\n return `${display.replace(/\\.0$/, \"\")}h window`;\n }\n const minutes = Math.round(windowMinutes);\n return `${minutes}m window`;\n}\n\nfunction formatDurationFromSeconds(seconds?: number | null): string | null {\n if (typeof seconds !== \"number\" || Number.isNaN(seconds)) {\n return null;\n }\n if (seconds <= 0) {\n return \"now\";\n }\n const minutes = Math.floor(seconds / 60);\n if (minutes === 0) {\n return `${Math.max(1, Math.round(seconds))}s`;\n }\n if (minutes < 60) {\n return `${minutes}m`;\n }\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n if (hours < 24) {\n return remainingMinutes ? `${hours}h ${remainingMinutes}m` : `${hours}h`;\n }\n const days = Math.floor(hours / 24);\n const remainingHours = hours % 24;\n return remainingHours ? `${days}d ${remainingHours}h` : `${days}d`;\n}\n\nfunction formatResetText(window: RateLimitWindow): string | null {\n if (window.resetsAt) {\n return formatRelativeTime(window.resetsAt) ?? window.resetsAt;\n }\n const durationText = formatDurationFromSeconds(window.resetsInSeconds);\n if (!durationText) return null;\n if (durationText === \"now\") return \"now\";\n return `in ${durationText}`;\n}\n\ntype RateLimitRow = {\n label: string;\n used: string;\n reset: string | null;\n};\n\nfunction formatWindowUsage(window: RateLimitWindow): RateLimitRow | null {\n const label = formatWindowLabel(window.windowMinutes) ?? \"window\";\n const usedPercent =\n typeof window.usedPercent === \"number\" && Number.isFinite(window.usedPercent)\n ? `${Math.round(Math.max(0, Math.min(100, window.usedPercent)))}%`\n : \"n/a\";\n const resetText = formatResetText(window);\n return {\n label,\n used: usedPercent,\n reset: resetText ? `reset ${resetText}` : null,\n };\n}\n\ntype UsageInfo = {\n summary: string;\n rows: RateLimitRow[] | null;\n usageSummary: RateLimitUsageSummary;\n};\n\ntype RateLimitUsageKey = \"primary\" | \"secondary\";\n\ntype RateLimitUsageSummary = {\n windowKey: RateLimitUsageKey;\n usagePercent: number;\n remainingPercent: number;\n hasUsage: boolean;\n resetsInSeconds: number | null;\n windowMinutes: number | null;\n};\n\nconst EMPTY_USAGE_SUMMARY: RateLimitUsageSummary = {\n windowKey: \"primary\",\n usagePercent: 0,\n remainingPercent: 100,\n hasUsage: false,\n resetsInSeconds: null,\n windowMinutes: null,\n};\n\nfunction toFiniteNumberOrNull(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction summarizeRateLimitSnapshot(snapshot: RateLimitSnapshot | null | undefined): RateLimitUsageSummary {\n if (!snapshot) {\n return { ...EMPTY_USAGE_SUMMARY };\n }\n\n const entries: Array<{ key: RateLimitUsageKey; window: RateLimitWindow | undefined }> = [\n { key: \"primary\", window: snapshot.primary },\n { key: \"secondary\", window: snapshot.secondary },\n ];\n\n let summary: RateLimitUsageSummary = { ...EMPTY_USAGE_SUMMARY };\n let initialized = false;\n\n for (const entry of entries) {\n if (!entry.window) {\n continue;\n }\n\n const usageValueRaw = toFiniteNumberOrNull(entry.window.usedPercent);\n const usageValue = usageValueRaw === null ? 0 : Math.max(0, Math.min(100, usageValueRaw));\n const remainingValue = 100 - usageValue;\n const hasUsage = usageValueRaw !== null;\n const resetsInSeconds = toFiniteNumberOrNull(entry.window.resetsInSeconds);\n const windowMinutes = toFiniteNumberOrNull(entry.window.windowMinutes);\n\n if (!initialized) {\n initialized = true;\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n continue;\n }\n\n if (hasUsage && summary.hasUsage && usageValue > summary.usagePercent) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n continue;\n }\n\n if (!hasUsage && !summary.hasUsage && summary.resetsInSeconds !== null) {\n if (resetsInSeconds !== null && resetsInSeconds < summary.resetsInSeconds) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n }\n continue;\n }\n\n if (!hasUsage && !summary.hasUsage && summary.resetsInSeconds === null && resetsInSeconds !== null) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n continue;\n }\n\n if (hasUsage && !summary.hasUsage) {\n summary = {\n windowKey: entry.key,\n usagePercent: usageValue,\n remainingPercent: remainingValue,\n hasUsage,\n resetsInSeconds,\n windowMinutes,\n };\n }\n }\n\n return summary;\n}\n\nfunction fallbackUsage(profile: Profile): UsageInfo {\n const usageSummary = summarizeRateLimitSnapshot(profile.rateLimit ?? null);\n if (!profile.isValid) {\n return { summary: \"invalid\", rows: null, usageSummary };\n }\n if (profile.tokenStatus?.requiresUserAction) {\n return { summary: \"auth required\", rows: null, usageSummary };\n }\n return { summary: \"n/a\", rows: null, usageSummary };\n}\n\nasync function resolveProfileUsage(\n manager: ProfileManager,\n profile: Profile,\n codexPath: string,\n): Promise<UsageInfo> {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n return fallbackUsage(profile);\n }\n\n try {\n const snapshot = await manager.readLiveRateLimits(profile.name, { codexPath });\n if (!snapshot) {\n const usageSummary = summarizeRateLimitSnapshot(profile.rateLimit ?? null);\n return { summary: \"n/a\", rows: null, usageSummary };\n }\n const rows: RateLimitRow[] = [];\n if (snapshot.primary) {\n const row = formatWindowUsage(snapshot.primary);\n if (row) rows.push(row);\n }\n if (snapshot.secondary) {\n const row = formatWindowUsage(snapshot.secondary);\n if (row) rows.push(row);\n }\n const maxPercent = maxUsedPercent(snapshot);\n const summary = typeof maxPercent === \"number\"\n ? `${Math.round(maxPercent)}%`\n : \"n/a\";\n return { summary, rows: rows.length > 0 ? rows : null, usageSummary: summarizeRateLimitSnapshot(snapshot) };\n } catch {\n return fallbackUsage(profile);\n }\n}\n\ntype AutoRollCandidate = {\n profile: Profile;\n usageSummary: RateLimitUsageSummary;\n};\n\nfunction compareAutoRollCandidates(\n a: AutoRollCandidate,\n b: AutoRollCandidate,\n priorityRanks: Map<string, number>,\n): number {\n const aRank = priorityRanks.get(resolveProfileIdentityKeyFromProfile(a.profile));\n const bRank = priorityRanks.get(resolveProfileIdentityKeyFromProfile(b.profile));\n if (aRank !== undefined || bRank !== undefined) {\n if (aRank === undefined) return 1;\n if (bRank === undefined) return -1;\n if (aRank !== bRank) return aRank - bRank;\n }\n\n if (a.usageSummary.remainingPercent !== b.usageSummary.remainingPercent) {\n return b.usageSummary.remainingPercent - a.usageSummary.remainingPercent;\n }\n const aReset = a.usageSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n const bReset = b.usageSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n if (aReset !== bReset) {\n return aReset - bReset;\n }\n return a.profile.name.localeCompare(b.profile.name);\n}\n\nfunction computeAutoRollCandidate(\n profiles: Profile[],\n usageMap: Map<string, UsageInfo>,\n currentProfileName: string,\n currentSummary: RateLimitUsageSummary,\n switchRemainingThreshold: number,\n priorityOrder: string[] = [],\n blockedProfileNames: ReadonlySet<string> = new Set(),\n): AutoRollCandidate | null {\n const priorityRanks = new Map<string, number>();\n for (const [index, key] of priorityOrder.entries()) {\n const normalized = key.trim();\n if (normalized && !priorityRanks.has(normalized)) {\n priorityRanks.set(normalized, index);\n }\n }\n\n const candidates = profiles\n .filter(profile =>\n profile.name !== currentProfileName &&\n !blockedProfileNames.has(profile.name) &&\n profile.isValid &&\n !profile.tokenStatus?.requiresUserAction\n )\n .map(profile => ({\n profile,\n usageSummary: usageMap.get(profile.name)?.usageSummary ?? summarizeRateLimitSnapshot(profile.rateLimit ?? null),\n }));\n\n if (candidates.length === 0) {\n return null;\n }\n\n const belowThreshold = candidates\n .filter(\n candidate =>\n candidate.usageSummary.hasUsage &&\n candidate.usageSummary.remainingPercent > switchRemainingThreshold,\n )\n .sort((a, b) => compareAutoRollCandidates(a, b, priorityRanks));\n let selected = belowThreshold[0] ?? null;\n\n if (!selected) {\n selected = candidates\n .filter(candidate => !candidate.usageSummary.hasUsage)\n .sort((a, b) => compareAutoRollCandidates(a, b, priorityRanks))[0] ?? null;\n }\n\n if (!selected) {\n return null;\n }\n\n if (selected.usageSummary.hasUsage && currentSummary.hasUsage) {\n if (selected.usageSummary.remainingPercent < currentSummary.remainingPercent) {\n return null;\n }\n if (selected.usageSummary.remainingPercent === currentSummary.remainingPercent) {\n const selectedReset = selected.usageSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n const currentReset = currentSummary.resetsInSeconds ?? Number.POSITIVE_INFINITY;\n if (selectedReset >= currentReset) {\n return null;\n }\n }\n }\n\n return selected;\n}\n\nfunction formatPlan(profile: Profile): string {\n const metadata = profile.metadata;\n if (!metadata) {\n return \"No plan details\";\n }\n const parts: string[] = [];\n if (metadata.planType) {\n parts.push(toTitleCase(metadata.planType));\n }\n const until = metadata.subscription?.activeUntil;\n if (until) {\n const formatted = formatShortDate(until);\n if (formatted) {\n parts.push(`Until ${formatted}`);\n }\n }\n return parts.join(\" · \") || \"No plan details\";\n}\n\nfunction formatAuth(profile: Profile): string {\n const metadata = profile.metadata;\n const relative = formatRelativeTime(metadata?.tokenAuthTime);\n if (relative) return relative;\n if (metadata?.tokenAuthTime) return metadata.tokenAuthTime;\n return \"Not authenticated yet\";\n}\n\nfunction printProfileDetails(profile: Profile, usage?: UsageInfo | null): void {\n const email = profile.email ?? \"Unknown\";\n const plan = formatPlan(profile);\n const orgs = formatOrganizations(profile.metadata?.organizations) ?? \"No organizations\";\n const auth = formatAuth(profile);\n const workspace = profile.workspaceName ?? profile.workspaceId ?? null;\n\n const entries: Array<{ label: string; value: string }> = [\n { label: \"email\", value: email },\n { label: \"plan\", value: plan },\n { label: \"orgs\", value: orgs },\n { label: \"auth\", value: auth },\n ];\n if (workspace) {\n entries.push({ label: \"workspace\", value: workspace });\n }\n const pad = Math.max(...entries.map(entry => entry.label.length));\n for (const entry of entries) {\n console.log(` ${entry.label.padEnd(pad)} : ${entry.value}`);\n }\n\n if (usage) {\n if (usage.rows && usage.rows.length > 0) {\n const labelPad = Math.max(...usage.rows.map(row => row.label.length));\n const usedPad = Math.max(...usage.rows.map(row => row.used.length));\n console.log(` rate limits:`);\n for (const row of usage.rows) {\n const resetText = row.reset ? ` ${row.reset}` : \"\";\n console.log(` ${row.label.padEnd(labelPad)} ${row.used.padStart(usedPad)}${resetText}`);\n }\n return;\n }\n console.log(` rate limits: ${usage.summary}`);\n }\n}\n\nasync function mapWithConcurrency<T, R>(\n items: T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n const workerCount = Math.max(1, Math.min(limit, items.length));\n let nextIndex = 0;\n\n const workers = Array.from({ length: workerCount }, async () => {\n while (true) {\n const current = nextIndex++;\n if (current >= items.length) {\n return;\n }\n results[current] = await fn(items[current], current);\n }\n });\n\n await Promise.all(workers);\n return results;\n}\n\nfunction parseAutoRollSwitchRemainingThreshold(\n flags: string[],\n fallbackThreshold: number,\n): number {\n const explicitLeft = parseNumericFlag(flags, \"--switch-left\");\n\n if (explicitLeft !== null) {\n if (Number.isNaN(explicitLeft)) {\n throw new Error(\"Invalid --switch-left value. Use --switch-left=0-50.\");\n }\n if (\n explicitLeft < AUTO_ROLL_SWITCH_REMAINING_MIN ||\n explicitLeft > AUTO_ROLL_SWITCH_REMAINING_MAX\n ) {\n throw new Error(\"Invalid --switch-left value. Use a number between 0 and 50.\");\n }\n return sanitizeAutoRollSwitchRemainingThreshold(explicitLeft);\n }\n\n return sanitizeAutoRollSwitchRemainingThreshold(fallbackThreshold);\n}\n\nfunction parseAutoRollIntervalSeconds(flags: string[]): number {\n const explicitInterval = parseIntegerFlag(flags, \"--interval\");\n if (explicitInterval === null) {\n return DEFAULT_AUTOROLL_INTERVAL_SECONDS;\n }\n if (Number.isNaN(explicitInterval) || explicitInterval <= 0) {\n throw new Error(\"Invalid --interval value. Use --interval=<seconds> with a positive integer.\");\n }\n return explicitInterval;\n}\n\nfunction resolveActivateCodexFlag(flags: string[], fallback: boolean): boolean {\n const activate = hasFlag(flags, \"--activate-codex\") || hasFlag(flags, \"--restart-codex\");\n const noActivate =\n hasFlag(flags, \"--no-activate-codex\") || hasFlag(flags, \"--no-restart-codex\");\n if (activate && noActivate) {\n throw new Error(\"Use either --activate-codex or --no-activate-codex, not both.\");\n }\n if (activate) {\n return true;\n }\n if (noActivate) {\n return false;\n }\n return fallback;\n}\n\nfunction findProfileKey(profiles: Profile[], name: string): string | null {\n const profile = profiles.find(entry => entry.name === name);\n return profile ? profileRateLimitKey(profile) : null;\n}\n\nfunction rearmBlockedProfiles(\n blockedProfiles: Set<string> | undefined,\n usageMap: Map<string, UsageInfo>,\n rearmRemainingThreshold: number,\n): void {\n if (!blockedProfiles) {\n return;\n }\n for (const profileName of Array.from(blockedProfiles)) {\n const summary = usageMap.get(profileName)?.usageSummary;\n if (\n !summary ||\n !summary.hasUsage ||\n summary.remainingPercent > rearmRemainingThreshold\n ) {\n blockedProfiles.delete(profileName);\n }\n }\n}\n\nasync function rememberOfficialCodexSwitch(profileKey: string | null): Promise<void> {\n try {\n await recordOfficialCodexProfileSwitch(profileKey);\n } catch (error) {\n console.warn(\n `Could not record official Codex sync state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction formatOfficialCodexProfileAction(result: OfficialCodexProfileActionPayload): string {\n if (result.status === \"restarted\") {\n return \"Official Codex activated.\";\n }\n if (result.status === \"started\") {\n return \"Official Codex started.\";\n }\n if (result.status === \"focused\") {\n return \"Official Codex focused.\";\n }\n if (result.status === \"already-running\") {\n return \"Official Codex already running.\";\n }\n if (result.status === \"failed\") {\n return `Official Codex activation failed: ${result.reason}.`;\n }\n if (result.status === \"skipped\" || result.status === \"not-running\") {\n return `Official Codex activation skipped: ${result.reason}.`;\n }\n return \"Official Codex activation status unknown.\";\n}\n\nfunction findUnmanagedOfficialCodexActivationTarget(\n instances: OfficialCodexInstancesPayload,\n profileName: string,\n profileKey: string | null,\n): {\n target: OfficialCodexUnmanagedInstancePayload | null;\n ambiguous: boolean;\n unverified: boolean;\n} {\n const activatable = instances.unmanaged.filter((instance) => instance.pid);\n const matched =\n activatable.find((instance) => {\n if (profileKey && instance.profileKey) {\n return instance.profileKey === profileKey;\n }\n if (instance.profileKey) {\n return false;\n }\n return instance.profileName === profileName;\n }) ?? null;\n if (matched) {\n return { target: matched, ambiguous: false, unverified: false };\n }\n if (activatable.length > 1) {\n return { target: null, ambiguous: true, unverified: false };\n }\n return { target: null, ambiguous: false, unverified: activatable.length === 1 };\n}\n\nasync function focusUnmanagedOfficialCodexWindow(\n profileName: string,\n target: OfficialCodexUnmanagedInstancePayload,\n): Promise<OfficialCodexProfileActionPayload> {\n return focusOfficialCodexObservedProfileInstance(\n target.profileName ?? profileName,\n target.pid,\n target.appServerPid,\n );\n}\n\nasync function recordCliOfficialCodexActivationResult(\n profileName: string,\n profileKey: string | null,\n action: OfficialCodexProfileActionPayload,\n): Promise<void> {\n const verifiedAction =\n action.status === \"started\" ||\n action.status === \"restarted\" ||\n action.status === \"focused\";\n const pid =\n verifiedAction ? action.instance?.pid ?? null : null;\n const status =\n verifiedAction\n ? action.status\n : action.status === \"failed\"\n ? \"failed\"\n : \"skipped\";\n const reason = verifiedAction ? null : action.reason ?? action.status;\n\n try {\n await recordOfficialCodexActivationResult({\n status,\n reason,\n profileKey,\n pid,\n });\n await recordOfficialCodexActivity({\n kind: \"official-codex-activation\",\n status,\n reason,\n targetProfileName: profileName,\n profileKey,\n phase: \"cli\",\n pid,\n activationRequested: false,\n activationResult: status,\n });\n } catch (error) {\n console.warn(\n `Could not record official Codex activation state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nasync function recordCliOfficialCodexActivationSkipped(\n profileName: string,\n profileKey: string | null,\n reason: string,\n): Promise<void> {\n await recordCliOfficialCodexActivationResult(profileName, profileKey, {\n status: \"skipped\",\n profileName,\n instance: null,\n reason,\n });\n}\n\nasync function maybeActivateOfficialCodex(options: {\n manager: ProfileManager;\n enabled: boolean;\n profileName: string;\n profileKey: string | null;\n launchIfNotRunning?: boolean;\n}): Promise<string | null> {\n if (!options.enabled) {\n return null;\n }\n try {\n const runtime = await options.manager.prepareProfileRuntime(options.profileName, {\n syncFromActiveAuthBeforeAction: false,\n });\n const launchOptions = {\n profileName: options.profileName,\n profileKey: options.profileKey,\n profileHome: runtime.profileHome,\n };\n const instances = await getOfficialCodexProfileInstances();\n if (instances.state === \"unsupported\") {\n await recordCliOfficialCodexActivationSkipped(\n options.profileName,\n options.profileKey,\n \"unsupported-platform\",\n );\n return \"Official Codex activation skipped: unsupported-platform.\";\n }\n if (instances.state === \"not-found\") {\n await recordCliOfficialCodexActivationSkipped(\n options.profileName,\n options.profileKey,\n \"official-codex-app-not-found\",\n );\n return \"Official Codex activation skipped: official-codex-app-not-found.\";\n }\n const managedRunning = instances.instances.some(\n (instance) => instance.profileName === options.profileName && instance.running,\n );\n const unmanaged = findUnmanagedOfficialCodexActivationTarget(\n instances,\n options.profileName,\n options.profileKey,\n );\n if (unmanaged.target && !managedRunning) {\n const action = await focusUnmanagedOfficialCodexWindow(\n options.profileName,\n unmanaged.target,\n );\n await recordCliOfficialCodexActivationResult(\n options.profileName,\n options.profileKey,\n action,\n );\n return formatOfficialCodexProfileAction(action);\n }\n if (unmanaged.ambiguous && !managedRunning) {\n await recordCliOfficialCodexActivationSkipped(\n options.profileName,\n options.profileKey,\n \"ambiguous-official-codex-windows\",\n );\n return \"Official Codex activation skipped: ambiguous-official-codex-windows.\";\n }\n if (unmanaged.unverified && !managedRunning) {\n await recordCliOfficialCodexActivationSkipped(\n options.profileName,\n options.profileKey,\n \"unverified-official-codex-window\",\n );\n return \"Official Codex activation skipped: unverified-official-codex-window.\";\n }\n if (managedRunning) {\n const action = await focusOfficialCodexProfileInstance(options.profileName);\n await recordCliOfficialCodexActivationResult(\n options.profileName,\n options.profileKey,\n action,\n );\n return formatOfficialCodexProfileAction(action);\n }\n if (options.launchIfNotRunning === false) {\n await recordCliOfficialCodexActivationSkipped(\n options.profileName,\n options.profileKey,\n \"official-codex-app-not-running\",\n );\n return \"Official Codex activation skipped: official-codex-app-not-running.\";\n }\n const action = await launchOfficialCodexProfileInstance(launchOptions);\n await recordCliOfficialCodexActivationResult(\n options.profileName,\n options.profileKey,\n action,\n );\n return formatOfficialCodexProfileAction(action);\n } catch (error) {\n await recordCliOfficialCodexActivationResult(options.profileName, options.profileKey, {\n status: \"failed\",\n profileName: options.profileName,\n instance: null,\n reason: error instanceof Error ? error.message : \"activation-threw\",\n });\n return `Official Codex activation failed: ${error instanceof Error ? error.message : String(error)}.`;\n }\n}\n\nasync function collectUsageMap(\n manager: ProfileManager,\n profiles: Profile[],\n codexPath: string,\n): Promise<Map<string, UsageInfo>> {\n const usageMap = new Map<string, UsageInfo>();\n const uniqueProfilesByAccount = new Map<string, Profile>();\n for (const profile of profiles) {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n continue;\n }\n const key = profileRateLimitKey(profile);\n if (!uniqueProfilesByAccount.has(key)) {\n uniqueProfilesByAccount.set(key, profile);\n }\n }\n\n const uniqueProfiles = Array.from(uniqueProfilesByAccount.values());\n const limit = Math.max(1, uniqueProfiles.length);\n const results = await mapWithConcurrency(uniqueProfiles, limit, (profile) =>\n resolveProfileUsage(manager, profile, codexPath),\n );\n\n const usageByAccount = new Map<string, UsageInfo>();\n for (const [index, profile] of uniqueProfiles.entries()) {\n usageByAccount.set(profileRateLimitKey(profile), results[index]);\n }\n\n for (const profile of profiles) {\n if (!profile.isValid || profile.tokenStatus?.requiresUserAction) {\n usageMap.set(profile.name, fallbackUsage(profile));\n continue;\n }\n usageMap.set(\n profile.name,\n usageByAccount.get(profileRateLimitKey(profile)) ?? fallbackUsage(profile),\n );\n }\n return usageMap;\n}\n\nasync function runAutoRollPass(\n manager: ProfileManager,\n options: {\n switchRemainingThreshold: number;\n rearmRemainingThreshold: number;\n dryRun: boolean;\n priorityOrder?: string[];\n activateOfficialCodex: boolean;\n launchOfficialCodexWhenClosed?: boolean;\n blockedProfiles?: Set<string>;\n blockCurrentUntilRearm?: boolean;\n },\n): Promise<{ switched: boolean; message: string; source: string | null; target: string | null }> {\n const profiles = await manager.listProfiles();\n if (!profiles.length) {\n return { switched: false, message: \"No profiles found.\", source: null, target: null };\n }\n\n const current = await manager.getCurrentProfile();\n if (!current.name) {\n return { switched: false, message: \"No active profile.\", source: null, target: null };\n }\n\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n throw new Error(\"Codex CLI binary not found on PATH. Auto-roll requires codex for live rate limits.\");\n }\n\n const usageMap = await collectUsageMap(manager, profiles, codexPath);\n rearmBlockedProfiles(\n options.blockedProfiles,\n usageMap,\n options.rearmRemainingThreshold,\n );\n const currentProfile = profiles.find(profile => profile.name === current.name);\n if (!currentProfile) {\n return {\n switched: false,\n message: `Current profile '${current.name}' is missing from saved profiles.`,\n source: current.name,\n target: null,\n };\n }\n\n const currentUsage = usageMap.get(current.name)?.usageSummary ?? summarizeRateLimitSnapshot(currentProfile.rateLimit ?? null);\n if (!currentUsage.hasUsage) {\n return {\n switched: false,\n message: `No live rate-limit usage for '${current.name}'. Skipping auto-roll.`,\n source: current.name,\n target: null,\n };\n }\n\n if (options.blockedProfiles?.has(current.name)) {\n if (currentUsage.remainingPercent > options.rearmRemainingThreshold) {\n options.blockedProfiles.delete(current.name);\n } else {\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left; waiting for re-arm above ${options.rearmRemainingThreshold}% left.`,\n source: current.name,\n target: null,\n };\n }\n }\n\n if (\n options.blockCurrentUntilRearm &&\n currentUsage.remainingPercent <= options.switchRemainingThreshold\n ) {\n options.blockedProfiles?.add(current.name);\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left; waiting for re-arm above ${options.rearmRemainingThreshold}% left.`,\n source: current.name,\n target: null,\n };\n }\n\n if (currentUsage.remainingPercent > options.switchRemainingThreshold) {\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left, above switch threshold ${options.switchRemainingThreshold}% left.`,\n source: current.name,\n target: null,\n };\n }\n\n const candidate = computeAutoRollCandidate(\n profiles,\n usageMap,\n current.name,\n currentUsage,\n options.switchRemainingThreshold,\n options.priorityOrder ?? [],\n options.blockedProfiles,\n );\n if (!candidate) {\n return {\n switched: false,\n message: `No eligible profile to switch from '${current.name}' at ${Math.round(currentUsage.remainingPercent)}% left.`,\n source: current.name,\n target: null,\n };\n }\n\n const candidateUsage = candidate.usageSummary.hasUsage ? `${Math.round(candidate.usageSummary.remainingPercent)}% left` : \"n/a\";\n if (options.dryRun) {\n const activationSuffix = options.activateOfficialCodex\n ? \" Official Codex would activate the target profile window after the switch.\"\n : \"\";\n return {\n switched: false,\n message: `[dry-run] Would switch '${current.name}' (${Math.round(currentUsage.remainingPercent)}% left) -> '${candidate.profile.name}' (${candidateUsage}).${activationSuffix}`,\n source: current.name,\n target: candidate.profile.name,\n };\n }\n\n await manager.switchToProfile(candidate.profile.name);\n const targetProfileKey = profileRateLimitKey(candidate.profile);\n await rememberOfficialCodexSwitch(targetProfileKey);\n const activationMessage = await maybeActivateOfficialCodex({\n manager,\n enabled: options.activateOfficialCodex,\n profileName: candidate.profile.name,\n profileKey: targetProfileKey,\n launchIfNotRunning: options.launchOfficialCodexWhenClosed === true,\n });\n options.blockedProfiles?.add(current.name);\n return {\n switched: true,\n message: `Auto-rolled '${current.name}' (${Math.round(currentUsage.remainingPercent)}% left) -> '${candidate.profile.name}' (${candidateUsage}).${activationMessage ? ` ${activationMessage}` : \"\"}`,\n source: current.name,\n target: candidate.profile.name,\n };\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport async function handleProfileCommand(\n args: string[],\n version: string,\n): Promise<void> {\n const flags = args.filter(arg => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printHelp(version);\n return;\n }\n\n const manager = new ProfileManager();\n\n switch (sub) {\n case \"list\": {\n const profiles = await manager.listProfiles();\n const current = await manager.getCurrentProfile();\n if (!profiles.length) {\n console.log(\"No profiles found.\");\n return;\n }\n const compact = hasFlag(flags, \"--compact\");\n const withUsage = !hasFlag(flags, \"--no-usage\");\n let usageMap: Map<string, UsageInfo> | null = null;\n if (withUsage) {\n const codexPath = resolveCodexBinary();\n if (!codexPath) {\n usageMap = new Map();\n for (const profile of profiles) {\n usageMap.set(profile.name, {\n summary: \"codex cli missing\",\n rows: null,\n usageSummary: summarizeRateLimitSnapshot(profile.rateLimit ?? null),\n });\n }\n } else {\n usageMap = await collectUsageMap(manager, profiles, codexPath);\n }\n }\n for (const [index, profile] of profiles.entries()) {\n const marker = current.name === profile.name ? \"*\" : \" \";\n const label = formatProfileLabel(profile.name, profile.displayName);\n if (index > 0) {\n console.log(\"\");\n }\n const activeLabel = current.name === profile.name ? \" (active)\" : \"\";\n console.log(`${marker} ${label}${activeLabel}`);\n if (compact) continue;\n const usage = usageMap?.get(profile.name) ?? null;\n printProfileDetails(profile, usage);\n }\n return;\n }\n case \"current\": {\n const current = await manager.getCurrentProfile();\n if (!current.name) {\n console.log(\"No active profile.\");\n return;\n }\n console.log(current.name);\n return;\n }\n case \"add\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n await assertProfileCreationAllowed(manager);\n if (!hasFlag(flags, \"--skip-login\")) {\n const loginMode = resolveLoginMode(parseLoginMode(flags));\n await runCodexLogin(loginMode);\n }\n const profile = await manager.createProfile(name);\n const label = profile ? formatProfileLabel(profile.name, profile.displayName) : name;\n console.log(`Profile created: ${label}`);\n return;\n }\n case \"refresh\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n if (!hasFlag(flags, \"--skip-login\")) {\n const loginMode = resolveLoginMode(parseLoginMode(flags));\n await runCodexLogin(loginMode);\n }\n const profile = await manager.refreshProfileAuth(name);\n const label = formatProfileLabel(profile.name, profile.displayName);\n console.log(`Profile refreshed: ${label}`);\n return;\n }\n case \"switch\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n const activateOfficialCodex = resolveActivateCodexFlag(flags, false);\n const profiles = await manager.listProfiles();\n const targetProfileKey = findProfileKey(profiles, name);\n await manager.switchToProfile(name);\n console.log(`Switched to profile: ${name}`);\n await rememberOfficialCodexSwitch(targetProfileKey);\n const activationMessage = await maybeActivateOfficialCodex({\n manager,\n enabled: activateOfficialCodex,\n profileName: name,\n profileKey: targetProfileKey,\n });\n if (activationMessage) {\n console.log(activationMessage);\n }\n return;\n }\n case \"autoroll\":\n case \"auto-roll\": {\n const license = await licenseService.getStatus();\n if (!license.isPro) {\n throw new Error(\"Auto-roll requires a Pro license.\");\n }\n const watch = hasFlag(flags, \"--watch\");\n const dryRun = hasFlag(flags, \"--dry-run\");\n const settings = await getStoredAutoRollSettings().catch(() => null);\n const activateOfficialCodex = resolveActivateCodexFlag(flags, true);\n const fallbackSwitchRemainingThreshold =\n typeof settings?.switchRemainingThreshold === \"number\" &&\n Number.isFinite(settings.switchRemainingThreshold)\n ? settings.switchRemainingThreshold\n : DEFAULT_AUTO_ROLL_SWITCH_REMAINING_THRESHOLD;\n const switchRemainingThreshold = parseAutoRollSwitchRemainingThreshold(\n flags,\n fallbackSwitchRemainingThreshold,\n );\n const rearmRemainingThreshold = sanitizeAutoRollRearmRemainingThreshold(\n settings?.rearmRemainingThreshold ??\n DEFAULT_AUTO_ROLL_REARM_REMAINING_THRESHOLD,\n switchRemainingThreshold,\n );\n const intervalSeconds = parseAutoRollIntervalSeconds(flags);\n\n if (watch) {\n console.log(\n `Auto-roll watch: switch at/below ${switchRemainingThreshold}% left | re-arm above ${rearmRemainingThreshold}% left | interval ${intervalSeconds}s${dryRun ? \" | dry-run\" : \"\"}${activateOfficialCodex ? \" | activate-codex\" : \" | no-activate-codex\"}`,\n );\n const blockedProfiles = new Set<string>();\n let lastObservedProfile: string | null = null;\n let stop = false;\n process.on(\"SIGINT\", () => {\n stop = true;\n });\n process.on(\"SIGTERM\", () => {\n stop = true;\n });\n\n while (!stop) {\n const current = await manager.getCurrentProfile();\n const currentName = current.name ?? null;\n const blockCurrentUntilRearm = Boolean(\n currentName &&\n lastObservedProfile &&\n currentName !== lastObservedProfile,\n );\n const result = await runAutoRollPass(manager, {\n switchRemainingThreshold,\n rearmRemainingThreshold,\n dryRun,\n priorityOrder: settings?.priorityOrder ?? [],\n activateOfficialCodex,\n launchOfficialCodexWhenClosed:\n settings?.launchOfficialCodexWhenClosedOnAutoRoll === true,\n blockedProfiles,\n blockCurrentUntilRearm,\n });\n console.log(result.message);\n lastObservedProfile = result.switched\n ? (result.target ?? currentName)\n : (currentName ?? result.source);\n if (stop) {\n break;\n }\n await delay(intervalSeconds * 1000);\n }\n console.log(\"Auto-roll watch stopped.\");\n return;\n }\n\n const result = await runAutoRollPass(manager, {\n switchRemainingThreshold,\n rearmRemainingThreshold,\n dryRun,\n priorityOrder: settings?.priorityOrder ?? [],\n activateOfficialCodex,\n launchOfficialCodexWhenClosed:\n settings?.launchOfficialCodexWhenClosedOnAutoRoll === true,\n });\n console.log(result.message);\n return;\n }\n case \"delete\": {\n const name = params[1];\n if (!name) {\n throw new Error(\"Profile name is required.\");\n }\n await manager.deleteProfile(name);\n console.log(`Profile deleted: ${name}`);\n return;\n }\n case \"rename\": {\n const from = params[1];\n const to = params[2];\n if (!from || !to) {\n throw new Error(\"Old and new profile names are required.\");\n }\n await manager.renameProfile(from, to);\n console.log(`Profile renamed: ${from} -> ${to}`);\n return;\n }\n default:\n printHelp(version);\n return;\n }\n}\n","import type { ProfileData, ProfileMetadata } from \"../profiles/types.ts\";\n\nexport const CLOUD_SYNC_SCHEMA_VERSION = 1 as const;\n\nexport interface CloudSyncProfileRecord {\n name: string;\n displayName: string | null;\n data: ProfileData;\n metadata?: ProfileMetadata;\n accountId: string | null;\n workspaceId: string | null;\n workspaceName: string | null;\n email: string | null;\n authMethod: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n}\n\nexport interface CloudSyncSnapshot {\n schemaVersion: typeof CLOUD_SYNC_SCHEMA_VERSION;\n updatedAt: string;\n profiles: CloudSyncProfileRecord[];\n configTomlContent: string | null;\n settingsJson: Record<string, unknown> | null;\n}\n\nexport interface CloudSyncGetResponse {\n snapshot: CloudSyncSnapshot | null;\n}\n\nexport interface CloudSyncMetaResponse {\n updatedAt: string | null;\n}\n\nexport type CloudSyncPutStatus = \"applied\" | \"stale\";\n\nexport interface CloudSyncPutResponse {\n status: CloudSyncPutStatus;\n snapshot: CloudSyncSnapshot;\n}\n","export function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function toIsoOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : new Date(parsed).toISOString();\n}\n","import {\n CLOUD_SYNC_SCHEMA_VERSION,\n type CloudSyncGetResponse,\n type CloudSyncMetaResponse,\n type CloudSyncPutResponse,\n type CloudSyncSnapshot,\n} from \"@codexuse/contracts/cloud-sync/types\";\nimport { isRecord, toIsoOrNull } from \"@codexuse/shared/core/type-guards\";\n\nconst DEFAULT_CLOUD_SYNC_API_BASE_URL = \"https://api.codexuse.com\";\nconst CLOUD_SYNC_TIMEOUT_MS = 15_000;\n\nexport class CloudSyncClientError extends Error {\n readonly status: number | null;\n\n constructor(message: string, status: number | null = null) {\n super(message);\n this.name = \"CloudSyncClientError\";\n this.status = status;\n }\n}\n\nfunction normalizeBaseUrl(value: string): string {\n const trimmed = value.trim();\n return trimmed.endsWith(\"/\") ? trimmed.slice(0, -1) : trimmed;\n}\n\nexport function getCloudSyncApiBaseUrl(): string {\n const fromEnv = typeof process.env.CODEXUSE_API_BASE_URL === \"string\"\n ? process.env.CODEXUSE_API_BASE_URL\n : \"\";\n\n if (fromEnv.trim().length === 0) {\n return DEFAULT_CLOUD_SYNC_API_BASE_URL;\n }\n\n return normalizeBaseUrl(fromEnv);\n}\n\nfunction buildSyncUrl(pathname: string): string {\n const baseUrl = getCloudSyncApiBaseUrl();\n const normalizedPath = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n return `${baseUrl}${normalizedPath}`;\n}\n\nfunction normalizeSnapshot(value: unknown): CloudSyncSnapshot | null {\n if (!isRecord(value)) {\n return null;\n }\n\n const updatedAt = toIsoOrNull(value.updatedAt);\n if (!updatedAt) {\n return null;\n }\n\n const schemaVersion = Number(value.schemaVersion);\n if (!Number.isFinite(schemaVersion) || schemaVersion !== CLOUD_SYNC_SCHEMA_VERSION) {\n return null;\n }\n\n const rawProfiles = Array.isArray(value.profiles) ? value.profiles : [];\n const profiles = rawProfiles\n .map((entry) => (isRecord(entry) ? entry : null))\n .filter((entry): entry is Record<string, unknown> => Boolean(entry))\n .map((entry) => {\n const data = isRecord(entry.data) ? entry.data : {};\n const metadata = isRecord(entry.metadata) ? entry.metadata : undefined;\n return {\n name: typeof entry.name === \"string\" ? entry.name : \"\",\n displayName: typeof entry.displayName === \"string\" ? entry.displayName : null,\n data,\n metadata,\n accountId: typeof entry.accountId === \"string\" ? entry.accountId : null,\n workspaceId: typeof entry.workspaceId === \"string\" ? entry.workspaceId : null,\n workspaceName: typeof entry.workspaceName === \"string\" ? entry.workspaceName : null,\n email: typeof entry.email === \"string\" ? entry.email : null,\n authMethod: typeof entry.authMethod === \"string\" ? entry.authMethod : null,\n createdAt: typeof entry.createdAt === \"string\" ? entry.createdAt : null,\n updatedAt: typeof entry.updatedAt === \"string\" ? entry.updatedAt : null,\n };\n })\n .filter((entry) => entry.name.trim().length > 0);\n\n const rawSettings = value.settingsJson;\n const settingsJson = isRecord(rawSettings) ? rawSettings : null;\n\n return {\n schemaVersion: CLOUD_SYNC_SCHEMA_VERSION,\n updatedAt,\n profiles,\n configTomlContent: typeof value.configTomlContent === \"string\" ? value.configTomlContent : null,\n settingsJson,\n };\n}\n\nasync function requestJson<T>(\n method: \"GET\" | \"PUT\",\n pathname: string,\n licenseKey: string,\n body?: unknown,\n rawBody?: string,\n): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), CLOUD_SYNC_TIMEOUT_MS);\n\n try {\n const response = await fetch(buildSyncUrl(pathname), {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-codexuse-license-key\": licenseKey,\n },\n body: typeof rawBody === \"string\"\n ? rawBody\n : body === undefined\n ? undefined\n : JSON.stringify(body),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const message = await response.text().catch(() => \"\");\n throw new CloudSyncClientError(\n message || `Cloud sync request failed (${response.status}).`,\n response.status,\n );\n }\n\n return (await response.json()) as T;\n } catch (error) {\n if (error instanceof CloudSyncClientError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new CloudSyncClientError(\"Cloud sync request timed out.\");\n }\n\n throw new CloudSyncClientError(\n error instanceof Error ? error.message : \"Cloud sync request failed.\",\n );\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport async function fetchRemoteSnapshot(licenseKey: string): Promise<CloudSyncSnapshot | null> {\n const response = await requestJson<CloudSyncGetResponse>(\"GET\", \"/v1/sync/snapshot\", licenseKey);\n return normalizeSnapshot(response.snapshot);\n}\n\nexport async function fetchRemoteSnapshotMeta(licenseKey: string): Promise<string | null> {\n const response = await requestJson<CloudSyncMetaResponse>(\n \"GET\",\n \"/v1/sync/snapshot/meta\",\n licenseKey,\n );\n return toIsoOrNull(response.updatedAt);\n}\n\nexport async function pushRemoteSnapshot(\n licenseKey: string,\n snapshot: CloudSyncSnapshot,\n options?: { serializedSnapshot?: string },\n): Promise<CloudSyncPutResponse> {\n const serializedSnapshot = typeof options?.serializedSnapshot === \"string\"\n ? options.serializedSnapshot\n : JSON.stringify(snapshot);\n const response = await requestJson<CloudSyncPutResponse>(\n \"PUT\",\n \"/v1/sync/snapshot\",\n licenseKey,\n undefined,\n `{\"snapshot\":${serializedSnapshot}}`,\n );\n\n const normalized = normalizeSnapshot(response.snapshot);\n if (!normalized) {\n throw new CloudSyncClientError(\"Cloud sync server returned an invalid snapshot payload.\");\n }\n\n const status = response.status === \"stale\" ? \"stale\" : \"applied\";\n return {\n status,\n snapshot: normalized,\n };\n}\n","import { parse, stringify } from \"@iarna/toml\";\nimport {\n getCodexConfigMetadata,\n} from \"@codexuse/runtime-codex/codex/config-metadata\";\nimport {\n ensureTrailingNewline,\n getConfigPath,\n getUpdatedAt,\n normalizeLineEndings,\n readConfigContent,\n writeConfigContent,\n} from \"@codexuse/runtime-codex/codex/config-io\";\nimport type { CodexHomePathOptions } from \"@codexuse/runtime-codex/codex/home\";\nimport { YOLO_PRESET } from \"@codexuse/runtime-codex/codex/config-presets\";\nimport type {\n CodexConfigDiagnostic,\n CodexConfigMetadata,\n CodexConfigSettingsSummary,\n CodexConfigSnapshotPayload,\n CodexConfigUpdatePayload,\n CodexFeatureStage,\n McpServerConfig,\n} from \"@codexuse/contracts/codex/config-types\";\nimport { formatUserFacingError } from \"@codexuse/shared/core/errors\";\n\nexport type {\n CodexConfigDiagnostic,\n CodexConfigSettingsSummary,\n CodexConfigSnapshotPayload,\n CodexConfigUpdatePayload,\n CodexFeatureUpdateMap,\n McpServerConfig,\n} from \"@codexuse/contracts/codex/config-types\";\n\ntype RawConfig = Record<string, unknown>;\n\ntype ParsedResult = {\n data: RawConfig | null;\n error: string | null;\n};\n\nfunction tryParseToml(content: string): ParsedResult {\n try {\n const parsed = parse(content) as RawConfig;\n return { data: parsed ?? {}, error: null };\n } catch (error) {\n const maybe = error as Partial<{ line: number; column: number; col: number }>;\n const line = typeof maybe?.line === \"number\" ? maybe.line : null;\n const column = typeof maybe?.column === \"number\" ? maybe.column : typeof maybe?.col === \"number\" ? maybe.col : null;\n const location = line !== null ? `line ${line}${column !== null ? `, column ${column}` : \"\"}` : null;\n\n const friendly = formatUserFacingError(error, {\n fallback: \"Invalid config.toml syntax. Fix it and try again.\",\n maxLength: 180,\n });\n const message = location ? `${friendly} (near ${location}).` : friendly;\n return { data: null, error: message };\n }\n}\n\nfunction toStringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction toBooleanOrNull(value: unknown): boolean | null {\n if (typeof value === \"boolean\") {\n return value;\n }\n return null;\n}\n\nfunction toNumberOrNull(value: unknown): number | null {\n if (typeof value !== \"number\") {\n return null;\n }\n return Number.isFinite(value) ? value : null;\n}\n\nfunction toStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value\n .map(entry => (typeof entry === \"string\" ? entry.trim() : \"\"))\n .filter(entry => entry.length > 0);\n}\n\nfunction toStringRecord(value: unknown): Record<string, string> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n\n const result: Record<string, string> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (typeof raw !== \"string\") {\n continue;\n }\n const normalizedKey = key.trim();\n const normalizedValue = raw.trim();\n if (!normalizedKey || !normalizedValue) {\n continue;\n }\n result[normalizedKey] = normalizedValue;\n }\n return result;\n}\n\nfunction buildSettingsSummary(data: RawConfig | null): CodexConfigSettingsSummary {\n const noticeCandidate = data && typeof data[\"notice\"] === \"object\" && data[\"notice\"] !== null\n ? (data[\"notice\"] as RawConfig)\n : null;\n\n const featuresCandidate =\n data && typeof data[\"features\"] === \"object\" && data[\"features\"] !== null && !Array.isArray(data[\"features\"])\n ? (data[\"features\"] as RawConfig)\n : null;\n\n const toolsCandidate =\n data && typeof data[\"tools\"] === \"object\" && data[\"tools\"] !== null && !Array.isArray(data[\"tools\"])\n ? (data[\"tools\"] as RawConfig)\n : null;\n\n const featureValues: Record<string, boolean | null> = {};\n if (featuresCandidate) {\n for (const [key, value] of Object.entries(featuresCandidate)) {\n featureValues[key] = toBooleanOrNull(value);\n }\n }\n\n const modelMigrationsRaw = noticeCandidate ? toStringRecord(noticeCandidate[\"model_migrations\"]) : {};\n\n return {\n model: data ? toStringOrNull(data[\"model\"]) : null,\n reviewModel: data ? toStringOrNull(data[\"review_model\"]) : null,\n modelReasoningEffort: data ? toStringOrNull(data[\"model_reasoning_effort\"]) : null,\n modelReasoningSummary: data ? toStringOrNull(data[\"model_reasoning_summary\"]) : null,\n modelVerbosity: data ? toStringOrNull(data[\"model_verbosity\"]) : null,\n approvalPolicy: data ? toStringOrNull(data[\"approval_policy\"]) : null,\n sandboxMode: data ? toStringOrNull(data[\"sandbox_mode\"]) : null,\n webSearch: data ? toStringOrNull(data[\"web_search\"]) : null,\n personality: data ? toStringOrNull(data[\"personality\"]) : null,\n toolOutputTokenLimit: data ? toNumberOrNull(data[\"tool_output_token_limit\"]) : null,\n modelAutoCompactTokenLimit: data ? toNumberOrNull(data[\"model_auto_compact_token_limit\"]) : null,\n modelContextWindow: data ? toNumberOrNull(data[\"model_context_window\"]) : null,\n features: {\n unifiedExec: featuresCandidate ? toBooleanOrNull(featuresCandidate[\"unified_exec\"]) : null,\n shellSnapshot: featuresCandidate ? toBooleanOrNull(featuresCandidate[\"shell_snapshot\"]) : null,\n values: featureValues,\n },\n tools: {\n webSearch: toolsCandidate ? toBooleanOrNull(toolsCandidate[\"web_search\"]) : null,\n viewImage: toolsCandidate ? toBooleanOrNull(toolsCandidate[\"view_image\"]) : null,\n },\n notice: {\n hideFullAccessWarning: noticeCandidate ? toBooleanOrNull(noticeCandidate[\"hide_full_access_warning\"]) : null,\n hideGpt51MigrationPrompt: noticeCandidate ? toBooleanOrNull(noticeCandidate[\"hide_gpt5_1_migration_prompt\"]) : null,\n hideLegacyGpt51CodexMaxMigrationPrompt: noticeCandidate\n ? toBooleanOrNull(noticeCandidate[\"hide_gpt-5.1-codex-max_migration_prompt\"])\n : null,\n hideRateLimitModelNudge: noticeCandidate ? toBooleanOrNull(noticeCandidate[\"hide_rate_limit_model_nudge\"]) : null,\n modelMigrations: Object.keys(modelMigrationsRaw).length > 0 ? modelMigrationsRaw : null,\n },\n };\n}\n\nfunction parseRmcpClientEnabled(data: RawConfig | null): boolean {\n const rawFeatures =\n data && typeof data[\"features\"] === \"object\" && data[\"features\"] !== null && !Array.isArray(data[\"features\"])\n ? (data[\"features\"] as RawConfig)\n : null;\n\n if (rawFeatures && typeof rawFeatures[\"rmcp_client\"] === \"boolean\") {\n return rawFeatures[\"rmcp_client\"] as boolean;\n }\n\n if (data && typeof data[\"experimental_use_rmcp_client\"] === \"boolean\") {\n return data[\"experimental_use_rmcp_client\"] as boolean;\n }\n\n return false;\n}\n\nfunction parseMcpServer(name: string, rawValue: unknown): McpServerConfig | null {\n if (typeof rawValue !== \"object\" || rawValue === null || Array.isArray(rawValue)) {\n return null;\n }\n const raw = rawValue as RawConfig;\n const typeValue = toStringOrNull(raw[\"type\"]);\n const command = toStringOrNull(raw[\"command\"]);\n const args = toStringArray(raw[\"args\"]);\n const env = toStringRecord(raw[\"env\"]);\n const envVars = toStringArray(raw[\"env_vars\"]);\n const cwd = toStringOrNull(raw[\"cwd\"]);\n const url = toStringOrNull(raw[\"url\"]);\n const bearerTokenEnvVar = toStringOrNull(raw[\"bearer_token_env_var\"]);\n const httpHeaders = toStringRecord(raw[\"http_headers\"]);\n const envHttpHeaders = toStringRecord(raw[\"env_http_headers\"]);\n const startupTimeoutSec = toNumberOrNull(raw[\"startup_timeout_sec\"]);\n const toolTimeoutSec = toNumberOrNull(raw[\"tool_timeout_sec\"]);\n const enabledTools = toStringArray(raw[\"enabled_tools\"]);\n const disabledTools = toStringArray(raw[\"disabled_tools\"]);\n const enabled = typeof raw[\"enabled\"] === \"boolean\" ? raw[\"enabled\"] : true;\n const transport: \"stdio\" | \"http\" | \"sse\" =\n typeValue === \"stdio\" || typeValue === \"http\" || typeValue === \"sse\"\n ? typeValue\n : url\n ? \"http\"\n : \"stdio\";\n\n return {\n name,\n transport,\n enabled,\n command,\n args: args.length > 0 ? args : null,\n cwd,\n env: Object.keys(env).length > 0 ? env : null,\n envVars: envVars.length > 0 ? envVars : null,\n url,\n bearerTokenEnvVar,\n httpHeaders: Object.keys(httpHeaders).length > 0 ? httpHeaders : null,\n envHttpHeaders: Object.keys(envHttpHeaders).length > 0 ? envHttpHeaders : null,\n startupTimeoutSec,\n toolTimeoutSec,\n enabledTools: enabledTools.length > 0 ? enabledTools : null,\n disabledTools: disabledTools.length > 0 ? disabledTools : null,\n };\n}\n\nfunction buildMcpServersList(data: RawConfig | null): McpServerConfig[] {\n const rawServers = data?.[\"mcp_servers\"];\n if (typeof rawServers !== \"object\" || rawServers === null || Array.isArray(rawServers)) {\n return [];\n }\n\n const servers: McpServerConfig[] = [];\n for (const [name, rawValue] of Object.entries(rawServers)) {\n const parsed = parseMcpServer(name, rawValue);\n if (parsed) {\n servers.push(parsed);\n }\n }\n return servers;\n}\n\nfunction getFeatureStage(metadata: CodexConfigMetadata, featureKey: string): CodexFeatureStage {\n const found = metadata.featureCatalog.find(entry => entry.key === featureKey);\n return found?.stage ?? \"unknown\";\n}\n\nfunction looksLikeSecretValue(value: string): boolean {\n const normalized = value.trim();\n if (normalized.length < 12) {\n return false;\n }\n if (/\\s/.test(normalized)) {\n return false;\n }\n if (!/^[A-Za-z0-9._:-]+$/.test(normalized)) {\n return false;\n }\n const hasLetters = /[A-Za-z]/.test(normalized);\n const hasNumbers = /\\d/.test(normalized);\n return hasLetters && hasNumbers;\n}\n\nfunction buildConfigDiagnostics(\n data: RawConfig | null,\n summary: CodexConfigSettingsSummary,\n mcpServers: McpServerConfig[],\n metadata: CodexConfigMetadata,\n): CodexConfigDiagnostic[] {\n const diagnostics: CodexConfigDiagnostic[] = [];\n\n const featureTable =\n data && typeof data[\"features\"] === \"object\" && data[\"features\"] !== null && !Array.isArray(data[\"features\"])\n ? (data[\"features\"] as RawConfig)\n : null;\n\n const knownTopLevelKeys = new Set(metadata.schemaTopLevelKeys);\n if (data) {\n for (const key of Object.keys(data)) {\n if (knownTopLevelKeys.has(key)) {\n continue;\n }\n diagnostics.push({\n id: `unknown-top-level:${key}`,\n category: \"config\",\n severity: \"warning\",\n title: `Unknown config key: ${key}`,\n message: `This top-level key is not in the known Codex schema and may be ignored by Codex CLI.`,\n fixId: null,\n fixLabel: null,\n });\n }\n }\n\n if (featureTable) {\n const knownFeatureKeys = new Set(metadata.schemaFeatureKeys);\n for (const [featureKey] of Object.entries(featureTable)) {\n if (!knownFeatureKeys.has(featureKey)) {\n diagnostics.push({\n id: `unknown-feature:${featureKey}`,\n category: \"feature\",\n severity: \"warning\",\n title: `Unknown feature flag: features.${featureKey}`,\n message: \"This feature is not recognized in the current schema. Keeping it is non-destructive, but it may do nothing.\",\n fixId: `remove-feature:${featureKey}`,\n fixLabel: \"Remove flag\",\n });\n continue;\n }\n\n const stage = getFeatureStage(metadata, featureKey);\n if (stage === \"deprecated\") {\n diagnostics.push({\n id: `deprecated-feature:${featureKey}`,\n category: \"feature\",\n severity: \"warning\",\n title: `Deprecated feature flag: features.${featureKey}`,\n message: \"Codex marks this feature as deprecated. Prefer removing it.\",\n fixId: `remove-feature:${featureKey}`,\n fixLabel: \"Remove deprecated flag\",\n });\n }\n }\n }\n\n for (const server of mcpServers) {\n if (server.transport === \"stdio\" && server.args) {\n for (let index = 0; index < server.args.length; index += 1) {\n const value = server.args[index] ?? \"\";\n if (/(api[-_]?key|token|secret)\\s*=\\s*/i.test(value)) {\n diagnostics.push({\n id: `mcp-secret-arg:${server.name}:${index}`,\n category: \"security\",\n severity: \"warning\",\n title: `Potential secret in MCP args (${server.name})`,\n message: \"Argument text appears to contain a literal token/API key. Move secrets to environment variables.\",\n fixId: null,\n fixLabel: null,\n });\n }\n }\n }\n\n if (server.httpHeaders) {\n for (const [header, headerValue] of Object.entries(server.httpHeaders)) {\n if (!looksLikeSecretValue(headerValue)) {\n continue;\n }\n diagnostics.push({\n id: `mcp-secret-header:${server.name}:${header}`,\n category: \"security\",\n severity: \"warning\",\n title: `Potential secret in MCP header (${server.name})`,\n message: `HTTP header '${header}' appears to contain a literal secret. Prefer env_http_headers or bearer_token_env_var.`,\n fixId: null,\n fixLabel: null,\n });\n }\n }\n }\n\n if (summary.approvalPolicy === \"never\" && summary.sandboxMode === \"danger-full-access\") {\n diagnostics.push({\n id: \"risk:yolo-combo\",\n category: \"risk\",\n severity: \"risk\",\n title: \"High-risk execution mode enabled\",\n message: \"approval_policy=never + sandbox_mode=danger-full-access removes approval and sandbox guardrails.\",\n fixId: null,\n fixLabel: null,\n });\n }\n\n return diagnostics;\n}\n\nfunction isYoloApplied(summary: CodexConfigSettingsSummary): boolean {\n return (\n summary.model === YOLO_PRESET.model &&\n summary.reviewModel === YOLO_PRESET.reviewModel &&\n summary.modelReasoningEffort === YOLO_PRESET.modelReasoningEffort &&\n summary.modelReasoningSummary === YOLO_PRESET.modelReasoningSummary &&\n summary.modelVerbosity === YOLO_PRESET.modelVerbosity &&\n summary.approvalPolicy === YOLO_PRESET.approvalPolicy &&\n summary.sandboxMode === YOLO_PRESET.sandboxMode &&\n summary.webSearch === YOLO_PRESET.webSearch &&\n summary.personality === YOLO_PRESET.personality &&\n summary.toolOutputTokenLimit === YOLO_PRESET.toolOutputTokenLimit &&\n summary.modelAutoCompactTokenLimit === YOLO_PRESET.modelAutoCompactTokenLimit &&\n summary.features.unifiedExec === true &&\n summary.features.shellSnapshot === true &&\n summary.notice.hideFullAccessWarning === true &&\n summary.notice.hideGpt51MigrationPrompt === true &&\n summary.notice.hideRateLimitModelNudge === true\n );\n}\n\nasync function buildSnapshot(\n content: string,\n exists: boolean,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const configPath = getConfigPath(options);\n const parsed = tryParseToml(content);\n const summary = buildSettingsSummary(parsed.data);\n const updatedAt = await getUpdatedAt(configPath, exists);\n const mcpServers = buildMcpServersList(parsed.data);\n const rmcpClientEnabled = parseRmcpClientEnabled(parsed.data);\n const metadata = await getCodexConfigMetadata();\n const diagnostics = parsed.error\n ? []\n : buildConfigDiagnostics(parsed.data, summary, mcpServers, metadata);\n\n return {\n path: configPath,\n exists,\n content,\n settings: summary,\n mcpServers,\n rmcpClientEnabled,\n parseError: parsed.error,\n isYoloPreset: parsed.error ? false : isYoloApplied(summary),\n updatedAt,\n metadata,\n diagnostics,\n };\n}\n\nfunction sanitizeString(value: string | null | undefined): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction sanitizeNumber(value: number | null | undefined): number | null {\n if (value === undefined || value === null) {\n return null;\n }\n if (!Number.isFinite(value)) {\n throw new Error(\"Numeric value must be finite.\");\n }\n return value;\n}\n\nfunction normalizeStringArrayInput(values?: string[] | null): string[] | null {\n if (!values) {\n return null;\n }\n const normalized = values\n .map(value => sanitizeString(value))\n .filter((value): value is string => Boolean(value));\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeStringRecordInput(record?: Record<string, string> | null): Record<string, string> | null {\n if (!record) {\n return null;\n }\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(record)) {\n const normalizedKey = sanitizeString(key);\n const normalizedValue = sanitizeString(value);\n if (normalizedKey && normalizedValue) {\n normalized[normalizedKey] = normalizedValue;\n }\n }\n return Object.keys(normalized).length > 0 ? normalized : null;\n}\n\nfunction applySuggestedFixes(current: RawConfig, fixIds?: string[] | null): RawConfig {\n if (!fixIds || fixIds.length === 0) {\n return current;\n }\n\n let next: RawConfig = { ...current };\n\n for (const fixId of fixIds) {\n if (!fixId.startsWith(\"remove-feature:\")) {\n continue;\n }\n\n const featureKey = fixId.slice(\"remove-feature:\".length).trim();\n if (!featureKey) {\n continue;\n }\n\n const rawFeatures =\n typeof next[\"features\"] === \"object\" && next[\"features\"] !== null && !Array.isArray(next[\"features\"])\n ? { ...(next[\"features\"] as RawConfig) }\n : {};\n\n if (!Object.prototype.hasOwnProperty.call(rawFeatures, featureKey)) {\n continue;\n }\n\n delete rawFeatures[featureKey];\n if (Object.keys(rawFeatures).length === 0) {\n delete next[\"features\"];\n } else {\n next[\"features\"] = rawFeatures;\n }\n }\n\n return next;\n}\n\nfunction applyUpdatesToConfig(current: RawConfig, updates: CodexConfigUpdatePayload): RawConfig {\n const next: RawConfig = { ...current };\n\n const applyStringField = (key: string, candidate?: string | null) => {\n if (candidate === undefined) {\n return;\n }\n const normalized = sanitizeString(candidate);\n if (!normalized) {\n delete next[key];\n } else {\n next[key] = normalized;\n }\n };\n\n const applyNumberField = (key: string, candidate?: number | null) => {\n if (candidate === undefined) {\n return;\n }\n const normalized = sanitizeNumber(candidate);\n if (normalized === null) {\n delete next[key];\n } else {\n next[key] = normalized;\n }\n };\n\n applyStringField(\"model\", updates.model);\n applyStringField(\"review_model\", updates.reviewModel);\n applyStringField(\"model_reasoning_effort\", updates.modelReasoningEffort);\n applyStringField(\"model_reasoning_summary\", updates.modelReasoningSummary);\n applyStringField(\"model_verbosity\", updates.modelVerbosity);\n applyStringField(\"approval_policy\", updates.approvalPolicy);\n applyStringField(\"sandbox_mode\", updates.sandboxMode);\n applyStringField(\"web_search\", updates.webSearch);\n applyStringField(\"personality\", updates.personality);\n\n applyNumberField(\"tool_output_token_limit\", updates.toolOutputTokenLimit);\n applyNumberField(\"model_auto_compact_token_limit\", updates.modelAutoCompactTokenLimit);\n applyNumberField(\"model_context_window\", updates.modelContextWindow);\n\n if (updates.features) {\n const rawFeatures =\n typeof next[\"features\"] === \"object\" && next[\"features\"] !== null && !Array.isArray(next[\"features\"])\n ? { ...(next[\"features\"] as RawConfig) }\n : {};\n\n const applyFeatureField = (key: string, candidate: boolean | null | undefined) => {\n if (candidate === undefined) {\n return;\n }\n if (candidate === null) {\n delete rawFeatures[key];\n return;\n }\n rawFeatures[key] = candidate;\n };\n\n for (const [rawKey, candidate] of Object.entries(updates.features)) {\n const key = rawKey === \"unifiedExec\"\n ? \"unified_exec\"\n : rawKey === \"shellSnapshot\"\n ? \"shell_snapshot\"\n : rawKey;\n applyFeatureField(key, candidate);\n }\n\n if (Object.keys(rawFeatures).length === 0) {\n delete next[\"features\"];\n } else {\n next[\"features\"] = rawFeatures;\n }\n }\n\n if (updates.tools) {\n const rawTools =\n typeof next[\"tools\"] === \"object\" && next[\"tools\"] !== null && !Array.isArray(next[\"tools\"])\n ? { ...(next[\"tools\"] as RawConfig) }\n : {};\n\n const applyToolField = (key: string, candidate?: boolean | null) => {\n if (candidate === undefined) {\n return;\n }\n if (candidate === null) {\n delete rawTools[key];\n } else {\n rawTools[key] = candidate;\n }\n };\n\n applyToolField(\"web_search\", updates.tools.webSearch);\n applyToolField(\"view_image\", updates.tools.viewImage);\n\n if (Object.keys(rawTools).length === 0) {\n delete next[\"tools\"];\n } else {\n next[\"tools\"] = rawTools;\n }\n }\n\n if (updates.notice) {\n const rawNotice = next[\"notice\"];\n const currentNotice =\n rawNotice && typeof rawNotice === \"object\" && rawNotice !== null\n ? { ...(rawNotice as RawConfig) }\n : {};\n\n const applyBooleanField = (key: string, candidate?: boolean | null) => {\n if (candidate === undefined) {\n return;\n }\n if (candidate === null) {\n delete currentNotice[key];\n } else {\n currentNotice[key] = candidate;\n }\n };\n\n const applyRecordField = (key: string, candidate?: Record<string, string> | null) => {\n if (candidate === undefined) {\n return;\n }\n const normalized = normalizeStringRecordInput(candidate);\n if (!normalized) {\n delete currentNotice[key];\n } else {\n currentNotice[key] = normalized;\n }\n };\n\n applyBooleanField(\"hide_full_access_warning\", updates.notice.hideFullAccessWarning);\n applyBooleanField(\"hide_gpt5_1_migration_prompt\", updates.notice.hideGpt51MigrationPrompt);\n applyBooleanField(\n \"hide_gpt-5.1-codex-max_migration_prompt\",\n updates.notice.hideLegacyGpt51CodexMaxMigrationPrompt,\n );\n applyBooleanField(\"hide_rate_limit_model_nudge\", updates.notice.hideRateLimitModelNudge);\n applyRecordField(\"model_migrations\", updates.notice.modelMigrations);\n\n if (Object.keys(currentNotice).length === 0) {\n delete next[\"notice\"];\n } else {\n next[\"notice\"] = currentNotice;\n }\n }\n\n return applySuggestedFixes(next, updates.applyFixes);\n}\n\nfunction validateMcpServerName(name: string): string {\n const normalized = sanitizeString(name);\n if (!normalized) {\n throw new Error(\"MCP server name is required.\");\n }\n if (!/^[A-Za-z0-9._-]+$/.test(normalized)) {\n throw new Error(\"MCP server name must use letters, numbers, periods, underscores, or hyphens.\");\n }\n return normalized;\n}\n\nfunction applyMcpServerUpsert(\n current: RawConfig,\n server: McpServerConfig,\n rmcpClientEnabled?: boolean | null,\n): RawConfig {\n const name = validateMcpServerName(server.name ?? \"\");\n const next: RawConfig = { ...current };\n const rawServers =\n typeof next[\"mcp_servers\"] === \"object\" && next[\"mcp_servers\"] !== null && !Array.isArray(next[\"mcp_servers\"])\n ? { ...(next[\"mcp_servers\"] as RawConfig) }\n : {};\n\n const base =\n typeof rawServers[name] === \"object\" && rawServers[name] !== null && !Array.isArray(rawServers[name])\n ? { ...(rawServers[name] as RawConfig) }\n : {};\n\n const updated: RawConfig = { ...base };\n\n const setStringField = (key: string, value: string | null | undefined) => {\n const normalized = sanitizeString(value ?? null);\n if (!normalized) {\n delete updated[key];\n return;\n }\n updated[key] = normalized;\n };\n\n const setStringArrayField = (key: string, values: string[] | null | undefined) => {\n const normalized = normalizeStringArrayInput(values);\n if (!normalized) {\n delete updated[key];\n return;\n }\n updated[key] = normalized;\n };\n\n const setRecordField = (key: string, values: Record<string, string> | null | undefined) => {\n const normalized = normalizeStringRecordInput(values);\n if (!normalized) {\n delete updated[key];\n return;\n }\n updated[key] = normalized;\n };\n\n const setNumberField = (key: string, value: number | null | undefined) => {\n if (value === null || value === undefined) {\n delete updated[key];\n return;\n }\n if (!Number.isFinite(value)) {\n throw new Error(`Invalid numeric value for ${key}.`);\n }\n updated[key] = value;\n };\n\n updated[\"enabled\"] = Boolean(server.enabled);\n updated[\"type\"] = server.transport;\n setNumberField(\"startup_timeout_sec\", server.startupTimeoutSec);\n setNumberField(\"tool_timeout_sec\", server.toolTimeoutSec);\n setStringArrayField(\"enabled_tools\", server.enabledTools);\n setStringArrayField(\"disabled_tools\", server.disabledTools);\n\n if (server.transport !== \"stdio\") {\n setStringField(\"url\", server.url);\n if (!sanitizeString(server.url)) {\n throw new Error(\"HTTP/SSE MCP server requires a URL.\");\n }\n setStringField(\"bearer_token_env_var\", server.bearerTokenEnvVar);\n setRecordField(\"http_headers\", server.httpHeaders);\n setRecordField(\"env_http_headers\", server.envHttpHeaders);\n delete updated[\"command\"];\n delete updated[\"args\"];\n delete updated[\"env\"];\n delete updated[\"env_vars\"];\n delete updated[\"cwd\"];\n } else {\n setStringField(\"command\", server.command);\n if (!sanitizeString(server.command)) {\n throw new Error(\"STDIO MCP server requires a command.\");\n }\n setStringArrayField(\"args\", server.args);\n setRecordField(\"env\", server.env);\n setStringArrayField(\"env_vars\", server.envVars);\n setStringField(\"cwd\", server.cwd);\n delete updated[\"url\"];\n delete updated[\"bearer_token_env_var\"];\n delete updated[\"http_headers\"];\n delete updated[\"env_http_headers\"];\n }\n\n rawServers[name] = updated;\n if (Object.keys(rawServers).length > 0) {\n next[\"mcp_servers\"] = rawServers;\n } else {\n delete next[\"mcp_servers\"];\n }\n\n const rmcpEnabledValue = rmcpClientEnabled ?? parseRmcpClientEnabled(next);\n return applyRmcpClientFlag(next, rmcpEnabledValue);\n}\n\nfunction applyMcpServerRemoval(current: RawConfig, serverName: string): RawConfig {\n const name = validateMcpServerName(serverName);\n const next: RawConfig = { ...current };\n const rawServers =\n typeof next[\"mcp_servers\"] === \"object\" && next[\"mcp_servers\"] !== null && !Array.isArray(next[\"mcp_servers\"])\n ? { ...(next[\"mcp_servers\"] as RawConfig) }\n : {};\n\n if (!Object.prototype.hasOwnProperty.call(rawServers, name)) {\n return next;\n }\n\n delete rawServers[name];\n if (Object.keys(rawServers).length > 0) {\n next[\"mcp_servers\"] = rawServers;\n } else {\n delete next[\"mcp_servers\"];\n }\n return next;\n}\n\nfunction applyRmcpClientFlag(current: RawConfig, enabled: boolean): RawConfig {\n const next: RawConfig = { ...current };\n const rawFeatures =\n typeof next[\"features\"] === \"object\" && next[\"features\"] !== null && !Array.isArray(next[\"features\"])\n ? { ...(next[\"features\"] as RawConfig) }\n : {};\n\n if (enabled) {\n rawFeatures[\"rmcp_client\"] = true;\n } else {\n delete rawFeatures[\"rmcp_client\"];\n }\n\n if (Object.keys(rawFeatures).length > 0) {\n next[\"features\"] = rawFeatures;\n } else {\n delete next[\"features\"];\n }\n\n delete next[\"experimental_use_rmcp_client\"];\n return next;\n}\n\nasync function readParsedConfigOrThrow(options?: CodexHomePathOptions): Promise<RawConfig> {\n const { content } = await readConfigContent(options);\n const parsed = tryParseToml(content);\n\n if (!parsed.data) {\n throw new Error(parsed.error ?? \"config.toml contains invalid TOML syntax.\");\n }\n\n return parsed.data;\n}\n\nexport async function getCodexConfigSnapshot(\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const { content, exists } = await readConfigContent(options);\n return buildSnapshot(content, exists, options);\n}\n\nexport async function saveCodexConfigContent(\n content: string,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const normalized = ensureTrailingNewline(normalizeLineEndings(content));\n const parsed = tryParseToml(normalized);\n if (!parsed.data) {\n throw new Error(parsed.error ?? \"config.toml contains invalid TOML syntax.\");\n }\n await writeConfigContent(normalized, options);\n return buildSnapshot(normalized, true, options);\n}\n\nexport async function updateCodexConfigValues(\n updates: CodexConfigUpdatePayload,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(options);\n const updated = applyUpdatesToConfig(parsed, updates);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, options);\n return buildSnapshot(serialized, true, options);\n}\n\nexport async function applyYoloOpinionatedMode(\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n return updateCodexConfigValues(YOLO_PRESET, options);\n}\n\nexport async function upsertMcpServer(\n server: McpServerConfig,\n options?: { rmcpClientEnabled?: boolean | null },\n storageOptions?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(storageOptions);\n const updated = applyMcpServerUpsert(parsed, server, options?.rmcpClientEnabled);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, storageOptions);\n return buildSnapshot(serialized, true, storageOptions);\n}\n\nexport async function removeMcpServer(\n serverName: string,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(options);\n const updated = applyMcpServerRemoval(parsed, serverName);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, options);\n return buildSnapshot(serialized, true, options);\n}\n\nexport async function setRmcpClient(\n enabled: boolean,\n options?: CodexHomePathOptions,\n): Promise<CodexConfigSnapshotPayload> {\n const parsed = await readParsedConfigOrThrow(options);\n const updated = applyRmcpClientFlag(parsed, enabled);\n const serialized = ensureTrailingNewline(stringify(updated as Record<string, any>));\n await writeConfigContent(serialized, options);\n return buildSnapshot(serialized, true, options);\n}\n","import { spawn } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { requireCodexCli } from \"@codexuse/runtime-codex/codex/cli\";\nimport type {\n CodexConfigMetadata,\n CodexFeatureCatalogEntry,\n CodexFeatureStage,\n} from \"@codexuse/contracts/codex/config-types\";\n\nexport type {\n CodexConfigMetadata,\n CodexFeatureCatalogEntry,\n CodexFeatureStage,\n} from \"@codexuse/contracts/codex/config-types\";\n\nconst CONFIG_SCHEMA_URL = \"https://raw.githubusercontent.com/openai/codex/main/codex-rs/core/config.schema.json\";\nconst METADATA_CACHE_TTL_MS = 60_000;\n\nconst FALLBACK_SCHEMA_TOP_LEVEL_KEYS = [\n \"agents\",\n \"analytics\",\n \"approval_policy\",\n \"apps\",\n \"chatgpt_base_url\",\n \"check_for_update_on_startup\",\n \"cli_auth_credentials_store\",\n \"compact_prompt\",\n \"developer_instructions\",\n \"disable_paste_burst\",\n \"experimental_compact_prompt_file\",\n \"experimental_use_freeform_apply_patch\",\n \"experimental_use_unified_exec_tool\",\n \"features\",\n \"feedback\",\n \"file_opener\",\n \"forced_chatgpt_workspace_id\",\n \"forced_login_method\",\n \"ghost_snapshot\",\n \"hide_agent_reasoning\",\n \"history\",\n \"instructions\",\n \"log_dir\",\n \"mcp_oauth_callback_port\",\n \"mcp_oauth_credentials_store\",\n \"mcp_servers\",\n \"model\",\n \"model_auto_compact_token_limit\",\n \"model_context_window\",\n \"model_instructions_file\",\n \"model_provider\",\n \"model_providers\",\n \"model_reasoning_effort\",\n \"model_reasoning_summary\",\n \"model_supports_reasoning_summaries\",\n \"model_verbosity\",\n \"notice\",\n \"notify\",\n \"oss_provider\",\n \"otel\",\n \"personality\",\n \"profile\",\n \"profiles\",\n \"project_doc_fallback_filenames\",\n \"project_doc_max_bytes\",\n \"project_root_markers\",\n \"projects\",\n \"review_model\",\n \"sandbox_mode\",\n \"sandbox_workspace_write\",\n \"shell_environment_policy\",\n \"show_raw_agent_reasoning\",\n \"skills\",\n \"suppress_unstable_features_warning\",\n \"tool_output_token_limit\",\n \"tools\",\n \"tui\",\n \"web_search\",\n \"windows_wsl_setup_acknowledged\",\n];\n\nconst FALLBACK_FEATURE_KEYS = [\n \"apply_patch_freeform\",\n \"apps\",\n \"child_agents_md\",\n \"collab\",\n \"collaboration_modes\",\n \"connectors\",\n \"elevated_windows_sandbox\",\n \"enable_experimental_windows_sandbox\",\n \"enable_request_compression\",\n \"experimental_use_freeform_apply_patch\",\n \"experimental_use_unified_exec_tool\",\n \"experimental_windows_sandbox\",\n \"include_apply_patch_tool\",\n \"memory_tool\",\n \"personality\",\n \"powershell_utf8\",\n \"remote_models\",\n \"request_rule\",\n \"responses_websockets\",\n \"responses_websockets_v2\",\n \"runtime_metrics\",\n \"search_tool\",\n \"shell_snapshot\",\n \"shell_tool\",\n \"skill_env_var_dependency_prompt\",\n \"skill_mcp_dependency_install\",\n \"sqlite\",\n \"steer\",\n \"undo\",\n \"unified_exec\",\n \"use_linux_sandbox_bwrap\",\n \"web_search\",\n \"web_search_cached\",\n \"web_search_request\",\n];\n\nlet metadataCache: CodexConfigMetadata | null = null;\nlet metadataCacheAt = 0;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));\n}\n\nasync function runCommand(\n command: string,\n args: string[],\n timeoutMs = 3_000,\n): Promise<{ stdout: string; exitCode: number | null }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: process.env,\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout?.on(\"data\", chunk => {\n stdout += chunk.toString();\n });\n\n child.stderr?.on(\"data\", chunk => {\n stderr += chunk.toString();\n });\n\n const timeout = setTimeout(() => {\n child.kill();\n reject(new Error(`Command timed out: ${command} ${args.join(\" \")}`));\n }, timeoutMs);\n\n child.on(\"error\", error => {\n clearTimeout(timeout);\n reject(error);\n });\n\n child.on(\"close\", code => {\n clearTimeout(timeout);\n if (code !== 0 && !stdout.trim() && stderr.trim()) {\n resolve({ stdout: stderr, exitCode: code });\n return;\n }\n resolve({ stdout, exitCode: code });\n });\n });\n}\n\nasync function runCodexCommand(args: string[]): Promise<{ stdout: string; exitCode: number | null }> {\n const codexPath = await requireCodexCli();\n const isJsLauncher = codexPath.endsWith(\".js\");\n const command = isJsLauncher ? process.execPath : codexPath;\n const commandArgs = isJsLauncher ? [codexPath, ...args] : args;\n return runCommand(command, commandArgs);\n}\n\nfunction parseFeatureCatalog(output: string): CodexFeatureCatalogEntry[] {\n const entries: CodexFeatureCatalogEntry[] = [];\n const lines = output.split(/\\r?\\n/).map(line => line.trim()).filter(Boolean);\n\n for (const line of lines) {\n const match = line.match(/^(\\S+)\\s+(stable|experimental|deprecated|under development)\\s+(true|false)$/i);\n if (!match) {\n continue;\n }\n const [, key, stageRaw, enabledRaw] = match;\n const stage = stageRaw.toLowerCase() as Exclude<CodexFeatureStage, \"unknown\">;\n entries.push({\n key,\n stage,\n enabled: enabledRaw === \"true\",\n });\n }\n\n return entries.sort((a, b) => a.key.localeCompare(b.key));\n}\n\nfunction parseSchemaKeys(schemaRaw: string): { topLevelKeys: string[]; featureKeys: string[] } {\n const parsed = JSON.parse(schemaRaw) as unknown;\n if (!isRecord(parsed)) {\n return {\n topLevelKeys: FALLBACK_SCHEMA_TOP_LEVEL_KEYS,\n featureKeys: FALLBACK_FEATURE_KEYS,\n };\n }\n\n const properties = isRecord(parsed.properties) ? parsed.properties : {};\n const topLevelKeys = uniqueSorted(Object.keys(properties));\n\n const features = isRecord(properties.features) ? properties.features : {};\n const featureProperties = isRecord(features.properties) ? features.properties : {};\n const featureKeys = uniqueSorted(Object.keys(featureProperties));\n\n return {\n topLevelKeys: topLevelKeys.length > 0 ? topLevelKeys : FALLBACK_SCHEMA_TOP_LEVEL_KEYS,\n featureKeys: featureKeys.length > 0 ? featureKeys : FALLBACK_FEATURE_KEYS,\n };\n}\n\nasync function readSchemaFromLocal(): Promise<string | null> {\n const candidates = [\n process.env.CODEX_CONFIG_SCHEMA_PATH,\n path.join(process.cwd(), \"codex-rs\", \"core\", \"config.schema.json\"),\n path.join(process.cwd(), \"node_modules\", \"@openai\", \"codex\", \"codex-rs\", \"core\", \"config.schema.json\"),\n ].filter((candidate): candidate is string => Boolean(candidate));\n\n for (const candidate of candidates) {\n try {\n return await readFile(candidate, \"utf8\");\n } catch {\n // Continue to next candidate.\n }\n }\n\n return null;\n}\n\nasync function readSchemaFromRemote(): Promise<string | null> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 2_500);\n\n try {\n const response = await fetch(CONFIG_SCHEMA_URL, {\n signal: controller.signal,\n headers: {\n \"User-Agent\": \"codexuse-desktop\",\n },\n });\n\n if (!response.ok) {\n return null;\n }\n\n return await response.text();\n } catch {\n return null;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function readSchemaKeys(): Promise<{ topLevelKeys: string[]; featureKeys: string[] }> {\n const local = await readSchemaFromLocal();\n if (local) {\n try {\n return parseSchemaKeys(local);\n } catch {\n // Fallback to remote/fallback sets.\n }\n }\n\n const remote = await readSchemaFromRemote();\n if (remote) {\n try {\n return parseSchemaKeys(remote);\n } catch {\n // Fallback below.\n }\n }\n\n return {\n topLevelKeys: FALLBACK_SCHEMA_TOP_LEVEL_KEYS,\n featureKeys: FALLBACK_FEATURE_KEYS,\n };\n}\n\nasync function readCodexVersion(): Promise<string | null> {\n try {\n const { stdout } = await runCodexCommand([\"--version\"]);\n const value = stdout.trim();\n return value.length > 0 ? value : null;\n } catch {\n return null;\n }\n}\n\nasync function readFeatureCatalog(): Promise<CodexFeatureCatalogEntry[]> {\n try {\n const { stdout } = await runCodexCommand([\"features\", \"list\"]);\n return parseFeatureCatalog(stdout);\n } catch {\n return [];\n }\n}\n\nexport async function getCodexConfigMetadata(forceRefresh = false): Promise<CodexConfigMetadata> {\n const now = Date.now();\n if (!forceRefresh && metadataCache && (now - metadataCacheAt) < METADATA_CACHE_TTL_MS) {\n return metadataCache;\n }\n\n const [schemaKeys, featureCatalog, codexVersion] = await Promise.all([\n readSchemaKeys(),\n readFeatureCatalog(),\n readCodexVersion(),\n ]);\n\n const catalogMap = new Map<string, CodexFeatureCatalogEntry>();\n for (const entry of featureCatalog) {\n catalogMap.set(entry.key, entry);\n }\n\n for (const featureKey of schemaKeys.featureKeys) {\n if (!catalogMap.has(featureKey)) {\n catalogMap.set(featureKey, {\n key: featureKey,\n stage: \"unknown\",\n enabled: null,\n });\n }\n }\n\n const mergedFeatureCatalog = Array.from(catalogMap.values()).sort((a, b) => a.key.localeCompare(b.key));\n\n const metadata: CodexConfigMetadata = {\n schemaTopLevelKeys: uniqueSorted(schemaKeys.topLevelKeys),\n schemaFeatureKeys: uniqueSorted(schemaKeys.featureKeys),\n featureCatalog: mergedFeatureCatalog,\n codexVersion,\n fetchedAt: now,\n };\n\n metadataCache = metadata;\n metadataCacheAt = now;\n return metadata;\n}\n","import { mkdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { resolveCodexHomeDir, type CodexHomePathOptions } from \"@codexuse/runtime-codex/codex/home\";\nimport { DEFAULT_CONFIG_TEMPLATE } from \"@codexuse/runtime-codex/codex/config-presets\";\n\nexport function getConfigPath(options?: CodexHomePathOptions): string {\n return path.join(resolveCodexHomeDir(options), \"config.toml\");\n}\n\nasync function ensureConfigDirExists(filePath: string): Promise<void> {\n const dir = path.dirname(filePath);\n await mkdir(dir, { recursive: true });\n}\n\nexport function normalizeLineEndings(content: string): string {\n return content.replace(/\\r\\n/g, \"\\n\");\n}\n\nexport function ensureTrailingNewline(content: string): string {\n return content.endsWith(\"\\n\") ? content : `${content}\\n`;\n}\n\nexport async function readConfigContent(\n options?: CodexHomePathOptions,\n): Promise<{ exists: boolean; content: string }> {\n const configPath = getConfigPath(options);\n try {\n const content = await readFile(configPath, \"utf8\");\n return {\n exists: true,\n content: normalizeLineEndings(content),\n };\n } catch (error) {\n const nodeError = error as NodeJS.ErrnoException;\n if (nodeError.code === \"ENOENT\") {\n return {\n exists: false,\n content: DEFAULT_CONFIG_TEMPLATE,\n };\n }\n throw error;\n }\n}\n\nexport async function writeConfigContent(\n content: string,\n options?: CodexHomePathOptions,\n): Promise<void> {\n const configPath = getConfigPath(options);\n await ensureConfigDirExists(configPath);\n const normalized = ensureTrailingNewline(normalizeLineEndings(content));\n await writeFile(configPath, normalized, \"utf8\");\n}\n\nexport async function getUpdatedAt(\n configPath: string,\n exists: boolean,\n): Promise<number | null> {\n if (!exists) {\n return null;\n }\n\n try {\n const stats = await stat(configPath);\n return stats.mtimeMs;\n } catch (error) {\n const nodeError = error as NodeJS.ErrnoException;\n if (nodeError.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\nimport { getAppState, getUserDataDir } from \"@codexuse/runtime-app-state/app/state\";\n\nexport type CodexHomePathOptions = {\n codexHomePath?: string | null;\n};\n\nexport type CodexRuntimeContextSource = \"explicit\" | \"profile\" | \"settings\" | \"default\";\n\nexport type CodexRuntimeContext = {\n codexHomePath: string;\n profileName: string | null;\n source: CodexRuntimeContextSource;\n};\n\nexport function resolveHomeDir(): string {\n return process.env.HOME || os.homedir();\n}\n\nfunction expandHomePrefix(input: string, homeDir: string): string {\n if (input === \"~\") {\n return homeDir;\n }\n if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n return path.join(homeDir, input.slice(2));\n }\n return input;\n}\n\nfunction normalizePathCandidate(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nexport function normalizeCodexHomePath(input?: string | null): string | null {\n const configured = normalizePathCandidate(input);\n if (!configured) {\n return null;\n }\n return path.resolve(expandHomePrefix(configured, resolveHomeDir()));\n}\n\nexport function resolveDefaultCodexHomeDir(): string {\n return path.join(resolveHomeDir(), \".codex\");\n}\n\nexport function resolveProfileCodexHomeDir(profileName: string): string {\n return path.join(getUserDataDir(), \"profile-homes\", profileName);\n}\n\nexport function resolveCodexAuthPath(options?: CodexHomePathOptions): string {\n return path.join(resolveCodexHomeDir(options), \"auth.json\");\n}\n\nexport function resolveCodexHomeDir(options?: CodexHomePathOptions): string {\n return normalizeCodexHomePath(options?.codexHomePath) ?? resolveDefaultCodexHomeDir();\n}\n\nexport async function resolveCodexRuntimeContext(\n options?: CodexHomePathOptions,\n): Promise<CodexRuntimeContext> {\n const explicit = normalizeCodexHomePath(options?.codexHomePath);\n if (explicit) {\n return {\n codexHomePath: explicit,\n profileName: null,\n source: \"explicit\",\n };\n }\n\n const state = await getAppState();\n const configured = normalizeCodexHomePath(\n (state.runtimeSettings as Record<string, unknown>)?.codexHome as string | null | undefined,\n );\n if (configured) {\n return {\n codexHomePath: configured,\n profileName: null,\n source: \"settings\",\n };\n }\n\n return {\n codexHomePath: resolveDefaultCodexHomeDir(),\n profileName: null,\n source: \"default\",\n };\n}\n\nexport async function resolveExternalCodexRuntimeContext(\n options?: CodexHomePathOptions,\n): Promise<CodexRuntimeContext> {\n const explicit = normalizeCodexHomePath(options?.codexHomePath);\n if (explicit) {\n return {\n codexHomePath: explicit,\n profileName: null,\n source: \"explicit\",\n };\n }\n\n const state = await getAppState();\n const configured = normalizeCodexHomePath(\n (state.runtimeSettings as Record<string, unknown>)?.codexHome as string | null | undefined,\n );\n if (configured) {\n return {\n codexHomePath: configured,\n profileName: null,\n source: \"settings\",\n };\n }\n\n return {\n codexHomePath: resolveDefaultCodexHomeDir(),\n profileName: null,\n source: \"default\",\n };\n}\n\nexport async function resolveGlobalCodexRuntimeContext(\n options?: CodexHomePathOptions,\n): Promise<CodexRuntimeContext> {\n return resolveExternalCodexRuntimeContext(options);\n}\n","import type { CodexConfigUpdatePayload } from \"@codexuse/contracts/codex/config-types\";\n\nexport const DEFAULT_CONFIG_TEMPLATE = [\n \"# ~/.codex/config.toml (managed by CodexUse)\",\n \"# Safe defaults with prompts and sandboxed access.\",\n \"# To enable full access, opt into the YOLO preset from settings.\",\n \"\",\n 'model = \"gpt-5.3-codex\"',\n 'review_model = \"gpt-5.3-codex\"',\n 'model_reasoning_effort = \"medium\"',\n 'model_reasoning_summary = \"auto\"',\n 'model_verbosity = \"medium\"',\n 'approval_policy = \"on-request\"',\n 'sandbox_mode = \"read-only\"',\n 'web_search = \"cached\"',\n \"\",\n].join(\"\\n\");\n\nexport const SUPPORTED_REASONING_EFFORT = new Set([\"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"none\"]);\n\nexport const YOLO_PRESET: CodexConfigUpdatePayload = {\n model: \"gpt-5.3-codex\",\n reviewModel: \"gpt-5.3-codex\",\n modelReasoningEffort: \"xhigh\",\n modelReasoningSummary: \"detailed\",\n modelVerbosity: \"high\",\n approvalPolicy: \"never\",\n sandboxMode: \"danger-full-access\",\n webSearch: \"live\",\n personality: \"pragmatic\",\n toolOutputTokenLimit: 25_000,\n modelAutoCompactTokenLimit: 233_000,\n features: {\n unifiedExec: true,\n shellSnapshot: true,\n },\n notice: {\n hideFullAccessWarning: true,\n hideGpt51MigrationPrompt: true,\n hideRateLimitModelNudge: true,\n },\n};\n","/* eslint-disable-next-line no-control-regex */\nconst ANSI_PATTERN = /\\u001B\\[[0-9;]*m/g;\n\nexport type UserFacingErrorCode =\n | \"ERR_AUTH\"\n | \"ERR_CLI_UNAVAILABLE\"\n | \"ERR_DISK_FULL\"\n | \"ERR_NETWORK\"\n | \"ERR_NOT_FOUND\"\n | \"ERR_PERMISSION\"\n | \"ERR_PROVIDER\"\n | \"ERR_RATE_LIMIT\"\n | \"ERR_TIMEOUT\"\n | \"ERR_UNKNOWN\";\n\nexport type UserFacingErrorInfo = {\n code: UserFacingErrorCode;\n referenceId: string;\n title: string;\n message: string;\n recovery: string;\n technicalMessage: string;\n technicalDetails: string;\n retryable: boolean;\n};\n\nfunction stripAnsi(value: string): string {\n return value.replace(ANSI_PATTERN, \"\");\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nexport function compactErrorText(value: string, maxLength = 220): string {\n if (!value) {\n return \"\";\n }\n const cleaned = normalizeWhitespace(stripAnsi(String(value)));\n if (!cleaned) {\n return \"\";\n }\n if (cleaned.length <= maxLength) {\n return cleaned;\n }\n return `${cleaned.slice(0, maxLength).trimEnd()}…`;\n}\n\nfunction createErrorReferenceId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`.toUpperCase();\n}\n\nfunction serializeUnknownError(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof Error) {\n return value.stack ?? value.message;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction extractRawMessage(error: unknown): string {\n if (error === null || typeof error === \"undefined\") {\n return \"\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n\nfunction normalizeRawMessage(rawMessage: string): string {\n let cleaned = normalizeWhitespace(stripAnsi(rawMessage));\n if (!cleaned) {\n return \"\";\n }\n if (cleaned.startsWith(\"Error invoking remote method\")) {\n cleaned = cleaned.replace(/^Error invoking remote method '[^']+': Error: /, \"\");\n }\n if (cleaned.toLowerCase().includes(\"openai codex\") && cleaned.toLowerCase().includes(\"workdir:\")) {\n const parts = cleaned.split(/error:/i);\n if (parts.length > 1) {\n return parts[parts.length - 1]?.trim() ?? cleaned;\n }\n }\n return cleaned;\n}\n\nfunction resolveCategory(\n cleaned: string,\n options: {\n fallback: string;\n notFoundFallback?: string;\n },\n): Omit<UserFacingErrorInfo, \"referenceId\" | \"technicalMessage\" | \"technicalDetails\"> {\n const lower = cleaned.toLowerCase();\n\n if (options.notFoundFallback && (lower.includes(\"enoent\") || lower.includes(\"not found\"))) {\n return {\n code: \"ERR_NOT_FOUND\",\n title: \"We couldn't find that item\",\n message: options.notFoundFallback,\n recovery: \"Check the path or selection, then try again.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"rate limit\") ||\n lower.includes(\"quota exceeded\") ||\n lower.includes(\"too many requests\") ||\n lower.includes(\"429\")\n ) {\n return {\n code: \"ERR_RATE_LIMIT\",\n title: \"Rate limit reached\",\n message: \"The provider is rate limited right now.\",\n recovery: \"Wait a moment, switch profiles, or try again.\",\n retryable: true,\n };\n }\n\n if (lower.includes(\"timeout\") || lower.includes(\"timed out\")) {\n return {\n code: \"ERR_TIMEOUT\",\n title: \"Request timed out\",\n message: \"The operation took too long to finish.\",\n recovery: \"Check the connection and try again.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"network\") ||\n lower.includes(\"econn\") ||\n lower.includes(\"networkerror\") ||\n lower.includes(\"connection refused\") ||\n lower.includes(\"socket hang up\")\n ) {\n return {\n code: \"ERR_NETWORK\",\n title: \"Can't reach the service\",\n message: \"CodexUse couldn't connect to the required service.\",\n recovery: \"Check your internet or local server connection, then retry.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"token_invalidated\") ||\n lower.includes(\"session invalidated\") ||\n lower.includes(\"session expired\") ||\n lower.includes(\"refresh token\") ||\n lower.includes(\"unauthorized\") ||\n lower.includes(\"401\")\n ) {\n return {\n code: \"ERR_AUTH\",\n title: \"Sign-in expired\",\n message: \"This account needs to sign in again.\",\n recovery: \"Reconnect the profile, then retry the action.\",\n retryable: true,\n };\n }\n\n if (lower.includes(\"permission\") || lower.includes(\"eacces\") || lower.includes(\"operation not permitted\")) {\n return {\n code: \"ERR_PERMISSION\",\n title: \"Permission denied\",\n message: \"CodexUse doesn't have permission to do that.\",\n recovery: \"Check the file permissions or restart the app and try again.\",\n retryable: true,\n };\n }\n\n if (lower.includes(\"enospc\") || lower.includes(\"disk full\") || lower.includes(\"no space left\")) {\n return {\n code: \"ERR_DISK_FULL\",\n title: \"Disk is full\",\n message: \"CodexUse couldn't save data because the disk is full.\",\n recovery: \"Free up disk space, then try again.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"codex cli\") ||\n lower.includes(\"command not found\") ||\n lower.includes(\"spawn codex\") ||\n lower.includes(\"could not find codex\")\n ) {\n return {\n code: \"ERR_CLI_UNAVAILABLE\",\n title: \"Codex CLI unavailable\",\n message: \"CodexUse couldn't start the Codex CLI.\",\n recovery: \"Check Runtime > Codex and confirm the CLI is installed correctly.\",\n retryable: true,\n };\n }\n\n if (\n lower.includes(\"provider\") ||\n lower.includes(\"model\") ||\n lower.includes(\"openai\") ||\n lower.includes(\"anthropic\")\n ) {\n return {\n code: \"ERR_PROVIDER\",\n title: \"Provider request failed\",\n message: \"The AI provider rejected or failed the request.\",\n recovery: \"Try again, or switch the active profile or model.\",\n retryable: true,\n };\n }\n\n return {\n code: \"ERR_UNKNOWN\",\n title: \"Something went wrong\",\n message: options.fallback,\n recovery: \"Try again. If it keeps happening, report the error with the reference below.\",\n retryable: true,\n };\n}\n\nexport function resolveUserFacingError(\n error: unknown,\n options: {\n fallback?: string;\n notFoundFallback?: string;\n } = {},\n): UserFacingErrorInfo {\n const fallback = options.fallback ?? \"Something went wrong. Please try again.\";\n const rawMessage = extractRawMessage(error);\n const cleaned = normalizeRawMessage(rawMessage);\n const category = resolveCategory(cleaned, {\n fallback,\n ...(options.notFoundFallback ? { notFoundFallback: options.notFoundFallback } : {}),\n });\n\n return {\n ...category,\n referenceId: createErrorReferenceId(),\n technicalMessage: compactErrorText(cleaned || rawMessage || fallback, 400),\n technicalDetails: compactErrorText(serializeUnknownError(error), 4000),\n };\n}\n\nexport function formatUserFacingError(\n error: unknown,\n options: {\n fallback?: string;\n notFoundFallback?: string;\n maxLength?: number;\n } = {},\n): string {\n let cleaned = resolveUserFacingError(error, options).message;\n const maxLength = typeof options.maxLength === \"number\" ? options.maxLength : 220;\n if (cleaned.length > maxLength) {\n cleaned = `${cleaned.slice(0, maxLength).trimEnd()}…`;\n }\n\n return cleaned;\n}\n","import {\n CLOUD_SYNC_SCHEMA_VERSION,\n type CloudSyncProfileRecord,\n type CloudSyncSnapshot,\n} from \"@codexuse/contracts/cloud-sync/types\";\nimport {\n CloudSyncClientError,\n fetchRemoteSnapshotMeta,\n fetchRemoteSnapshot,\n pushRemoteSnapshot,\n} from \"@codexuse/runtime-profiles/cloud-sync/client\";\nimport { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { getCodexConfigSnapshot, saveCodexConfigContent } from \"@codexuse/runtime-codex/codex/config\";\nimport { resolveCodexRuntimeContext } from \"@codexuse/runtime-codex/codex/home\";\nimport {\n getStoredLicense,\n readCodexSettingsJsonRaw,\n writeCodexSettingsJsonRaw,\n} from \"@codexuse/runtime-codex/codex/settings\";\nimport { getAppState, patchAppState } from \"@codexuse/runtime-app-state/app/state\";\nimport { licenseService } from \"@codexuse/runtime-profiles/license/service\";\nimport { logInfo, logWarn } from \"@codexuse/shared/core/logger\";\nimport { formatUserFacingError } from \"@codexuse/shared/core/errors\";\nimport type { CloudSyncRunResultPayload, CloudSyncStatusPayload } from \"@codexuse/contracts/desktop/ipc-types\";\nimport { isRecord } from \"@codexuse/shared/core/type-guards\";\n\nconst SYNC_SIZE_WARN_BYTES = 1 * 1024 * 1024;\nconst SYNC_SIZE_MAX_BYTES = 5 * 1024 * 1024;\nconst MB_DIVISOR = 1024 * 1024;\n\ninterface CloudSyncStateFile {\n lastPushAt?: string;\n lastPullAt?: string;\n lastError?: string;\n remoteUpdatedAt?: string;\n}\n\ntype Eligibility = {\n canSync: boolean;\n reason: string | null;\n licenseKey: string | null;\n licenseState: string | null;\n};\n\ntype BuildLocalSnapshotOptions = {\n enforcePushGuards?: boolean;\n};\n\nfunction mapProfilesFromAppState(raw: unknown): CloudSyncProfileRecord[] {\n if (!isRecord(raw)) {\n return [];\n }\n\n const profiles: CloudSyncProfileRecord[] = [];\n\n for (const [name, value] of Object.entries(raw)) {\n if (!isRecord(value)) {\n continue;\n }\n\n const data = isRecord(value.data) ? value.data : null;\n if (!data) {\n continue;\n }\n\n const normalizedName = typeof name === \"string\" ? name.trim() : \"\";\n if (!normalizedName) {\n continue;\n }\n\n profiles.push({\n name: normalizedName,\n displayName: typeof value.displayName === \"string\" ? value.displayName : null,\n data,\n metadata: isRecord(value.metadata) ? value.metadata : undefined,\n accountId: typeof value.accountId === \"string\" ? value.accountId : null,\n workspaceId: typeof value.workspaceId === \"string\" ? value.workspaceId : null,\n workspaceName: typeof value.workspaceName === \"string\" ? value.workspaceName : null,\n email: typeof value.email === \"string\" ? value.email : null,\n authMethod: typeof value.authMethod === \"string\" ? value.authMethod : null,\n createdAt: typeof value.createdAt === \"string\" ? value.createdAt : null,\n updatedAt: typeof value.updatedAt === \"string\" ? value.updatedAt : null,\n });\n }\n\n return profiles;\n}\n\nfunction summarizeSnapshot(snapshot: CloudSyncSnapshot): {\n profiles: number;\n configBytes: number;\n settingsKeys: number;\n} {\n const configBytes =\n typeof snapshot.configTomlContent === \"string\" ? snapshot.configTomlContent.length : 0;\n const settingsKeys =\n isRecord(snapshot.settingsJson) ? Object.keys(snapshot.settingsJson).length : 0;\n\n return {\n profiles: snapshot.profiles.length,\n configBytes,\n settingsKeys,\n };\n}\n\nasync function readState(): Promise<CloudSyncStateFile> {\n const state = await getAppState();\n return {\n lastPushAt: state.sync.lastPushAt ?? undefined,\n lastPullAt: state.sync.lastPullAt ?? undefined,\n lastError: state.sync.lastError ?? undefined,\n remoteUpdatedAt: state.sync.remoteUpdatedAt ?? undefined,\n };\n}\n\nasync function writeState(patch: Partial<CloudSyncStateFile>): Promise<void> {\n await patchAppState({\n sync: {\n ...(typeof patch.lastPushAt === \"string\" ? { lastPushAt: patch.lastPushAt } : {}),\n ...(typeof patch.lastPullAt === \"string\" ? { lastPullAt: patch.lastPullAt } : {}),\n ...(typeof patch.lastError === \"string\" ? { lastError: patch.lastError } : patch.lastError === undefined ? { lastError: null } : {}),\n ...(typeof patch.remoteUpdatedAt === \"string\"\n ? { remoteUpdatedAt: patch.remoteUpdatedAt }\n : {}),\n },\n });\n}\n\nasync function resolveEligibility(): Promise<Eligibility> {\n const stored = await getStoredLicense();\n const licenseKey = typeof stored?.licenseKey === \"string\" ? stored.licenseKey.trim() : \"\";\n\n if (!licenseKey) {\n return {\n canSync: false,\n reason: \"License key is required for cloud sync.\",\n licenseKey: null,\n licenseState: null,\n };\n }\n\n const status = await licenseService.getStatus();\n const active = status.state === \"active\" || status.state === \"grace\";\n if (!active) {\n return {\n canSync: false,\n reason: \"Cloud sync requires an active Pro license.\",\n licenseKey,\n licenseState: status.state,\n };\n }\n\n return {\n canSync: true,\n reason: null,\n licenseKey,\n licenseState: status.state,\n };\n}\n\nfunction formatMegabytes(bytes: number): string {\n return (bytes / MB_DIVISOR).toFixed(2);\n}\n\nasync function buildLocalSnapshot(\n profileManager: ProfileManager,\n options: BuildLocalSnapshotOptions = {},\n): Promise<CloudSyncSnapshot> {\n const enforcePushGuards = options.enforcePushGuards !== false;\n const profilesFromManager = await profileManager.exportProfilesForCloudSync();\n const state = await getAppState();\n const profilesFromState = mapProfilesFromAppState(state.profilesByName);\n const profiles = profilesFromManager.length > 0 ? profilesFromManager : profilesFromState;\n const runtimeContext = await resolveCodexRuntimeContext();\n const config = await getCodexConfigSnapshot({\n codexHomePath: runtimeContext.codexHomePath,\n });\n const settingsJson = await readCodexSettingsJsonRaw();\n\n const hasProfiles = profiles.length > 0;\n const hasConfig = typeof config.content === \"string\" && config.content.trim().length > 0;\n const hasSettings = isRecord(settingsJson) && Object.keys(settingsJson).length > 0;\n\n if (enforcePushGuards && !hasProfiles && !hasConfig && !hasSettings) {\n throw new Error(\"Refusing to push an empty cloud sync snapshot.\");\n }\n\n const snapshot: CloudSyncSnapshot = {\n schemaVersion: CLOUD_SYNC_SCHEMA_VERSION,\n updatedAt: new Date().toISOString(),\n profiles,\n configTomlContent: config.exists ? config.content : null,\n settingsJson,\n };\n\n if (!enforcePushGuards) {\n return snapshot;\n }\n\n return snapshot;\n}\n\nasync function applyRemoteSnapshot(profileManager: ProfileManager, snapshot: CloudSyncSnapshot): Promise<void> {\n await profileManager.replaceProfilesFromCloudSync(snapshot.profiles ?? []);\n\n if (typeof snapshot.configTomlContent === \"string\") {\n const runtimeContext = await resolveCodexRuntimeContext();\n await saveCodexConfigContent(snapshot.configTomlContent, {\n codexHomePath: runtimeContext.codexHomePath,\n });\n }\n\n if (snapshot.settingsJson && isRecord(snapshot.settingsJson)) {\n await writeCodexSettingsJsonRaw(snapshot.settingsJson);\n } else {\n await writeCodexSettingsJsonRaw({});\n }\n}\n\nfunction toRunError(mode: \"push\" | \"pull\", error: unknown): CloudSyncRunResultPayload {\n const message = formatUserFacingError(error, {\n fallback: `Cloud sync ${mode} failed.`,\n });\n\n return {\n mode,\n status: \"error\",\n message,\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n}\n\nexport async function getCloudSyncStatus(): Promise<CloudSyncStatusPayload> {\n const eligibility = await resolveEligibility();\n const state = await readState();\n\n let remoteUpdatedAt: string | null = state.remoteUpdatedAt ?? null;\n if (eligibility.canSync && eligibility.licenseKey) {\n try {\n remoteUpdatedAt = await fetchRemoteSnapshotMeta(eligibility.licenseKey);\n } catch (error) {\n if (error instanceof CloudSyncClientError && error.status === 404) {\n try {\n const remote = await fetchRemoteSnapshot(eligibility.licenseKey);\n remoteUpdatedAt = remote?.updatedAt ?? null;\n } catch {\n // Keep status lightweight when remote endpoint is unavailable.\n }\n }\n // Keep status lightweight when remote endpoint is unavailable.\n }\n }\n\n return {\n canSync: eligibility.canSync,\n reason: eligibility.reason,\n licenseState: eligibility.licenseState,\n hasLicenseKey: Boolean(eligibility.licenseKey),\n lastPushAt: state.lastPushAt ?? null,\n lastPullAt: state.lastPullAt ?? null,\n lastError: state.lastError ?? null,\n remoteUpdatedAt,\n };\n}\n\nexport async function pushCloudSync(): Promise<CloudSyncRunResultPayload> {\n const eligibility = await resolveEligibility();\n if (!eligibility.canSync || !eligibility.licenseKey) {\n return {\n mode: \"push\",\n status: \"skipped\",\n message: eligibility.reason ?? \"Cloud sync unavailable.\",\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n }\n\n const profileManager = new ProfileManager();\n\n try {\n await profileManager.initialize();\n const localSnapshot = await buildLocalSnapshot(profileManager, { enforcePushGuards: true });\n const serializedSnapshot = JSON.stringify(localSnapshot);\n const snapshotBytes = Buffer.byteLength(serializedSnapshot, \"utf8\");\n if (snapshotBytes > SYNC_SIZE_WARN_BYTES) {\n logWarn(\"[cloud-sync] push snapshot is large\", {\n bytes: snapshotBytes,\n megabytes: formatMegabytes(snapshotBytes),\n });\n }\n if (snapshotBytes > SYNC_SIZE_MAX_BYTES) {\n throw new Error(\n `Snapshot too large to sync (${formatMegabytes(snapshotBytes)} MB). Reduce profiles or config size.`,\n );\n }\n if (process.env.NODE_ENV !== \"production\") {\n logInfo(\"[cloud-sync] push snapshot summary\", summarizeSnapshot(localSnapshot));\n }\n const remote = await pushRemoteSnapshot(eligibility.licenseKey, localSnapshot, {\n serializedSnapshot,\n });\n\n await writeState({\n lastPushAt: new Date().toISOString(),\n remoteUpdatedAt: remote.snapshot.updatedAt,\n lastError: undefined,\n });\n\n if (remote.status === \"stale\") {\n return {\n mode: \"push\",\n status: \"stale\",\n message: \"Remote cloud snapshot is newer. Pull first.\",\n localUpdatedAt: localSnapshot.updatedAt,\n remoteUpdatedAt: remote.snapshot.updatedAt,\n };\n }\n\n return {\n mode: \"push\",\n status: \"applied\",\n message: \"Cloud sync push completed.\",\n localUpdatedAt: localSnapshot.updatedAt,\n remoteUpdatedAt: remote.snapshot.updatedAt,\n };\n } catch (error) {\n const result = toRunError(\"push\", error);\n const lastError = error instanceof CloudSyncClientError ? error.message : result.message;\n await writeState({ lastError });\n return result;\n }\n}\n\nexport async function pullCloudSync(): Promise<CloudSyncRunResultPayload> {\n const eligibility = await resolveEligibility();\n if (!eligibility.canSync || !eligibility.licenseKey) {\n return {\n mode: \"pull\",\n status: \"skipped\",\n message: eligibility.reason ?? \"Cloud sync unavailable.\",\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n }\n\n const profileManager = new ProfileManager();\n\n try {\n await profileManager.initialize();\n const remote = await fetchRemoteSnapshot(eligibility.licenseKey);\n\n if (!remote) {\n return {\n mode: \"pull\",\n status: \"skipped\",\n message: \"No cloud snapshot found.\",\n localUpdatedAt: null,\n remoteUpdatedAt: null,\n };\n }\n\n await applyRemoteSnapshot(profileManager, remote);\n await writeState({\n lastPullAt: new Date().toISOString(),\n remoteUpdatedAt: remote.updatedAt,\n lastError: undefined,\n });\n\n return {\n mode: \"pull\",\n status: \"applied\",\n message: \"Cloud sync pull completed.\",\n localUpdatedAt: remote.updatedAt,\n remoteUpdatedAt: remote.updatedAt,\n };\n } catch (error) {\n const result = toRunError(\"pull\", error);\n const lastError = error instanceof CloudSyncClientError ? error.message : result.message;\n await writeState({ lastError });\n return result;\n }\n}\n","import { getCloudSyncStatus, pullCloudSync, pushCloudSync } from \"@codexuse/runtime-profiles/cloud-sync/service\";\nimport { printHelp } from \"../app/help\";\nimport { hasFlag, stripFlags } from \"../platform/args\";\n\nfunction printSyncResult(result: Awaited<ReturnType<typeof pushCloudSync>>): void {\n console.log(result.message);\n if (result.localUpdatedAt) {\n console.log(`Local snapshot: ${result.localUpdatedAt}`);\n }\n if (result.remoteUpdatedAt) {\n console.log(`Remote snapshot: ${result.remoteUpdatedAt}`);\n }\n}\n\nexport async function handleSync(args: string[], version: string): Promise<void> {\n const flags = args.filter(arg => arg.startsWith(\"-\"));\n const params = stripFlags(args);\n const sub = params[0];\n\n if (!sub || hasFlag(flags, \"--help\") || hasFlag(flags, \"-h\")) {\n printHelp(version);\n return;\n }\n\n switch (sub) {\n case \"status\": {\n const status = await getCloudSyncStatus();\n console.log(`Can sync: ${status.canSync ? \"yes\" : \"no\"}`);\n console.log(`Has key: ${status.hasLicenseKey ? \"yes\" : \"no\"}`);\n if (status.licenseState) {\n console.log(`License state: ${status.licenseState}`);\n }\n if (status.reason) {\n console.log(`Reason: ${status.reason}`);\n }\n if (status.remoteUpdatedAt) {\n console.log(`Remote snapshot: ${status.remoteUpdatedAt}`);\n }\n if (status.lastPushAt) {\n console.log(`Last push: ${status.lastPushAt}`);\n }\n if (status.lastPullAt) {\n console.log(`Last pull: ${status.lastPullAt}`);\n }\n if (status.lastError) {\n console.log(`Last error: ${status.lastError}`);\n }\n return;\n }\n case \"pull\": {\n const result = await pullCloudSync();\n printSyncResult(result);\n if (result.status === \"error\") {\n process.exitCode = 1;\n }\n return;\n }\n case \"push\": {\n const result = await pushCloudSync();\n printSyncResult(result);\n if (result.status === \"error\") {\n process.exitCode = 1;\n }\n return;\n }\n default:\n printHelp(version);\n }\n}\n","import { getUserDataDir, initializeAppState } from \"@codexuse/runtime-app-state/app/state\";\n\nlet cliStorageReadyPromise: Promise<void> | null = null;\n\nexport async function ensureCliStorageReady(): Promise<void> {\n if (cliStorageReadyPromise) {\n return cliStorageReadyPromise;\n }\n\n cliStorageReadyPromise = (async () => {\n await initializeAppState(getUserDataDir());\n })().catch((error) => {\n cliStorageReadyPromise = null;\n throw error;\n });\n\n return cliStorageReadyPromise;\n}\n","import { handleAccountPoolCommand } from \"../commands/accountPool\";\nimport {\n handleBestCommand,\n handleDoctorCommand,\n handleRunCommand,\n} from \"../commands/codex\";\nimport { handleLicense } from \"../commands/license\";\nimport { handleProfileCommand } from \"../commands/profile\";\nimport { handleSync } from \"../commands/sync\";\nimport { printHelp } from \"./help\";\nimport { hasFlag } from \"../platform/args\";\nimport { ensureCliStorageReady } from \"../platform/storage\";\n\ndeclare const __CODEXUSE_CLI_VERSION__: string;\n\nconst VERSION = typeof __CODEXUSE_CLI_VERSION__ === \"string\"\n ? __CODEXUSE_CLI_VERSION__\n : \"0.0.0\";\n\nasync function runCli(): Promise<void> {\n const args = process.argv.slice(2);\n\n if (args.length === 0) {\n printHelp(VERSION);\n return;\n }\n\n if (args[0]?.startsWith(\"-\") && (hasFlag(args, \"--help\") || hasFlag(args, \"-h\"))) {\n printHelp(VERSION);\n return;\n }\n\n if (args[0]?.startsWith(\"-\") && (hasFlag(args, \"--version\") || hasFlag(args, \"-v\"))) {\n console.log(VERSION);\n return;\n }\n\n const command = args[0];\n const rest = args.slice(1);\n\n switch (command) {\n case \"doctor\":\n await ensureCliStorageReady();\n await handleDoctorCommand(rest);\n return;\n case \"run\":\n await ensureCliStorageReady();\n await handleRunCommand(rest);\n return;\n case \"best\":\n await ensureCliStorageReady();\n await handleBestCommand(rest);\n return;\n case \"account-pool\":\n case \"accounts-pool\":\n await ensureCliStorageReady();\n await handleAccountPoolCommand(rest, VERSION);\n return;\n case \"profile\":\n await ensureCliStorageReady();\n await handleProfileCommand(rest, VERSION);\n return;\n case \"license\":\n await ensureCliStorageReady();\n await handleLicense(rest, VERSION);\n return;\n case \"sync\":\n await ensureCliStorageReady();\n await handleSync(rest, VERSION);\n return;\n default:\n printHelp(VERSION);\n return;\n }\n}\n\nexport function runCliEntryPoint(): void {\n void runCli().catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exitCode = 1;\n });\n}\n","import { runCliEntryPoint } from \"./app/main\";\n\nrunCliEntryPoint();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,qFAAAA,UAAAC,SAAA;AAAA;AACA,QAAM,YAAY;AAClB,QAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA;AAAA,MAE9B,YAAa,KAAK,UAAU,YAAY;AACtC,cAAM,mBAAmB,KAAK,UAAU,UAAU;AAClD,aAAK,OAAO;AACZ,aAAK,OAAO;AACZ,YAAI,MAAM,kBAAmB,OAAM,kBAAkB,MAAM,YAAW;AAAA,MACxE;AAAA,IACF;AACA,QAAM,QAAN,MAAY;AAAA,MACV,YAAa,QAAQ;AACnB,aAAK,SAAS;AACd,aAAK,MAAM;AACX,aAAK,WAAW;AAChB,aAAK,SAAS;AACd,aAAK,cAAc;AACnB,aAAK,YAAY;AAAA,MACnB;AAAA,IACF;AACA,QAAM,SAAN,MAAa;AAAA,MACX,cAAe;AACb,aAAK,MAAM;AACX,aAAK,MAAM;AACX,aAAK,OAAO;AACZ,aAAK,MAAM,CAAC;AACZ,aAAK,MAAM,KAAK;AAChB,aAAK,QAAQ,CAAC;AACd,aAAK,OAAO;AACZ,aAAK,OAAO;AACZ,aAAK,KAAK;AACV,aAAK,QAAQ,IAAI,MAAM,KAAK,UAAU;AAAA,MACxC;AAAA,MAEA,MAAO,KAAK;AAEV,YAAI,IAAI,WAAW,KAAK,IAAI,UAAU,KAAM;AAE5C,aAAK,OAAO,OAAO,GAAG;AACtB,aAAK,KAAK;AACV,aAAK,OAAO;AACZ,YAAI;AACJ,eAAO,YAAY,SAAS,KAAK,SAAS,GAAG;AAC3C,oBAAU,KAAK,OAAO;AAAA,QACxB;AACA,aAAK,OAAO;AAAA,MACd;AAAA,MACA,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AAI,OAAO;AACnB;AAAA,EACF;AAEA,QAAM,UAAU,KAAK,CAAC;AACtB,QAAM,OAAO,KAAK,MAAM,CAAC;AAEzB,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,YAAM,sBAAsB;AAC5B,YAAM,oBAAoB,IAAI;AAC9B;AAAA,IACF,KAAK;AACH,YAAM,sBAAsB;AAC5B,YAAM,iBAAiB,IAAI;AAC3B;AAAA,IACF,KAAK;AACH,YAAM,sBAAsB;AAC5B,YAAM,kBAAkB,IAAI;AAC5B;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,YAAM,sBAAsB;AAC5B,YAAM,yBAAyB,MAAM,OAAO;AAC5C;AAAA,IACF,KAAK;AACH,YAAM,sBAAsB;AAC5B,YAAM,qBAAqB,MAAM,OAAO;AACxC;AAAA,IACF,KAAK;AACH,YAAM,sBAAsB;AAC5B,YAAM,cAAc,MAAM,OAAO;AACjC;AAAA,IACF,KAAK;AACH,YAAM,sBAAsB;AAC5B,YAAM,WAAW,MAAM,OAAO;AAC9B;AAAA,IACF;AACE,gBAAU,OAAO;AACjB;AAAA,EACJ;AACF;AAEO,SAAS,mBAAyB;AACvC,OAAK,OAAO,EAAE,MAAM,CAAC,UAAU;AAC7B,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,YAAQ,MAAM,OAAO;AACrB,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;;;AChFA,iBAAiB;","names":["exports","module","exports","module","exports","module","exports","module","exports","module","Date","exports","module","exports","module","exports","module","exports","module","index","blocksize","exports","module","exports","module","exports","module","stringify","tomlType","str","exports","import_node_crypto","import_node_path","import_node_path","fs","path","sqlite","database","isRecord","clone","os","path","clone","import_node_crypto","asString","isRecord","isRecord","asString","crypto","offer","crypto","fallbackStored","import_node_crypto","import_path","import_node_child_process","import_node_fs","import_node_os","import_node_path","import_node_fs","import_node_path","path","import_node_path","path","isRecord","asString","waitersForKey","parseTimestamp","fs","path","os","readline","REFRESH_TOKEN_REDEEMED_SNIPPET","fs","path","REFRESH_TOKEN_REDEEMED_SNIPPET","currentRecency","asRecord","asString","path","import_node_child_process","import_node_child_process","import_node_fs","import_node_path","ENV_HINTS","fileExists","path","stat","buildCodexCommand","buildCodexCommand","import_node_child_process","import_node_crypto","import_node_fs","import_node_os","import_node_path","import_node_fs","import_node_path","isRecord","fs","path","stat","sqlite","database","row","net","normalizeOfficialCodexRelayProfileId","normalizeOfficialCodexRelayProfileId","normalizeOfficialCodexPowerSettings","normalizeOfficialCodexQolSettings","event","path","runCommand","path","runCommand","path","runCommand","path","runningPids","mainPids","path","bridge","action","result","isRecord","isRecord","import_toml","import_node_child_process","import_node_path","isRecord","runCommand","path","import_promises","import_node_path","import_node_os","import_node_path","os","path","path","isRecord"]}
|