codexuse-cli 3.5.6 → 3.6.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/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/runtime-app-state/src/storage/documents.ts","../../../packages/runtime-app-state/src/app/runtimeSettings.ts","../../../packages/runtime-profiles/src/license/service.ts","../../../packages/contracts/src/settings/auto-roll.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/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/daemon.ts","../../../packages/shared/src/core/internal-js-runtime.ts","../src/commands/license.ts","../../../packages/runtime-profiles/src/license/guard.ts","../../../packages/runtime-profiles/src/profiles/rate-limit-notifier.ts","../src/platform/codexCli.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.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 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\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 \"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\";\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS = [\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 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 projectsCustomCodexModels: string[];\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 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 { ProfileData, ProfileMetadata } from \"@codexuse/contracts/profiles/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 {\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 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 analyticsViewed: 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 warningThreshold: number;\n switchThreshold: number;\n };\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 warningThreshold: 85,\n switchThreshold: 95,\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 analyticsViewed: 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 normalizeAppState(raw: unknown): AppState {\n const defaults = createDefaultAppState();\n if (!isRecord(raw)) {\n return defaults;\n }\n\n const next = deepMerge(defaults, raw as AppStatePatch);\n const merged = clone(next);\n\n merged.schemaVersion = 1;\n if (typeof merged.autoRoll.enabled !== \"boolean\") {\n merged.autoRoll.enabled = false;\n }\n if (!Number.isFinite(merged.autoRoll.warningThreshold)) {\n merged.autoRoll.warningThreshold = 85;\n }\n if (!Number.isFinite(merged.autoRoll.switchThreshold)) {\n merged.autoRoll.switchThreshold = 95;\n }\n if (\n merged.autoRoll.warningThreshold < 50 ||\n merged.autoRoll.warningThreshold > 99\n ) {\n merged.autoRoll.warningThreshold = 85;\n }\n if (\n merged.autoRoll.switchThreshold <= merged.autoRoll.warningThreshold ||\n merged.autoRoll.switchThreshold > 100\n ) {\n merged.autoRoll.switchThreshold = Math.min(\n 100,\n Math.max(merged.autoRoll.warningThreshold + 1, 95),\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 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\" || 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(merged.ui.profiles.customGroupFilter);\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(([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || typeof value !== \"boolean\") {\n return [];\n }\n return [[normalizedKey, value]];\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 (typeof merged.ui.onboarding.milestones.analyticsViewed !== \"boolean\") {\n merged.ui.onboarding.milestones.analyticsViewed = 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(([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 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(([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 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(([projectId, threadId]) => {\n const normalizedProjectId = asString(projectId);\n if (!normalizedProjectId) {\n return [];\n }\n const normalizedThreadId =\n typeof threadId === \"string\" && threadId.trim().length > 0 ? threadId.trim() : null;\n return [[normalizedProjectId, normalizedThreadId]];\n }),\n );\n }\n merged.ui.duplicateWarningDismissedKey = asString(merged.ui.duplicateWarningDismissedKey);\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(([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 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 { 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((merged as { telemetry?: { installId?: unknown } }).telemetry?.installId);\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(resolveStorageDbPath(), APP_STATE_DOCUMENT, normalizeAppState);\n}\n\nasync function writeAppStateToStorage(state: AppState): Promise<AppState> {\n return writeDocument(resolveStorageDbPath(), APP_STATE_DOCUMENT, normalizeAppState(state));\n}\n\nasync function ensureInitialized(): Promise<AppState> {\n if (appStateCache) {\n return appStateCache;\n }\n\n const loaded = (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 = (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 = 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 (!allowBeforeMigrationComplete && current.migration.status !== \"complete\") {\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","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;\n\ntype StatementLike = {\n get: (...params: any[]) => any;\n all: (...params: any[]) => any[];\n run: (...params: any[]) => any;\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 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 = db\n .prepare(\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n )\n .get(namespace);\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 withDatabase(dbPath, (db) => {\n const normalizedValue = clone(value);\n beginImmediate(db);\n try {\n db.prepare(\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 ).run(namespace, JSON.stringify(normalizedValue), new Date().toISOString());\n commit(db);\n return normalizedValue;\n } catch (error) {\n rollback(db);\n throw error;\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 withDatabase(input.dbPath, (db) => {\n beginImmediate(db);\n try {\n const row = db\n .prepare(\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n )\n .get(input.namespace);\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 db.prepare(\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 ).run(input.namespace, JSON.stringify(next), new Date().toISOString());\n commit(db);\n return clone(next);\n } catch (error) {\n rollback(db);\n throw error;\n }\n });\n}\n\nexport async function deleteDocument(dbPath: string, namespace: string): Promise<void> {\n await withDatabase(dbPath, (db) => {\n beginImmediate(db);\n try {\n db.prepare(`DELETE FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`).run(namespace);\n commit(db);\n } catch (error) {\n rollback(db);\n throw error;\n }\n });\n}\n","import {\n getAppState,\n updateAppState,\n} from \"./state\";\n\ntype JsonRecord = Record<string, unknown>;\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\nexport async function readAppSettings(): Promise<JsonRecord> {\n const appState = await getAppState();\n return stripLegacyAppSettingsKeys(asRecord(appState.runtimeSettings));\n}\n\nexport async function writeAppSettings(\n settings: JsonRecord,\n onUpdated?: (settings: JsonRecord) => void | Promise<void>,\n): Promise<JsonRecord> {\n const nextSettings = stripLegacyAppSettingsKeys(asRecord(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();\n }\n\n async getStatus(options: { forceRefresh?: boolean } = {}): Promise<LicenseStatus> {\n const forceRefresh = Boolean(options.forceRefresh);\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) {\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","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_WARNING_THRESHOLD = 85;\nexport const DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD = 95;\nexport const AUTO_ROLL_WARNING_MIN = 50;\nconst AUTO_ROLL_WARNING_MAX = 99;\nconst AUTO_ROLL_SWITCH_MAX = 100;\n\nfunction clampNumber(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\nfunction resolveFiniteNumber(value: number, fallback: number): number {\n return Number.isFinite(value) ? value : fallback;\n}\n\nexport function sanitizeAutoRollWarningThreshold(value: number): number {\n const numeric = resolveFiniteNumber(value, DEFAULT_AUTO_ROLL_WARNING_THRESHOLD);\n return clampNumber(numeric, AUTO_ROLL_WARNING_MIN, AUTO_ROLL_WARNING_MAX);\n}\n\nexport function sanitizeAutoRollSwitchThreshold(\n value: number,\n warningThreshold: number,\n): number {\n const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);\n const numeric = resolveFiniteNumber(value, DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD);\n return clampNumber(numeric, sanitizedWarning + 1, AUTO_ROLL_SWITCH_MAX);\n}\n\nexport function sanitizeAutoRollThresholds(\n warningThreshold: number,\n switchThreshold: number,\n): Pick<AutoRollSettings, \"warningThreshold\" | \"switchThreshold\"> {\n const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);\n const sanitizedSwitch = sanitizeAutoRollSwitchThreshold(switchThreshold, sanitizedWarning);\n return {\n warningThreshold: sanitizedWarning,\n switchThreshold: sanitizedSwitch,\n };\n}\n\nexport function normalizeAutoRollSettings(\n raw?: Partial<AutoRollSettings> | null,\n): AutoRollSettings {\n const enabled = typeof raw?.enabled === \"boolean\" ? raw.enabled : DEFAULT_AUTO_ROLL_ENABLED;\n const rawWarning = resolveFiniteNumber(\n typeof raw?.warningThreshold === \"number\" ? raw.warningThreshold : Number.NaN,\n DEFAULT_AUTO_ROLL_WARNING_THRESHOLD,\n );\n const rawSwitch = resolveFiniteNumber(\n typeof raw?.switchThreshold === \"number\" ? raw.switchThreshold : Number.NaN,\n DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD,\n );\n\n const {\n warningThreshold: normalizedWarning,\n switchThreshold: normalizedSwitch,\n } = sanitizeAutoRollThresholds(rawWarning, rawSwitch);\n\n return {\n enabled,\n warningThreshold: normalizedWarning,\n switchThreshold: normalizedSwitch,\n };\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 warningThreshold: normalized.warningThreshold,\n switchThreshold: normalized.switchThreshold,\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 warningThreshold: autoRoll.warningThreshold,\n switchThreshold: autoRoll.switchThreshold,\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 { fetchRateLimitsViaRpc } from '@codexuse/runtime-codex/codex/rpc';\nimport type { CloudSyncProfileRecord } from '@codexuse/contracts/cloud-sync/types';\nimport { getLastProfileName, persistLastProfileName } from '@codexuse/runtime-codex/codex/settings';\nimport {\n getAppState,\n getUserDataDir,\n updateAppState,\n type ProfileDashboardState,\n type ProfileRecordState,\n} from '@codexuse/runtime-app-state/app/state';\nimport { logError, 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 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 async readPreferredProfileName(): Promise<string | null> {\n try {\n return await getLastProfileName();\n } catch (error) {\n logWarn('Failed to read preferred profile name:', error);\n return null;\n }\n }\n\n private async persistPreferredProfileName(name: string | null): Promise<void> {\n try {\n await persistLastProfileName(name);\n } catch (error) {\n logWarn('Failed to persist preferred profile name:', error);\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 async captureActiveAuthSnapshot(): Promise<ActiveAuthSnapshot> {\n await this.initialize();\n\n let raw: string;\n try {\n raw = await fs.readFile(this.activeAuth, 'utf8');\n } catch (error) {\n if (this.isNotFoundError(error)) {\n return {\n fingerprint: null,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\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 snapshot active auth file:', error);\n this.lastActiveAuthErrorSignature = signature;\n }\n return {\n fingerprint: null,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\n }\n\n const trimmed = raw.trim();\n if (!trimmed) {\n return {\n fingerprint: null,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\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 workspaceId: workspace.id ?? null,\n };\n } catch {\n return {\n fingerprint,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\n }\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 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.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 projectId =\n 'project_id' in data && typeof (data as ProfileData).project_id === 'string'\n ? (data as ProfileData).project_id?.trim()\n : undefined;\n if (projectId) {\n return projectId;\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 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 getProfileRowByAccountId(\n accountId: string,\n options?: { authMethod?: string | null; preferAuthMethod?: string | null },\n ): Promise<ProfileRecord | undefined> {\n const records = await this.listProfileRecords();\n const matches = records.filter(record => {\n const storedAccountId = record.accountId ?? this.getAccountIdFromData(record.data);\n return storedAccountId === accountId;\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 async getProfileRowByAccountAndWorkspace(\n accountId: 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 const storedAccountId = record.accountId ?? this.getAccountIdFromData(record.data);\n if (storedAccountId !== accountId) {\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 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 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 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 if (data.email) {\n profile.email = data.email;\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 existingAccountId = this.getAccountIdFromData(existing);\n const newAccountId = this.getAccountIdFromData(normalized);\n\n if (existingAccountId && newAccountId && existingAccountId !== newAccountId) {\n logWarn(\n `Skipped syncing tokens for profile '${profileName}' because Codex auth switched to account '${newAccountId}'.`,\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 return;\n }\n\n await this.syncProfileTokensFromActiveAuth(profileName, record.data, authPath);\n }),\n );\n }\n\n /**\n * Create a new profile by running codex login\n */\n async createProfile(name: string): Promise<Profile | null> {\n await this.initialize();\n\n const profileName = this.normalizeProfileName(name);\n if (await this.getProfileRowByName(profileName)) {\n throw new Error(`Profile '${profileName}' already exists!`);\n }\n\n let authData: ActiveAuth;\n try {\n const authRaw = await fs.readFile(this.activeAuth, 'utf8');\n authData = JSON.parse(authRaw) as ActiveAuth;\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 const normalizedProfile = this.normalizeProfileData(authData);\n normalizedProfile.created_at = normalizedProfile.created_at ?? new Date().toISOString();\n if (typeof normalizedProfile.auth_method === 'string') {\n normalizedProfile.auth_method = normalizedProfile.auth_method.trim().toLowerCase();\n }\n normalizedProfile.auth_method = normalizedProfile.auth_method ?? 'codex-cli';\n\n const metadata = this.extractProfileMetadata(normalizedProfile);\n const workspace = this.resolveWorkspaceIdentity(normalizedProfile, metadata);\n normalizedProfile.workspace_id = normalizedProfile.workspace_id ?? workspace.id ?? DEFAULT_WORKSPACE_ID;\n if (workspace.name) {\n normalizedProfile.workspace_name = normalizedProfile.workspace_name ?? workspace.name;\n }\n\n const accountId = this.getAccountIdFromData(normalizedProfile);\n if (accountId) {\n const requestedWorkspace = normalizedProfile.workspace_id ?? DEFAULT_WORKSPACE_ID;\n const duplicate = await this.getProfileRowByAccountAndWorkspace(accountId, requestedWorkspace, { authMethod: 'codex-cli' });\n if (duplicate) {\n normalizedProfile.workspace_id = `${requestedWorkspace}:${profileName}`;\n normalizedProfile.workspace_name = normalizedProfile.workspace_name ?? profileName;\n }\n }\n\n const resolvedEmail = this.resolveProfileEmail(normalizedProfile, metadata);\n if (resolvedEmail) {\n normalizedProfile.email = resolvedEmail;\n }\n\n try {\n await this.persistProfileRecord(profileName, normalizedProfile, metadata);\n const stored = await this.getProfileRowByName(profileName);\n return stored ? this.buildProfileFromRow(stored) : null;\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 * Switch to a different profile\n */\n async switchToProfile(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\n try {\n const profileData = record.data;\n const codexFormat = this.convertToCodexFormat(profileData);\n await this.writeAtomic(this.activeAuth, JSON.stringify(codexFormat, null, 2));\n await this.persistPreferredProfileName(profileName);\n return true;\n } catch (error) {\n logError('Error switching profile:', error);\n throw new Error('Failed to switch profile');\n }\n }\n\n async refreshProfileAuth(name: string): Promise<Profile> {\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 existing: ProfileData = record.data;\n let activeAuth: ActiveAuth;\n try {\n const authContent = await fs.readFile(this.activeAuth, 'utf8');\n activeAuth = JSON.parse(authContent) as ActiveAuth;\n } catch (error) {\n if (this.isNotFoundError(error)) {\n throw new Error('Codex CLI did not produce an auth file. Complete the login before refreshing this profile.');\n }\n logError('Failed to read Codex auth file during refresh:', error);\n throw new Error('Failed to read Codex auth file. Complete the login and try again.');\n }\n\n const normalized = this.normalizeProfileData(activeAuth);\n const existingAccountId = this.getAccountIdFromData(existing);\n const newAccountId = this.getAccountIdFromData(normalized);\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\n if (existingAccountId && newAccountId && existingAccountId !== newAccountId) {\n throw new Error(\n `Active Codex login is for account '${newAccountId}', but profile '${profileName}' is tied to '${existingAccountId}'. Create a new profile for the new account instead.`,\n );\n }\n\n if (existingAccountId && normalized.workspace_id) {\n const currentWorkspace = this.resolveWorkspaceIdentity(existing, this.extractProfileMetadata(existing));\n const targetWorkspaceId = normalized.workspace_id;\n const currentWorkspaceId = currentWorkspace.id ?? DEFAULT_WORKSPACE_ID;\n if (targetWorkspaceId !== currentWorkspaceId) {\n const duplicate = await this.getProfileRowByAccountAndWorkspace(existingAccountId, 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 * 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(() =>\n this.runWithPreparedProfileHome(name, action, {\n syncFromActiveAuthBeforeAction: true,\n }),\n ),\n );\n }\n\n async readLiveRateLimits(\n name: string,\n options: { codexPath?: string } = {},\n ): Promise<RateLimitSnapshot | null> {\n return this.enqueueProfileOperation(name, () =>\n this.runWithPreparedProfileHome(\n name,\n env => fetchRateLimitsViaRpc(env, { codexPath: options.codexPath }),\n { syncFromActiveAuthBeforeAction: false },\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 preferred = await this.readPreferredProfileName();\n if (preferred && preferred === sourceName) {\n await this.persistPreferredProfileName(targetName);\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 if (!record.accountId) {\n const dashboardState = await this.readProfileDashboardState();\n delete dashboardState.customGroupsByAccountKey[resolveFallbackAccountKey(profileName)];\n await this.writeProfileDashboardState(dashboardState);\n }\n const preferred = await this.readPreferredProfileName();\n if (preferred && preferred === profileName) {\n await this.persistPreferredProfileName(null);\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 return true;\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 const preferred = await this.readPreferredProfileName();\n if (preferred && removed.includes(preferred)) {\n await this.persistPreferredProfileName(null);\n }\n return removed;\n }\n\n /**\n * Check if the current auth matches a profile (for smart detection)\n */\n async getCurrentProfile(): Promise<{ name: string | null; trusted: boolean }> {\n await this.initialize();\n const preferredName = await this.readPreferredProfileName();\n if (preferredName) {\n try {\n const normalizedPreferred = this.normalizeProfileName(preferredName);\n const preferredRecord = await this.getProfileRowByName(normalizedPreferred);\n if (preferredRecord) {\n return { name: normalizedPreferred, trusted: true };\n }\n } catch {\n // fall through to active auth detection\n }\n }\n const activeAuth = await this.readActiveAuthFile();\n\n if (activeAuth) {\n const normalizedAuth = this.normalizeProfileData(activeAuth);\n const authMetadata = this.extractProfileMetadata(normalizedAuth);\n const workspace = this.resolveWorkspaceIdentity(normalizedAuth, authMetadata);\n const activeAccountId = this.getAccountIdFromData(normalizedAuth);\n\n if (activeAccountId) {\n const scoped = await this.getProfileRowByAccountAndWorkspace(activeAccountId, workspace.id ?? DEFAULT_WORKSPACE_ID, {\n preferAuthMethod: 'codex-cli',\n });\n if (scoped) {\n const normalized = this.normalizeProfileName(scoped.name);\n await this.persistPreferredProfileName(normalized);\n return { name: normalized, trusted: true };\n }\n\n const matching = await this.getProfileRowByAccountId(activeAccountId, { preferAuthMethod: 'codex-cli' });\n if (matching) {\n const normalized = this.normalizeProfileName(matching.name);\n await this.persistPreferredProfileName(normalized);\n return { name: normalized, trusted: true };\n }\n }\n }\n\n const preferred = await this.readPreferredProfileName();\n if (preferred) {\n try {\n const normalized = this.normalizeProfileName(preferred);\n const exists = await this.getProfileRowByName(normalized);\n if (exists) {\n return { name: normalized, trusted: true };\n }\n } catch {\n await this.persistPreferredProfileName(null);\n return { name: null, trusted: false };\n }\n await this.persistPreferredProfileName(null);\n }\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 const preferred = await this.readPreferredProfileName();\n if (preferred) {\n try {\n const normalizedPreferred = this.normalizeProfileName(preferred);\n if (!normalized.has(normalizedPreferred)) {\n await this.persistPreferredProfileName(null);\n }\n } catch {\n await this.persistPreferredProfileName(null);\n }\n }\n\n return {\n imported: normalized.size,\n removed,\n };\n }\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 { RateLimitSnapshot, RateLimitWindow } 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 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\nconst RPC_TIMEOUT_MS = 10_000;\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\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\" ? (payload as Record<string, unknown>) : 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(parsed.tokens?.access_token);\n const candidates = [rootLastRefresh, nestedLastRefresh, rootAccessIssuedAt, nestedAccessIssuedAt]\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\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 (typeof updatedRecency === \"number\" && typeof currentRecency === \"number\") {\n return updatedRecency > currentRecency;\n }\n\n if (typeof updatedRecency === \"number\" && typeof currentRecency !== \"number\") {\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(message: RpcMessage, requestId: number): 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 cleanup();\n reject(new Error(\"codex RPC timed out\"));\n }, Math.max(1, timeoutMs));\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 = 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(rpc?: RpcRateLimitWindow | null): 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\" && 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 = 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 { rateLimits?: RpcRateLimitSnapshot } | 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 ?? process.env.HOME ?? process.env.USERPROFILE ?? os.homedir(),\n \".codex\",\n \"auth.json\",\n ));\n\n try {\n initialSourceAuth = await fs.readFile(sourceAuthPath, \"utf8\").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, { id: 2, method: \"account/rateLimits/read\", params: {} });\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.readFile(sourceAuthPath, \"utf8\").catch(() => null);\n if (shouldWriteBackAuth(initialSourceAuth, currentSourceAuth, updatedAuth)) {\n await fs.writeFile(sourceAuthPath, updatedAuth, \"utf8\");\n } else if (\n currentSourceAuth &&\n currentSourceAuth !== updatedAuth &&\n currentSourceAuth !== initialSourceAuth\n ) {\n logWarn(\"Skipped stale auth sync-back after rate-limit probe; source auth changed in flight.\", {\n sourceAuthPath,\n currentRecencyMs: extractAuthRecencyMs(currentSourceAuth),\n updatedRecencyMs: extractAuthRecencyMs(updatedAuth),\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 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 if (!pathValue) {\n return null;\n }\n const entries = pathValue\n .split(path.delimiter)\n .map(entry => entry.trim())\n .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) {\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.warn>): void {\n if (isTestEnv && !isMocked(console.warn)) {\n return;\n }\n console.warn(...args);\n}\n","export function printHelp(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 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>\n codexuse profile autoroll [--threshold=50-100] [--dry-run] [--watch] [--interval=seconds]\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 --threshold=NN Auto-roll switch threshold percent (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 --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`);\n}\n","import type { CodexLoginMode } from \"./codexCli\";\n\nexport const DEFAULT_AUTOROLL_INTERVAL_SECONDS = 30;\nexport const DEFAULT_AUTOROLL_THRESHOLD = 95;\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, 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 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\nfunction buildCodexCommand(codexPath: string, args: string[]): { command: string; args: string[]; shell: boolean } {\n const normalized = codexPath.toLowerCase();\n const isJs = normalized.endsWith(\".js\");\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 { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { assertProfileCreationAllowed } from \"@codexuse/runtime-profiles/license/guard\";\nimport { maxUsedPercent } from \"@codexuse/runtime-profiles/profiles/rate-limit-notifier\";\nimport { getStoredAutoRollSettings } from \"@codexuse/runtime-codex/codex/settings\";\nimport type {\n OrganizationInfo,\n Profile,\n RateLimitSnapshot,\n RateLimitWindow,\n} from \"@codexuse/contracts/profiles/types\";\nimport {\n DEFAULT_AUTOROLL_INTERVAL_SECONDS,\n DEFAULT_AUTOROLL_THRESHOLD,\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 profile.accountId ?? `profile:${profile.name}`;\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 hasUsage: boolean;\n resetsInSeconds: number | null;\n windowMinutes: number | null;\n};\n\nconst EMPTY_USAGE_SUMMARY: RateLimitUsageSummary = {\n windowKey: \"primary\",\n usagePercent: 0,\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 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 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 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 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 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 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(a: AutoRollCandidate, b: AutoRollCandidate): number {\n if (a.usageSummary.usagePercent !== b.usageSummary.usagePercent) {\n return a.usageSummary.usagePercent - b.usageSummary.usagePercent;\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 switchThreshold: number,\n): AutoRollCandidate | null {\n const candidates = profiles\n .filter(profile => profile.name !== currentProfileName && profile.isValid && !profile.tokenStatus?.requiresUserAction)\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(candidate => candidate.usageSummary.hasUsage && candidate.usageSummary.usagePercent < switchThreshold)\n .sort(compareAutoRollCandidates);\n let selected = belowThreshold[0] ?? null;\n\n if (!selected) {\n selected = candidates\n .filter(candidate => candidate.usageSummary.hasUsage)\n .sort(compareAutoRollCandidates)[0] ?? null;\n }\n\n if (!selected) {\n selected = candidates\n .filter(candidate => !candidate.usageSummary.hasUsage)\n .sort((a, b) => {\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 })[0] ?? null;\n }\n\n if (!selected) {\n return null;\n }\n\n if (selected.usageSummary.hasUsage && currentSummary.hasUsage) {\n if (selected.usageSummary.usagePercent > currentSummary.usagePercent) {\n return null;\n }\n if (selected.usageSummary.usagePercent === currentSummary.usagePercent) {\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 parseAutoRollThreshold(flags: string[], fallbackThreshold: number): number {\n const explicitThreshold = parseNumericFlag(flags, \"--threshold\");\n if (explicitThreshold === null) {\n return fallbackThreshold;\n }\n if (Number.isNaN(explicitThreshold)) {\n throw new Error(\"Invalid --threshold value. Use --threshold=50-100.\");\n }\n if (explicitThreshold < 50 || explicitThreshold > 100) {\n throw new Error(\"Invalid --threshold value. Use a number between 50 and 100.\");\n }\n return Math.round(explicitThreshold);\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\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 threshold: number;\n dryRun: 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 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 (currentUsage.usagePercent < options.threshold) {\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.usagePercent)}%, below threshold ${options.threshold}%.`,\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.threshold,\n );\n if (!candidate) {\n return {\n switched: false,\n message: `No eligible profile to switch from '${current.name}' at ${Math.round(currentUsage.usagePercent)}%.`,\n source: current.name,\n target: null,\n };\n }\n\n const candidateUsage = candidate.usageSummary.hasUsage ? `${Math.round(candidate.usageSummary.usagePercent)}%` : \"n/a\";\n if (options.dryRun) {\n return {\n switched: false,\n message: `[dry-run] Would switch '${current.name}' (${Math.round(currentUsage.usagePercent)}%) -> '${candidate.profile.name}' (${candidateUsage}).`,\n source: current.name,\n target: candidate.profile.name,\n };\n }\n\n await manager.switchToProfile(candidate.profile.name);\n return {\n switched: true,\n message: `Auto-rolled '${current.name}' (${Math.round(currentUsage.usagePercent)}%) -> '${candidate.profile.name}' (${candidateUsage}).`,\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 await manager.switchToProfile(name);\n console.log(`Switched to profile: ${name}`);\n return;\n }\n case \"autoroll\":\n case \"auto-roll\": {\n const watch = hasFlag(flags, \"--watch\");\n const dryRun = hasFlag(flags, \"--dry-run\");\n const settings = await getStoredAutoRollSettings().catch(() => null);\n const fallbackThreshold =\n typeof settings?.switchThreshold === \"number\" && Number.isFinite(settings.switchThreshold)\n ? Math.round(settings.switchThreshold)\n : DEFAULT_AUTOROLL_THRESHOLD;\n const threshold = parseAutoRollThreshold(flags, fallbackThreshold);\n const intervalSeconds = parseAutoRollIntervalSeconds(flags);\n\n if (watch) {\n console.log(`Auto-roll watch: threshold ${threshold}% | interval ${intervalSeconds}s${dryRun ? \" | dry-run\" : \"\"}`);\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 result = await runAutoRollPass(manager, { threshold, dryRun });\n console.log(result.message);\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, { threshold, dryRun });\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 profileName = normalizePathCandidate(state.app.lastProfileName);\n if (profileName && state.profilesByName[profileName]) {\n return {\n codexHomePath: resolveProfileCodexHomeDir(profileName),\n profileName,\n source: \"profile\",\n };\n }\n\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","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 warningThreshold: autoRoll.warningThreshold,\n switchThreshold: autoRoll.switchThreshold,\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 warningThreshold: autoRoll.warningThreshold,\n switchThreshold: autoRoll.switchThreshold,\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 { 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 \"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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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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ACtB,QAAM,OAAO,KAAK,MAAM,CAAC;AAEzB,UAAQ,SAAS;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,KAAK;AACH,YAAM,sBAAsB;AAC5B,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;;;ACpEA,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","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_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_fs","import_node_path","ENV_HINTS","fileExists","path","stat","buildCodexCommand","result","import_node_fs","import_node_path","isRecord","isRecord","import_toml","import_node_child_process","import_node_path","isRecord","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/chat-scrollback.ts","../../../packages/contracts/src/settings/commit-message-prompt.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/contracts/src/settings/auto-roll.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/daemon.ts","../../../packages/shared/src/core/internal-js-runtime.ts","../src/commands/license.ts","../../../packages/runtime-profiles/src/license/guard.ts","../../../packages/runtime-profiles/src/profiles/rate-limit-notifier.ts","../src/platform/codexCli.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.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 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\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 \"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\";\n\nexport const DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS = [\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 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 projectsCustomCodexModels: string[];\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 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 { ProfileData, ProfileMetadata } from \"@codexuse/contracts/profiles/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 {\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 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 analyticsViewed: 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 warningThreshold: number;\n switchThreshold: number;\n };\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 warningThreshold: 85,\n switchThreshold: 95,\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 analyticsViewed: 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 normalizeAppState(raw: unknown): AppState {\n const defaults = createDefaultAppState();\n if (!isRecord(raw)) {\n return defaults;\n }\n\n const next = deepMerge(defaults, raw as AppStatePatch);\n const merged = clone(next);\n\n merged.schemaVersion = 1;\n if (typeof merged.autoRoll.enabled !== \"boolean\") {\n merged.autoRoll.enabled = false;\n }\n if (!Number.isFinite(merged.autoRoll.warningThreshold)) {\n merged.autoRoll.warningThreshold = 85;\n }\n if (!Number.isFinite(merged.autoRoll.switchThreshold)) {\n merged.autoRoll.switchThreshold = 95;\n }\n if (\n merged.autoRoll.warningThreshold < 50 ||\n merged.autoRoll.warningThreshold > 99\n ) {\n merged.autoRoll.warningThreshold = 85;\n }\n if (\n merged.autoRoll.switchThreshold <= merged.autoRoll.warningThreshold ||\n merged.autoRoll.switchThreshold > 100\n ) {\n merged.autoRoll.switchThreshold = Math.min(\n 100,\n Math.max(merged.autoRoll.warningThreshold + 1, 95),\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 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\" || 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(merged.ui.profiles.customGroupFilter);\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(([key, value]) => {\n const normalizedKey = asString(key);\n if (!normalizedKey || typeof value !== \"boolean\") {\n return [];\n }\n return [[normalizedKey, value]];\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 (typeof merged.ui.onboarding.milestones.analyticsViewed !== \"boolean\") {\n merged.ui.onboarding.milestones.analyticsViewed = 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(([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 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(([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 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(([projectId, threadId]) => {\n const normalizedProjectId = asString(projectId);\n if (!normalizedProjectId) {\n return [];\n }\n const normalizedThreadId =\n typeof threadId === \"string\" && threadId.trim().length > 0 ? threadId.trim() : null;\n return [[normalizedProjectId, normalizedThreadId]];\n }),\n );\n }\n merged.ui.duplicateWarningDismissedKey = asString(merged.ui.duplicateWarningDismissedKey);\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(([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 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 { 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((merged as { telemetry?: { installId?: unknown } }).telemetry?.installId);\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(resolveStorageDbPath(), APP_STATE_DOCUMENT, normalizeAppState);\n}\n\nasync function writeAppStateToStorage(state: AppState): Promise<AppState> {\n return writeDocument(resolveStorageDbPath(), APP_STATE_DOCUMENT, normalizeAppState(state));\n}\n\nasync function ensureInitialized(): Promise<AppState> {\n if (appStateCache) {\n return appStateCache;\n }\n\n const loaded = (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 = (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 = 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 (!allowBeforeMigrationComplete && current.migration.status !== \"complete\") {\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","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};\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\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 = db\n .prepare(\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n )\n .get(namespace);\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 db.prepare(\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 ).run(namespace, JSON.stringify(normalizedValue), new Date().toISOString());\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 = db\n .prepare(\n `SELECT value_json AS valueJson FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`,\n )\n .get(input.namespace);\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 db.prepare(\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 ).run(input.namespace, JSON.stringify(next), new Date().toISOString());\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 db.prepare(`DELETE FROM ${APP_STORAGE_TABLE} WHERE namespace = ?`).run(namespace);\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>;\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\nexport async function readAppSettings(): Promise<JsonRecord> {\n const appState = await getAppState();\n return stripLegacyAppSettingsKeys(asRecord(appState.runtimeSettings));\n}\n\nexport async function writeAppSettings(\n settings: JsonRecord,\n onUpdated?: (settings: JsonRecord) => void | Promise<void>,\n): Promise<JsonRecord> {\n const nextSettings = stripLegacyAppSettingsKeys(asRecord(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();\n }\n\n async getStatus(options: { forceRefresh?: boolean } = {}): Promise<LicenseStatus> {\n const forceRefresh = Boolean(options.forceRefresh);\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) {\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","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_WARNING_THRESHOLD = 85;\nexport const DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD = 95;\nexport const AUTO_ROLL_WARNING_MIN = 50;\nconst AUTO_ROLL_WARNING_MAX = 99;\nconst AUTO_ROLL_SWITCH_MAX = 100;\n\nfunction clampNumber(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\nfunction resolveFiniteNumber(value: number, fallback: number): number {\n return Number.isFinite(value) ? value : fallback;\n}\n\nexport function sanitizeAutoRollWarningThreshold(value: number): number {\n const numeric = resolveFiniteNumber(value, DEFAULT_AUTO_ROLL_WARNING_THRESHOLD);\n return clampNumber(numeric, AUTO_ROLL_WARNING_MIN, AUTO_ROLL_WARNING_MAX);\n}\n\nexport function sanitizeAutoRollSwitchThreshold(\n value: number,\n warningThreshold: number,\n): number {\n const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);\n const numeric = resolveFiniteNumber(value, DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD);\n return clampNumber(numeric, sanitizedWarning + 1, AUTO_ROLL_SWITCH_MAX);\n}\n\nexport function sanitizeAutoRollThresholds(\n warningThreshold: number,\n switchThreshold: number,\n): Pick<AutoRollSettings, \"warningThreshold\" | \"switchThreshold\"> {\n const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);\n const sanitizedSwitch = sanitizeAutoRollSwitchThreshold(switchThreshold, sanitizedWarning);\n return {\n warningThreshold: sanitizedWarning,\n switchThreshold: sanitizedSwitch,\n };\n}\n\nexport function normalizeAutoRollSettings(\n raw?: Partial<AutoRollSettings> | null,\n): AutoRollSettings {\n const enabled = typeof raw?.enabled === \"boolean\" ? raw.enabled : DEFAULT_AUTO_ROLL_ENABLED;\n const rawWarning = resolveFiniteNumber(\n typeof raw?.warningThreshold === \"number\" ? raw.warningThreshold : Number.NaN,\n DEFAULT_AUTO_ROLL_WARNING_THRESHOLD,\n );\n const rawSwitch = resolveFiniteNumber(\n typeof raw?.switchThreshold === \"number\" ? raw.switchThreshold : Number.NaN,\n DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD,\n );\n\n const {\n warningThreshold: normalizedWarning,\n switchThreshold: normalizedSwitch,\n } = sanitizeAutoRollThresholds(rawWarning, rawSwitch);\n\n return {\n enabled,\n warningThreshold: normalizedWarning,\n switchThreshold: normalizedSwitch,\n };\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 warningThreshold: normalized.warningThreshold,\n switchThreshold: normalized.switchThreshold,\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 warningThreshold: autoRoll.warningThreshold,\n switchThreshold: autoRoll.switchThreshold,\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 { fetchRateLimitsViaRpc } from '@codexuse/runtime-codex/codex/rpc';\nimport type { CloudSyncProfileRecord } from '@codexuse/contracts/cloud-sync/types';\nimport { getLastProfileName, persistLastProfileName } from '@codexuse/runtime-codex/codex/settings';\nimport {\n getAppState,\n getUserDataDir,\n updateAppState,\n type ProfileDashboardState,\n type ProfileRecordState,\n} from '@codexuse/runtime-app-state/app/state';\nimport { logError, 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 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 async readPreferredProfileName(): Promise<string | null> {\n try {\n return await getLastProfileName();\n } catch (error) {\n logWarn('Failed to read preferred profile name:', error);\n return null;\n }\n }\n\n private async persistPreferredProfileName(name: string | null): Promise<void> {\n try {\n await persistLastProfileName(name);\n } catch (error) {\n logWarn('Failed to persist preferred profile name:', error);\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 async captureActiveAuthSnapshot(): Promise<ActiveAuthSnapshot> {\n await this.initialize();\n\n let raw: string;\n try {\n raw = await fs.readFile(this.activeAuth, 'utf8');\n } catch (error) {\n if (this.isNotFoundError(error)) {\n return {\n fingerprint: null,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\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 snapshot active auth file:', error);\n this.lastActiveAuthErrorSignature = signature;\n }\n return {\n fingerprint: null,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\n }\n\n const trimmed = raw.trim();\n if (!trimmed) {\n return {\n fingerprint: null,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\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 workspaceId: workspace.id ?? null,\n };\n } catch {\n return {\n fingerprint,\n email: null,\n accountId: null,\n userId: null,\n chatgptUserId: null,\n workspaceId: null,\n };\n }\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 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 getProfileRowByIdentityKey(\n identityKey: string,\n options?: { authMethod?: string | null; preferAuthMethod?: string | null },\n ): Promise<ProfileRecord | undefined> {\n const records = await this.listProfileRecords();\n const matches = records.filter(record => this.resolveProfileIdentityFromRecord(record) === identityKey);\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 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 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 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 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 if (data.email) {\n profile.email = data.email;\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 logWarn(\n `Skipped syncing tokens for profile '${profileName}' because Codex auth switched to a different OpenAI identity.`,\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 return;\n }\n\n await this.syncProfileTokensFromActiveAuth(profileName, record.data, authPath);\n }),\n );\n }\n\n /**\n * Create a new profile by running codex login\n */\n async createProfile(name: string): Promise<Profile | null> {\n await this.initialize();\n\n const profileName = this.normalizeProfileName(name);\n if (await this.getProfileRowByName(profileName)) {\n throw new Error(`Profile '${profileName}' already exists!`);\n }\n\n let authData: ActiveAuth;\n try {\n const authRaw = await fs.readFile(this.activeAuth, 'utf8');\n authData = JSON.parse(authRaw) as ActiveAuth;\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 const normalizedProfile = this.normalizeProfileData(authData);\n normalizedProfile.created_at = normalizedProfile.created_at ?? new Date().toISOString();\n if (typeof normalizedProfile.auth_method === 'string') {\n normalizedProfile.auth_method = normalizedProfile.auth_method.trim().toLowerCase();\n }\n normalizedProfile.auth_method = normalizedProfile.auth_method ?? 'codex-cli';\n\n const metadata = this.extractProfileMetadata(normalizedProfile);\n const workspace = this.resolveWorkspaceIdentity(normalizedProfile, metadata);\n normalizedProfile.workspace_id = normalizedProfile.workspace_id ?? workspace.id ?? DEFAULT_WORKSPACE_ID;\n if (workspace.name) {\n normalizedProfile.workspace_name = normalizedProfile.workspace_name ?? workspace.name;\n }\n\n const resolvedEmail = this.resolveProfileEmail(normalizedProfile, metadata);\n if (resolvedEmail) {\n normalizedProfile.email = resolvedEmail;\n }\n\n try {\n await this.persistProfileRecord(profileName, normalizedProfile, metadata);\n const stored = await this.getProfileRowByName(profileName);\n return stored ? this.buildProfileFromRow(stored) : null;\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 * Switch to a different profile\n */\n async switchToProfile(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\n try {\n const profileData = record.data;\n const codexFormat = this.convertToCodexFormat(profileData);\n await this.writeAtomic(this.activeAuth, JSON.stringify(codexFormat, null, 2));\n await this.persistPreferredProfileName(profileName);\n return true;\n } catch (error) {\n logError('Error switching profile:', error);\n throw new Error('Failed to switch profile');\n }\n }\n\n async refreshProfileAuth(name: string): Promise<Profile> {\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 existing: ProfileData = record.data;\n let activeAuth: ActiveAuth;\n try {\n const authContent = await fs.readFile(this.activeAuth, 'utf8');\n activeAuth = JSON.parse(authContent) as ActiveAuth;\n } catch (error) {\n if (this.isNotFoundError(error)) {\n throw new Error('Codex CLI did not produce an auth file. Complete the login before refreshing this profile.');\n }\n logError('Failed to read Codex auth file during refresh:', error);\n throw new Error('Failed to read Codex auth file. Complete the login and try again.');\n }\n\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 * 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(() =>\n this.runWithPreparedProfileHome(name, action, {\n syncFromActiveAuthBeforeAction: true,\n }),\n ),\n );\n }\n\n async readLiveRateLimits(\n name: string,\n options: { codexPath?: string } = {},\n ): Promise<RateLimitSnapshot | null> {\n return this.enqueueProfileOperation(name, () =>\n this.runWithPreparedProfileHome(\n name,\n env => fetchRateLimitsViaRpc(env, { codexPath: options.codexPath }),\n { syncFromActiveAuthBeforeAction: false },\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 preferred = await this.readPreferredProfileName();\n if (preferred && preferred === sourceName) {\n await this.persistPreferredProfileName(targetName);\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 if (!record.accountId) {\n const dashboardState = await this.readProfileDashboardState();\n delete dashboardState.customGroupsByAccountKey[resolveFallbackAccountKey(profileName)];\n await this.writeProfileDashboardState(dashboardState);\n }\n const preferred = await this.readPreferredProfileName();\n if (preferred && preferred === profileName) {\n await this.persistPreferredProfileName(null);\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 return true;\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 const preferred = await this.readPreferredProfileName();\n if (preferred && removed.includes(preferred)) {\n await this.persistPreferredProfileName(null);\n }\n return removed;\n }\n\n /**\n * Check if the current auth matches a profile (for smart detection)\n */\n async getCurrentProfile(): Promise<{ name: string | null; trusted: boolean }> {\n await this.initialize();\n const preferredName = await this.readPreferredProfileName();\n if (preferredName) {\n try {\n const normalizedPreferred = this.normalizeProfileName(preferredName);\n const preferredRecord = await this.getProfileRowByName(normalizedPreferred);\n if (preferredRecord) {\n return { name: normalizedPreferred, trusted: true };\n }\n } catch {\n // fall through to active auth detection\n }\n }\n const activeAuth = await this.readActiveAuthFile();\n\n if (activeAuth) {\n const normalizedAuth = this.normalizeProfileData(activeAuth);\n const authMetadata = this.extractProfileMetadata(normalizedAuth);\n const workspace = this.resolveWorkspaceIdentity(normalizedAuth, authMetadata);\n const activeIdentityKey = this.resolveProfileIdentityFromData(null, normalizedAuth, authMetadata);\n\n if (activeIdentityKey) {\n const scoped = await this.getProfileRowByIdentityAndWorkspace(activeIdentityKey, workspace.id ?? DEFAULT_WORKSPACE_ID, {\n preferAuthMethod: 'codex-cli',\n });\n if (scoped) {\n const normalized = this.normalizeProfileName(scoped.name);\n await this.persistPreferredProfileName(normalized);\n return { name: normalized, trusted: true };\n }\n\n const matching = await this.getProfileRowByIdentityKey(activeIdentityKey, { preferAuthMethod: 'codex-cli' });\n if (matching) {\n const normalized = this.normalizeProfileName(matching.name);\n await this.persistPreferredProfileName(normalized);\n return { name: normalized, trusted: true };\n }\n }\n }\n\n const preferred = await this.readPreferredProfileName();\n if (preferred) {\n try {\n const normalized = this.normalizeProfileName(preferred);\n const exists = await this.getProfileRowByName(normalized);\n if (exists) {\n return { name: normalized, trusted: true };\n }\n } catch {\n await this.persistPreferredProfileName(null);\n return { name: null, trusted: false };\n }\n await this.persistPreferredProfileName(null);\n }\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 const preferred = await this.readPreferredProfileName();\n if (preferred) {\n try {\n const normalizedPreferred = this.normalizeProfileName(preferred);\n if (!normalized.has(normalizedPreferred)) {\n await this.persistPreferredProfileName(null);\n }\n } catch {\n await this.persistPreferredProfileName(null);\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 { RateLimitSnapshot, RateLimitWindow } 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 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\nconst RPC_TIMEOUT_MS = 10_000;\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\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\" ? (payload as Record<string, unknown>) : 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(parsed.tokens?.access_token);\n const candidates = [rootLastRefresh, nestedLastRefresh, rootAccessIssuedAt, nestedAccessIssuedAt]\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\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 (typeof updatedRecency === \"number\" && typeof currentRecency === \"number\") {\n return updatedRecency > currentRecency;\n }\n\n if (typeof updatedRecency === \"number\" && typeof currentRecency !== \"number\") {\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(message: RpcMessage, requestId: number): 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 cleanup();\n reject(new Error(\"codex RPC timed out\"));\n }, Math.max(1, timeoutMs));\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 = 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(rpc?: RpcRateLimitWindow | null): 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\" && 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 = 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 { rateLimits?: RpcRateLimitSnapshot } | 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 ?? process.env.HOME ?? process.env.USERPROFILE ?? os.homedir(),\n \".codex\",\n \"auth.json\",\n ));\n\n try {\n initialSourceAuth = await fs.readFile(sourceAuthPath, \"utf8\").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, { id: 2, method: \"account/rateLimits/read\", params: {} });\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.readFile(sourceAuthPath, \"utf8\").catch(() => null);\n if (shouldWriteBackAuth(initialSourceAuth, currentSourceAuth, updatedAuth)) {\n await fs.writeFile(sourceAuthPath, updatedAuth, \"utf8\");\n } else if (\n currentSourceAuth &&\n currentSourceAuth !== updatedAuth &&\n currentSourceAuth !== initialSourceAuth\n ) {\n logWarn(\"Skipped stale auth sync-back after rate-limit probe; source auth changed in flight.\", {\n sourceAuthPath,\n currentRecencyMs: extractAuthRecencyMs(currentSourceAuth),\n updatedRecencyMs: extractAuthRecencyMs(updatedAuth),\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 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 if (!pathValue) {\n return null;\n }\n const entries = pathValue\n .split(path.delimiter)\n .map(entry => entry.trim())\n .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) {\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.warn>): void {\n if (isTestEnv && !isMocked(console.warn)) {\n return;\n }\n console.warn(...args);\n}\n","export function printHelp(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 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>\n codexuse profile autoroll [--threshold=50-100] [--dry-run] [--watch] [--interval=seconds]\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 --threshold=NN Auto-roll switch threshold percent (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 --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`);\n}\n","import type { CodexLoginMode } from \"./codexCli\";\n\nexport const DEFAULT_AUTOROLL_INTERVAL_SECONDS = 30;\nexport const DEFAULT_AUTOROLL_THRESHOLD = 95;\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, 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 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\nfunction buildCodexCommand(codexPath: string, args: string[]): { command: string; args: string[]; shell: boolean } {\n const normalized = codexPath.toLowerCase();\n const isJs = normalized.endsWith(\".js\");\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 { ProfileManager } from \"@codexuse/runtime-profiles/profiles/profile-manager\";\nimport { assertProfileCreationAllowed } from \"@codexuse/runtime-profiles/license/guard\";\nimport { maxUsedPercent } from \"@codexuse/runtime-profiles/profiles/rate-limit-notifier\";\nimport { getStoredAutoRollSettings } from \"@codexuse/runtime-codex/codex/settings\";\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 DEFAULT_AUTOROLL_INTERVAL_SECONDS,\n DEFAULT_AUTOROLL_THRESHOLD,\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 hasUsage: boolean;\n resetsInSeconds: number | null;\n windowMinutes: number | null;\n};\n\nconst EMPTY_USAGE_SUMMARY: RateLimitUsageSummary = {\n windowKey: \"primary\",\n usagePercent: 0,\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 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 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 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 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 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 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(a: AutoRollCandidate, b: AutoRollCandidate): number {\n if (a.usageSummary.usagePercent !== b.usageSummary.usagePercent) {\n return a.usageSummary.usagePercent - b.usageSummary.usagePercent;\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 switchThreshold: number,\n): AutoRollCandidate | null {\n const candidates = profiles\n .filter(profile => profile.name !== currentProfileName && profile.isValid && !profile.tokenStatus?.requiresUserAction)\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(candidate => candidate.usageSummary.hasUsage && candidate.usageSummary.usagePercent < switchThreshold)\n .sort(compareAutoRollCandidates);\n let selected = belowThreshold[0] ?? null;\n\n if (!selected) {\n selected = candidates\n .filter(candidate => candidate.usageSummary.hasUsage)\n .sort(compareAutoRollCandidates)[0] ?? null;\n }\n\n if (!selected) {\n selected = candidates\n .filter(candidate => !candidate.usageSummary.hasUsage)\n .sort((a, b) => {\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 })[0] ?? null;\n }\n\n if (!selected) {\n return null;\n }\n\n if (selected.usageSummary.hasUsage && currentSummary.hasUsage) {\n if (selected.usageSummary.usagePercent > currentSummary.usagePercent) {\n return null;\n }\n if (selected.usageSummary.usagePercent === currentSummary.usagePercent) {\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 parseAutoRollThreshold(flags: string[], fallbackThreshold: number): number {\n const explicitThreshold = parseNumericFlag(flags, \"--threshold\");\n if (explicitThreshold === null) {\n return fallbackThreshold;\n }\n if (Number.isNaN(explicitThreshold)) {\n throw new Error(\"Invalid --threshold value. Use --threshold=50-100.\");\n }\n if (explicitThreshold < 50 || explicitThreshold > 100) {\n throw new Error(\"Invalid --threshold value. Use a number between 50 and 100.\");\n }\n return Math.round(explicitThreshold);\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\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 threshold: number;\n dryRun: 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 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 (currentUsage.usagePercent < options.threshold) {\n return {\n switched: false,\n message: `'${current.name}' at ${Math.round(currentUsage.usagePercent)}%, below threshold ${options.threshold}%.`,\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.threshold,\n );\n if (!candidate) {\n return {\n switched: false,\n message: `No eligible profile to switch from '${current.name}' at ${Math.round(currentUsage.usagePercent)}%.`,\n source: current.name,\n target: null,\n };\n }\n\n const candidateUsage = candidate.usageSummary.hasUsage ? `${Math.round(candidate.usageSummary.usagePercent)}%` : \"n/a\";\n if (options.dryRun) {\n return {\n switched: false,\n message: `[dry-run] Would switch '${current.name}' (${Math.round(currentUsage.usagePercent)}%) -> '${candidate.profile.name}' (${candidateUsage}).`,\n source: current.name,\n target: candidate.profile.name,\n };\n }\n\n await manager.switchToProfile(candidate.profile.name);\n return {\n switched: true,\n message: `Auto-rolled '${current.name}' (${Math.round(currentUsage.usagePercent)}%) -> '${candidate.profile.name}' (${candidateUsage}).`,\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 await manager.switchToProfile(name);\n console.log(`Switched to profile: ${name}`);\n return;\n }\n case \"autoroll\":\n case \"auto-roll\": {\n const watch = hasFlag(flags, \"--watch\");\n const dryRun = hasFlag(flags, \"--dry-run\");\n const settings = await getStoredAutoRollSettings().catch(() => null);\n const fallbackThreshold =\n typeof settings?.switchThreshold === \"number\" && Number.isFinite(settings.switchThreshold)\n ? Math.round(settings.switchThreshold)\n : DEFAULT_AUTOROLL_THRESHOLD;\n const threshold = parseAutoRollThreshold(flags, fallbackThreshold);\n const intervalSeconds = parseAutoRollIntervalSeconds(flags);\n\n if (watch) {\n console.log(`Auto-roll watch: threshold ${threshold}% | interval ${intervalSeconds}s${dryRun ? \" | dry-run\" : \"\"}`);\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 result = await runAutoRollPass(manager, { threshold, dryRun });\n console.log(result.message);\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, { threshold, dryRun });\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 profileName = normalizePathCandidate(state.app.lastProfileName);\n if (profileName && state.profilesByName[profileName]) {\n return {\n codexHomePath: resolveProfileCodexHomeDir(profileName),\n profileName,\n source: \"profile\",\n };\n }\n\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 warningThreshold: autoRoll.warningThreshold,\n switchThreshold: autoRoll.switchThreshold,\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 warningThreshold: autoRoll.warningThreshold,\n switchThreshold: autoRoll.switchThreshold,\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 { 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 \"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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ACrE,YAAQ,MAAM,OAAO;AACrB,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;;;ACpEA,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","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_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_fs","import_node_path","ENV_HINTS","fileExists","path","stat","buildCodexCommand","result","import_node_fs","import_node_path","isRecord","isRecord","import_toml","import_node_child_process","import_node_path","isRecord","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"]}